ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
(Generate patch)

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.60 by dl, Thu Aug 16 12:24:58 2012 UTC vs.
Revision 1.97 by jsr166, Mon Feb 11 20:43:59 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166e;
8 import jsr166e.LongAdder;
9 import jsr166e.ForkJoinPool;
10 import jsr166e.ForkJoinTask;
8  
9   import java.util.Comparator;
10   import java.util.Arrays;
# Line 24 | Line 21 | import java.util.Enumeration;
21   import java.util.ConcurrentModificationException;
22   import java.util.NoSuchElementException;
23   import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ThreadLocalRandom;
28 import java.util.concurrent.locks.LockSupport;
24   import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 + import java.util.concurrent.atomic.AtomicInteger;
26   import java.util.concurrent.atomic.AtomicReference;
31
27   import java.io.Serializable;
28  
29   /**
# Line 43 | Line 38 | import java.io.Serializable;
38   * interoperable with {@code Hashtable} in programs that rely on its
39   * thread safety but not on its synchronization details.
40   *
41 < * <p> Retrieval operations (including {@code get}) generally do not
41 > * <p>Retrieval operations (including {@code get}) generally do not
42   * block, so may overlap with update operations (including {@code put}
43   * and {@code remove}). Retrievals reflect the results of the most
44   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 59 | import java.io.Serializable;
59   * that may be adequate for monitoring or estimation purposes, but not
60   * for program control.
61   *
62 < * <p> The table is dynamically expanded when there are too many
62 > * <p>The table is dynamically expanded when there are too many
63   * collisions (i.e., keys that have distinct hash codes but fall into
64   * the same slot modulo the table size), with the expected average
65   * effect of maintaining roughly two bins per mapping (corresponding
# Line 85 | Line 80 | import java.io.Serializable;
80   * {@code hashCode()} is a sure way to slow down performance of any
81   * hash table.
82   *
83 + * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
84 + * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
85 + * (using {@link #keySet(Object)} when only keys are of interest, and the
86 + * mapped values are (perhaps transiently) not used or all take the
87 + * same mapping value.
88 + *
89 + * <p>A ConcurrentHashMapV8 can be used as scalable frequency map (a
90 + * form of histogram or multiset) by using {@link LongAdder} values
91 + * and initializing via {@link #computeIfAbsent}. For example, to add
92 + * a count to a {@code ConcurrentHashMapV8<String,LongAdder> freqs}, you
93 + * can use {@code freqs.computeIfAbsent(k -> new
94 + * LongAdder()).increment();}
95 + *
96   * <p>This class and its views and iterators implement all of the
97   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
98   * interfaces.
99   *
100 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
100 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
101   * does <em>not</em> allow {@code null} to be used as a key or value.
102   *
103 + * <p>ConcurrentHashMapV8s support sequential and parallel operations
104 + * bulk operations. (Parallel forms use the {@link
105 + * ForkJoinPool#commonPool()}). Tasks that may be used in other
106 + * contexts are available in class {@link ForkJoinTasks}. These
107 + * operations are designed to be safely, and often sensibly, applied
108 + * even with maps that are being concurrently updated by other
109 + * threads; for example, when computing a snapshot summary of the
110 + * values in a shared registry.  There are three kinds of operation,
111 + * each with four forms, accepting functions with Keys, Values,
112 + * Entries, and (Key, Value) arguments and/or return values. Because
113 + * the elements of a ConcurrentHashMapV8 are not ordered in any
114 + * particular way, and may be processed in different orders in
115 + * different parallel executions, the correctness of supplied
116 + * functions should not depend on any ordering, or on any other
117 + * objects or values that may transiently change while computation is
118 + * in progress; and except for forEach actions, should ideally be
119 + * side-effect-free.
120 + *
121 + * <ul>
122 + * <li> forEach: Perform a given action on each element.
123 + * A variant form applies a given transformation on each element
124 + * before performing the action.</li>
125 + *
126 + * <li> search: Return the first available non-null result of
127 + * applying a given function on each element; skipping further
128 + * search when a result is found.</li>
129 + *
130 + * <li> reduce: Accumulate each element.  The supplied reduction
131 + * function cannot rely on ordering (more formally, it should be
132 + * both associative and commutative).  There are five variants:
133 + *
134 + * <ul>
135 + *
136 + * <li> Plain reductions. (There is not a form of this method for
137 + * (key, value) function arguments since there is no corresponding
138 + * return type.)</li>
139 + *
140 + * <li> Mapped reductions that accumulate the results of a given
141 + * function applied to each element.</li>
142 + *
143 + * <li> Reductions to scalar doubles, longs, and ints, using a
144 + * given basis value.</li>
145 + *
146 + * </li>
147 + * </ul>
148 + * </ul>
149 + *
150 + * <p>The concurrency properties of bulk operations follow
151 + * from those of ConcurrentHashMapV8: Any non-null result returned
152 + * from {@code get(key)} and related access methods bears a
153 + * happens-before relation with the associated insertion or
154 + * update.  The result of any bulk operation reflects the
155 + * composition of these per-element relations (but is not
156 + * necessarily atomic with respect to the map as a whole unless it
157 + * is somehow known to be quiescent).  Conversely, because keys
158 + * and values in the map are never null, null serves as a reliable
159 + * atomic indicator of the current lack of any result.  To
160 + * maintain this property, null serves as an implicit basis for
161 + * all non-scalar reduction operations. For the double, long, and
162 + * int versions, the basis should be one that, when combined with
163 + * any other value, returns that other value (more formally, it
164 + * should be the identity element for the reduction). Most common
165 + * reductions have these properties; for example, computing a sum
166 + * with basis 0 or a minimum with basis MAX_VALUE.
167 + *
168 + * <p>Search and transformation functions provided as arguments
169 + * should similarly return null to indicate the lack of any result
170 + * (in which case it is not used). In the case of mapped
171 + * reductions, this also enables transformations to serve as
172 + * filters, returning null (or, in the case of primitive
173 + * specializations, the identity basis) if the element should not
174 + * be combined. You can create compound transformations and
175 + * filterings by composing them yourself under this "null means
176 + * there is nothing there now" rule before using them in search or
177 + * reduce operations.
178 + *
179 + * <p>Methods accepting and/or returning Entry arguments maintain
180 + * key-value associations. They may be useful for example when
181 + * finding the key for the greatest value. Note that "plain" Entry
182 + * arguments can be supplied using {@code new
183 + * AbstractMap.SimpleEntry(k,v)}.
184 + *
185 + * <p>Bulk operations may complete abruptly, throwing an
186 + * exception encountered in the application of a supplied
187 + * function. Bear in mind when handling such exceptions that other
188 + * concurrently executing functions could also have thrown
189 + * exceptions, or would have done so if the first exception had
190 + * not occurred.
191 + *
192 + * <p>Speedups for parallel compared to sequential forms are common
193 + * but not guaranteed.  Parallel operations involving brief functions
194 + * on small maps may execute more slowly than sequential forms if the
195 + * underlying work to parallelize the computation is more expensive
196 + * than the computation itself.  Similarly, parallelization may not
197 + * lead to much actual parallelism if all processors are busy
198 + * performing unrelated tasks.
199 + *
200 + * <p>All arguments to all task methods must be non-null.
201 + *
202 + * <p><em>jsr166e note: During transition, this class
203 + * uses nested functional interfaces with different names but the
204 + * same forms as those expected for JDK8.</em>
205 + *
206   * <p>This class is a member of the
207   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
208   * Java Collections Framework</a>.
209   *
99 * <p><em>jsr166e note: This class is a candidate replacement for
100 * java.util.concurrent.ConcurrentHashMap.  During transition, this
101 * class declares and uses nested functional interfaces with different
102 * names but the same forms as those expected for JDK8.<em>
103 *
210   * @since 1.5
211   * @author Doug Lea
212   * @param <K> the type of keys maintained by this map
# Line 117 | Line 223 | public class ConcurrentHashMapV8<K, V>
223       * portion of the elements, and so may be amenable to parallel
224       * execution.
225       *
226 <     * <p> This interface exports a subset of expected JDK8
226 >     * <p>This interface exports a subset of expected JDK8
227       * functionality.
228       *
229       * <p>Sample usage: Here is one (of the several) ways to compute
# Line 189 | Line 295 | public class ConcurrentHashMapV8<K, V>
295       * the same or better than java.util.HashMap, and to support high
296       * initial insertion rates on an empty table by many threads.
297       *
298 <     * Each key-value mapping is held in a Node.  Because Node fields
299 <     * can contain special values, they are defined using plain Object
300 <     * types. Similarly in turn, all internal methods that use them
301 <     * work off Object types. And similarly, so do the internal
302 <     * methods of auxiliary iterator and view classes.  All public
303 <     * generic typed methods relay in/out of these internal methods,
304 <     * supplying null-checks and casts as needed. This also allows
305 <     * many of the public methods to be factored into a smaller number
306 <     * of internal methods (although sadly not so for the five
201 <     * variants of put-related operations). The validation-based
202 <     * approach explained below leads to a lot of code sprawl because
298 >     * Each key-value mapping is held in a Node.  Because Node key
299 >     * fields can contain special values, they are defined using plain
300 >     * Object types (not type "K"). This leads to a lot of explicit
301 >     * casting (and many explicit warning suppressions to tell
302 >     * compilers not to complain about it). It also allows some of the
303 >     * public methods to be factored into a smaller number of internal
304 >     * methods (although sadly not so for the five variants of
305 >     * put-related operations). The validation-based approach
306 >     * explained below leads to a lot of code sprawl because
307       * retry-control precludes factoring into smaller methods.
308       *
309       * The table is lazily initialized to a power-of-two size upon the
# Line 213 | Line 317 | public class ConcurrentHashMapV8<K, V>
317       * as lookups check hash code and non-nullness of value before
318       * checking key equality.
319       *
320 <     * We use the top two bits of Node hash fields for control
321 <     * purposes -- they are available anyway because of addressing
322 <     * constraints.  As explained further below, these top bits are
323 <     * used as follows:
324 <     *  00 - Normal
325 <     *  01 - Locked
222 <     *  11 - Locked and may have a thread waiting for lock
223 <     *  10 - Node is a forwarding node
224 <     *
225 <     * The lower 30 bits of each Node's hash field contain a
226 <     * transformation of the key's hash code, except for forwarding
227 <     * nodes, for which the lower bits are zero (and so always have
228 <     * hash field == MOVED).
320 >     * We use the top (sign) bit of Node hash fields for control
321 >     * purposes -- it is available anyway because of addressing
322 >     * constraints.  Nodes with negative hash fields are forwarding
323 >     * nodes to either TreeBins or resized tables.  The lower 31 bits
324 >     * of each normal Node's hash field contain a transformation of
325 >     * the key's hash code.
326       *
327       * Insertion (via put or its variants) of the first node in an
328       * empty bin is performed by just CASing it to the bin.  This is
# Line 234 | Line 331 | public class ConcurrentHashMapV8<K, V>
331       * delete, and replace) require locks.  We do not want to waste
332       * the space required to associate a distinct lock object with
333       * each bin, so instead use the first node of a bin list itself as
334 <     * a lock. Blocking support for these locks relies on the builtin
335 <     * "synchronized" monitors.  However, we also need a tryLock
239 <     * construction, so we overlay these by using bits of the Node
240 <     * hash field for lock control (see above), and so normally use
241 <     * builtin monitors only for blocking and signalling using
242 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
334 >     * a lock. Locking support for these locks relies on builtin
335 >     * "synchronized" monitors.
336       *
337       * Using the first node of a list as a lock does not by itself
338       * suffice though: When a node is locked, any update must first
# Line 301 | Line 394 | public class ConcurrentHashMapV8<K, V>
394       * iterators in the same way.
395       *
396       * The table is resized when occupancy exceeds a percentage
397 <     * threshold (nominally, 0.75, but see below).  Only a single
398 <     * thread performs the resize (using field "sizeCtl", to arrange
399 <     * exclusion), but the table otherwise remains usable for reads
400 <     * and updates. Resizing proceeds by transferring bins, one by
401 <     * one, from the table to the next table.  Because we are using
402 <     * power-of-two expansion, the elements from each bin must either
403 <     * stay at same index, or move with a power of two offset. We
404 <     * eliminate unnecessary node creation by catching cases where old
405 <     * nodes can be reused because their next fields won't change.  On
406 <     * average, only about one-sixth of them need cloning when a table
407 <     * doubles. The nodes they replace will be garbage collectable as
408 <     * soon as they are no longer referenced by any reader thread that
409 <     * may be in the midst of concurrently traversing table.  Upon
410 <     * transfer, the old table bin contains only a special forwarding
411 <     * node (with hash field "MOVED") that contains the next table as
412 <     * its key. On encountering a forwarding node, access and update
413 <     * operations restart, using the new table.
414 <     *
415 <     * Each bin transfer requires its bin lock. However, unlike other
416 <     * cases, a transfer can skip a bin if it fails to acquire its
417 <     * lock, and revisit it later (unless it is a TreeBin). Method
418 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
419 <     * have been skipped because of failure to acquire a lock, and
420 <     * blocks only if none are available (i.e., only very rarely).
421 <     * The transfer operation must also ensure that all accessible
422 <     * bins in both the old and new table are usable by any traversal.
423 <     * When there are no lock acquisition failures, this is arranged
424 <     * simply by proceeding from the last bin (table.length - 1) up
425 <     * towards the first.  Upon seeing a forwarding node, traversals
426 <     * (see class Iter) arrange to move to the new table
427 <     * without revisiting nodes.  However, when any node is skipped
428 <     * during a transfer, all earlier table bins may have become
429 <     * visible, so are initialized with a reverse-forwarding node back
430 <     * to the old table until the new ones are established. (This
431 <     * sometimes requires transiently locking a forwarding node, which
432 <     * is possible under the above encoding.) These more expensive
433 <     * mechanics trigger only when necessary.
397 >     * threshold (nominally, 0.75, but see below).  Any thread
398 >     * noticing an overfull bin may assist in resizing after the
399 >     * initiating thread allocates and sets up the replacement
400 >     * array. However, rather than stalling, these other threads may
401 >     * proceed with insertions etc.  The use of TreeBins shields us
402 >     * from the worst case effects of overfilling while resizes are in
403 >     * progress.  Resizing proceeds by transferring bins, one by one,
404 >     * from the table to the next table. To enable concurrency, the
405 >     * next table must be (incrementally) prefilled with place-holders
406 >     * serving as reverse forwarders to the old table.  Because we are
407 >     * using power-of-two expansion, the elements from each bin must
408 >     * either stay at same index, or move with a power of two
409 >     * offset. We eliminate unnecessary node creation by catching
410 >     * cases where old nodes can be reused because their next fields
411 >     * won't change.  On average, only about one-sixth of them need
412 >     * cloning when a table doubles. The nodes they replace will be
413 >     * garbage collectable as soon as they are no longer referenced by
414 >     * any reader thread that may be in the midst of concurrently
415 >     * traversing table.  Upon transfer, the old table bin contains
416 >     * only a special forwarding node (with hash field "MOVED") that
417 >     * contains the next table as its key. On encountering a
418 >     * forwarding node, access and update operations restart, using
419 >     * the new table.
420 >     *
421 >     * Each bin transfer requires its bin lock, which can stall
422 >     * waiting for locks while resizing. However, because other
423 >     * threads can join in and help resize rather than contend for
424 >     * locks, average aggregate waits become shorter as resizing
425 >     * progresses.  The transfer operation must also ensure that all
426 >     * accessible bins in both the old and new table are usable by any
427 >     * traversal.  This is arranged by proceeding from the last bin
428 >     * (table.length - 1) up towards the first.  Upon seeing a
429 >     * forwarding node, traversals (see class Traverser) arrange to
430 >     * move to the new table without revisiting nodes.  However, to
431 >     * ensure that no intervening nodes are skipped, bin splitting can
432 >     * only begin after the associated reverse-forwarders are in
433 >     * place.
434       *
435       * The traversal scheme also applies to partial traversals of
436       * ranges of bins (via an alternate Traverser constructor)
# Line 352 | Line 445 | public class ConcurrentHashMapV8<K, V>
445       * These cases attempt to override the initial capacity settings,
446       * but harmlessly fail to take effect in cases of races.
447       *
448 <     * The element count is maintained using a LongAdder, which avoids
449 <     * contention on updates but can encounter cache thrashing if read
450 <     * too frequently during concurrent access. To avoid reading so
451 <     * often, resizing is attempted either when a bin lock is
452 <     * contended, or upon adding to a bin already holding two or more
453 <     * nodes (checked before adding in the xIfAbsent methods, after
454 <     * adding in others). Under uniform hash distributions, the
455 <     * probability of this occurring at threshold is around 13%,
456 <     * meaning that only about 1 in 8 puts check threshold (and after
457 <     * resizing, many fewer do so). But this approximation has high
458 <     * variance for small table sizes, so we check on any collision
459 <     * for sizes <= 64. The bulk putAll operation further reduces
460 <     * contention by only committing count updates upon these size
461 <     * checks.
448 >     * The element count is maintained using a specialization of
449 >     * LongAdder. We need to incorporate a specialization rather than
450 >     * just use a LongAdder in order to access implicit
451 >     * contention-sensing that leads to creation of multiple
452 >     * CounterCells.  The counter mechanics avoid contention on
453 >     * updates but can encounter cache thrashing if read too
454 >     * frequently during concurrent access. To avoid reading so often,
455 >     * resizing under contention is attempted only upon adding to a
456 >     * bin already holding two or more nodes. Under uniform hash
457 >     * distributions, the probability of this occurring at threshold
458 >     * is around 13%, meaning that only about 1 in 8 puts check
459 >     * threshold (and after resizing, many fewer do so). The bulk
460 >     * putAll operation further reduces contention by only committing
461 >     * count updates upon these size checks.
462       *
463       * Maintaining API and serialization compatibility with previous
464       * versions of this class introduces several oddities. Mainly: We
# Line 416 | Line 509 | public class ConcurrentHashMapV8<K, V>
509      private static final float LOAD_FACTOR = 0.75f;
510  
511      /**
419     * The buffer size for skipped bins during transfers. The
420     * value is arbitrary but should be large enough to avoid
421     * most locking stalls during resizes.
422     */
423    private static final int TRANSFER_BUFFER_SIZE = 32;
424
425    /**
512       * The bin count threshold for using a tree rather than list for a
513       * bin.  The value reflects the approximate break-even point for
514       * using tree-based operations.
515       */
516      private static final int TREE_THRESHOLD = 8;
517  
518 +    /**
519 +     * Minimum number of rebinnings per transfer step. Ranges are
520 +     * subdivided to allow multiple resizer threads.  This value
521 +     * serves as a lower bound to avoid resizers encountering
522 +     * excessive memory contention.  The value should be at least
523 +     * DEFAULT_CAPACITY.
524 +     */
525 +    private static final int MIN_TRANSFER_STRIDE = 16;
526 +
527      /*
528 <     * Encodings for special uses of Node hash fields. See above for
434 <     * explanation.
528 >     * Encodings for Node hash fields. See above for explanation.
529       */
530      static final int MOVED     = 0x80000000; // hash field for forwarding nodes
531 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
532 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
533 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
531 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
532 >
533 >    /** Number of CPUS, to place bounds on some sizings */
534 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
535 >
536 >    /* ---------------- Counters -------------- */
537 >
538 >    // Adapted from LongAdder and Striped64.
539 >    // See their internal docs for explanation.
540 >
541 >    // A padded cell for distributing counts
542 >    static final class CounterCell {
543 >        volatile long p0, p1, p2, p3, p4, p5, p6;
544 >        volatile long value;
545 >        volatile long q0, q1, q2, q3, q4, q5, q6;
546 >        CounterCell(long x) { value = x; }
547 >    }
548 >
549 >    /**
550 >     * Holder for the thread-local hash code determining which
551 >     * CounterCell to use. The code is initialized via the
552 >     * counterHashCodeGenerator, but may be moved upon collisions.
553 >     */
554 >    static final class CounterHashCode {
555 >        int code;
556 >    }
557 >
558 >    /**
559 >     * Generates initial value for per-thread CounterHashCodes
560 >     */
561 >    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
562 >
563 >    /**
564 >     * Increment for counterHashCodeGenerator. See class ThreadLocal
565 >     * for explanation.
566 >     */
567 >    static final int SEED_INCREMENT = 0x61c88647;
568 >
569 >    /**
570 >     * Per-thread counter hash codes. Shared across all instances.
571 >     */
572 >    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
573 >        new ThreadLocal<CounterHashCode>();
574  
575      /* ---------------- Fields -------------- */
576  
# Line 444 | Line 578 | public class ConcurrentHashMapV8<K, V>
578       * The array of bins. Lazily initialized upon first insertion.
579       * Size is always a power of two. Accessed directly by iterators.
580       */
581 <    transient volatile Node[] table;
581 >    transient volatile Node<V>[] table;
582  
583      /**
584 <     * The counter maintaining number of elements.
584 >     * The next table to use; non-null only while resizing.
585       */
586 <    private transient final LongAdder counter;
586 >    private transient volatile Node<V>[] nextTable;
587 >
588 >    /**
589 >     * Base counter value, used mainly when there is no contention,
590 >     * but also as a fallback during table initialization
591 >     * races. Updated via CAS.
592 >     */
593 >    private transient volatile long baseCount;
594  
595      /**
596       * Table initialization and resizing control.  When negative, the
597 <     * table is being initialized or resized. Otherwise, when table is
598 <     * null, holds the initial table size to use upon creation, or 0
599 <     * for default. After initialization, holds the next element count
600 <     * value upon which to resize the table.
597 >     * table is being initialized or resized: -1 for initialization,
598 >     * else -(1 + the number of active resizing threads).  Otherwise,
599 >     * when table is null, holds the initial table size to use upon
600 >     * creation, or 0 for default. After initialization, holds the
601 >     * next element count value upon which to resize the table.
602       */
603      private transient volatile int sizeCtl;
604  
605 +    /**
606 +     * The next table index (plus one) to split while resizing.
607 +     */
608 +    private transient volatile int transferIndex;
609 +
610 +    /**
611 +     * The least available table index to split while resizing.
612 +     */
613 +    private transient volatile int transferOrigin;
614 +
615 +    /**
616 +     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
617 +     */
618 +    private transient volatile int counterBusy;
619 +
620 +    /**
621 +     * Table of counter cells. When non-null, size is a power of 2.
622 +     */
623 +    private transient volatile CounterCell[] counterCells;
624 +
625      // views
626 <    private transient KeySet<K,V> keySet;
627 <    private transient Values<K,V> values;
628 <    private transient EntrySet<K,V> entrySet;
626 >    private transient KeySetView<K,V> keySet;
627 >    private transient ValuesView<K,V> values;
628 >    private transient EntrySetView<K,V> entrySet;
629  
630      /** For serialization compatibility. Null unless serialized; see below */
631      private Segment<K,V>[] segments;
# Line 482 | Line 644 | public class ConcurrentHashMapV8<K, V>
644       * inline assignments below.
645       */
646  
647 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
648 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
647 >    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
648 >        (Node<V>[] tab, int i) { // used by Traverser
649 >        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
650      }
651  
652 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
653 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
652 >    private static final <V> boolean casTabAt
653 >        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
654 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
655      }
656  
657 <    private static final void setTabAt(Node[] tab, int i, Node v) {
658 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
657 >    private static final <V> void setTabAt
658 >        (Node<V>[] tab, int i, Node<V> v) {
659 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
660      }
661  
662      /* ---------------- Nodes -------------- */
# Line 506 | Line 671 | public class ConcurrentHashMapV8<K, V>
671       * before a val, but can only be used after checking val to be
672       * non-null.
673       */
674 <    static class Node {
675 <        volatile int hash;
674 >    static class Node<V> {
675 >        final int hash;
676          final Object key;
677 <        volatile Object val;
678 <        volatile Node next;
677 >        volatile V val;
678 >        volatile Node<V> next;
679  
680 <        Node(int hash, Object key, Object val, Node next) {
680 >        Node(int hash, Object key, V val, Node<V> next) {
681              this.hash = hash;
682              this.key = key;
683              this.val = val;
684              this.next = next;
685          }
521
522        /** CompareAndSet the hash field */
523        final boolean casHash(int cmp, int val) {
524            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
525        }
526
527        /** The number of spins before blocking for a lock */
528        static final int MAX_SPINS =
529            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
530
531        /**
532         * Spins a while if LOCKED bit set and this node is the first
533         * of its bin, and then sets WAITING bits on hash field and
534         * blocks (once) if they are still set.  It is OK for this
535         * method to return even if lock is not available upon exit,
536         * which enables these simple single-wait mechanics.
537         *
538         * The corresponding signalling operation is performed within
539         * callers: Upon detecting that WAITING has been set when
540         * unlocking lock (via a failed CAS from non-waiting LOCKED
541         * state), unlockers acquire the sync lock and perform a
542         * notifyAll.
543         */
544        final void tryAwaitLock(Node[] tab, int i) {
545            if (tab != null && i >= 0 && i < tab.length) { // bounds check
546                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
547                int spins = MAX_SPINS, h;
548                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
549                    if (spins >= 0) {
550                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
551                        if (r >= 0 && --spins == 0)
552                            Thread.yield();  // yield before block
553                    }
554                    else if (casHash(h, h | WAITING)) {
555                        synchronized (this) {
556                            if (tabAt(tab, i) == this &&
557                                (hash & WAITING) == WAITING) {
558                                try {
559                                    wait();
560                                } catch (InterruptedException ie) {
561                                    Thread.currentThread().interrupt();
562                                }
563                            }
564                            else
565                                notifyAll(); // possibly won race vs signaller
566                        }
567                        break;
568                    }
569                }
570            }
571        }
572
573        // Unsafe mechanics for casHash
574        private static final sun.misc.Unsafe UNSAFE;
575        private static final long hashOffset;
576
577        static {
578            try {
579                UNSAFE = getUnsafe();
580                Class<?> k = Node.class;
581                hashOffset = UNSAFE.objectFieldOffset
582                    (k.getDeclaredField("hash"));
583            } catch (Exception e) {
584                throw new Error(e);
585            }
586        }
686      }
687  
688      /* ---------------- TreeBins -------------- */
# Line 591 | Line 690 | public class ConcurrentHashMapV8<K, V>
690      /**
691       * Nodes for use in TreeBins
692       */
693 <    static final class TreeNode extends Node {
694 <        TreeNode parent;  // red-black tree links
695 <        TreeNode left;
696 <        TreeNode right;
697 <        TreeNode prev;    // needed to unlink next upon deletion
693 >    static final class TreeNode<V> extends Node<V> {
694 >        TreeNode<V> parent;  // red-black tree links
695 >        TreeNode<V> left;
696 >        TreeNode<V> right;
697 >        TreeNode<V> prev;    // needed to unlink next upon deletion
698          boolean red;
699  
700 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
700 >        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
701              super(hash, key, val, next);
702              this.parent = parent;
703          }
# Line 647 | Line 746 | public class ConcurrentHashMapV8<K, V>
746       * and writers. Since we don't need to export full Lock API, we
747       * just override the minimal AQS methods and use them directly.
748       */
749 <    static final class TreeBin extends AbstractQueuedSynchronizer {
749 >    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
750          private static final long serialVersionUID = 2249069246763182397L;
751 <        transient TreeNode root;  // root of tree
752 <        transient TreeNode first; // head of next-pointer list
751 >        transient TreeNode<V> root;  // root of tree
752 >        transient TreeNode<V> first; // head of next-pointer list
753  
754          /* AQS overrides */
755          public final boolean isHeldExclusively() { return getState() > 0; }
# Line 681 | Line 780 | public class ConcurrentHashMapV8<K, V>
780          }
781  
782          /** From CLR */
783 <        private void rotateLeft(TreeNode p) {
783 >        private void rotateLeft(TreeNode<V> p) {
784              if (p != null) {
785 <                TreeNode r = p.right, pp, rl;
785 >                TreeNode<V> r = p.right, pp, rl;
786                  if ((rl = p.right = r.left) != null)
787                      rl.parent = p;
788                  if ((pp = r.parent = p.parent) == null)
# Line 698 | Line 797 | public class ConcurrentHashMapV8<K, V>
797          }
798  
799          /** From CLR */
800 <        private void rotateRight(TreeNode p) {
800 >        private void rotateRight(TreeNode<V> p) {
801              if (p != null) {
802 <                TreeNode l = p.left, pp, lr;
802 >                TreeNode<V> l = p.left, pp, lr;
803                  if ((lr = p.left = l.right) != null)
804                      lr.parent = p;
805                  if ((pp = l.parent = p.parent) == null)
# Line 718 | Line 817 | public class ConcurrentHashMapV8<K, V>
817           * Returns the TreeNode (or null if not found) for the given key
818           * starting at given root.
819           */
820 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
821 <        final TreeNode getTreeNode(int h, Object k, TreeNode p) {
820 >        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
821 >            (int h, Object k, TreeNode<V> p) {
822              Class<?> c = k.getClass();
823              while (p != null) {
824                  int dir, ph;  Object pk; Class<?> pc;
# Line 729 | Line 828 | public class ConcurrentHashMapV8<K, V>
828                      if (c != (pc = pk.getClass()) ||
829                          !(k instanceof Comparable) ||
830                          (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
831 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
832 <                        TreeNode r = null, s = null, pl, pr;
833 <                        if (dir >= 0) {
834 <                            if ((pl = p.left) != null && h <= pl.hash)
835 <                                s = pl;
831 >                        if ((dir = (c == pc) ? 0 :
832 >                             c.getName().compareTo(pc.getName())) == 0) {
833 >                            TreeNode<V> r = null, pl, pr; // check both sides
834 >                            if ((pr = p.right) != null && h >= pr.hash &&
835 >                                (r = getTreeNode(h, k, pr)) != null)
836 >                                return r;
837 >                            else if ((pl = p.left) != null && h <= pl.hash)
838 >                                dir = -1;
839 >                            else // nothing there
840 >                                return null;
841                          }
738                        else if ((pr = p.right) != null && h >= pr.hash)
739                            s = pr;
740                        if (s != null && (r = getTreeNode(h, k, s)) != null)
741                            return r;
842                      }
843                  }
844                  else
# Line 753 | Line 853 | public class ConcurrentHashMapV8<K, V>
853           * read-lock to call getTreeNode, but during failure to get
854           * lock, searches along next links.
855           */
856 <        final Object getValue(int h, Object k) {
857 <            Node r = null;
856 >        final V getValue(int h, Object k) {
857 >            Node<V> r = null;
858              int c = getState(); // Must read lock state first
859 <            for (Node e = first; e != null; e = e.next) {
859 >            for (Node<V> e = first; e != null; e = e.next) {
860                  if (c <= 0 && compareAndSetState(c, c - 1)) {
861                      try {
862                          r = getTreeNode(h, k, root);
# Line 765 | Line 865 | public class ConcurrentHashMapV8<K, V>
865                      }
866                      break;
867                  }
868 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
868 >                else if (e.hash == h && k.equals(e.key)) {
869                      r = e;
870                      break;
871                  }
# Line 779 | Line 879 | public class ConcurrentHashMapV8<K, V>
879           * Finds or adds a node.
880           * @return null if added
881           */
882 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
883 <        final TreeNode putTreeNode(int h, Object k, Object v) {
882 >        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
883 >            (int h, Object k, V v) {
884              Class<?> c = k.getClass();
885 <            TreeNode pp = root, p = null;
885 >            TreeNode<V> pp = root, p = null;
886              int dir = 0;
887              while (pp != null) { // find existing node or leaf to insert at
888                  int ph;  Object pk; Class<?> pc;
# Line 793 | Line 893 | public class ConcurrentHashMapV8<K, V>
893                      if (c != (pc = pk.getClass()) ||
894                          !(k instanceof Comparable) ||
895                          (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
896 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
897 <                        TreeNode r = null, s = null, pl, pr;
898 <                        if (dir >= 0) {
899 <                            if ((pl = p.left) != null && h <= pl.hash)
900 <                                s = pl;
896 >                        TreeNode<V> s = null, r = null, pr;
897 >                        if ((dir = (c == pc) ? 0 :
898 >                             c.getName().compareTo(pc.getName())) == 0) {
899 >                            if ((pr = p.right) != null && h >= pr.hash &&
900 >                                (r = getTreeNode(h, k, pr)) != null)
901 >                                return r;
902 >                            else // continue left
903 >                                dir = -1;
904                          }
905                          else if ((pr = p.right) != null && h >= pr.hash)
906                              s = pr;
# Line 810 | Line 913 | public class ConcurrentHashMapV8<K, V>
913                  pp = (dir > 0) ? p.right : p.left;
914              }
915  
916 <            TreeNode f = first;
917 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
916 >            TreeNode<V> f = first;
917 >            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
918              if (p == null)
919                  root = x;
920              else { // attach and rebalance; adapted from CLR
921 <                TreeNode xp, xpp;
921 >                TreeNode<V> xp, xpp;
922                  if (f != null)
923                      f.prev = x;
924                  if (dir <= 0)
# Line 825 | Line 928 | public class ConcurrentHashMapV8<K, V>
928                  x.red = true;
929                  while (x != null && (xp = x.parent) != null && xp.red &&
930                         (xpp = xp.parent) != null) {
931 <                    TreeNode xppl = xpp.left;
931 >                    TreeNode<V> xppl = xpp.left;
932                      if (xp == xppl) {
933 <                        TreeNode y = xpp.right;
933 >                        TreeNode<V> y = xpp.right;
934                          if (y != null && y.red) {
935                              y.red = false;
936                              xp.red = false;
# Line 849 | Line 952 | public class ConcurrentHashMapV8<K, V>
952                          }
953                      }
954                      else {
955 <                        TreeNode y = xppl;
955 >                        TreeNode<V> y = xppl;
956                          if (y != null && y.red) {
957                              y.red = false;
958                              xp.red = false;
# Line 871 | Line 974 | public class ConcurrentHashMapV8<K, V>
974                          }
975                      }
976                  }
977 <                TreeNode r = root;
977 >                TreeNode<V> r = root;
978                  if (r != null && r.red)
979                      r.red = false;
980              }
# Line 886 | Line 989 | public class ConcurrentHashMapV8<K, V>
989           * that are accessible independently of lock. So instead we
990           * swap the tree linkages.
991           */
992 <        final void deleteTreeNode(TreeNode p) {
993 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
994 <            TreeNode pred = p.prev;
992 >        final void deleteTreeNode(TreeNode<V> p) {
993 >            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
994 >            TreeNode<V> pred = p.prev;
995              if (pred == null)
996                  first = next;
997              else
998                  pred.next = next;
999              if (next != null)
1000                  next.prev = pred;
1001 <            TreeNode replacement;
1002 <            TreeNode pl = p.left;
1003 <            TreeNode pr = p.right;
1001 >            TreeNode<V> replacement;
1002 >            TreeNode<V> pl = p.left;
1003 >            TreeNode<V> pr = p.right;
1004              if (pl != null && pr != null) {
1005 <                TreeNode s = pr, sl;
1005 >                TreeNode<V> s = pr, sl;
1006                  while ((sl = s.left) != null) // find successor
1007                      s = sl;
1008                  boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1009 <                TreeNode sr = s.right;
1010 <                TreeNode pp = p.parent;
1009 >                TreeNode<V> sr = s.right;
1010 >                TreeNode<V> pp = p.parent;
1011                  if (s == pr) { // p was s's direct parent
1012                      p.parent = s;
1013                      s.right = p;
1014                  }
1015                  else {
1016 <                    TreeNode sp = s.parent;
1016 >                    TreeNode<V> sp = s.parent;
1017                      if ((p.parent = sp) != null) {
1018                          if (s == sp.left)
1019                              sp.left = p;
# Line 935 | Line 1038 | public class ConcurrentHashMapV8<K, V>
1038              }
1039              else
1040                  replacement = (pl != null) ? pl : pr;
1041 <            TreeNode pp = p.parent;
1041 >            TreeNode<V> pp = p.parent;
1042              if (replacement == null) {
1043                  if (pp == null) {
1044                      root = null;
# Line 954 | Line 1057 | public class ConcurrentHashMapV8<K, V>
1057                  p.left = p.right = p.parent = null;
1058              }
1059              if (!p.red) { // rebalance, from CLR
1060 <                TreeNode x = replacement;
1060 >                TreeNode<V> x = replacement;
1061                  while (x != null) {
1062 <                    TreeNode xp, xpl;
1062 >                    TreeNode<V> xp, xpl;
1063                      if (x.red || (xp = x.parent) == null) {
1064                          x.red = false;
1065                          break;
1066                      }
1067                      if (x == (xpl = xp.left)) {
1068 <                        TreeNode sib = xp.right;
1068 >                        TreeNode<V> sib = xp.right;
1069                          if (sib != null && sib.red) {
1070                              sib.red = false;
1071                              xp.red = true;
# Line 972 | Line 1075 | public class ConcurrentHashMapV8<K, V>
1075                          if (sib == null)
1076                              x = xp;
1077                          else {
1078 <                            TreeNode sl = sib.left, sr = sib.right;
1078 >                            TreeNode<V> sl = sib.left, sr = sib.right;
1079                              if ((sr == null || !sr.red) &&
1080                                  (sl == null || !sl.red)) {
1081                                  sib.red = true;
# Line 984 | Line 1087 | public class ConcurrentHashMapV8<K, V>
1087                                          sl.red = false;
1088                                      sib.red = true;
1089                                      rotateRight(sib);
1090 <                                    sib = (xp = x.parent) == null ? null : xp.right;
1090 >                                    sib = (xp = x.parent) == null ?
1091 >                                        null : xp.right;
1092                                  }
1093                                  if (sib != null) {
1094                                      sib.red = (xp == null) ? false : xp.red;
# Line 1000 | Line 1104 | public class ConcurrentHashMapV8<K, V>
1104                          }
1105                      }
1106                      else { // symmetric
1107 <                        TreeNode sib = xpl;
1107 >                        TreeNode<V> sib = xpl;
1108                          if (sib != null && sib.red) {
1109                              sib.red = false;
1110                              xp.red = true;
# Line 1010 | Line 1114 | public class ConcurrentHashMapV8<K, V>
1114                          if (sib == null)
1115                              x = xp;
1116                          else {
1117 <                            TreeNode sl = sib.left, sr = sib.right;
1117 >                            TreeNode<V> sl = sib.left, sr = sib.right;
1118                              if ((sl == null || !sl.red) &&
1119                                  (sr == null || !sr.red)) {
1120                                  sib.red = true;
# Line 1022 | Line 1126 | public class ConcurrentHashMapV8<K, V>
1126                                          sr.red = false;
1127                                      sib.red = true;
1128                                      rotateLeft(sib);
1129 <                                    sib = (xp = x.parent) == null ? null : xp.left;
1129 >                                    sib = (xp = x.parent) == null ?
1130 >                                        null : xp.left;
1131                                  }
1132                                  if (sib != null) {
1133                                      sib.red = (xp == null) ? false : xp.red;
# Line 1052 | Line 1157 | public class ConcurrentHashMapV8<K, V>
1157      /* ---------------- Collision reduction methods -------------- */
1158  
1159      /**
1160 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
1160 >     * Spreads higher bits to lower, and also forces top bit to 0.
1161       * Because the table uses power-of-two masking, sets of hashes
1162       * that vary only in bits above the current mask will always
1163       * collide. (Among known examples are sets of Float keys holding
# Line 1070 | Line 1175 | public class ConcurrentHashMapV8<K, V>
1175      }
1176  
1177      /**
1178 <     * Replaces a list bin with a tree bin. Call only when locked.
1179 <     * Fails to replace if the given key is non-comparable or table
1180 <     * is, or needs, resizing.
1181 <     */
1182 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1183 <        if ((key instanceof Comparable) &&
1184 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1185 <            TreeBin t = new TreeBin();
1186 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1082 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1083 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
1178 >     * Replaces a list bin with a tree bin if key is comparable.  Call
1179 >     * only when locked.
1180 >     */
1181 >    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1182 >        if (key instanceof Comparable) {
1183 >            TreeBin<V> t = new TreeBin<V>();
1184 >            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1185 >                t.putTreeNode(e.hash, e.key, e.val);
1186 >            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1187          }
1188      }
1189  
1190      /* ---------------- Internal access and update methods -------------- */
1191  
1192      /** Implementation for get and containsKey */
1193 <    private final Object internalGet(Object k) {
1193 >    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1194          int h = spread(k.hashCode());
1195 <        retry: for (Node[] tab = table; tab != null;) {
1196 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1195 >        retry: for (Node<V>[] tab = table; tab != null;) {
1196 >            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1197              for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1198 <                if ((eh = e.hash) == MOVED) {
1198 >                if ((eh = e.hash) < 0) {
1199                      if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1200 <                        return ((TreeBin)ek).getValue(h, k);
1201 <                    else {                        // restart with new table
1202 <                        tab = (Node[])ek;
1200 >                        return ((TreeBin<V>)ek).getValue(h, k);
1201 >                    else {                      // restart with new table
1202 >                        tab = (Node<V>[])ek;
1203                          continue retry;
1204                      }
1205                  }
1206 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1206 >                else if (eh == h && (ev = e.val) != null &&
1207                           ((ek = e.key) == k || k.equals(ek)))
1208                      return ev;
1209              }
# Line 1114 | Line 1217 | public class ConcurrentHashMapV8<K, V>
1217       * Replaces node value with v, conditional upon match of cv if
1218       * non-null.  If resulting value is null, delete.
1219       */
1220 <    private final Object internalReplace(Object k, Object v, Object cv) {
1220 >    @SuppressWarnings("unchecked") private final V internalReplace
1221 >        (Object k, V v, Object cv) {
1222          int h = spread(k.hashCode());
1223 <        Object oldVal = null;
1224 <        for (Node[] tab = table;;) {
1225 <            Node f; int i, fh; Object fk;
1223 >        V oldVal = null;
1224 >        for (Node<V>[] tab = table;;) {
1225 >            Node<V> f; int i, fh; Object fk;
1226              if (tab == null ||
1227                  (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1228                  break;
1229 <            else if ((fh = f.hash) == MOVED) {
1229 >            else if ((fh = f.hash) < 0) {
1230                  if ((fk = f.key) instanceof TreeBin) {
1231 <                    TreeBin t = (TreeBin)fk;
1231 >                    TreeBin<V> t = (TreeBin<V>)fk;
1232                      boolean validated = false;
1233                      boolean deleted = false;
1234                      t.acquire(0);
1235                      try {
1236                          if (tabAt(tab, i) == f) {
1237                              validated = true;
1238 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1238 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1239                              if (p != null) {
1240 <                                Object pv = p.val;
1240 >                                V pv = p.val;
1241                                  if (cv == null || cv == pv || cv.equals(pv)) {
1242                                      oldVal = pv;
1243                                      if ((p.val = v) == null) {
# Line 1148 | Line 1252 | public class ConcurrentHashMapV8<K, V>
1252                      }
1253                      if (validated) {
1254                          if (deleted)
1255 <                            counter.add(-1L);
1255 >                            addCount(-1L, -1);
1256                          break;
1257                      }
1258                  }
1259                  else
1260 <                    tab = (Node[])fk;
1260 >                    tab = (Node<V>[])fk;
1261              }
1262 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1262 >            else if (fh != h && f.next == null) // precheck
1263                  break;                          // rules out possible existence
1264 <            else if ((fh & LOCKED) != 0) {
1161 <                checkForResize();               // try resizing if can't get lock
1162 <                f.tryAwaitLock(tab, i);
1163 <            }
1164 <            else if (f.casHash(fh, fh | LOCKED)) {
1264 >            else {
1265                  boolean validated = false;
1266                  boolean deleted = false;
1267 <                try {
1267 >                synchronized (f) {
1268                      if (tabAt(tab, i) == f) {
1269                          validated = true;
1270 <                        for (Node e = f, pred = null;;) {
1271 <                            Object ek, ev;
1272 <                            if ((e.hash & HASH_BITS) == h &&
1270 >                        for (Node<V> e = f, pred = null;;) {
1271 >                            Object ek; V ev;
1272 >                            if (e.hash == h &&
1273                                  ((ev = e.val) != null) &&
1274                                  ((ek = e.key) == k || k.equals(ek))) {
1275                                  if (cv == null || cv == ev || cv.equals(ev)) {
1276                                      oldVal = ev;
1277                                      if ((e.val = v) == null) {
1278                                          deleted = true;
1279 <                                        Node en = e.next;
1279 >                                        Node<V> en = e.next;
1280                                          if (pred != null)
1281                                              pred.next = en;
1282                                          else
# Line 1190 | Line 1290 | public class ConcurrentHashMapV8<K, V>
1290                                  break;
1291                          }
1292                      }
1193                } finally {
1194                    if (!f.casHash(fh | LOCKED, fh)) {
1195                        f.hash = fh;
1196                        synchronized (f) { f.notifyAll(); };
1197                    }
1293                  }
1294                  if (validated) {
1295                      if (deleted)
1296 <                        counter.add(-1L);
1296 >                        addCount(-1L, -1);
1297                      break;
1298                  }
1299              }
# Line 1207 | Line 1302 | public class ConcurrentHashMapV8<K, V>
1302      }
1303  
1304      /*
1305 <     * Internal versions of the six insertion methods, each a
1306 <     * little more complicated than the last. All have
1212 <     * the same basic structure as the first (internalPut):
1305 >     * Internal versions of insertion methods
1306 >     * All have the same basic structure as the first (internalPut):
1307       *  1. If table uninitialized, create
1308       *  2. If bin empty, try to CAS new node
1309       *  3. If bin stale, use new table
1310       *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1311       *  5. Lock and validate; if valid, scan and add or update
1312       *
1313 <     * The others interweave other checks and/or alternative actions:
1314 <     *  * Plain put checks for and performs resize after insertion.
1315 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1316 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1317 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1318 <     *    mechanics to deal with, calls, potential exceptions and null
1319 <     *    returns from function call.
1226 <     *  * compute uses the same function-call mechanics, but without
1227 <     *    the prescans
1228 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1229 <     *    update function if present
1230 <     *  * putAll attempts to pre-allocate enough table space
1231 <     *    and more lazily performs count updates and checks.
1232 <     *
1233 <     * Someday when details settle down a bit more, it might be worth
1234 <     * some factoring to reduce sprawl.
1313 >     * The putAll method differs mainly in attempting to pre-allocate
1314 >     * enough table space, and also more lazily performs count updates
1315 >     * and checks.
1316 >     *
1317 >     * Most of the function-accepting methods can't be factored nicely
1318 >     * because they require different functional forms, so instead
1319 >     * sprawl out similar mechanics.
1320       */
1321  
1322 <    /** Implementation for put */
1323 <    private final Object internalPut(Object k, Object v) {
1322 >    /** Implementation for put and putIfAbsent */
1323 >    @SuppressWarnings("unchecked") private final V internalPut
1324 >        (K k, V v, boolean onlyIfAbsent) {
1325 >        if (k == null || v == null) throw new NullPointerException();
1326          int h = spread(k.hashCode());
1327 <        int count = 0;
1328 <        for (Node[] tab = table;;) {
1329 <            int i; Node f; int fh; Object fk;
1327 >        int len = 0;
1328 >        for (Node<V>[] tab = table;;) {
1329 >            int i, fh; Node<V> f; Object fk; V fv;
1330              if (tab == null)
1331                  tab = initTable();
1332              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1333 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1333 >                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1334                      break;                   // no lock when adding to empty bin
1335              }
1336 <            else if ((fh = f.hash) == MOVED) {
1336 >            else if ((fh = f.hash) < 0) {
1337                  if ((fk = f.key) instanceof TreeBin) {
1338 <                    TreeBin t = (TreeBin)fk;
1339 <                    Object oldVal = null;
1338 >                    TreeBin<V> t = (TreeBin<V>)fk;
1339 >                    V oldVal = null;
1340                      t.acquire(0);
1341                      try {
1342                          if (tabAt(tab, i) == f) {
1343 <                            count = 2;
1344 <                            TreeNode p = t.putTreeNode(h, k, v);
1343 >                            len = 2;
1344 >                            TreeNode<V> p = t.putTreeNode(h, k, v);
1345                              if (p != null) {
1346                                  oldVal = p.val;
1347 <                                p.val = v;
1347 >                                if (!onlyIfAbsent)
1348 >                                    p.val = v;
1349                              }
1350                          }
1351                      } finally {
1352                          t.release(0);
1353                      }
1354 <                    if (count != 0) {
1354 >                    if (len != 0) {
1355                          if (oldVal != null)
1356                              return oldVal;
1357                          break;
1358                      }
1359                  }
1360                  else
1361 <                    tab = (Node[])fk;
1361 >                    tab = (Node<V>[])fk;
1362              }
1363 <            else if ((fh & LOCKED) != 0) {
1364 <                checkForResize();
1365 <                f.tryAwaitLock(tab, i);
1366 <            }
1367 <            else if (f.casHash(fh, fh | LOCKED)) {
1368 <                Object oldVal = null;
1281 <                try {                        // needed in case equals() throws
1363 >            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1364 >                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1365 >                return fv;
1366 >            else {
1367 >                V oldVal = null;
1368 >                synchronized (f) {
1369                      if (tabAt(tab, i) == f) {
1370 <                        count = 1;
1371 <                        for (Node e = f;; ++count) {
1372 <                            Object ek, ev;
1373 <                            if ((e.hash & HASH_BITS) == h &&
1370 >                        len = 1;
1371 >                        for (Node<V> e = f;; ++len) {
1372 >                            Object ek; V ev;
1373 >                            if (e.hash == h &&
1374                                  (ev = e.val) != null &&
1375                                  ((ek = e.key) == k || k.equals(ek))) {
1376                                  oldVal = ev;
1377 <                                e.val = v;
1377 >                                if (!onlyIfAbsent)
1378 >                                    e.val = v;
1379                                  break;
1380                              }
1381 <                            Node last = e;
1381 >                            Node<V> last = e;
1382                              if ((e = e.next) == null) {
1383 <                                last.next = new Node(h, k, v, null);
1384 <                                if (count >= TREE_THRESHOLD)
1383 >                                last.next = new Node<V>(h, k, v, null);
1384 >                                if (len >= TREE_THRESHOLD)
1385                                      replaceWithTreeBin(tab, i, k);
1386                                  break;
1387                              }
1388                          }
1389                      }
1302                } finally {                  // unlock and signal if needed
1303                    if (!f.casHash(fh | LOCKED, fh)) {
1304                        f.hash = fh;
1305                        synchronized (f) { f.notifyAll(); };
1306                    }
1390                  }
1391 <                if (count != 0) {
1391 >                if (len != 0) {
1392                      if (oldVal != null)
1393                          return oldVal;
1311                    if (tab.length <= 64)
1312                        count = 2;
1313                    break;
1314                }
1315            }
1316        }
1317        counter.add(1L);
1318        if (count > 1)
1319            checkForResize();
1320        return null;
1321    }
1322
1323    /** Implementation for putIfAbsent */
1324    private final Object internalPutIfAbsent(Object k, Object v) {
1325        int h = spread(k.hashCode());
1326        int count = 0;
1327        for (Node[] tab = table;;) {
1328            int i; Node f; int fh; Object fk, fv;
1329            if (tab == null)
1330                tab = initTable();
1331            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1332                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1394                      break;
1334            }
1335            else if ((fh = f.hash) == MOVED) {
1336                if ((fk = f.key) instanceof TreeBin) {
1337                    TreeBin t = (TreeBin)fk;
1338                    Object oldVal = null;
1339                    t.acquire(0);
1340                    try {
1341                        if (tabAt(tab, i) == f) {
1342                            count = 2;
1343                            TreeNode p = t.putTreeNode(h, k, v);
1344                            if (p != null)
1345                                oldVal = p.val;
1346                        }
1347                    } finally {
1348                        t.release(0);
1349                    }
1350                    if (count != 0) {
1351                        if (oldVal != null)
1352                            return oldVal;
1353                        break;
1354                    }
1355                }
1356                else
1357                    tab = (Node[])fk;
1358            }
1359            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1360                     ((fk = f.key) == k || k.equals(fk)))
1361                return fv;
1362            else {
1363                Node g = f.next;
1364                if (g != null) { // at least 2 nodes -- search and maybe resize
1365                    for (Node e = g;;) {
1366                        Object ek, ev;
1367                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1368                            ((ek = e.key) == k || k.equals(ek)))
1369                            return ev;
1370                        if ((e = e.next) == null) {
1371                            checkForResize();
1372                            break;
1373                        }
1374                    }
1375                }
1376                if (((fh = f.hash) & LOCKED) != 0) {
1377                    checkForResize();
1378                    f.tryAwaitLock(tab, i);
1379                }
1380                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1381                    Object oldVal = null;
1382                    try {
1383                        if (tabAt(tab, i) == f) {
1384                            count = 1;
1385                            for (Node e = f;; ++count) {
1386                                Object ek, ev;
1387                                if ((e.hash & HASH_BITS) == h &&
1388                                    (ev = e.val) != null &&
1389                                    ((ek = e.key) == k || k.equals(ek))) {
1390                                    oldVal = ev;
1391                                    break;
1392                                }
1393                                Node last = e;
1394                                if ((e = e.next) == null) {
1395                                    last.next = new Node(h, k, v, null);
1396                                    if (count >= TREE_THRESHOLD)
1397                                        replaceWithTreeBin(tab, i, k);
1398                                    break;
1399                                }
1400                            }
1401                        }
1402                    } finally {
1403                        if (!f.casHash(fh | LOCKED, fh)) {
1404                            f.hash = fh;
1405                            synchronized (f) { f.notifyAll(); };
1406                        }
1407                    }
1408                    if (count != 0) {
1409                        if (oldVal != null)
1410                            return oldVal;
1411                        if (tab.length <= 64)
1412                            count = 2;
1413                        break;
1414                    }
1395                  }
1396              }
1397          }
1398 <        counter.add(1L);
1419 <        if (count > 1)
1420 <            checkForResize();
1398 >        addCount(1L, len);
1399          return null;
1400      }
1401  
1402      /** Implementation for computeIfAbsent */
1403 <    private final Object internalComputeIfAbsent(K k,
1404 <                                                 Fun<? super K, ?> mf) {
1403 >    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1404 >        (K k, Fun<? super K, ? extends V> mf) {
1405 >        if (k == null || mf == null)
1406 >            throw new NullPointerException();
1407          int h = spread(k.hashCode());
1408 <        Object val = null;
1409 <        int count = 0;
1410 <        for (Node[] tab = table;;) {
1411 <            Node f; int i, fh; Object fk, fv;
1408 >        V val = null;
1409 >        int len = 0;
1410 >        for (Node<V>[] tab = table;;) {
1411 >            Node<V> f; int i; Object fk;
1412              if (tab == null)
1413                  tab = initTable();
1414              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1415 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1416 <                if (casTabAt(tab, i, null, node)) {
1417 <                    count = 1;
1418 <                    try {
1419 <                        if ((val = mf.apply(k)) != null)
1420 <                            node.val = val;
1421 <                    } finally {
1422 <                        if (val == null)
1423 <                            setTabAt(tab, i, null);
1424 <                        if (!node.casHash(fh, h)) {
1445 <                            node.hash = h;
1446 <                            synchronized (node) { node.notifyAll(); };
1415 >                Node<V> node = new Node<V>(h, k, null, null);
1416 >                synchronized (node) {
1417 >                    if (casTabAt(tab, i, null, node)) {
1418 >                        len = 1;
1419 >                        try {
1420 >                            if ((val = mf.apply(k)) != null)
1421 >                                node.val = val;
1422 >                        } finally {
1423 >                            if (val == null)
1424 >                                setTabAt(tab, i, null);
1425                          }
1426                      }
1427                  }
1428 <                if (count != 0)
1428 >                if (len != 0)
1429                      break;
1430              }
1431 <            else if ((fh = f.hash) == MOVED) {
1431 >            else if (f.hash < 0) {
1432                  if ((fk = f.key) instanceof TreeBin) {
1433 <                    TreeBin t = (TreeBin)fk;
1433 >                    TreeBin<V> t = (TreeBin<V>)fk;
1434                      boolean added = false;
1435                      t.acquire(0);
1436                      try {
1437                          if (tabAt(tab, i) == f) {
1438 <                            count = 1;
1439 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1438 >                            len = 1;
1439 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1440                              if (p != null)
1441                                  val = p.val;
1442                              else if ((val = mf.apply(k)) != null) {
1443                                  added = true;
1444 <                                count = 2;
1444 >                                len = 2;
1445                                  t.putTreeNode(h, k, val);
1446                              }
1447                          }
1448                      } finally {
1449                          t.release(0);
1450                      }
1451 <                    if (count != 0) {
1451 >                    if (len != 0) {
1452                          if (!added)
1453                              return val;
1454                          break;
1455                      }
1456                  }
1457                  else
1458 <                    tab = (Node[])fk;
1458 >                    tab = (Node<V>[])fk;
1459              }
1482            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1483                     ((fk = f.key) == k || k.equals(fk)))
1484                return fv;
1460              else {
1461 <                Node g = f.next;
1462 <                if (g != null) {
1463 <                    for (Node e = g;;) {
1464 <                        Object ek, ev;
1465 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1491 <                            ((ek = e.key) == k || k.equals(ek)))
1492 <                            return ev;
1493 <                        if ((e = e.next) == null) {
1494 <                            checkForResize();
1495 <                            break;
1496 <                        }
1497 <                    }
1498 <                }
1499 <                if (((fh = f.hash) & LOCKED) != 0) {
1500 <                    checkForResize();
1501 <                    f.tryAwaitLock(tab, i);
1461 >                for (Node<V> e = f; e != null; e = e.next) { // prescan
1462 >                    Object ek; V ev;
1463 >                    if (e.hash == h && (ev = e.val) != null &&
1464 >                        ((ek = e.key) == k || k.equals(ek)))
1465 >                        return ev;
1466                  }
1467 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1468 <                    boolean added = false;
1469 <                    try {
1470 <                        if (tabAt(tab, i) == f) {
1471 <                            count = 1;
1472 <                            for (Node e = f;; ++count) {
1473 <                                Object ek, ev;
1474 <                                if ((e.hash & HASH_BITS) == h &&
1475 <                                    (ev = e.val) != null &&
1476 <                                    ((ek = e.key) == k || k.equals(ek))) {
1477 <                                    val = ev;
1478 <                                    break;
1479 <                                }
1480 <                                Node last = e;
1481 <                                if ((e = e.next) == null) {
1482 <                                    if ((val = mf.apply(k)) != null) {
1483 <                                        added = true;
1484 <                                        last.next = new Node(h, k, val, null);
1485 <                                        if (count >= TREE_THRESHOLD)
1522 <                                            replaceWithTreeBin(tab, i, k);
1523 <                                    }
1524 <                                    break;
1467 >                boolean added = false;
1468 >                synchronized (f) {
1469 >                    if (tabAt(tab, i) == f) {
1470 >                        len = 1;
1471 >                        for (Node<V> e = f;; ++len) {
1472 >                            Object ek; V ev;
1473 >                            if (e.hash == h &&
1474 >                                (ev = e.val) != null &&
1475 >                                ((ek = e.key) == k || k.equals(ek))) {
1476 >                                val = ev;
1477 >                                break;
1478 >                            }
1479 >                            Node<V> last = e;
1480 >                            if ((e = e.next) == null) {
1481 >                                if ((val = mf.apply(k)) != null) {
1482 >                                    added = true;
1483 >                                    last.next = new Node<V>(h, k, val, null);
1484 >                                    if (len >= TREE_THRESHOLD)
1485 >                                        replaceWithTreeBin(tab, i, k);
1486                                  }
1487 +                                break;
1488                              }
1489                          }
1528                    } finally {
1529                        if (!f.casHash(fh | LOCKED, fh)) {
1530                            f.hash = fh;
1531                            synchronized (f) { f.notifyAll(); };
1532                        }
1533                    }
1534                    if (count != 0) {
1535                        if (!added)
1536                            return val;
1537                        if (tab.length <= 64)
1538                            count = 2;
1539                        break;
1490                      }
1491                  }
1492 +                if (len != 0) {
1493 +                    if (!added)
1494 +                        return val;
1495 +                    break;
1496 +                }
1497              }
1498          }
1499 <        if (val != null) {
1500 <            counter.add(1L);
1546 <            if (count > 1)
1547 <                checkForResize();
1548 <        }
1499 >        if (val != null)
1500 >            addCount(1L, len);
1501          return val;
1502      }
1503  
1504      /** Implementation for compute */
1505 <    @SuppressWarnings("unchecked")
1506 <    private final Object internalCompute(K k, boolean onlyIfPresent,
1507 <                                             BiFun<? super K, ? super V, ? extends V> mf) {
1505 >    @SuppressWarnings("unchecked") private final V internalCompute
1506 >        (K k, boolean onlyIfPresent,
1507 >         BiFun<? super K, ? super V, ? extends V> mf) {
1508 >        if (k == null || mf == null)
1509 >            throw new NullPointerException();
1510          int h = spread(k.hashCode());
1511 <        Object val = null;
1511 >        V val = null;
1512          int delta = 0;
1513 <        int count = 0;
1514 <        for (Node[] tab = table;;) {
1515 <            Node f; int i, fh; Object fk;
1513 >        int len = 0;
1514 >        for (Node<V>[] tab = table;;) {
1515 >            Node<V> f; int i, fh; Object fk;
1516              if (tab == null)
1517                  tab = initTable();
1518              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1519                  if (onlyIfPresent)
1520                      break;
1521 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1522 <                if (casTabAt(tab, i, null, node)) {
1523 <                    try {
1524 <                        count = 1;
1525 <                        if ((val = mf.apply(k, null)) != null) {
1526 <                            node.val = val;
1527 <                            delta = 1;
1528 <                        }
1529 <                    } finally {
1530 <                        if (delta == 0)
1531 <                            setTabAt(tab, i, null);
1532 <                        if (!node.casHash(fh, h)) {
1579 <                            node.hash = h;
1580 <                            synchronized (node) { node.notifyAll(); };
1521 >                Node<V> node = new Node<V>(h, k, null, null);
1522 >                synchronized (node) {
1523 >                    if (casTabAt(tab, i, null, node)) {
1524 >                        try {
1525 >                            len = 1;
1526 >                            if ((val = mf.apply(k, null)) != null) {
1527 >                                node.val = val;
1528 >                                delta = 1;
1529 >                            }
1530 >                        } finally {
1531 >                            if (delta == 0)
1532 >                                setTabAt(tab, i, null);
1533                          }
1534                      }
1535                  }
1536 <                if (count != 0)
1536 >                if (len != 0)
1537                      break;
1538              }
1539 <            else if ((fh = f.hash) == MOVED) {
1539 >            else if ((fh = f.hash) < 0) {
1540                  if ((fk = f.key) instanceof TreeBin) {
1541 <                    TreeBin t = (TreeBin)fk;
1541 >                    TreeBin<V> t = (TreeBin<V>)fk;
1542                      t.acquire(0);
1543                      try {
1544                          if (tabAt(tab, i) == f) {
1545 <                            count = 1;
1546 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1547 <                            Object pv = (p == null) ? null : p.val;
1548 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1545 >                            len = 1;
1546 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1547 >                            if (p == null && onlyIfPresent)
1548 >                                break;
1549 >                            V pv = (p == null) ? null : p.val;
1550 >                            if ((val = mf.apply(k, pv)) != null) {
1551                                  if (p != null)
1552                                      p.val = val;
1553                                  else {
1554 <                                    count = 2;
1554 >                                    len = 2;
1555                                      delta = 1;
1556                                      t.putTreeNode(h, k, val);
1557                                  }
# Line 1610 | Line 1564 | public class ConcurrentHashMapV8<K, V>
1564                      } finally {
1565                          t.release(0);
1566                      }
1567 <                    if (count != 0)
1567 >                    if (len != 0)
1568                          break;
1569                  }
1570                  else
1571 <                    tab = (Node[])fk;
1571 >                    tab = (Node<V>[])fk;
1572              }
1573 <            else if ((fh & LOCKED) != 0) {
1574 <                checkForResize();
1621 <                f.tryAwaitLock(tab, i);
1622 <            }
1623 <            else if (f.casHash(fh, fh | LOCKED)) {
1624 <                try {
1573 >            else {
1574 >                synchronized (f) {
1575                      if (tabAt(tab, i) == f) {
1576 <                        count = 1;
1577 <                        for (Node e = f, pred = null;; ++count) {
1578 <                            Object ek, ev;
1579 <                            if ((e.hash & HASH_BITS) == h &&
1576 >                        len = 1;
1577 >                        for (Node<V> e = f, pred = null;; ++len) {
1578 >                            Object ek; V ev;
1579 >                            if (e.hash == h &&
1580                                  (ev = e.val) != null &&
1581                                  ((ek = e.key) == k || k.equals(ek))) {
1582 <                                val = mf.apply(k, (V)ev);
1582 >                                val = mf.apply(k, ev);
1583                                  if (val != null)
1584                                      e.val = val;
1585                                  else {
1586                                      delta = -1;
1587 <                                    Node en = e.next;
1587 >                                    Node<V> en = e.next;
1588                                      if (pred != null)
1589                                          pred.next = en;
1590                                      else
# Line 1644 | Line 1594 | public class ConcurrentHashMapV8<K, V>
1594                              }
1595                              pred = e;
1596                              if ((e = e.next) == null) {
1597 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1598 <                                    pred.next = new Node(h, k, val, null);
1597 >                                if (!onlyIfPresent &&
1598 >                                    (val = mf.apply(k, null)) != null) {
1599 >                                    pred.next = new Node<V>(h, k, val, null);
1600                                      delta = 1;
1601 <                                    if (count >= TREE_THRESHOLD)
1601 >                                    if (len >= TREE_THRESHOLD)
1602                                          replaceWithTreeBin(tab, i, k);
1603                                  }
1604                                  break;
1605                              }
1606                          }
1607                      }
1657                } finally {
1658                    if (!f.casHash(fh | LOCKED, fh)) {
1659                        f.hash = fh;
1660                        synchronized (f) { f.notifyAll(); };
1661                    }
1608                  }
1609 <                if (count != 0) {
1664 <                    if (tab.length <= 64)
1665 <                        count = 2;
1609 >                if (len != 0)
1610                      break;
1667                }
1611              }
1612          }
1613 <        if (delta != 0) {
1614 <            counter.add((long)delta);
1672 <            if (count > 1)
1673 <                checkForResize();
1674 <        }
1613 >        if (delta != 0)
1614 >            addCount((long)delta, len);
1615          return val;
1616      }
1617  
1618      /** Implementation for merge */
1619 <    @SuppressWarnings("unchecked")
1620 <    private final Object internalMerge(K k, V v,
1621 <                                       BiFun<? super V, ? super V, ? extends V> mf) {
1619 >    @SuppressWarnings("unchecked") private final V internalMerge
1620 >        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1621 >        if (k == null || v == null || mf == null)
1622 >            throw new NullPointerException();
1623          int h = spread(k.hashCode());
1624 <        Object val = null;
1624 >        V val = null;
1625          int delta = 0;
1626 <        int count = 0;
1627 <        for (Node[] tab = table;;) {
1628 <            int i; Node f; int fh; Object fk, fv;
1626 >        int len = 0;
1627 >        for (Node<V>[] tab = table;;) {
1628 >            int i; Node<V> f; Object fk; V fv;
1629              if (tab == null)
1630                  tab = initTable();
1631              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1632 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1632 >                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1633                      delta = 1;
1634                      val = v;
1635                      break;
1636                  }
1637              }
1638 <            else if ((fh = f.hash) == MOVED) {
1638 >            else if (f.hash < 0) {
1639                  if ((fk = f.key) instanceof TreeBin) {
1640 <                    TreeBin t = (TreeBin)fk;
1640 >                    TreeBin<V> t = (TreeBin<V>)fk;
1641                      t.acquire(0);
1642                      try {
1643                          if (tabAt(tab, i) == f) {
1644 <                            count = 1;
1645 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1646 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1644 >                            len = 1;
1645 >                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1646 >                            val = (p == null) ? v : mf.apply(p.val, v);
1647                              if (val != null) {
1648                                  if (p != null)
1649                                      p.val = val;
1650                                  else {
1651 <                                    count = 2;
1651 >                                    len = 2;
1652                                      delta = 1;
1653                                      t.putTreeNode(h, k, val);
1654                                  }
# Line 1720 | Line 1661 | public class ConcurrentHashMapV8<K, V>
1661                      } finally {
1662                          t.release(0);
1663                      }
1664 <                    if (count != 0)
1664 >                    if (len != 0)
1665                          break;
1666                  }
1667                  else
1668 <                    tab = (Node[])fk;
1728 <            }
1729 <            else if ((fh & LOCKED) != 0) {
1730 <                checkForResize();
1731 <                f.tryAwaitLock(tab, i);
1668 >                    tab = (Node<V>[])fk;
1669              }
1670 <            else if (f.casHash(fh, fh | LOCKED)) {
1671 <                try {
1670 >            else {
1671 >                synchronized (f) {
1672                      if (tabAt(tab, i) == f) {
1673 <                        count = 1;
1674 <                        for (Node e = f, pred = null;; ++count) {
1675 <                            Object ek, ev;
1676 <                            if ((e.hash & HASH_BITS) == h &&
1673 >                        len = 1;
1674 >                        for (Node<V> e = f, pred = null;; ++len) {
1675 >                            Object ek; V ev;
1676 >                            if (e.hash == h &&
1677                                  (ev = e.val) != null &&
1678                                  ((ek = e.key) == k || k.equals(ek))) {
1679 <                                val = mf.apply(v, (V)ev);
1679 >                                val = mf.apply(ev, v);
1680                                  if (val != null)
1681                                      e.val = val;
1682                                  else {
1683                                      delta = -1;
1684 <                                    Node en = e.next;
1684 >                                    Node<V> en = e.next;
1685                                      if (pred != null)
1686                                          pred.next = en;
1687                                      else
# Line 1755 | Line 1692 | public class ConcurrentHashMapV8<K, V>
1692                              pred = e;
1693                              if ((e = e.next) == null) {
1694                                  val = v;
1695 <                                pred.next = new Node(h, k, val, null);
1695 >                                pred.next = new Node<V>(h, k, val, null);
1696                                  delta = 1;
1697 <                                if (count >= TREE_THRESHOLD)
1697 >                                if (len >= TREE_THRESHOLD)
1698                                      replaceWithTreeBin(tab, i, k);
1699                                  break;
1700                              }
1701                          }
1702                      }
1766                } finally {
1767                    if (!f.casHash(fh | LOCKED, fh)) {
1768                        f.hash = fh;
1769                        synchronized (f) { f.notifyAll(); };
1770                    }
1703                  }
1704 <                if (count != 0) {
1773 <                    if (tab.length <= 64)
1774 <                        count = 2;
1704 >                if (len != 0)
1705                      break;
1776                }
1706              }
1707          }
1708 <        if (delta != 0) {
1709 <            counter.add((long)delta);
1781 <            if (count > 1)
1782 <                checkForResize();
1783 <        }
1708 >        if (delta != 0)
1709 >            addCount((long)delta, len);
1710          return val;
1711      }
1712  
1713      /** Implementation for putAll */
1714 <    private final void internalPutAll(Map<?, ?> m) {
1714 >    @SuppressWarnings("unchecked") private final void internalPutAll
1715 >        (Map<? extends K, ? extends V> m) {
1716          tryPresize(m.size());
1717          long delta = 0L;     // number of uncommitted additions
1718          boolean npe = false; // to throw exception on exit for nulls
1719          try {                // to clean up counts on other exceptions
1720 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1721 <                Object k, v;
1720 >            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
1721 >                Object k; V v;
1722                  if (entry == null || (k = entry.getKey()) == null ||
1723                      (v = entry.getValue()) == null) {
1724                      npe = true;
1725                      break;
1726                  }
1727                  int h = spread(k.hashCode());
1728 <                for (Node[] tab = table;;) {
1729 <                    int i; Node f; int fh; Object fk;
1728 >                for (Node<V>[] tab = table;;) {
1729 >                    int i; Node<V> f; int fh; Object fk;
1730                      if (tab == null)
1731                          tab = initTable();
1732                      else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1733 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1733 >                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1734                              ++delta;
1735                              break;
1736                          }
1737                      }
1738 <                    else if ((fh = f.hash) == MOVED) {
1738 >                    else if ((fh = f.hash) < 0) {
1739                          if ((fk = f.key) instanceof TreeBin) {
1740 <                            TreeBin t = (TreeBin)fk;
1740 >                            TreeBin<V> t = (TreeBin<V>)fk;
1741                              boolean validated = false;
1742                              t.acquire(0);
1743                              try {
1744                                  if (tabAt(tab, i) == f) {
1745                                      validated = true;
1746 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1746 >                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
1747                                      if (p != null)
1748                                          p.val = v;
1749                                      else {
# Line 1831 | Line 1758 | public class ConcurrentHashMapV8<K, V>
1758                                  break;
1759                          }
1760                          else
1761 <                            tab = (Node[])fk;
1761 >                            tab = (Node<V>[])fk;
1762                      }
1763 <                    else if ((fh & LOCKED) != 0) {
1764 <                        counter.add(delta);
1765 <                        delta = 0L;
1839 <                        checkForResize();
1840 <                        f.tryAwaitLock(tab, i);
1841 <                    }
1842 <                    else if (f.casHash(fh, fh | LOCKED)) {
1843 <                        int count = 0;
1844 <                        try {
1763 >                    else {
1764 >                        int len = 0;
1765 >                        synchronized (f) {
1766                              if (tabAt(tab, i) == f) {
1767 <                                count = 1;
1768 <                                for (Node e = f;; ++count) {
1769 <                                    Object ek, ev;
1770 <                                    if ((e.hash & HASH_BITS) == h &&
1767 >                                len = 1;
1768 >                                for (Node<V> e = f;; ++len) {
1769 >                                    Object ek; V ev;
1770 >                                    if (e.hash == h &&
1771                                          (ev = e.val) != null &&
1772                                          ((ek = e.key) == k || k.equals(ek))) {
1773                                          e.val = v;
1774                                          break;
1775                                      }
1776 <                                    Node last = e;
1776 >                                    Node<V> last = e;
1777                                      if ((e = e.next) == null) {
1778                                          ++delta;
1779 <                                        last.next = new Node(h, k, v, null);
1780 <                                        if (count >= TREE_THRESHOLD)
1779 >                                        last.next = new Node<V>(h, k, v, null);
1780 >                                        if (len >= TREE_THRESHOLD)
1781                                              replaceWithTreeBin(tab, i, k);
1782                                          break;
1783                                      }
1784                                  }
1785                              }
1865                        } finally {
1866                            if (!f.casHash(fh | LOCKED, fh)) {
1867                                f.hash = fh;
1868                                synchronized (f) { f.notifyAll(); };
1869                            }
1786                          }
1787 <                        if (count != 0) {
1788 <                            if (count > 1) {
1789 <                                counter.add(delta);
1787 >                        if (len != 0) {
1788 >                            if (len > 1) {
1789 >                                addCount(delta, len);
1790                                  delta = 0L;
1875                                checkForResize();
1791                              }
1792                              break;
1793                          }
# Line 1880 | Line 1795 | public class ConcurrentHashMapV8<K, V>
1795                  }
1796              }
1797          } finally {
1798 <            if (delta != 0)
1799 <                counter.add(delta);
1798 >            if (delta != 0L)
1799 >                addCount(delta, 2);
1800          }
1801          if (npe)
1802              throw new NullPointerException();
1803      }
1804  
1805 +    /**
1806 +     * Implementation for clear. Steps through each bin, removing all
1807 +     * nodes.
1808 +     */
1809 +    @SuppressWarnings("unchecked") private final void internalClear() {
1810 +        long delta = 0L; // negative number of deletions
1811 +        int i = 0;
1812 +        Node<V>[] tab = table;
1813 +        while (tab != null && i < tab.length) {
1814 +            Node<V> f = tabAt(tab, i);
1815 +            if (f == null)
1816 +                ++i;
1817 +            else if (f.hash < 0) {
1818 +                Object fk;
1819 +                if ((fk = f.key) instanceof TreeBin) {
1820 +                    TreeBin<V> t = (TreeBin<V>)fk;
1821 +                    t.acquire(0);
1822 +                    try {
1823 +                        if (tabAt(tab, i) == f) {
1824 +                            for (Node<V> p = t.first; p != null; p = p.next) {
1825 +                                if (p.val != null) { // (currently always true)
1826 +                                    p.val = null;
1827 +                                    --delta;
1828 +                                }
1829 +                            }
1830 +                            t.first = null;
1831 +                            t.root = null;
1832 +                            ++i;
1833 +                        }
1834 +                    } finally {
1835 +                        t.release(0);
1836 +                    }
1837 +                }
1838 +                else
1839 +                    tab = (Node<V>[])fk;
1840 +            }
1841 +            else {
1842 +                synchronized (f) {
1843 +                    if (tabAt(tab, i) == f) {
1844 +                        for (Node<V> e = f; e != null; e = e.next) {
1845 +                            if (e.val != null) {  // (currently always true)
1846 +                                e.val = null;
1847 +                                --delta;
1848 +                            }
1849 +                        }
1850 +                        setTabAt(tab, i, null);
1851 +                        ++i;
1852 +                    }
1853 +                }
1854 +            }
1855 +        }
1856 +        if (delta != 0L)
1857 +            addCount(delta, -1);
1858 +    }
1859 +
1860      /* ---------------- Table Initialization and Resizing -------------- */
1861  
1862      /**
# Line 1906 | Line 1876 | public class ConcurrentHashMapV8<K, V>
1876      /**
1877       * Initializes table, using the size recorded in sizeCtl.
1878       */
1879 <    private final Node[] initTable() {
1880 <        Node[] tab; int sc;
1879 >    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
1880 >        Node<V>[] tab; int sc;
1881          while ((tab = table) == null) {
1882              if ((sc = sizeCtl) < 0)
1883                  Thread.yield(); // lost initialization race; just spin
1884 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1884 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1885                  try {
1886                      if ((tab = table) == null) {
1887                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1888 <                        tab = table = new Node[n];
1888 >                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1889 >                        table = tab = (Node<V>[])tb;
1890                          sc = n - (n >>> 2);
1891                      }
1892                  } finally {
# Line 1928 | Line 1899 | public class ConcurrentHashMapV8<K, V>
1899      }
1900  
1901      /**
1902 <     * If table is too small and not already resizing, creates next
1903 <     * table and transfers bins.  Rechecks occupancy after a transfer
1904 <     * to see if another resize is already needed because resizings
1905 <     * are lagging additions.
1906 <     */
1907 <    private final void checkForResize() {
1908 <        Node[] tab; int n, sc;
1909 <        while ((tab = table) != null &&
1910 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1911 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1912 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1913 <            try {
1914 <                if (tab == table) {
1915 <                    table = rebuild(tab);
1916 <                    sc = (n << 1) - (n >>> 1);
1902 >     * Adds to count, and if table is too small and not already
1903 >     * resizing, initiates transfer. If already resizing, helps
1904 >     * perform transfer if work is available.  Rechecks occupancy
1905 >     * after a transfer to see if another resize is already needed
1906 >     * because resizings are lagging additions.
1907 >     *
1908 >     * @param x the count to add
1909 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1910 >     */
1911 >    private final void addCount(long x, int check) {
1912 >        CounterCell[] as; long b, s;
1913 >        if ((as = counterCells) != null ||
1914 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1915 >            CounterHashCode hc; CounterCell a; long v; int m;
1916 >            boolean uncontended = true;
1917 >            if ((hc = threadCounterHashCode.get()) == null ||
1918 >                as == null || (m = as.length - 1) < 0 ||
1919 >                (a = as[m & hc.code]) == null ||
1920 >                !(uncontended =
1921 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1922 >                fullAddCount(x, hc, uncontended);
1923 >                return;
1924 >            }
1925 >            if (check <= 1)
1926 >                return;
1927 >            s = sumCount();
1928 >        }
1929 >        if (check >= 0) {
1930 >            Node<V>[] tab, nt; int sc;
1931 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1932 >                   tab.length < MAXIMUM_CAPACITY) {
1933 >                if (sc < 0) {
1934 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1935 >                        (nt = nextTable) == null)
1936 >                        break;
1937 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1938 >                        transfer(tab, nt);
1939                  }
1940 <            } finally {
1941 <                sizeCtl = sc;
1940 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1941 >                    transfer(tab, null);
1942 >                s = sumCount();
1943              }
1944          }
1945      }
# Line 1955 | Line 1949 | public class ConcurrentHashMapV8<K, V>
1949       *
1950       * @param size number of elements (doesn't need to be perfectly accurate)
1951       */
1952 <    private final void tryPresize(int size) {
1952 >    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
1953          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1954              tableSizeFor(size + (size >>> 1) + 1);
1955          int sc;
1956          while ((sc = sizeCtl) >= 0) {
1957 <            Node[] tab = table; int n;
1957 >            Node<V>[] tab = table; int n;
1958              if (tab == null || (n = tab.length) == 0) {
1959                  n = (sc > c) ? sc : c;
1960 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1960 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1961                      try {
1962                          if (table == tab) {
1963 <                            table = new Node[n];
1963 >                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1964 >                            table = (Node<V>[])tb;
1965                              sc = n - (n >>> 2);
1966                          }
1967                      } finally {
# Line 1976 | Line 1971 | public class ConcurrentHashMapV8<K, V>
1971              }
1972              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1973                  break;
1974 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1975 <                try {
1976 <                    if (table == tab) {
1982 <                        table = rebuild(tab);
1983 <                        sc = (n << 1) - (n >>> 1);
1984 <                    }
1985 <                } finally {
1986 <                    sizeCtl = sc;
1987 <                }
1988 <            }
1974 >            else if (tab == table &&
1975 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1976 >                transfer(tab, null);
1977          }
1978      }
1979  
1980 <    /*
1980 >    /**
1981       * Moves and/or copies the nodes in each bin to new table. See
1982       * above for explanation.
1995     *
1996     * @return the new table
1983       */
1984 <    private static final Node[] rebuild(Node[] tab) {
1985 <        int n = tab.length;
1986 <        Node[] nextTab = new Node[n << 1];
1987 <        Node fwd = new Node(MOVED, nextTab, null, null);
1988 <        int[] buffer = null;       // holds bins to revisit; null until needed
1989 <        Node rev = null;           // reverse forwarder; null until needed
1990 <        int nbuffered = 0;         // the number of bins in buffer list
1991 <        int bufferIndex = 0;       // buffer index of current buffered bin
1992 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1993 <
1994 <        for (int i = bin;;) {      // start upwards sweep
1995 <            int fh; Node f;
1996 <            if ((f = tabAt(tab, i)) == null) {
1997 <                if (bin >= 0) {    // no lock needed (or available)
1998 <                    if (!casTabAt(tab, i, f, fwd))
1999 <                        continue;
2000 <                }
2001 <                else {             // transiently use a locked forwarding node
2002 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2003 <                    if (!casTabAt(tab, i, f, g))
2004 <                        continue;
1984 >    @SuppressWarnings("unchecked") private final void transfer
1985 >        (Node<V>[] tab, Node<V>[] nextTab) {
1986 >        int n = tab.length, stride;
1987 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1988 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1989 >        if (nextTab == null) {            // initiating
1990 >            try {
1991 >                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
1992 >                nextTab = (Node<V>[])tb;
1993 >            } catch (Throwable ex) {      // try to cope with OOME
1994 >                sizeCtl = Integer.MAX_VALUE;
1995 >                return;
1996 >            }
1997 >            nextTable = nextTab;
1998 >            transferOrigin = n;
1999 >            transferIndex = n;
2000 >            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2001 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2002 >                int nextk = (k > stride) ? k - stride : 0;
2003 >                for (int m = nextk; m < k; ++m)
2004 >                    nextTab[m] = rev;
2005 >                for (int m = n + nextk; m < n + k; ++m)
2006 >                    nextTab[m] = rev;
2007 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2008 >            }
2009 >        }
2010 >        int nextn = nextTab.length;
2011 >        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2012 >        boolean advance = true;
2013 >        for (int i = 0, bound = 0;;) {
2014 >            int nextIndex, nextBound; Node<V> f; Object fk;
2015 >            while (advance) {
2016 >                if (--i >= bound)
2017 >                    advance = false;
2018 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2019 >                    i = -1;
2020 >                    advance = false;
2021 >                }
2022 >                else if (U.compareAndSwapInt
2023 >                         (this, TRANSFERINDEX, nextIndex,
2024 >                          nextBound = (nextIndex > stride ?
2025 >                                       nextIndex - stride : 0))) {
2026 >                    bound = nextBound;
2027 >                    i = nextIndex - 1;
2028 >                    advance = false;
2029 >                }
2030 >            }
2031 >            if (i < 0 || i >= n || i + n >= nextn) {
2032 >                for (int sc;;) {
2033 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2034 >                        if (sc == -1) {
2035 >                            nextTable = null;
2036 >                            table = nextTab;
2037 >                            sizeCtl = (n << 1) - (n >>> 1);
2038 >                        }
2039 >                        return;
2040 >                    }
2041 >                }
2042 >            }
2043 >            else if ((f = tabAt(tab, i)) == null) {
2044 >                if (casTabAt(tab, i, null, fwd)) {
2045                      setTabAt(nextTab, i, null);
2046                      setTabAt(nextTab, i + n, null);
2047 <                    setTabAt(tab, i, fwd);
2022 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2023 <                        g.hash = MOVED;
2024 <                        synchronized (g) { g.notifyAll(); }
2025 <                    }
2047 >                    advance = true;
2048                  }
2049              }
2050 <            else if ((fh = f.hash) == MOVED) {
2051 <                Object fk = f.key;
2052 <                if (fk instanceof TreeBin) {
2053 <                    TreeBin t = (TreeBin)fk;
2054 <                    boolean validated = false;
2055 <                    t.acquire(0);
2056 <                    try {
2057 <                        if (tabAt(tab, i) == f) {
2058 <                            validated = true;
2059 <                            splitTreeBin(nextTab, i, t);
2060 <                            setTabAt(tab, i, fwd);
2050 >            else if (f.hash >= 0) {
2051 >                synchronized (f) {
2052 >                    if (tabAt(tab, i) == f) {
2053 >                        int runBit = f.hash & n;
2054 >                        Node<V> lastRun = f, lo = null, hi = null;
2055 >                        for (Node<V> p = f.next; p != null; p = p.next) {
2056 >                            int b = p.hash & n;
2057 >                            if (b != runBit) {
2058 >                                runBit = b;
2059 >                                lastRun = p;
2060 >                            }
2061                          }
2062 <                    } finally {
2063 <                        t.release(0);
2062 >                        if (runBit == 0)
2063 >                            lo = lastRun;
2064 >                        else
2065 >                            hi = lastRun;
2066 >                        for (Node<V> p = f; p != lastRun; p = p.next) {
2067 >                            int ph = p.hash;
2068 >                            Object pk = p.key; V pv = p.val;
2069 >                            if ((ph & n) == 0)
2070 >                                lo = new Node<V>(ph, pk, pv, lo);
2071 >                            else
2072 >                                hi = new Node<V>(ph, pk, pv, hi);
2073 >                        }
2074 >                        setTabAt(nextTab, i, lo);
2075 >                        setTabAt(nextTab, i + n, hi);
2076 >                        setTabAt(tab, i, fwd);
2077 >                        advance = true;
2078                      }
2043                    if (!validated)
2044                        continue;
2079                  }
2080              }
2081 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2082 <                boolean validated = false;
2083 <                try {              // split to lo and hi lists; copying as needed
2081 >            else if ((fk = f.key) instanceof TreeBin) {
2082 >                TreeBin<V> t = (TreeBin<V>)fk;
2083 >                t.acquire(0);
2084 >                try {
2085                      if (tabAt(tab, i) == f) {
2086 <                        validated = true;
2087 <                        splitBin(nextTab, i, f);
2086 >                        TreeBin<V> lt = new TreeBin<V>();
2087 >                        TreeBin<V> ht = new TreeBin<V>();
2088 >                        int lc = 0, hc = 0;
2089 >                        for (Node<V> e = t.first; e != null; e = e.next) {
2090 >                            int h = e.hash;
2091 >                            Object k = e.key; V v = e.val;
2092 >                            if ((h & n) == 0) {
2093 >                                ++lc;
2094 >                                lt.putTreeNode(h, k, v);
2095 >                            }
2096 >                            else {
2097 >                                ++hc;
2098 >                                ht.putTreeNode(h, k, v);
2099 >                            }
2100 >                        }
2101 >                        Node<V> ln, hn; // throw away trees if too small
2102 >                        if (lc < TREE_THRESHOLD) {
2103 >                            ln = null;
2104 >                            for (Node<V> p = lt.first; p != null; p = p.next)
2105 >                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2106 >                        }
2107 >                        else
2108 >                            ln = new Node<V>(MOVED, lt, null, null);
2109 >                        setTabAt(nextTab, i, ln);
2110 >                        if (hc < TREE_THRESHOLD) {
2111 >                            hn = null;
2112 >                            for (Node<V> p = ht.first; p != null; p = p.next)
2113 >                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2114 >                        }
2115 >                        else
2116 >                            hn = new Node<V>(MOVED, ht, null, null);
2117 >                        setTabAt(nextTab, i + n, hn);
2118                          setTabAt(tab, i, fwd);
2119 +                        advance = true;
2120                      }
2121                  } finally {
2122 <                    if (!f.casHash(fh | LOCKED, fh)) {
2057 <                        f.hash = fh;
2058 <                        synchronized (f) { f.notifyAll(); };
2059 <                    }
2122 >                    t.release(0);
2123                  }
2061                if (!validated)
2062                    continue;
2063            }
2064            else {
2065                if (buffer == null) // initialize buffer for revisits
2066                    buffer = new int[TRANSFER_BUFFER_SIZE];
2067                if (bin < 0 && bufferIndex > 0) {
2068                    int j = buffer[--bufferIndex];
2069                    buffer[bufferIndex] = i;
2070                    i = j;         // swap with another bin
2071                    continue;
2072                }
2073                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2074                    f.tryAwaitLock(tab, i);
2075                    continue;      // no other options -- block
2076                }
2077                if (rev == null)   // initialize reverse-forwarder
2078                    rev = new Node(MOVED, tab, null, null);
2079                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2080                    continue;      // recheck before adding to list
2081                buffer[nbuffered++] = i;
2082                setTabAt(nextTab, i, rev);     // install place-holders
2083                setTabAt(nextTab, i + n, rev);
2084            }
2085
2086            if (bin > 0)
2087                i = --bin;
2088            else if (buffer != null && nbuffered > 0) {
2089                bin = -1;
2090                i = buffer[bufferIndex = --nbuffered];
2124              }
2125              else
2126 <                return nextTab;
2126 >                advance = true; // already processed
2127          }
2128      }
2129  
2130 <    /**
2131 <     * Splits a normal bin with list headed by e into lo and hi parts;
2132 <     * installs in given table.
2133 <     */
2134 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2135 <        int bit = nextTab.length >>> 1; // bit to split on
2136 <        int runBit = e.hash & bit;
2137 <        Node lastRun = e, lo = null, hi = null;
2138 <        for (Node p = e.next; p != null; p = p.next) {
2106 <            int b = p.hash & bit;
2107 <            if (b != runBit) {
2108 <                runBit = b;
2109 <                lastRun = p;
2130 >    /* ---------------- Counter support -------------- */
2131 >
2132 >    final long sumCount() {
2133 >        CounterCell[] as = counterCells; CounterCell a;
2134 >        long sum = baseCount;
2135 >        if (as != null) {
2136 >            for (int i = 0; i < as.length; ++i) {
2137 >                if ((a = as[i]) != null)
2138 >                    sum += a.value;
2139              }
2140          }
2141 <        if (runBit == 0)
2113 <            lo = lastRun;
2114 <        else
2115 <            hi = lastRun;
2116 <        for (Node p = e; p != lastRun; p = p.next) {
2117 <            int ph = p.hash & HASH_BITS;
2118 <            Object pk = p.key, pv = p.val;
2119 <            if ((ph & bit) == 0)
2120 <                lo = new Node(ph, pk, pv, lo);
2121 <            else
2122 <                hi = new Node(ph, pk, pv, hi);
2123 <        }
2124 <        setTabAt(nextTab, i, lo);
2125 <        setTabAt(nextTab, i + bit, hi);
2141 >        return sum;
2142      }
2143  
2144 <    /**
2145 <     * Splits a tree bin into lo and hi parts; installs in given table.
2146 <     */
2147 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2148 <        int bit = nextTab.length >>> 1;
2149 <        TreeBin lt = new TreeBin();
2150 <        TreeBin ht = new TreeBin();
2151 <        int lc = 0, hc = 0;
2152 <        for (Node e = t.first; e != null; e = e.next) {
2137 <            int h = e.hash & HASH_BITS;
2138 <            Object k = e.key, v = e.val;
2139 <            if ((h & bit) == 0) {
2140 <                ++lc;
2141 <                lt.putTreeNode(h, k, v);
2142 <            }
2143 <            else {
2144 <                ++hc;
2145 <                ht.putTreeNode(h, k, v);
2146 <            }
2147 <        }
2148 <        Node ln, hn; // throw away trees if too small
2149 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2150 <            ln = null;
2151 <            for (Node p = lt.first; p != null; p = p.next)
2152 <                ln = new Node(p.hash, p.key, p.val, ln);
2153 <        }
2154 <        else
2155 <            ln = new Node(MOVED, lt, null, null);
2156 <        setTabAt(nextTab, i, ln);
2157 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2158 <            hn = null;
2159 <            for (Node p = ht.first; p != null; p = p.next)
2160 <                hn = new Node(p.hash, p.key, p.val, hn);
2144 >    // See LongAdder version for explanation
2145 >    private final void fullAddCount(long x, CounterHashCode hc,
2146 >                                    boolean wasUncontended) {
2147 >        int h;
2148 >        if (hc == null) {
2149 >            hc = new CounterHashCode();
2150 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2151 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2152 >            threadCounterHashCode.set(hc);
2153          }
2154          else
2155 <            hn = new Node(MOVED, ht, null, null);
2156 <        setTabAt(nextTab, i + bit, hn);
2157 <    }
2158 <
2159 <    /**
2160 <     * Implementation for clear. Steps through each bin, removing all
2161 <     * nodes.
2162 <     */
2163 <    private final void internalClear() {
2164 <        long delta = 0L; // negative number of deletions
2165 <        int i = 0;
2166 <        Node[] tab = table;
2167 <        while (tab != null && i < tab.length) {
2168 <            int fh; Object fk;
2169 <            Node f = tabAt(tab, i);
2170 <            if (f == null)
2171 <                ++i;
2172 <            else if ((fh = f.hash) == MOVED) {
2173 <                if ((fk = f.key) instanceof TreeBin) {
2174 <                    TreeBin t = (TreeBin)fk;
2175 <                    t.acquire(0);
2184 <                    try {
2185 <                        if (tabAt(tab, i) == f) {
2186 <                            for (Node p = t.first; p != null; p = p.next) {
2187 <                                p.val = null;
2188 <                                --delta;
2155 >            h = hc.code;
2156 >        boolean collide = false;                // True if last slot nonempty
2157 >        for (;;) {
2158 >            CounterCell[] as; CounterCell a; int n; long v;
2159 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2160 >                if ((a = as[(n - 1) & h]) == null) {
2161 >                    if (counterBusy == 0) {            // Try to attach new Cell
2162 >                        CounterCell r = new CounterCell(x); // Optimistic create
2163 >                        if (counterBusy == 0 &&
2164 >                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2165 >                            boolean created = false;
2166 >                            try {               // Recheck under lock
2167 >                                CounterCell[] rs; int m, j;
2168 >                                if ((rs = counterCells) != null &&
2169 >                                    (m = rs.length) > 0 &&
2170 >                                    rs[j = (m - 1) & h] == null) {
2171 >                                    rs[j] = r;
2172 >                                    created = true;
2173 >                                }
2174 >                            } finally {
2175 >                                counterBusy = 0;
2176                              }
2177 <                            t.first = null;
2178 <                            t.root = null;
2179 <                            ++i;
2177 >                            if (created)
2178 >                                break;
2179 >                            continue;           // Slot is now non-empty
2180                          }
2194                    } finally {
2195                        t.release(0);
2181                      }
2182 +                    collide = false;
2183                  }
2184 <                else
2185 <                    tab = (Node[])fk;
2186 <            }
2187 <            else if ((fh & LOCKED) != 0) {
2188 <                counter.add(delta); // opportunistically update count
2189 <                delta = 0L;
2190 <                f.tryAwaitLock(tab, i);
2191 <            }
2192 <            else if (f.casHash(fh, fh | LOCKED)) {
2193 <                try {
2194 <                    if (tabAt(tab, i) == f) {
2195 <                        for (Node e = f; e != null; e = e.next) {
2196 <                            e.val = null;
2197 <                            --delta;
2184 >                else if (!wasUncontended)       // CAS already known to fail
2185 >                    wasUncontended = true;      // Continue after rehash
2186 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2187 >                    break;
2188 >                else if (counterCells != as || n >= NCPU)
2189 >                    collide = false;            // At max size or stale
2190 >                else if (!collide)
2191 >                    collide = true;
2192 >                else if (counterBusy == 0 &&
2193 >                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2194 >                    try {
2195 >                        if (counterCells == as) {// Expand table unless stale
2196 >                            CounterCell[] rs = new CounterCell[n << 1];
2197 >                            for (int i = 0; i < n; ++i)
2198 >                                rs[i] = as[i];
2199 >                            counterCells = rs;
2200                          }
2201 <                        setTabAt(tab, i, null);
2202 <                        ++i;
2201 >                    } finally {
2202 >                        counterBusy = 0;
2203                      }
2204 <                } finally {
2205 <                    if (!f.casHash(fh | LOCKED, fh)) {
2206 <                        f.hash = fh;
2207 <                        synchronized (f) { f.notifyAll(); };
2204 >                    collide = false;
2205 >                    continue;                   // Retry with expanded table
2206 >                }
2207 >                h ^= h << 13;                   // Rehash
2208 >                h ^= h >>> 17;
2209 >                h ^= h << 5;
2210 >            }
2211 >            else if (counterBusy == 0 && counterCells == as &&
2212 >                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2213 >                boolean init = false;
2214 >                try {                           // Initialize table
2215 >                    if (counterCells == as) {
2216 >                        CounterCell[] rs = new CounterCell[2];
2217 >                        rs[h & 1] = new CounterCell(x);
2218 >                        counterCells = rs;
2219 >                        init = true;
2220                      }
2221 +                } finally {
2222 +                    counterBusy = 0;
2223                  }
2224 +                if (init)
2225 +                    break;
2226              }
2227 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2228 +                break;                          // Fall back on using base
2229          }
2230 <        if (delta != 0)
2225 <            counter.add(delta);
2230 >        hc.code = h;                            // Record index for next time
2231      }
2232  
2233      /* ----------------Table Traversal -------------- */
# Line 2237 | Line 2242 | public class ConcurrentHashMapV8<K, V>
2242       * change (including to null, indicating deletion), field nextVal
2243       * might not be accurate at point of use, but still maintains the
2244       * weak consistency property of holding a value that was once
2245 <     * valid.
2245 >     * valid. To support iterator.remove, the nextKey field is not
2246 >     * updated (nulled out) when the iterator cannot advance.
2247       *
2248       * Internal traversals directly access these fields, as in:
2249       * {@code while (it.advance() != null) { process(it.nextKey); }}
# Line 2264 | Line 2270 | public class ConcurrentHashMapV8<K, V>
2270       * across threads, iteration terminates if a bounds checks fails
2271       * for a table read.
2272       *
2273 <     * This class extends ForkJoinTask to streamline parallel
2274 <     * iteration in bulk operations (see BulkTask). This adds only an
2275 <     * int of space overhead, which is close enough to negligible in
2276 <     * cases where it is not needed to not worry about it.  Because
2277 <     * ForkJoinTask is Serializable, but iterators need not be, we
2278 <     * need to add warning suppressions.
2273 >     * This class extends CountedCompleter to streamline parallel
2274 >     * iteration in bulk operations. This adds only a few fields of
2275 >     * space overhead, which is small enough in cases where it is not
2276 >     * needed to not worry about it.  Because CountedCompleter is
2277 >     * Serializable, but iterators need not be, we need to add warning
2278 >     * suppressions.
2279       */
2280 <    @SuppressWarnings("serial")
2281 <    static class Traverser<K,V,R> extends ForkJoinTask<R> {
2280 >    @SuppressWarnings("serial") static class Traverser<K,V,R>
2281 >        extends CountedCompleter<R> {
2282          final ConcurrentHashMapV8<K, V> map;
2283 <        Node next;           // the next entry to use
2278 <        Node last;           // the last entry used
2283 >        Node<V> next;        // the next entry to use
2284          Object nextKey;      // cached key field of next
2285 <        Object nextVal;      // cached val field of next
2286 <        Node[] tab;          // current table; updated if resized
2285 >        V nextVal;           // cached val field of next
2286 >        Node<V>[] tab;       // current table; updated if resized
2287          int index;           // index of bin to use next
2288          int baseIndex;       // current index of initial table
2289          int baseLimit;       // index bound for initial table
2290 <        final int baseSize;  // initial table size
2290 >        int baseSize;        // initial table size
2291 >        int batch;           // split control
2292  
2293          /** Creates iterator for all entries in the table. */
2294          Traverser(ConcurrentHashMapV8<K, V> map) {
2295 <            this.tab = (this.map = map).table;
2290 <            baseLimit = baseSize = (tab == null) ? 0 : tab.length;
2295 >            this.map = map;
2296          }
2297  
2298 <        /** Creates iterator for split() methods */
2299 <        Traverser(Traverser<K,V,?> it, boolean split) {
2300 <            this.map = it.map;
2301 <            this.tab = it.tab;
2302 <            this.baseSize = it.baseSize;
2303 <            int lo = it.baseIndex;
2304 <            int hi = this.baseLimit = it.baseLimit;
2305 <            int i;
2306 <            if (split) // adjust parent
2307 <                i = it.baseLimit = (lo + hi + 1) >>> 1;
2308 <            else       // clone parent
2309 <                i = lo;
2310 <            this.index = this.baseIndex = i;
2298 >        /** Creates iterator for split() methods and task constructors */
2299 >        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2300 >            super(it);
2301 >            this.batch = batch;
2302 >            if ((this.map = map) != null && it != null) { // split parent
2303 >                Node<V>[] t;
2304 >                if ((t = it.tab) == null &&
2305 >                    (t = it.tab = map.table) != null)
2306 >                    it.baseLimit = it.baseSize = t.length;
2307 >                this.tab = t;
2308 >                this.baseSize = it.baseSize;
2309 >                int hi = this.baseLimit = it.baseLimit;
2310 >                it.baseLimit = this.index = this.baseIndex =
2311 >                    (hi + it.baseIndex + 1) >>> 1;
2312 >            }
2313          }
2314  
2315          /**
2316           * Advances next; returns nextVal or null if terminated.
2317           * See above for explanation.
2318           */
2319 <        final Object advance() {
2320 <            Node e = last = next;
2321 <            Object ev = null;
2319 >        @SuppressWarnings("unchecked") final V advance() {
2320 >            Node<V> e = next;
2321 >            V ev = null;
2322              outer: do {
2323                  if (e != null)                  // advance past used/skipped node
2324                      e = e.next;
2325                  while (e == null) {             // get to next non-null bin
2326 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2327 <                    if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
2328 <                        (t = tab) == null || i >= (n = t.length))
2326 >                    ConcurrentHashMapV8<K, V> m;
2327 >                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2328 >                    if ((t = tab) != null)
2329 >                        n = t.length;
2330 >                    else if ((m = map) != null && (t = tab = m.table) != null)
2331 >                        n = baseLimit = baseSize = t.length;
2332 >                    else
2333 >                        break outer;
2334 >                    if ((b = baseIndex) >= baseLimit ||
2335 >                        (i = index) < 0 || i >= n)
2336                          break outer;
2337 <                    else if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2337 >                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2338                          if ((ek = e.key) instanceof TreeBin)
2339 <                            e = ((TreeBin)ek).first;
2339 >                            e = ((TreeBin<V>)ek).first;
2340                          else {
2341 <                            tab = (Node[])ek;
2341 >                            tab = (Node<V>[])ek;
2342                              continue;           // restarts due to null val
2343                          }
2344                      }                           // visit upper slots if present
# Line 2337 | Line 2351 | public class ConcurrentHashMapV8<K, V>
2351          }
2352  
2353          public final void remove() {
2354 <            if (nextVal == null && last == null)
2355 <                advance();
2342 <            Node e = last;
2343 <            if (e == null)
2354 >            Object k = nextKey;
2355 >            if (k == null && (advance() == null || (k = nextKey) == null))
2356                  throw new IllegalStateException();
2357 <            last = null;
2346 <            map.remove(e.key);
2357 >            map.internalReplace(k, null, null);
2358          }
2359  
2360          public final boolean hasNext() {
# Line 2351 | Line 2362 | public class ConcurrentHashMapV8<K, V>
2362          }
2363  
2364          public final boolean hasMoreElements() { return hasNext(); }
2365 <        public final void setRawResult(Object x) { }
2366 <        public R getRawResult() { return null; }
2367 <        public boolean exec() { return true; }
2365 >
2366 >        public void compute() { } // default no-op CountedCompleter body
2367 >
2368 >        /**
2369 >         * Returns a batch value > 0 if this task should (and must) be
2370 >         * split, if so, adding to pending count, and in any case
2371 >         * updating batch value. The initial batch value is approx
2372 >         * exp2 of the number of times (minus one) to split task by
2373 >         * two before executing leaf action. This value is faster to
2374 >         * compute and more convenient to use as a guide to splitting
2375 >         * than is the depth, since it is used while dividing by two
2376 >         * anyway.
2377 >         */
2378 >        final int preSplit() {
2379 >            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2380 >            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2381 >                if ((t = tab) == null && (t = tab = m.table) != null)
2382 >                    baseLimit = baseSize = t.length;
2383 >                if (t != null) {
2384 >                    long n = m.sumCount();
2385 >                    int par = ((pool = getPool()) == null) ?
2386 >                        ForkJoinPool.getCommonPoolParallelism() :
2387 >                        pool.getParallelism();
2388 >                    int sp = par << 3; // slack of 8
2389 >                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2390 >                }
2391 >            }
2392 >            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2393 >            if ((batch = b) > 0)
2394 >                addToPendingCount(1);
2395 >            return b;
2396 >        }
2397 >
2398      }
2399  
2400      /* ---------------- Public operations -------------- */
# Line 2362 | Line 2403 | public class ConcurrentHashMapV8<K, V>
2403       * Creates a new, empty map with the default initial table size (16).
2404       */
2405      public ConcurrentHashMapV8() {
2365        this.counter = new LongAdder();
2406      }
2407  
2408      /**
# Line 2381 | Line 2421 | public class ConcurrentHashMapV8<K, V>
2421          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2422                     MAXIMUM_CAPACITY :
2423                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2384        this.counter = new LongAdder();
2424          this.sizeCtl = cap;
2425      }
2426  
# Line 2391 | Line 2430 | public class ConcurrentHashMapV8<K, V>
2430       * @param m the map
2431       */
2432      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2394        this.counter = new LongAdder();
2433          this.sizeCtl = DEFAULT_CAPACITY;
2434          internalPutAll(m);
2435      }
# Line 2442 | Line 2480 | public class ConcurrentHashMapV8<K, V>
2480          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2481          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2482              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2445        this.counter = new LongAdder();
2483          this.sizeCtl = cap;
2484      }
2485  
2486      /**
2487 +     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2488 +     * from the given type to {@code Boolean.TRUE}.
2489 +     *
2490 +     * @return the new set
2491 +     */
2492 +    public static <K> KeySetView<K,Boolean> newKeySet() {
2493 +        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(),
2494 +                                      Boolean.TRUE);
2495 +    }
2496 +
2497 +    /**
2498 +     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2499 +     * from the given type to {@code Boolean.TRUE}.
2500 +     *
2501 +     * @param initialCapacity The implementation performs internal
2502 +     * sizing to accommodate this many elements.
2503 +     * @throws IllegalArgumentException if the initial capacity of
2504 +     * elements is negative
2505 +     * @return the new set
2506 +     */
2507 +    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2508 +        return new KeySetView<K,Boolean>
2509 +            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2510 +    }
2511 +
2512 +    /**
2513       * {@inheritDoc}
2514       */
2515      public boolean isEmpty() {
2516 <        return counter.sum() <= 0L; // ignore transient negative values
2516 >        return sumCount() <= 0L; // ignore transient negative values
2517      }
2518  
2519      /**
2520       * {@inheritDoc}
2521       */
2522      public int size() {
2523 <        long n = counter.sum();
2523 >        long n = sumCount();
2524          return ((n < 0L) ? 0 :
2525                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2526                  (int)n);
# Line 2465 | Line 2528 | public class ConcurrentHashMapV8<K, V>
2528  
2529      /**
2530       * Returns the number of mappings. This method should be used
2531 <     * instead of {@link #size} because a ConcurrentHashMap may
2531 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2532       * contain more mappings than can be represented as an int. The
2533 <     * value returned is a snapshot; the actual count may differ if
2534 <     * there are ongoing concurrent insertions or removals.
2533 >     * value returned is an estimate; the actual count may differ if
2534 >     * there are concurrent insertions or removals.
2535       *
2536       * @return the number of mappings
2537       */
2538      public long mappingCount() {
2539 <        long n = counter.sum();
2539 >        long n = sumCount();
2540          return (n < 0L) ? 0L : n; // ignore transient negative values
2541      }
2542  
# Line 2488 | Line 2551 | public class ConcurrentHashMapV8<K, V>
2551       *
2552       * @throws NullPointerException if the specified key is null
2553       */
2491    @SuppressWarnings("unchecked")
2554      public V get(Object key) {
2555 <        if (key == null)
2556 <            throw new NullPointerException();
2557 <        return (V)internalGet(key);
2555 >        return internalGet(key);
2556 >    }
2557 >
2558 >    /**
2559 >     * Returns the value to which the specified key is mapped,
2560 >     * or the given defaultValue if this map contains no mapping for the key.
2561 >     *
2562 >     * @param key the key
2563 >     * @param defaultValue the value to return if this map contains
2564 >     * no mapping for the given key
2565 >     * @return the mapping for the key, if present; else the defaultValue
2566 >     * @throws NullPointerException if the specified key is null
2567 >     */
2568 >    public V getValueOrDefault(Object key, V defaultValue) {
2569 >        V v;
2570 >        return (v = internalGet(key)) == null ? defaultValue : v;
2571      }
2572  
2573      /**
# Line 2505 | Line 2580 | public class ConcurrentHashMapV8<K, V>
2580       * @throws NullPointerException if the specified key is null
2581       */
2582      public boolean containsKey(Object key) {
2508        if (key == null)
2509            throw new NullPointerException();
2583          return internalGet(key) != null;
2584      }
2585  
# Line 2523 | Line 2596 | public class ConcurrentHashMapV8<K, V>
2596      public boolean containsValue(Object value) {
2597          if (value == null)
2598              throw new NullPointerException();
2599 <        Object v;
2599 >        V v;
2600          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2601          while ((v = it.advance()) != null) {
2602              if (v == value || value.equals(v))
# Line 2547 | Line 2620 | public class ConcurrentHashMapV8<K, V>
2620       *         {@code false} otherwise
2621       * @throws NullPointerException if the specified value is null
2622       */
2623 <    public boolean contains(Object value) {
2623 >    @Deprecated public boolean contains(Object value) {
2624          return containsValue(value);
2625      }
2626  
# Line 2555 | Line 2628 | public class ConcurrentHashMapV8<K, V>
2628       * Maps the specified key to the specified value in this table.
2629       * Neither the key nor the value can be null.
2630       *
2631 <     * <p> The value can be retrieved by calling the {@code get} method
2631 >     * <p>The value can be retrieved by calling the {@code get} method
2632       * with a key that is equal to the original key.
2633       *
2634       * @param key key with which the specified value is to be associated
# Line 2564 | Line 2637 | public class ConcurrentHashMapV8<K, V>
2637       *         {@code null} if there was no mapping for {@code key}
2638       * @throws NullPointerException if the specified key or value is null
2639       */
2567    @SuppressWarnings("unchecked")
2640      public V put(K key, V value) {
2641 <        if (key == null || value == null)
2570 <            throw new NullPointerException();
2571 <        return (V)internalPut(key, value);
2641 >        return internalPut(key, value, false);
2642      }
2643  
2644      /**
# Line 2578 | Line 2648 | public class ConcurrentHashMapV8<K, V>
2648       *         or {@code null} if there was no mapping for the key
2649       * @throws NullPointerException if the specified key or value is null
2650       */
2581    @SuppressWarnings("unchecked")
2651      public V putIfAbsent(K key, V value) {
2652 <        if (key == null || value == null)
2584 <            throw new NullPointerException();
2585 <        return (V)internalPutIfAbsent(key, value);
2652 >        return internalPut(key, value, true);
2653      }
2654  
2655      /**
# Line 2626 | Line 2693 | public class ConcurrentHashMapV8<K, V>
2693       * @param key key with which the specified value is to be associated
2694       * @param mappingFunction the function to compute a value
2695       * @return the current (existing or computed) value associated with
2696 <     *         the specified key, or null if the computed value is null.
2696 >     *         the specified key, or null if the computed value is null
2697       * @throws NullPointerException if the specified key or mappingFunction
2698       *         is null
2699       * @throws IllegalStateException if the computation detectably
# Line 2635 | Line 2702 | public class ConcurrentHashMapV8<K, V>
2702       * @throws RuntimeException or Error if the mappingFunction does so,
2703       *         in which case the mapping is left unestablished
2704       */
2705 <    @SuppressWarnings("unchecked")
2706 <    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
2707 <        if (key == null || mappingFunction == null)
2641 <            throw new NullPointerException();
2642 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2705 >    public V computeIfAbsent
2706 >        (K key, Fun<? super K, ? extends V> mappingFunction) {
2707 >        return internalComputeIfAbsent(key, mappingFunction);
2708      }
2709  
2710      /**
# Line 2676 | Line 2741 | public class ConcurrentHashMapV8<K, V>
2741       * @throws RuntimeException or Error if the remappingFunction does so,
2742       *         in which case the mapping is unchanged
2743       */
2744 <    @SuppressWarnings("unchecked")
2745 <    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2746 <        if (key == null || remappingFunction == null)
2682 <            throw new NullPointerException();
2683 <        return (V)internalCompute(key, true, remappingFunction);
2744 >    public V computeIfPresent
2745 >        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2746 >        return internalCompute(key, true, remappingFunction);
2747      }
2748  
2749      /**
# Line 2723 | Line 2786 | public class ConcurrentHashMapV8<K, V>
2786       * @throws RuntimeException or Error if the remappingFunction does so,
2787       *         in which case the mapping is unchanged
2788       */
2789 <    @SuppressWarnings("unchecked")
2790 <    public V compute(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2791 <        if (key == null || remappingFunction == null)
2729 <            throw new NullPointerException();
2730 <        return (V)internalCompute(key, false, remappingFunction);
2789 >    public V compute
2790 >        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2791 >        return internalCompute(key, false, remappingFunction);
2792      }
2793  
2794      /**
# Line 2755 | Line 2816 | public class ConcurrentHashMapV8<K, V>
2816       * so the computation should be short and simple, and must not
2817       * attempt to update any other mappings of this Map.
2818       */
2819 <    @SuppressWarnings("unchecked")
2820 <    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2821 <        if (key == null || value == null || remappingFunction == null)
2822 <            throw new NullPointerException();
2762 <        return (V)internalMerge(key, value, remappingFunction);
2819 >    public V merge
2820 >        (K key, V value,
2821 >         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2822 >        return internalMerge(key, value, remappingFunction);
2823      }
2824  
2825      /**
# Line 2771 | Line 2831 | public class ConcurrentHashMapV8<K, V>
2831       *         {@code null} if there was no mapping for {@code key}
2832       * @throws NullPointerException if the specified key is null
2833       */
2834 <    @SuppressWarnings("unchecked")
2835 <        public V remove(Object key) {
2776 <        if (key == null)
2777 <            throw new NullPointerException();
2778 <        return (V)internalReplace(key, null, null);
2834 >    public V remove(Object key) {
2835 >        return internalReplace(key, null, null);
2836      }
2837  
2838      /**
# Line 2784 | Line 2841 | public class ConcurrentHashMapV8<K, V>
2841       * @throws NullPointerException if the specified key is null
2842       */
2843      public boolean remove(Object key, Object value) {
2844 <        if (key == null)
2788 <            throw new NullPointerException();
2789 <        if (value == null)
2790 <            return false;
2791 <        return internalReplace(key, null, value) != null;
2844 >        return value != null && internalReplace(key, null, value) != null;
2845      }
2846  
2847      /**
# Line 2809 | Line 2862 | public class ConcurrentHashMapV8<K, V>
2862       *         or {@code null} if there was no mapping for the key
2863       * @throws NullPointerException if the specified key or value is null
2864       */
2865 <    @SuppressWarnings("unchecked")
2813 <        public V replace(K key, V value) {
2865 >    public V replace(K key, V value) {
2866          if (key == null || value == null)
2867              throw new NullPointerException();
2868 <        return (V)internalReplace(key, value, null);
2868 >        return internalReplace(key, value, null);
2869      }
2870  
2871      /**
# Line 2826 | Line 2878 | public class ConcurrentHashMapV8<K, V>
2878      /**
2879       * Returns a {@link Set} view of the keys contained in this map.
2880       * The set is backed by the map, so changes to the map are
2881 <     * reflected in the set, and vice-versa.  The set supports element
2830 <     * removal, which removes the corresponding mapping from this map,
2831 <     * via the {@code Iterator.remove}, {@code Set.remove},
2832 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2833 <     * operations.  It does not support the {@code add} or
2834 <     * {@code addAll} operations.
2881 >     * reflected in the set, and vice-versa.
2882       *
2883 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2884 <     * that will never throw {@link ConcurrentModificationException},
2885 <     * and guarantees to traverse elements as they existed upon
2886 <     * construction of the iterator, and may (but is not guaranteed to)
2887 <     * reflect any modifications subsequent to construction.
2883 >     * @return the set view
2884 >     */
2885 >    public KeySetView<K,V> keySet() {
2886 >        KeySetView<K,V> ks = keySet;
2887 >        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2888 >    }
2889 >
2890 >    /**
2891 >     * Returns a {@link Set} view of the keys in this map, using the
2892 >     * given common mapped value for any additions (i.e., {@link
2893 >     * Collection#add} and {@link Collection#addAll}). This is of
2894 >     * course only appropriate if it is acceptable to use the same
2895 >     * value for all additions from this view.
2896 >     *
2897 >     * @param mappedValue the mapped value to use for any additions
2898 >     * @return the set view
2899 >     * @throws NullPointerException if the mappedValue is null
2900       */
2901 <    public Set<K> keySet() {
2902 <        KeySet<K,V> ks = keySet;
2903 <        return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
2901 >    public KeySetView<K,V> keySet(V mappedValue) {
2902 >        if (mappedValue == null)
2903 >            throw new NullPointerException();
2904 >        return new KeySetView<K,V>(this, mappedValue);
2905      }
2906  
2907      /**
2908       * Returns a {@link Collection} view of the values contained in this map.
2909       * The collection is backed by the map, so changes to the map are
2910 <     * reflected in the collection, and vice-versa.  The collection
2851 <     * supports element removal, which removes the corresponding
2852 <     * mapping from this map, via the {@code Iterator.remove},
2853 <     * {@code Collection.remove}, {@code removeAll},
2854 <     * {@code retainAll}, and {@code clear} operations.  It does not
2855 <     * support the {@code add} or {@code addAll} operations.
2856 <     *
2857 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2858 <     * that will never throw {@link ConcurrentModificationException},
2859 <     * and guarantees to traverse elements as they existed upon
2860 <     * construction of the iterator, and may (but is not guaranteed to)
2861 <     * reflect any modifications subsequent to construction.
2910 >     * reflected in the collection, and vice-versa.
2911       */
2912 <    public Collection<V> values() {
2913 <        Values<K,V> vs = values;
2914 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
2912 >    public ValuesView<K,V> values() {
2913 >        ValuesView<K,V> vs = values;
2914 >        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2915      }
2916  
2917      /**
# Line 2882 | Line 2931 | public class ConcurrentHashMapV8<K, V>
2931       * reflect any modifications subsequent to construction.
2932       */
2933      public Set<Map.Entry<K,V>> entrySet() {
2934 <        EntrySet<K,V> es = entrySet;
2935 <        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2934 >        EntrySetView<K,V> es = entrySet;
2935 >        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2936      }
2937  
2938      /**
# Line 2943 | Line 2992 | public class ConcurrentHashMapV8<K, V>
2992      public int hashCode() {
2993          int h = 0;
2994          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2995 <        Object v;
2995 >        V v;
2996          while ((v = it.advance()) != null) {
2997              h += it.nextKey.hashCode() ^ v.hashCode();
2998          }
# Line 2965 | Line 3014 | public class ConcurrentHashMapV8<K, V>
3014          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3015          StringBuilder sb = new StringBuilder();
3016          sb.append('{');
3017 <        Object v;
3017 >        V v;
3018          if ((v = it.advance()) != null) {
3019              for (;;) {
3020                  Object k = it.nextKey;
# Line 2996 | Line 3045 | public class ConcurrentHashMapV8<K, V>
3045                  return false;
3046              Map<?,?> m = (Map<?,?>) o;
3047              Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3048 <            Object val;
3048 >            V val;
3049              while ((val = it.advance()) != null) {
3050                  Object v = m.get(it.nextKey);
3051                  if (v == null || (v != val && !v.equals(val)))
# Line 3016 | Line 3065 | public class ConcurrentHashMapV8<K, V>
3065  
3066      /* ----------------Iterators -------------- */
3067  
3068 <    @SuppressWarnings("serial")
3069 <    static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3068 >    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3069 >        extends Traverser<K,V,Object>
3070          implements Spliterator<K>, Enumeration<K> {
3071          KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3072 <        KeyIterator(Traverser<K,V,Object> it, boolean split) {
3073 <            super(it, split);
3072 >        KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3073 >            super(map, it, -1);
3074          }
3075          public KeyIterator<K,V> split() {
3076 <            if (last != null || (next != null && nextVal == null))
3076 >            if (nextKey != null)
3077                  throw new IllegalStateException();
3078 <            return new KeyIterator<K,V>(this, true);
3078 >            return new KeyIterator<K,V>(map, this);
3079          }
3080 <        @SuppressWarnings("unchecked")
3032 <            public final K next() {
3080 >        @SuppressWarnings("unchecked") public final K next() {
3081              if (nextVal == null && advance() == null)
3082                  throw new NoSuchElementException();
3083              Object k = nextKey;
# Line 3040 | Line 3088 | public class ConcurrentHashMapV8<K, V>
3088          public final K nextElement() { return next(); }
3089      }
3090  
3091 <    @SuppressWarnings("serial")
3092 <    static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3091 >    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3092 >        extends Traverser<K,V,Object>
3093          implements Spliterator<V>, Enumeration<V> {
3094          ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3095 <        ValueIterator(Traverser<K,V,Object> it, boolean split) {
3096 <            super(it, split);
3095 >        ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3096 >            super(map, it, -1);
3097          }
3098          public ValueIterator<K,V> split() {
3099 <            if (last != null || (next != null && nextVal == null))
3099 >            if (nextKey != null)
3100                  throw new IllegalStateException();
3101 <            return new ValueIterator<K,V>(this, true);
3101 >            return new ValueIterator<K,V>(map, this);
3102          }
3103  
3104 <        @SuppressWarnings("unchecked")
3105 <            public final V next() {
3058 <            Object v;
3104 >        public final V next() {
3105 >            V v;
3106              if ((v = nextVal) == null && (v = advance()) == null)
3107                  throw new NoSuchElementException();
3108              nextVal = null;
3109 <            return (V) v;
3109 >            return v;
3110          }
3111  
3112          public final V nextElement() { return next(); }
3113      }
3114  
3115 <    @SuppressWarnings("serial")
3116 <    static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3115 >    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3116 >        extends Traverser<K,V,Object>
3117          implements Spliterator<Map.Entry<K,V>> {
3118          EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3119 <        EntryIterator(Traverser<K,V,Object> it, boolean split) {
3120 <            super(it, split);
3119 >        EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3120 >            super(map, it, -1);
3121          }
3122          public EntryIterator<K,V> split() {
3123 <            if (last != null || (next != null && nextVal == null))
3123 >            if (nextKey != null)
3124                  throw new IllegalStateException();
3125 <            return new EntryIterator<K,V>(this, true);
3125 >            return new EntryIterator<K,V>(map, this);
3126          }
3127  
3128 <        @SuppressWarnings("unchecked")
3129 <            public final Map.Entry<K,V> next() {
3083 <            Object v;
3128 >        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3129 >            V v;
3130              if ((v = nextVal) == null && (v = advance()) == null)
3131                  throw new NoSuchElementException();
3132              Object k = nextKey;
3133              nextVal = null;
3134 <            return new MapEntry<K,V>((K)k, (V)v, map);
3134 >            return new MapEntry<K,V>((K)k, v, map);
3135          }
3136      }
3137  
# Line 3132 | Line 3178 | public class ConcurrentHashMapV8<K, V>
3178          }
3179      }
3180  
3135    /* ----------------Views -------------- */
3136
3181      /**
3182 <     * Base class for views.
3182 >     * Returns exportable snapshot entry for the given key and value
3183 >     * when write-through can't or shouldn't be used.
3184       */
3185 <    static abstract class CHMView<K, V> {
3186 <        final ConcurrentHashMapV8<K, V> map;
3142 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
3143 <        public final int size()                 { return map.size(); }
3144 <        public final boolean isEmpty()          { return map.isEmpty(); }
3145 <        public final void clear()               { map.clear(); }
3146 <
3147 <        // implementations below rely on concrete classes supplying these
3148 <        abstract public Iterator<?> iterator();
3149 <        abstract public boolean contains(Object o);
3150 <        abstract public boolean remove(Object o);
3151 <
3152 <        private static final String oomeMsg = "Required array size too large";
3153 <
3154 <        public final Object[] toArray() {
3155 <            long sz = map.mappingCount();
3156 <            if (sz > (long)(MAX_ARRAY_SIZE))
3157 <                throw new OutOfMemoryError(oomeMsg);
3158 <            int n = (int)sz;
3159 <            Object[] r = new Object[n];
3160 <            int i = 0;
3161 <            Iterator<?> it = iterator();
3162 <            while (it.hasNext()) {
3163 <                if (i == n) {
3164 <                    if (n >= MAX_ARRAY_SIZE)
3165 <                        throw new OutOfMemoryError(oomeMsg);
3166 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3167 <                        n = MAX_ARRAY_SIZE;
3168 <                    else
3169 <                        n += (n >>> 1) + 1;
3170 <                    r = Arrays.copyOf(r, n);
3171 <                }
3172 <                r[i++] = it.next();
3173 <            }
3174 <            return (i == n) ? r : Arrays.copyOf(r, i);
3175 <        }
3176 <
3177 <        @SuppressWarnings("unchecked")
3178 <            public final <T> T[] toArray(T[] a) {
3179 <            long sz = map.mappingCount();
3180 <            if (sz > (long)(MAX_ARRAY_SIZE))
3181 <                throw new OutOfMemoryError(oomeMsg);
3182 <            int m = (int)sz;
3183 <            T[] r = (a.length >= m) ? a :
3184 <                (T[])java.lang.reflect.Array
3185 <                .newInstance(a.getClass().getComponentType(), m);
3186 <            int n = r.length;
3187 <            int i = 0;
3188 <            Iterator<?> it = iterator();
3189 <            while (it.hasNext()) {
3190 <                if (i == n) {
3191 <                    if (n >= MAX_ARRAY_SIZE)
3192 <                        throw new OutOfMemoryError(oomeMsg);
3193 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3194 <                        n = MAX_ARRAY_SIZE;
3195 <                    else
3196 <                        n += (n >>> 1) + 1;
3197 <                    r = Arrays.copyOf(r, n);
3198 <                }
3199 <                r[i++] = (T)it.next();
3200 <            }
3201 <            if (a == r && i < n) {
3202 <                r[i] = null; // null-terminate
3203 <                return r;
3204 <            }
3205 <            return (i == n) ? r : Arrays.copyOf(r, i);
3206 <        }
3207 <
3208 <        public final int hashCode() {
3209 <            int h = 0;
3210 <            for (Iterator<?> it = iterator(); it.hasNext();)
3211 <                h += it.next().hashCode();
3212 <            return h;
3213 <        }
3214 <
3215 <        public final String toString() {
3216 <            StringBuilder sb = new StringBuilder();
3217 <            sb.append('[');
3218 <            Iterator<?> it = iterator();
3219 <            if (it.hasNext()) {
3220 <                for (;;) {
3221 <                    Object e = it.next();
3222 <                    sb.append(e == this ? "(this Collection)" : e);
3223 <                    if (!it.hasNext())
3224 <                        break;
3225 <                    sb.append(',').append(' ');
3226 <                }
3227 <            }
3228 <            return sb.append(']').toString();
3229 <        }
3230 <
3231 <        public final boolean containsAll(Collection<?> c) {
3232 <            if (c != this) {
3233 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3234 <                    Object e = it.next();
3235 <                    if (e == null || !contains(e))
3236 <                        return false;
3237 <                }
3238 <            }
3239 <            return true;
3240 <        }
3241 <
3242 <        public final boolean removeAll(Collection<?> c) {
3243 <            boolean modified = false;
3244 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3245 <                if (c.contains(it.next())) {
3246 <                    it.remove();
3247 <                    modified = true;
3248 <                }
3249 <            }
3250 <            return modified;
3251 <        }
3252 <
3253 <        public final boolean retainAll(Collection<?> c) {
3254 <            boolean modified = false;
3255 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3256 <                if (!c.contains(it.next())) {
3257 <                    it.remove();
3258 <                    modified = true;
3259 <                }
3260 <            }
3261 <            return modified;
3262 <        }
3263 <
3264 <    }
3265 <
3266 <    static final class KeySet<K,V> extends CHMView<K,V> implements Set<K> {
3267 <        KeySet(ConcurrentHashMapV8<K, V> map)  {
3268 <            super(map);
3269 <        }
3270 <        public final boolean contains(Object o) { return map.containsKey(o); }
3271 <        public final boolean remove(Object o)   { return map.remove(o) != null; }
3272 <        public final Iterator<K> iterator() {
3273 <            return new KeyIterator<K,V>(map);
3274 <        }
3275 <        public final boolean add(K e) {
3276 <            throw new UnsupportedOperationException();
3277 <        }
3278 <        public final boolean addAll(Collection<? extends K> c) {
3279 <            throw new UnsupportedOperationException();
3280 <        }
3281 <        public boolean equals(Object o) {
3282 <            Set<?> c;
3283 <            return ((o instanceof Set) &&
3284 <                    ((c = (Set<?>)o) == this ||
3285 <                     (containsAll(c) && c.containsAll(this))));
3286 <        }
3287 <    }
3288 <
3289 <
3290 <    static final class Values<K,V> extends CHMView<K,V>
3291 <        implements Collection<V> {
3292 <        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
3293 <        public final boolean contains(Object o) { return map.containsValue(o); }
3294 <        public final boolean remove(Object o) {
3295 <            if (o != null) {
3296 <                Iterator<V> it = new ValueIterator<K,V>(map);
3297 <                while (it.hasNext()) {
3298 <                    if (o.equals(it.next())) {
3299 <                        it.remove();
3300 <                        return true;
3301 <                    }
3302 <                }
3303 <            }
3304 <            return false;
3305 <        }
3306 <        public final Iterator<V> iterator() {
3307 <            return new ValueIterator<K,V>(map);
3308 <        }
3309 <        public final boolean add(V e) {
3310 <            throw new UnsupportedOperationException();
3311 <        }
3312 <        public final boolean addAll(Collection<? extends V> c) {
3313 <            throw new UnsupportedOperationException();
3314 <        }
3315 <
3316 <    }
3317 <
3318 <    static final class EntrySet<K,V> extends CHMView<K,V>
3319 <        implements Set<Map.Entry<K,V>> {
3320 <        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
3321 <        public final boolean contains(Object o) {
3322 <            Object k, v, r; Map.Entry<?,?> e;
3323 <            return ((o instanceof Map.Entry) &&
3324 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3325 <                    (r = map.get(k)) != null &&
3326 <                    (v = e.getValue()) != null &&
3327 <                    (v == r || v.equals(r)));
3328 <        }
3329 <        public final boolean remove(Object o) {
3330 <            Object k, v; Map.Entry<?,?> e;
3331 <            return ((o instanceof Map.Entry) &&
3332 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3333 <                    (v = e.getValue()) != null &&
3334 <                    map.remove(k, v));
3335 <        }
3336 <        public final Iterator<Map.Entry<K,V>> iterator() {
3337 <            return new EntryIterator<K,V>(map);
3338 <        }
3339 <        public final boolean add(Entry<K,V> e) {
3340 <            throw new UnsupportedOperationException();
3341 <        }
3342 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3343 <            throw new UnsupportedOperationException();
3344 <        }
3345 <        public boolean equals(Object o) {
3346 <            Set<?> c;
3347 <            return ((o instanceof Set) &&
3348 <                    ((c = (Set<?>)o) == this ||
3349 <                     (containsAll(c) && c.containsAll(this))));
3350 <        }
3185 >    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3186 >        return new AbstractMap.SimpleEntry<K,V>(k, v);
3187      }
3188  
3189      /* ---------------- Serialization Support -------------- */
# Line 3371 | Line 3207 | public class ConcurrentHashMapV8<K, V>
3207       * for each key-value mapping, followed by a null pair.
3208       * The key-value mappings are emitted in no particular order.
3209       */
3210 <    @SuppressWarnings("unchecked")
3211 <        private void writeObject(java.io.ObjectOutputStream s)
3210 >    @SuppressWarnings("unchecked") private void writeObject
3211 >        (java.io.ObjectOutputStream s)
3212          throws java.io.IOException {
3213          if (segments == null) { // for serialization compatibility
3214              segments = (Segment<K,V>[])
# Line 3382 | Line 3218 | public class ConcurrentHashMapV8<K, V>
3218          }
3219          s.defaultWriteObject();
3220          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3221 <        Object v;
3221 >        V v;
3222          while ((v = it.advance()) != null) {
3223              s.writeObject(it.nextKey);
3224              s.writeObject(v);
# Line 3396 | Line 3232 | public class ConcurrentHashMapV8<K, V>
3232       * Reconstitutes the instance from a stream (that is, deserializes it).
3233       * @param s the stream
3234       */
3235 <    @SuppressWarnings("unchecked")
3236 <        private void readObject(java.io.ObjectInputStream s)
3235 >    @SuppressWarnings("unchecked") private void readObject
3236 >        (java.io.ObjectInputStream s)
3237          throws java.io.IOException, ClassNotFoundException {
3238          s.defaultReadObject();
3239          this.segments = null; // unneeded
3404        // initialize transient final field
3405        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3240  
3241          // Create all nodes, then place in table once size is known
3242          long size = 0L;
3243 <        Node p = null;
3243 >        Node<V> p = null;
3244          for (;;) {
3245              K k = (K) s.readObject();
3246              V v = (V) s.readObject();
3247              if (k != null && v != null) {
3248                  int h = spread(k.hashCode());
3249 <                p = new Node(h, k, v, p);
3249 >                p = new Node<V>(h, k, v, p);
3250                  ++size;
3251              }
3252              else
# Line 3430 | Line 3264 | public class ConcurrentHashMapV8<K, V>
3264              int sc = sizeCtl;
3265              boolean collide = false;
3266              if (n > sc &&
3267 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3267 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3268                  try {
3269                      if (table == null) {
3270                          init = true;
3271 <                        Node[] tab = new Node[n];
3271 >                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3272 >                        Node<V>[] tab = (Node<V>[])rt;
3273                          int mask = n - 1;
3274                          while (p != null) {
3275                              int j = p.hash & mask;
3276 <                            Node next = p.next;
3277 <                            Node q = p.next = tabAt(tab, j);
3276 >                            Node<V> next = p.next;
3277 >                            Node<V> q = p.next = tabAt(tab, j);
3278                              setTabAt(tab, j, p);
3279                              if (!collide && q != null && q.hash == p.hash)
3280                                  collide = true;
3281                              p = next;
3282                          }
3283                          table = tab;
3284 <                        counter.add(size);
3284 >                        addCount(size, -1);
3285                          sc = n - (n >>> 2);
3286                      }
3287                  } finally {
3288                      sizeCtl = sc;
3289                  }
3290                  if (collide) { // rescan and convert to TreeBins
3291 <                    Node[] tab = table;
3291 >                    Node<V>[] tab = table;
3292                      for (int i = 0; i < tab.length; ++i) {
3293                          int c = 0;
3294 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3294 >                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3295                              if (++c > TREE_THRESHOLD &&
3296                                  (e.key instanceof Comparable)) {
3297                                  replaceWithTreeBin(tab, i, e.key);
# Line 3468 | Line 3303 | public class ConcurrentHashMapV8<K, V>
3303              }
3304              if (!init) { // Can only happen if unsafely published.
3305                  while (p != null) {
3306 <                    internalPut(p.key, p.val);
3306 >                    internalPut((K)p.key, p.val, false);
3307                      p = p.next;
3308                  }
3309              }
3310          }
3311      }
3312  
3478
3313      // -------------------------------------------------------
3314  
3315      // Sams
# Line 3517 | Line 3351 | public class ConcurrentHashMapV8<K, V>
3351  
3352      // -------------------------------------------------------
3353  
3354 +    // Sequential bulk operations
3355 +
3356      /**
3357 <     * Returns an extended {@link Parallel} view of this map using the
3522 <     * given executor for bulk parallel operations.
3357 >     * Performs the given action for each (key, value).
3358       *
3359 <     * @param executor the executor
3525 <     * @return a parallel view
3359 >     * @param action the action
3360       */
3361 <    public Parallel parallel(ForkJoinPool executor)  {
3362 <        return new Parallel(executor);
3361 >    @SuppressWarnings("unchecked") public void forEachSequentially
3362 >        (BiAction<K,V> action) {
3363 >        if (action == null) throw new NullPointerException();
3364 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3365 >        V v;
3366 >        while ((v = it.advance()) != null)
3367 >            action.apply((K)it.nextKey, v);
3368      }
3369  
3370      /**
3371 <     * An extended view of a ConcurrentHashMap supporting bulk
3372 <     * parallel operations. These operations are designed to be
3373 <     * safely, and often sensibly, applied even with maps that are
3374 <     * being concurrently updated by other threads; for example, when
3375 <     * computing a snapshot summary of the values in a shared
3376 <     * registry.  There are three kinds of operation, each with four
3377 <     * forms, accepting functions with Keys, Values, Entries, and
3539 <     * (Key, Value) arguments and/or return values. Because the
3540 <     * elements of a ConcurrentHashMap are not ordered in any
3541 <     * particular way, and may be processed in different orders in
3542 <     * different parallel executions, the correctness of supplied
3543 <     * functions should not depend on any ordering, or on any other
3544 <     * objects or values that may transiently change while computation
3545 <     * is in progress; and except for forEach actions, should ideally
3546 <     * be side-effect-free.
3547 <     *
3548 <     * <ul>
3549 <     * <li> forEach: Perform a given action on each element.
3550 <     * A variant form applies a given transformation on each element
3551 <     * before performing the action.</li>
3552 <     *
3553 <     * <li> search: Return the first available non-null result of
3554 <     * applying a given function on each element; skipping further
3555 <     * search when a result is found.</li>
3556 <     *
3557 <     * <li> reduce: Accumulate each element.  The supplied reduction
3558 <     * function cannot rely on ordering (more formally, it should be
3559 <     * both associative and commutative).  There are five variants:
3560 <     *
3561 <     * <ul>
3562 <     *
3563 <     * <li> Plain reductions. (There is not a form of this method for
3564 <     * (key, value) function arguments since there is no corresponding
3565 <     * return type.)</li>
3566 <     *
3567 <     * <li> Mapped reductions that accumulate the results of a given
3568 <     * function applied to each element.</li>
3569 <     *
3570 <     * <li> Reductions to scalar doubles, longs, and ints, using a
3571 <     * given basis value.</li>
3572 <     *
3573 <     * </li>
3574 <     * </ul>
3575 <     * </ul>
3576 <     *
3577 <     * <p>The concurrency properties of the bulk operations follow
3578 <     * from those of ConcurrentHashMap: Any non-null result returned
3579 <     * from {@code get(key)} and related access methods bears a
3580 <     * happens-before relation with the associated insertion or
3581 <     * update.  The result of any bulk operation reflects the
3582 <     * composition of these per-element relations (but is not
3583 <     * necessarily atomic with respect to the map as a whole unless it
3584 <     * is somehow known to be quiescent).  Conversely, because keys
3585 <     * and values in the map are never null, null serves as a reliable
3586 <     * atomic indicator of the current lack of any result.  To
3587 <     * maintain this property, null serves as an implicit basis for
3588 <     * all non-scalar reduction operations. For the double, long, and
3589 <     * int versions, the basis should be one that, when combined with
3590 <     * any other value, returns that other value (more formally, it
3591 <     * should be the identity element for the reduction). Most common
3592 <     * reductions have these properties; for example, computing a sum
3593 <     * with basis 0 or a minimum with basis MAX_VALUE.
3594 <     *
3595 <     * <p>Search and transformation functions provided as arguments
3596 <     * should similarly return null to indicate the lack of any result
3597 <     * (in which case it is not used). In the case of mapped
3598 <     * reductions, this also enables transformations to serve as
3599 <     * filters, returning null (or, in the case of primitive
3600 <     * specializations, the identity basis) if the element should not
3601 <     * be combined. You can create compound transformations and
3602 <     * filterings by composing them yourself under this "null means
3603 <     * there is nothing there now" rule before using them in search or
3604 <     * reduce operations.
3605 <     *
3606 <     * <p>Methods accepting and/or returning Entry arguments maintain
3607 <     * key-value associations. They may be useful for example when
3608 <     * finding the key for the greatest value. Note that "plain" Entry
3609 <     * arguments can be supplied using {@code new
3610 <     * AbstractMap.SimpleEntry(k,v)}.
3611 <     *
3612 <     * <p> Bulk operations may complete abruptly, throwing an
3613 <     * exception encountered in the application of a supplied
3614 <     * function. Bear in mind when handling such exceptions that other
3615 <     * concurrently executing functions could also have thrown
3616 <     * exceptions, or would have done so if the first exception had
3617 <     * not occurred.
3618 <     *
3619 <     * <p>Parallel speedups compared to sequential processing are
3620 <     * common but not guaranteed.  Operations involving brief
3621 <     * functions on small maps may execute more slowly than sequential
3622 <     * loops if the underlying work to parallelize the computation is
3623 <     * more expensive than the computation itself. Similarly,
3624 <     * parallelization may not lead to much actual parallelism if all
3625 <     * processors are busy performing unrelated tasks.
3626 <     *
3627 <     * <p> All arguments to all task methods must be non-null.
3628 <     *
3629 <     * <p><em>jsr166e note: During transition, this class
3630 <     * uses nested functional interfaces with different names but the
3631 <     * same forms as those expected for JDK8.<em>
3371 >     * Performs the given action for each non-null transformation
3372 >     * of each (key, value).
3373 >     *
3374 >     * @param transformer a function returning the transformation
3375 >     * for an element, or null if there is no transformation (in
3376 >     * which case the action is not applied)
3377 >     * @param action the action
3378       */
3379 <    public class Parallel {
3380 <        final ForkJoinPool fjp;
3381 <
3382 <        /**
3383 <         * Returns an extended view of this map using the given
3384 <         * executor for bulk parallel operations.
3385 <         *
3386 <         * @param executor the executor
3387 <         */
3388 <        public Parallel(ForkJoinPool executor)  {
3643 <            this.fjp = executor;
3379 >    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3380 >        (BiFun<? super K, ? super V, ? extends U> transformer,
3381 >         Action<U> action) {
3382 >        if (transformer == null || action == null)
3383 >            throw new NullPointerException();
3384 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3385 >        V v; U u;
3386 >        while ((v = it.advance()) != null) {
3387 >            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3388 >                action.apply(u);
3389          }
3390 +    }
3391  
3392 <        /**
3393 <         * Performs the given action for each (key, value).
3394 <         *
3395 <         * @param action the action
3396 <         */
3397 <        public void forEach(BiAction<K,V> action) {
3398 <            fjp.invoke(ForkJoinTasks.forEach
3399 <                       (ConcurrentHashMapV8.this, action));
3392 >    /**
3393 >     * Returns a non-null result from applying the given search
3394 >     * function on each (key, value), or null if none.
3395 >     *
3396 >     * @param searchFunction a function returning a non-null
3397 >     * result on success, else null
3398 >     * @return a non-null result from applying the given search
3399 >     * function on each (key, value), or null if none
3400 >     */
3401 >    @SuppressWarnings("unchecked") public <U> U searchSequentially
3402 >        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3403 >        if (searchFunction == null) throw new NullPointerException();
3404 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3405 >        V v; U u;
3406 >        while ((v = it.advance()) != null) {
3407 >            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3408 >                return u;
3409          }
3410 +        return null;
3411 +    }
3412  
3413 <        /**
3414 <         * Performs the given action for each non-null transformation
3415 <         * of each (key, value).
3416 <         *
3417 <         * @param transformer a function returning the transformation
3418 <         * for an element, or null of there is no transformation (in
3419 <         * which case the action is not applied).
3420 <         * @param action the action
3421 <         */
3422 <        public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3423 <                                Action<U> action) {
3424 <            fjp.invoke(ForkJoinTasks.forEach
3425 <                       (ConcurrentHashMapV8.this, transformer, action));
3413 >    /**
3414 >     * Returns the result of accumulating the given transformation
3415 >     * of all (key, value) pairs using the given reducer to
3416 >     * combine values, or null if none.
3417 >     *
3418 >     * @param transformer a function returning the transformation
3419 >     * for an element, or null if there is no transformation (in
3420 >     * which case it is not combined)
3421 >     * @param reducer a commutative associative combining function
3422 >     * @return the result of accumulating the given transformation
3423 >     * of all (key, value) pairs
3424 >     */
3425 >    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3426 >        (BiFun<? super K, ? super V, ? extends U> transformer,
3427 >         BiFun<? super U, ? super U, ? extends U> reducer) {
3428 >        if (transformer == null || reducer == null)
3429 >            throw new NullPointerException();
3430 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3431 >        U r = null, u; V v;
3432 >        while ((v = it.advance()) != null) {
3433 >            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3434 >                r = (r == null) ? u : reducer.apply(r, u);
3435          }
3436 +        return r;
3437 +    }
3438  
3439 <        /**
3440 <         * Returns a non-null result from applying the given search
3441 <         * function on each (key, value), or null if none.  Upon
3442 <         * success, further element processing is suppressed and the
3443 <         * results of any other parallel invocations of the search
3444 <         * function are ignored.
3445 <         *
3446 <         * @param searchFunction a function returning a non-null
3447 <         * result on success, else null
3448 <         * @return a non-null result from applying the given search
3449 <         * function on each (key, value), or null if none
3450 <         */
3451 <        public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3452 <            return fjp.invoke(ForkJoinTasks.search
3453 <                              (ConcurrentHashMapV8.this, searchFunction));
3454 <        }
3439 >    /**
3440 >     * Returns the result of accumulating the given transformation
3441 >     * of all (key, value) pairs using the given reducer to
3442 >     * combine values, and the given basis as an identity value.
3443 >     *
3444 >     * @param transformer a function returning the transformation
3445 >     * for an element
3446 >     * @param basis the identity (initial default value) for the reduction
3447 >     * @param reducer a commutative associative combining function
3448 >     * @return the result of accumulating the given transformation
3449 >     * of all (key, value) pairs
3450 >     */
3451 >    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3452 >        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3453 >         double basis,
3454 >         DoubleByDoubleToDouble reducer) {
3455 >        if (transformer == null || reducer == null)
3456 >            throw new NullPointerException();
3457 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3458 >        double r = basis; V v;
3459 >        while ((v = it.advance()) != null)
3460 >            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3461 >        return r;
3462 >    }
3463  
3464 <        /**
3465 <         * Returns the result of accumulating the given transformation
3466 <         * of all (key, value) pairs using the given reducer to
3467 <         * combine values, or null if none.
3468 <         *
3469 <         * @param transformer a function returning the transformation
3470 <         * for an element, or null of there is no transformation (in
3471 <         * which case it is not combined).
3472 <         * @param reducer a commutative associative combining function
3473 <         * @return the result of accumulating the given transformation
3474 <         * of all (key, value) pairs
3475 <         */
3476 <        public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3477 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3478 <            return fjp.invoke(ForkJoinTasks.reduce
3479 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3480 <        }
3464 >    /**
3465 >     * Returns the result of accumulating the given transformation
3466 >     * of all (key, value) pairs using the given reducer to
3467 >     * combine values, and the given basis as an identity value.
3468 >     *
3469 >     * @param transformer a function returning the transformation
3470 >     * for an element
3471 >     * @param basis the identity (initial default value) for the reduction
3472 >     * @param reducer a commutative associative combining function
3473 >     * @return the result of accumulating the given transformation
3474 >     * of all (key, value) pairs
3475 >     */
3476 >    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3477 >        (ObjectByObjectToLong<? super K, ? super V> transformer,
3478 >         long basis,
3479 >         LongByLongToLong reducer) {
3480 >        if (transformer == null || reducer == null)
3481 >            throw new NullPointerException();
3482 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3483 >        long r = basis; V v;
3484 >        while ((v = it.advance()) != null)
3485 >            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3486 >        return r;
3487 >    }
3488  
3489 <        /**
3490 <         * Returns the result of accumulating the given transformation
3491 <         * of all (key, value) pairs using the given reducer to
3492 <         * combine values, and the given basis as an identity value.
3493 <         *
3494 <         * @param transformer a function returning the transformation
3495 <         * for an element
3496 <         * @param basis the identity (initial default value) for the reduction
3497 <         * @param reducer a commutative associative combining function
3498 <         * @return the result of accumulating the given transformation
3499 <         * of all (key, value) pairs
3500 <         */
3501 <        public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3502 <                                     double basis,
3503 <                                     DoubleByDoubleToDouble reducer) {
3504 <            return fjp.invoke(ForkJoinTasks.reduceToDouble
3505 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3506 <        }
3489 >    /**
3490 >     * Returns the result of accumulating the given transformation
3491 >     * of all (key, value) pairs using the given reducer to
3492 >     * combine values, and the given basis as an identity value.
3493 >     *
3494 >     * @param transformer a function returning the transformation
3495 >     * for an element
3496 >     * @param basis the identity (initial default value) for the reduction
3497 >     * @param reducer a commutative associative combining function
3498 >     * @return the result of accumulating the given transformation
3499 >     * of all (key, value) pairs
3500 >     */
3501 >    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3502 >        (ObjectByObjectToInt<? super K, ? super V> transformer,
3503 >         int basis,
3504 >         IntByIntToInt reducer) {
3505 >        if (transformer == null || reducer == null)
3506 >            throw new NullPointerException();
3507 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3508 >        int r = basis; V v;
3509 >        while ((v = it.advance()) != null)
3510 >            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3511 >        return r;
3512 >    }
3513  
3514 <        /**
3515 <         * Returns the result of accumulating the given transformation
3516 <         * of all (key, value) pairs using the given reducer to
3517 <         * combine values, and the given basis as an identity value.
3518 <         *
3519 <         * @param transformer a function returning the transformation
3520 <         * for an element
3521 <         * @param basis the identity (initial default value) for the reduction
3522 <         * @param reducer a commutative associative combining function
3523 <         * @return the result of accumulating the given transformation
3524 <         * of all (key, value) pairs
3525 <         */
3737 <        public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3738 <                                 long basis,
3739 <                                 LongByLongToLong reducer) {
3740 <            return fjp.invoke(ForkJoinTasks.reduceToLong
3741 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3742 <        }
3514 >    /**
3515 >     * Performs the given action for each key.
3516 >     *
3517 >     * @param action the action
3518 >     */
3519 >    @SuppressWarnings("unchecked") public void forEachKeySequentially
3520 >        (Action<K> action) {
3521 >        if (action == null) throw new NullPointerException();
3522 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3523 >        while (it.advance() != null)
3524 >            action.apply((K)it.nextKey);
3525 >    }
3526  
3527 <        /**
3528 <         * Returns the result of accumulating the given transformation
3529 <         * of all (key, value) pairs using the given reducer to
3530 <         * combine values, and the given basis as an identity value.
3531 <         *
3532 <         * @param transformer a function returning the transformation
3533 <         * for an element
3534 <         * @param basis the identity (initial default value) for the reduction
3535 <         * @param reducer a commutative associative combining function
3536 <         * @return the result of accumulating the given transformation
3537 <         * of all (key, value) pairs
3538 <         */
3539 <        public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3540 <                               int basis,
3541 <                               IntByIntToInt reducer) {
3542 <            return fjp.invoke(ForkJoinTasks.reduceToInt
3543 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3527 >    /**
3528 >     * Performs the given action for each non-null transformation
3529 >     * of each key.
3530 >     *
3531 >     * @param transformer a function returning the transformation
3532 >     * for an element, or null if there is no transformation (in
3533 >     * which case the action is not applied)
3534 >     * @param action the action
3535 >     */
3536 >    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3537 >        (Fun<? super K, ? extends U> transformer,
3538 >         Action<U> action) {
3539 >        if (transformer == null || action == null)
3540 >            throw new NullPointerException();
3541 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3542 >        U u;
3543 >        while (it.advance() != null) {
3544 >            if ((u = transformer.apply((K)it.nextKey)) != null)
3545 >                action.apply(u);
3546          }
3547 +        ForkJoinTasks.forEachKey
3548 +            (this, transformer, action).invoke();
3549 +    }
3550  
3551 <        /**
3552 <         * Performs the given action for each key.
3553 <         *
3554 <         * @param action the action
3555 <         */
3556 <        public void forEachKey(Action<K> action) {
3557 <            fjp.invoke(ForkJoinTasks.forEachKey
3558 <                       (ConcurrentHashMapV8.this, action));
3551 >    /**
3552 >     * Returns a non-null result from applying the given search
3553 >     * function on each key, or null if none.
3554 >     *
3555 >     * @param searchFunction a function returning a non-null
3556 >     * result on success, else null
3557 >     * @return a non-null result from applying the given search
3558 >     * function on each key, or null if none
3559 >     */
3560 >    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3561 >        (Fun<? super K, ? extends U> searchFunction) {
3562 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3563 >        U u;
3564 >        while (it.advance() != null) {
3565 >            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3566 >                return u;
3567          }
3568 +        return null;
3569 +    }
3570  
3571 <        /**
3572 <         * Performs the given action for each non-null transformation
3573 <         * of each key.
3574 <         *
3575 <         * @param transformer a function returning the transformation
3576 <         * for an element, or null of there is no transformation (in
3577 <         * which case the action is not applied).
3578 <         * @param action the action
3579 <         */
3580 <        public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3581 <                                   Action<U> action) {
3582 <            fjp.invoke(ForkJoinTasks.forEachKey
3583 <                       (ConcurrentHashMapV8.this, transformer, action));
3571 >    /**
3572 >     * Returns the result of accumulating all keys using the given
3573 >     * reducer to combine values, or null if none.
3574 >     *
3575 >     * @param reducer a commutative associative combining function
3576 >     * @return the result of accumulating all keys using the given
3577 >     * reducer to combine values, or null if none
3578 >     */
3579 >    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3580 >        (BiFun<? super K, ? super K, ? extends K> reducer) {
3581 >        if (reducer == null) throw new NullPointerException();
3582 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3583 >        K r = null;
3584 >        while (it.advance() != null) {
3585 >            K u = (K)it.nextKey;
3586 >            r = (r == null) ? u : reducer.apply(r, u);
3587 >        }
3588 >        return r;
3589 >    }
3590 >
3591 >    /**
3592 >     * Returns the result of accumulating the given transformation
3593 >     * of all keys using the given reducer to combine values, or
3594 >     * null if none.
3595 >     *
3596 >     * @param transformer a function returning the transformation
3597 >     * for an element, or null if there is no transformation (in
3598 >     * which case it is not combined)
3599 >     * @param reducer a commutative associative combining function
3600 >     * @return the result of accumulating the given transformation
3601 >     * of all keys
3602 >     */
3603 >    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3604 >        (Fun<? super K, ? extends U> transformer,
3605 >         BiFun<? super U, ? super U, ? extends U> reducer) {
3606 >        if (transformer == null || reducer == null)
3607 >            throw new NullPointerException();
3608 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3609 >        U r = null, u;
3610 >        while (it.advance() != null) {
3611 >            if ((u = transformer.apply((K)it.nextKey)) != null)
3612 >                r = (r == null) ? u : reducer.apply(r, u);
3613          }
3614 +        return r;
3615 +    }
3616  
3617 <        /**
3618 <         * Returns a non-null result from applying the given search
3619 <         * function on each key, or null if none. Upon success,
3620 <         * further element processing is suppressed and the results of
3621 <         * any other parallel invocations of the search function are
3622 <         * ignored.
3623 <         *
3624 <         * @param searchFunction a function returning a non-null
3625 <         * result on success, else null
3626 <         * @return a non-null result from applying the given search
3627 <         * function on each key, or null if none
3628 <         */
3629 <        public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3630 <            return fjp.invoke(ForkJoinTasks.searchKeys
3631 <                              (ConcurrentHashMapV8.this, searchFunction));
3617 >    /**
3618 >     * Returns the result of accumulating the given transformation
3619 >     * of all keys using the given reducer to combine values, and
3620 >     * the given basis as an identity value.
3621 >     *
3622 >     * @param transformer a function returning the transformation
3623 >     * for an element
3624 >     * @param basis the identity (initial default value) for the reduction
3625 >     * @param reducer a commutative associative combining function
3626 >     * @return  the result of accumulating the given transformation
3627 >     * of all keys
3628 >     */
3629 >    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3630 >        (ObjectToDouble<? super K> transformer,
3631 >         double basis,
3632 >         DoubleByDoubleToDouble reducer) {
3633 >        if (transformer == null || reducer == null)
3634 >            throw new NullPointerException();
3635 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3636 >        double r = basis;
3637 >        while (it.advance() != null)
3638 >            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3639 >        return r;
3640 >    }
3641 >
3642 >    /**
3643 >     * Returns the result of accumulating the given transformation
3644 >     * of all keys using the given reducer to combine values, and
3645 >     * the given basis as an identity value.
3646 >     *
3647 >     * @param transformer a function returning the transformation
3648 >     * for an element
3649 >     * @param basis the identity (initial default value) for the reduction
3650 >     * @param reducer a commutative associative combining function
3651 >     * @return the result of accumulating the given transformation
3652 >     * of all keys
3653 >     */
3654 >    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3655 >        (ObjectToLong<? super K> transformer,
3656 >         long basis,
3657 >         LongByLongToLong reducer) {
3658 >        if (transformer == null || reducer == null)
3659 >            throw new NullPointerException();
3660 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3661 >        long r = basis;
3662 >        while (it.advance() != null)
3663 >            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3664 >        return r;
3665 >    }
3666 >
3667 >    /**
3668 >     * Returns the result of accumulating the given transformation
3669 >     * of all keys using the given reducer to combine values, and
3670 >     * the given basis as an identity value.
3671 >     *
3672 >     * @param transformer a function returning the transformation
3673 >     * for an element
3674 >     * @param basis the identity (initial default value) for the reduction
3675 >     * @param reducer a commutative associative combining function
3676 >     * @return the result of accumulating the given transformation
3677 >     * of all keys
3678 >     */
3679 >    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3680 >        (ObjectToInt<? super K> transformer,
3681 >         int basis,
3682 >         IntByIntToInt reducer) {
3683 >        if (transformer == null || reducer == null)
3684 >            throw new NullPointerException();
3685 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3686 >        int r = basis;
3687 >        while (it.advance() != null)
3688 >            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3689 >        return r;
3690 >    }
3691 >
3692 >    /**
3693 >     * Performs the given action for each value.
3694 >     *
3695 >     * @param action the action
3696 >     */
3697 >    public void forEachValueSequentially(Action<V> action) {
3698 >        if (action == null) throw new NullPointerException();
3699 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3700 >        V v;
3701 >        while ((v = it.advance()) != null)
3702 >            action.apply(v);
3703 >    }
3704 >
3705 >    /**
3706 >     * Performs the given action for each non-null transformation
3707 >     * of each value.
3708 >     *
3709 >     * @param transformer a function returning the transformation
3710 >     * for an element, or null if there is no transformation (in
3711 >     * which case the action is not applied)
3712 >     */
3713 >    public <U> void forEachValueSequentially
3714 >        (Fun<? super V, ? extends U> transformer,
3715 >         Action<U> action) {
3716 >        if (transformer == null || action == null)
3717 >            throw new NullPointerException();
3718 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3719 >        V v; U u;
3720 >        while ((v = it.advance()) != null) {
3721 >            if ((u = transformer.apply(v)) != null)
3722 >                action.apply(u);
3723          }
3724 +    }
3725  
3726 <        /**
3727 <         * Returns the result of accumulating all keys using the given
3728 <         * reducer to combine values, or null if none.
3729 <         *
3730 <         * @param reducer a commutative associative combining function
3731 <         * @return the result of accumulating all keys using the given
3732 <         * reducer to combine values, or null if none
3733 <         */
3734 <        public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3735 <            return fjp.invoke(ForkJoinTasks.reduceKeys
3736 <                              (ConcurrentHashMapV8.this, reducer));
3726 >    /**
3727 >     * Returns a non-null result from applying the given search
3728 >     * function on each value, or null if none.
3729 >     *
3730 >     * @param searchFunction a function returning a non-null
3731 >     * result on success, else null
3732 >     * @return a non-null result from applying the given search
3733 >     * function on each value, or null if none
3734 >     */
3735 >    public <U> U searchValuesSequentially
3736 >        (Fun<? super V, ? extends U> searchFunction) {
3737 >        if (searchFunction == null) throw new NullPointerException();
3738 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3739 >        V v; U u;
3740 >        while ((v = it.advance()) != null) {
3741 >            if ((u = searchFunction.apply(v)) != null)
3742 >                return u;
3743          }
3744 +        return null;
3745 +    }
3746  
3747 <        /**
3748 <         * Returns the result of accumulating the given transformation
3749 <         * of all keys using the given reducer to combine values, or
3750 <         * null if none.
3751 <         *
3752 <         * @param transformer a function returning the transformation
3753 <         * for an element, or null of there is no transformation (in
3754 <         * which case it is not combined).
3755 <         * @param reducer a commutative associative combining function
3756 <         * @return the result of accumulating the given transformation
3757 <         * of all keys
3758 <         */
3759 <        public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3760 <                                BiFun<? super U, ? super U, ? extends U> reducer) {
3761 <            return fjp.invoke(ForkJoinTasks.reduceKeys
3762 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3747 >    /**
3748 >     * Returns the result of accumulating all values using the
3749 >     * given reducer to combine values, or null if none.
3750 >     *
3751 >     * @param reducer a commutative associative combining function
3752 >     * @return  the result of accumulating all values
3753 >     */
3754 >    public V reduceValuesSequentially
3755 >        (BiFun<? super V, ? super V, ? extends V> reducer) {
3756 >        if (reducer == null) throw new NullPointerException();
3757 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3758 >        V r = null; V v;
3759 >        while ((v = it.advance()) != null)
3760 >            r = (r == null) ? v : reducer.apply(r, v);
3761 >        return r;
3762 >    }
3763 >
3764 >    /**
3765 >     * Returns the result of accumulating the given transformation
3766 >     * of all values using the given reducer to combine values, or
3767 >     * null if none.
3768 >     *
3769 >     * @param transformer a function returning the transformation
3770 >     * for an element, or null if there is no transformation (in
3771 >     * which case it is not combined)
3772 >     * @param reducer a commutative associative combining function
3773 >     * @return the result of accumulating the given transformation
3774 >     * of all values
3775 >     */
3776 >    public <U> U reduceValuesSequentially
3777 >        (Fun<? super V, ? extends U> transformer,
3778 >         BiFun<? super U, ? super U, ? extends U> reducer) {
3779 >        if (transformer == null || reducer == null)
3780 >            throw new NullPointerException();
3781 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3782 >        U r = null, u; V v;
3783 >        while ((v = it.advance()) != null) {
3784 >            if ((u = transformer.apply(v)) != null)
3785 >                r = (r == null) ? u : reducer.apply(r, u);
3786          }
3787 +        return r;
3788 +    }
3789  
3790 <        /**
3791 <         * Returns the result of accumulating the given transformation
3792 <         * of all keys using the given reducer to combine values, and
3793 <         * the given basis as an identity value.
3794 <         *
3795 <         * @param transformer a function returning the transformation
3796 <         * for an element
3797 <         * @param basis the identity (initial default value) for the reduction
3798 <         * @param reducer a commutative associative combining function
3799 <         * @return  the result of accumulating the given transformation
3800 <         * of all keys
3801 <         */
3802 <        public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3803 <                                         double basis,
3804 <                                         DoubleByDoubleToDouble reducer) {
3805 <            return fjp.invoke(ForkJoinTasks.reduceKeysToDouble
3806 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3790 >    /**
3791 >     * Returns the result of accumulating the given transformation
3792 >     * of all values using the given reducer to combine values,
3793 >     * and the given basis as an identity value.
3794 >     *
3795 >     * @param transformer a function returning the transformation
3796 >     * for an element
3797 >     * @param basis the identity (initial default value) for the reduction
3798 >     * @param reducer a commutative associative combining function
3799 >     * @return the result of accumulating the given transformation
3800 >     * of all values
3801 >     */
3802 >    public double reduceValuesToDoubleSequentially
3803 >        (ObjectToDouble<? super V> transformer,
3804 >         double basis,
3805 >         DoubleByDoubleToDouble reducer) {
3806 >        if (transformer == null || reducer == null)
3807 >            throw new NullPointerException();
3808 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3809 >        double r = basis; V v;
3810 >        while ((v = it.advance()) != null)
3811 >            r = reducer.apply(r, transformer.apply(v));
3812 >        return r;
3813 >    }
3814 >
3815 >    /**
3816 >     * Returns the result of accumulating the given transformation
3817 >     * of all values using the given reducer to combine values,
3818 >     * and the given basis as an identity value.
3819 >     *
3820 >     * @param transformer a function returning the transformation
3821 >     * for an element
3822 >     * @param basis the identity (initial default value) for the reduction
3823 >     * @param reducer a commutative associative combining function
3824 >     * @return the result of accumulating the given transformation
3825 >     * of all values
3826 >     */
3827 >    public long reduceValuesToLongSequentially
3828 >        (ObjectToLong<? super V> transformer,
3829 >         long basis,
3830 >         LongByLongToLong reducer) {
3831 >        if (transformer == null || reducer == null)
3832 >            throw new NullPointerException();
3833 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3834 >        long r = basis; V v;
3835 >        while ((v = it.advance()) != null)
3836 >            r = reducer.apply(r, transformer.apply(v));
3837 >        return r;
3838 >    }
3839 >
3840 >    /**
3841 >     * Returns the result of accumulating the given transformation
3842 >     * of all values using the given reducer to combine values,
3843 >     * and the given basis as an identity value.
3844 >     *
3845 >     * @param transformer a function returning the transformation
3846 >     * for an element
3847 >     * @param basis the identity (initial default value) for the reduction
3848 >     * @param reducer a commutative associative combining function
3849 >     * @return the result of accumulating the given transformation
3850 >     * of all values
3851 >     */
3852 >    public int reduceValuesToIntSequentially
3853 >        (ObjectToInt<? super V> transformer,
3854 >         int basis,
3855 >         IntByIntToInt reducer) {
3856 >        if (transformer == null || reducer == null)
3857 >            throw new NullPointerException();
3858 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3859 >        int r = basis; V v;
3860 >        while ((v = it.advance()) != null)
3861 >            r = reducer.apply(r, transformer.apply(v));
3862 >        return r;
3863 >    }
3864 >
3865 >    /**
3866 >     * Performs the given action for each entry.
3867 >     *
3868 >     * @param action the action
3869 >     */
3870 >    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3871 >        (Action<Map.Entry<K,V>> action) {
3872 >        if (action == null) throw new NullPointerException();
3873 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874 >        V v;
3875 >        while ((v = it.advance()) != null)
3876 >            action.apply(entryFor((K)it.nextKey, v));
3877 >    }
3878 >
3879 >    /**
3880 >     * Performs the given action for each non-null transformation
3881 >     * of each entry.
3882 >     *
3883 >     * @param transformer a function returning the transformation
3884 >     * for an element, or null if there is no transformation (in
3885 >     * which case the action is not applied)
3886 >     * @param action the action
3887 >     */
3888 >    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3889 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3890 >         Action<U> action) {
3891 >        if (transformer == null || action == null)
3892 >            throw new NullPointerException();
3893 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3894 >        V v; U u;
3895 >        while ((v = it.advance()) != null) {
3896 >            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3897 >                action.apply(u);
3898          }
3899 +    }
3900  
3901 <        /**
3902 <         * Returns the result of accumulating the given transformation
3903 <         * of all keys using the given reducer to combine values, and
3904 <         * the given basis as an identity value.
3905 <         *
3906 <         * @param transformer a function returning the transformation
3907 <         * for an element
3908 <         * @param basis the identity (initial default value) for the reduction
3909 <         * @param reducer a commutative associative combining function
3910 <         * @return the result of accumulating the given transformation
3911 <         * of all keys
3912 <         */
3913 <        public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3914 <                                     long basis,
3915 <                                     LongByLongToLong reducer) {
3916 <            return fjp.invoke(ForkJoinTasks.reduceKeysToLong
3917 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3901 >    /**
3902 >     * Returns a non-null result from applying the given search
3903 >     * function on each entry, or null if none.
3904 >     *
3905 >     * @param searchFunction a function returning a non-null
3906 >     * result on success, else null
3907 >     * @return a non-null result from applying the given search
3908 >     * function on each entry, or null if none
3909 >     */
3910 >    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
3911 >        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3912 >        if (searchFunction == null) throw new NullPointerException();
3913 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3914 >        V v; U u;
3915 >        while ((v = it.advance()) != null) {
3916 >            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3917 >                return u;
3918          }
3919 +        return null;
3920 +    }
3921  
3922 <        /**
3923 <         * Returns the result of accumulating the given transformation
3924 <         * of all keys using the given reducer to combine values, and
3925 <         * the given basis as an identity value.
3926 <         *
3927 <         * @param transformer a function returning the transformation
3928 <         * for an element
3929 <         * @param basis the identity (initial default value) for the reduction
3930 <         * @param reducer a commutative associative combining function
3931 <         * @return the result of accumulating the given transformation
3932 <         * of all keys
3933 <         */
3934 <        public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3935 <                                   int basis,
3936 <                                   IntByIntToInt reducer) {
3889 <            return fjp.invoke(ForkJoinTasks.reduceKeysToInt
3890 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3922 >    /**
3923 >     * Returns the result of accumulating all entries using the
3924 >     * given reducer to combine values, or null if none.
3925 >     *
3926 >     * @param reducer a commutative associative combining function
3927 >     * @return the result of accumulating all entries
3928 >     */
3929 >    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
3930 >        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3931 >        if (reducer == null) throw new NullPointerException();
3932 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3933 >        Map.Entry<K,V> r = null; V v;
3934 >        while ((v = it.advance()) != null) {
3935 >            Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3936 >            r = (r == null) ? u : reducer.apply(r, u);
3937          }
3938 +        return r;
3939 +    }
3940  
3941 <        /**
3942 <         * Performs the given action for each value.
3943 <         *
3944 <         * @param action the action
3945 <         */
3946 <        public void forEachValue(Action<V> action) {
3947 <            fjp.invoke(ForkJoinTasks.forEachValue
3948 <                       (ConcurrentHashMapV8.this, action));
3941 >    /**
3942 >     * Returns the result of accumulating the given transformation
3943 >     * of all entries using the given reducer to combine values,
3944 >     * or null if none.
3945 >     *
3946 >     * @param transformer a function returning the transformation
3947 >     * for an element, or null if there is no transformation (in
3948 >     * which case it is not combined)
3949 >     * @param reducer a commutative associative combining function
3950 >     * @return the result of accumulating the given transformation
3951 >     * of all entries
3952 >     */
3953 >    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
3954 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3955 >         BiFun<? super U, ? super U, ? extends U> reducer) {
3956 >        if (transformer == null || reducer == null)
3957 >            throw new NullPointerException();
3958 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3959 >        U r = null, u; V v;
3960 >        while ((v = it.advance()) != null) {
3961 >            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3962 >                r = (r == null) ? u : reducer.apply(r, u);
3963          }
3964 +        return r;
3965 +    }
3966 +
3967 +    /**
3968 +     * Returns the result of accumulating the given transformation
3969 +     * of all entries using the given reducer to combine values,
3970 +     * and the given basis as an identity value.
3971 +     *
3972 +     * @param transformer a function returning the transformation
3973 +     * for an element
3974 +     * @param basis the identity (initial default value) for the reduction
3975 +     * @param reducer a commutative associative combining function
3976 +     * @return the result of accumulating the given transformation
3977 +     * of all entries
3978 +     */
3979 +    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
3980 +        (ObjectToDouble<Map.Entry<K,V>> transformer,
3981 +         double basis,
3982 +         DoubleByDoubleToDouble reducer) {
3983 +        if (transformer == null || reducer == null)
3984 +            throw new NullPointerException();
3985 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3986 +        double r = basis; V v;
3987 +        while ((v = it.advance()) != null)
3988 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3989 +        return r;
3990 +    }
3991 +
3992 +    /**
3993 +     * Returns the result of accumulating the given transformation
3994 +     * of all entries using the given reducer to combine values,
3995 +     * and the given basis as an identity value.
3996 +     *
3997 +     * @param transformer a function returning the transformation
3998 +     * for an element
3999 +     * @param basis the identity (initial default value) for the reduction
4000 +     * @param reducer a commutative associative combining function
4001 +     * @return  the result of accumulating the given transformation
4002 +     * of all entries
4003 +     */
4004 +    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4005 +        (ObjectToLong<Map.Entry<K,V>> transformer,
4006 +         long basis,
4007 +         LongByLongToLong reducer) {
4008 +        if (transformer == null || reducer == null)
4009 +            throw new NullPointerException();
4010 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4011 +        long r = basis; V v;
4012 +        while ((v = it.advance()) != null)
4013 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4014 +        return r;
4015 +    }
4016 +
4017 +    /**
4018 +     * Returns the result of accumulating the given transformation
4019 +     * of all entries using the given reducer to combine values,
4020 +     * and the given basis as an identity value.
4021 +     *
4022 +     * @param transformer a function returning the transformation
4023 +     * for an element
4024 +     * @param basis the identity (initial default value) for the reduction
4025 +     * @param reducer a commutative associative combining function
4026 +     * @return the result of accumulating the given transformation
4027 +     * of all entries
4028 +     */
4029 +    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4030 +        (ObjectToInt<Map.Entry<K,V>> transformer,
4031 +         int basis,
4032 +         IntByIntToInt reducer) {
4033 +        if (transformer == null || reducer == null)
4034 +            throw new NullPointerException();
4035 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4036 +        int r = basis; V v;
4037 +        while ((v = it.advance()) != null)
4038 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4039 +        return r;
4040 +    }
4041 +
4042 +    // Parallel bulk operations
4043 +
4044 +    /**
4045 +     * Performs the given action for each (key, value).
4046 +     *
4047 +     * @param action the action
4048 +     */
4049 +    public void forEachInParallel(BiAction<K,V> action) {
4050 +        ForkJoinTasks.forEach
4051 +            (this, action).invoke();
4052 +    }
4053 +
4054 +    /**
4055 +     * Performs the given action for each non-null transformation
4056 +     * of each (key, value).
4057 +     *
4058 +     * @param transformer a function returning the transformation
4059 +     * for an element, or null if there is no transformation (in
4060 +     * which case the action is not applied)
4061 +     * @param action the action
4062 +     */
4063 +    public <U> void forEachInParallel
4064 +        (BiFun<? super K, ? super V, ? extends U> transformer,
4065 +                            Action<U> action) {
4066 +        ForkJoinTasks.forEach
4067 +            (this, transformer, action).invoke();
4068 +    }
4069 +
4070 +    /**
4071 +     * Returns a non-null result from applying the given search
4072 +     * function on each (key, value), or null if none.  Upon
4073 +     * success, further element processing is suppressed and the
4074 +     * results of any other parallel invocations of the search
4075 +     * function are ignored.
4076 +     *
4077 +     * @param searchFunction a function returning a non-null
4078 +     * result on success, else null
4079 +     * @return a non-null result from applying the given search
4080 +     * function on each (key, value), or null if none
4081 +     */
4082 +    public <U> U searchInParallel
4083 +        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4084 +        return ForkJoinTasks.search
4085 +            (this, searchFunction).invoke();
4086 +    }
4087 +
4088 +    /**
4089 +     * Returns the result of accumulating the given transformation
4090 +     * of all (key, value) pairs using the given reducer to
4091 +     * combine values, or null if none.
4092 +     *
4093 +     * @param transformer a function returning the transformation
4094 +     * for an element, or null if there is no transformation (in
4095 +     * which case it is not combined)
4096 +     * @param reducer a commutative associative combining function
4097 +     * @return the result of accumulating the given transformation
4098 +     * of all (key, value) pairs
4099 +     */
4100 +    public <U> U reduceInParallel
4101 +        (BiFun<? super K, ? super V, ? extends U> transformer,
4102 +         BiFun<? super U, ? super U, ? extends U> reducer) {
4103 +        return ForkJoinTasks.reduce
4104 +            (this, transformer, reducer).invoke();
4105 +    }
4106 +
4107 +    /**
4108 +     * Returns the result of accumulating the given transformation
4109 +     * of all (key, value) pairs using the given reducer to
4110 +     * combine values, and the given basis as an identity value.
4111 +     *
4112 +     * @param transformer a function returning the transformation
4113 +     * for an element
4114 +     * @param basis the identity (initial default value) for the reduction
4115 +     * @param reducer a commutative associative combining function
4116 +     * @return the result of accumulating the given transformation
4117 +     * of all (key, value) pairs
4118 +     */
4119 +    public double reduceToDoubleInParallel
4120 +        (ObjectByObjectToDouble<? super K, ? super V> transformer,
4121 +         double basis,
4122 +         DoubleByDoubleToDouble reducer) {
4123 +        return ForkJoinTasks.reduceToDouble
4124 +            (this, transformer, basis, reducer).invoke();
4125 +    }
4126 +
4127 +    /**
4128 +     * Returns the result of accumulating the given transformation
4129 +     * of all (key, value) pairs using the given reducer to
4130 +     * combine values, and the given basis as an identity value.
4131 +     *
4132 +     * @param transformer a function returning the transformation
4133 +     * for an element
4134 +     * @param basis the identity (initial default value) for the reduction
4135 +     * @param reducer a commutative associative combining function
4136 +     * @return the result of accumulating the given transformation
4137 +     * of all (key, value) pairs
4138 +     */
4139 +    public long reduceToLongInParallel
4140 +        (ObjectByObjectToLong<? super K, ? super V> transformer,
4141 +         long basis,
4142 +         LongByLongToLong reducer) {
4143 +        return ForkJoinTasks.reduceToLong
4144 +            (this, transformer, basis, reducer).invoke();
4145 +    }
4146 +
4147 +    /**
4148 +     * Returns the result of accumulating the given transformation
4149 +     * of all (key, value) pairs using the given reducer to
4150 +     * combine values, and the given basis as an identity value.
4151 +     *
4152 +     * @param transformer a function returning the transformation
4153 +     * for an element
4154 +     * @param basis the identity (initial default value) for the reduction
4155 +     * @param reducer a commutative associative combining function
4156 +     * @return the result of accumulating the given transformation
4157 +     * of all (key, value) pairs
4158 +     */
4159 +    public int reduceToIntInParallel
4160 +        (ObjectByObjectToInt<? super K, ? super V> transformer,
4161 +         int basis,
4162 +         IntByIntToInt reducer) {
4163 +        return ForkJoinTasks.reduceToInt
4164 +            (this, transformer, basis, reducer).invoke();
4165 +    }
4166 +
4167 +    /**
4168 +     * Performs the given action for each key.
4169 +     *
4170 +     * @param action the action
4171 +     */
4172 +    public void forEachKeyInParallel(Action<K> action) {
4173 +        ForkJoinTasks.forEachKey
4174 +            (this, action).invoke();
4175 +    }
4176 +
4177 +    /**
4178 +     * Performs the given action for each non-null transformation
4179 +     * of each key.
4180 +     *
4181 +     * @param transformer a function returning the transformation
4182 +     * for an element, or null if there is no transformation (in
4183 +     * which case the action is not applied)
4184 +     * @param action the action
4185 +     */
4186 +    public <U> void forEachKeyInParallel
4187 +        (Fun<? super K, ? extends U> transformer,
4188 +         Action<U> action) {
4189 +        ForkJoinTasks.forEachKey
4190 +            (this, transformer, action).invoke();
4191 +    }
4192 +
4193 +    /**
4194 +     * Returns a non-null result from applying the given search
4195 +     * function on each key, or null if none. Upon success,
4196 +     * further element processing is suppressed and the results of
4197 +     * any other parallel invocations of the search function are
4198 +     * ignored.
4199 +     *
4200 +     * @param searchFunction a function returning a non-null
4201 +     * result on success, else null
4202 +     * @return a non-null result from applying the given search
4203 +     * function on each key, or null if none
4204 +     */
4205 +    public <U> U searchKeysInParallel
4206 +        (Fun<? super K, ? extends U> searchFunction) {
4207 +        return ForkJoinTasks.searchKeys
4208 +            (this, searchFunction).invoke();
4209 +    }
4210 +
4211 +    /**
4212 +     * Returns the result of accumulating all keys using the given
4213 +     * reducer to combine values, or null if none.
4214 +     *
4215 +     * @param reducer a commutative associative combining function
4216 +     * @return the result of accumulating all keys using the given
4217 +     * reducer to combine values, or null if none
4218 +     */
4219 +    public K reduceKeysInParallel
4220 +        (BiFun<? super K, ? super K, ? extends K> reducer) {
4221 +        return ForkJoinTasks.reduceKeys
4222 +            (this, reducer).invoke();
4223 +    }
4224 +
4225 +    /**
4226 +     * Returns the result of accumulating the given transformation
4227 +     * of all keys using the given reducer to combine values, or
4228 +     * null if none.
4229 +     *
4230 +     * @param transformer a function returning the transformation
4231 +     * for an element, or null if there is no transformation (in
4232 +     * which case it is not combined)
4233 +     * @param reducer a commutative associative combining function
4234 +     * @return the result of accumulating the given transformation
4235 +     * of all keys
4236 +     */
4237 +    public <U> U reduceKeysInParallel
4238 +        (Fun<? super K, ? extends U> transformer,
4239 +         BiFun<? super U, ? super U, ? extends U> reducer) {
4240 +        return ForkJoinTasks.reduceKeys
4241 +            (this, transformer, reducer).invoke();
4242 +    }
4243 +
4244 +    /**
4245 +     * Returns the result of accumulating the given transformation
4246 +     * of all keys using the given reducer to combine values, and
4247 +     * the given basis as an identity value.
4248 +     *
4249 +     * @param transformer a function returning the transformation
4250 +     * for an element
4251 +     * @param basis the identity (initial default value) for the reduction
4252 +     * @param reducer a commutative associative combining function
4253 +     * @return  the result of accumulating the given transformation
4254 +     * of all keys
4255 +     */
4256 +    public double reduceKeysToDoubleInParallel
4257 +        (ObjectToDouble<? super K> transformer,
4258 +         double basis,
4259 +         DoubleByDoubleToDouble reducer) {
4260 +        return ForkJoinTasks.reduceKeysToDouble
4261 +            (this, transformer, basis, reducer).invoke();
4262 +    }
4263 +
4264 +    /**
4265 +     * Returns the result of accumulating the given transformation
4266 +     * of all keys using the given reducer to combine values, and
4267 +     * the given basis as an identity value.
4268 +     *
4269 +     * @param transformer a function returning the transformation
4270 +     * for an element
4271 +     * @param basis the identity (initial default value) for the reduction
4272 +     * @param reducer a commutative associative combining function
4273 +     * @return the result of accumulating the given transformation
4274 +     * of all keys
4275 +     */
4276 +    public long reduceKeysToLongInParallel
4277 +        (ObjectToLong<? super K> transformer,
4278 +         long basis,
4279 +         LongByLongToLong reducer) {
4280 +        return ForkJoinTasks.reduceKeysToLong
4281 +            (this, transformer, basis, reducer).invoke();
4282 +    }
4283 +
4284 +    /**
4285 +     * Returns the result of accumulating the given transformation
4286 +     * of all keys using the given reducer to combine values, and
4287 +     * the given basis as an identity value.
4288 +     *
4289 +     * @param transformer a function returning the transformation
4290 +     * for an element
4291 +     * @param basis the identity (initial default value) for the reduction
4292 +     * @param reducer a commutative associative combining function
4293 +     * @return the result of accumulating the given transformation
4294 +     * of all keys
4295 +     */
4296 +    public int reduceKeysToIntInParallel
4297 +        (ObjectToInt<? super K> transformer,
4298 +         int basis,
4299 +         IntByIntToInt reducer) {
4300 +        return ForkJoinTasks.reduceKeysToInt
4301 +            (this, transformer, basis, reducer).invoke();
4302 +    }
4303 +
4304 +    /**
4305 +     * Performs the given action for each value.
4306 +     *
4307 +     * @param action the action
4308 +     */
4309 +    public void forEachValueInParallel(Action<V> action) {
4310 +        ForkJoinTasks.forEachValue
4311 +            (this, action).invoke();
4312 +    }
4313 +
4314 +    /**
4315 +     * Performs the given action for each non-null transformation
4316 +     * of each value.
4317 +     *
4318 +     * @param transformer a function returning the transformation
4319 +     * for an element, or null if there is no transformation (in
4320 +     * which case the action is not applied)
4321 +     */
4322 +    public <U> void forEachValueInParallel
4323 +        (Fun<? super V, ? extends U> transformer,
4324 +         Action<U> action) {
4325 +        ForkJoinTasks.forEachValue
4326 +            (this, transformer, action).invoke();
4327 +    }
4328 +
4329 +    /**
4330 +     * Returns a non-null result from applying the given search
4331 +     * function on each value, or null if none.  Upon success,
4332 +     * further element processing is suppressed and the results of
4333 +     * any other parallel invocations of the search function are
4334 +     * ignored.
4335 +     *
4336 +     * @param searchFunction a function returning a non-null
4337 +     * result on success, else null
4338 +     * @return a non-null result from applying the given search
4339 +     * function on each value, or null if none
4340 +     */
4341 +    public <U> U searchValuesInParallel
4342 +        (Fun<? super V, ? extends U> searchFunction) {
4343 +        return ForkJoinTasks.searchValues
4344 +            (this, searchFunction).invoke();
4345 +    }
4346 +
4347 +    /**
4348 +     * Returns the result of accumulating all values using the
4349 +     * given reducer to combine values, or null if none.
4350 +     *
4351 +     * @param reducer a commutative associative combining function
4352 +     * @return  the result of accumulating all values
4353 +     */
4354 +    public V reduceValuesInParallel
4355 +        (BiFun<? super V, ? super V, ? extends V> reducer) {
4356 +        return ForkJoinTasks.reduceValues
4357 +            (this, reducer).invoke();
4358 +    }
4359 +
4360 +    /**
4361 +     * Returns the result of accumulating the given transformation
4362 +     * of all values using the given reducer to combine values, or
4363 +     * null if none.
4364 +     *
4365 +     * @param transformer a function returning the transformation
4366 +     * for an element, or null if there is no transformation (in
4367 +     * which case it is not combined)
4368 +     * @param reducer a commutative associative combining function
4369 +     * @return the result of accumulating the given transformation
4370 +     * of all values
4371 +     */
4372 +    public <U> U reduceValuesInParallel
4373 +        (Fun<? super V, ? extends U> transformer,
4374 +         BiFun<? super U, ? super U, ? extends U> reducer) {
4375 +        return ForkJoinTasks.reduceValues
4376 +            (this, transformer, reducer).invoke();
4377 +    }
4378 +
4379 +    /**
4380 +     * Returns the result of accumulating the given transformation
4381 +     * of all values using the given reducer to combine values,
4382 +     * and the given basis as an identity value.
4383 +     *
4384 +     * @param transformer a function returning the transformation
4385 +     * for an element
4386 +     * @param basis the identity (initial default value) for the reduction
4387 +     * @param reducer a commutative associative combining function
4388 +     * @return the result of accumulating the given transformation
4389 +     * of all values
4390 +     */
4391 +    public double reduceValuesToDoubleInParallel
4392 +        (ObjectToDouble<? super V> transformer,
4393 +         double basis,
4394 +         DoubleByDoubleToDouble reducer) {
4395 +        return ForkJoinTasks.reduceValuesToDouble
4396 +            (this, transformer, basis, reducer).invoke();
4397 +    }
4398 +
4399 +    /**
4400 +     * Returns the result of accumulating the given transformation
4401 +     * of all values using the given reducer to combine values,
4402 +     * and the given basis as an identity value.
4403 +     *
4404 +     * @param transformer a function returning the transformation
4405 +     * for an element
4406 +     * @param basis the identity (initial default value) for the reduction
4407 +     * @param reducer a commutative associative combining function
4408 +     * @return the result of accumulating the given transformation
4409 +     * of all values
4410 +     */
4411 +    public long reduceValuesToLongInParallel
4412 +        (ObjectToLong<? super V> transformer,
4413 +         long basis,
4414 +         LongByLongToLong reducer) {
4415 +        return ForkJoinTasks.reduceValuesToLong
4416 +            (this, transformer, basis, reducer).invoke();
4417 +    }
4418 +
4419 +    /**
4420 +     * Returns the result of accumulating the given transformation
4421 +     * of all values using the given reducer to combine values,
4422 +     * and the given basis as an identity value.
4423 +     *
4424 +     * @param transformer a function returning the transformation
4425 +     * for an element
4426 +     * @param basis the identity (initial default value) for the reduction
4427 +     * @param reducer a commutative associative combining function
4428 +     * @return the result of accumulating the given transformation
4429 +     * of all values
4430 +     */
4431 +    public int reduceValuesToIntInParallel
4432 +        (ObjectToInt<? super V> transformer,
4433 +         int basis,
4434 +         IntByIntToInt reducer) {
4435 +        return ForkJoinTasks.reduceValuesToInt
4436 +            (this, transformer, basis, reducer).invoke();
4437 +    }
4438 +
4439 +    /**
4440 +     * Performs the given action for each entry.
4441 +     *
4442 +     * @param action the action
4443 +     */
4444 +    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4445 +        ForkJoinTasks.forEachEntry
4446 +            (this, action).invoke();
4447 +    }
4448 +
4449 +    /**
4450 +     * Performs the given action for each non-null transformation
4451 +     * of each entry.
4452 +     *
4453 +     * @param transformer a function returning the transformation
4454 +     * for an element, or null if there is no transformation (in
4455 +     * which case the action is not applied)
4456 +     * @param action the action
4457 +     */
4458 +    public <U> void forEachEntryInParallel
4459 +        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4460 +         Action<U> action) {
4461 +        ForkJoinTasks.forEachEntry
4462 +            (this, transformer, action).invoke();
4463 +    }
4464 +
4465 +    /**
4466 +     * Returns a non-null result from applying the given search
4467 +     * function on each entry, or null if none.  Upon success,
4468 +     * further element processing is suppressed and the results of
4469 +     * any other parallel invocations of the search function are
4470 +     * ignored.
4471 +     *
4472 +     * @param searchFunction a function returning a non-null
4473 +     * result on success, else null
4474 +     * @return a non-null result from applying the given search
4475 +     * function on each entry, or null if none
4476 +     */
4477 +    public <U> U searchEntriesInParallel
4478 +        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4479 +        return ForkJoinTasks.searchEntries
4480 +            (this, searchFunction).invoke();
4481 +    }
4482 +
4483 +    /**
4484 +     * Returns the result of accumulating all entries using the
4485 +     * given reducer to combine values, or null if none.
4486 +     *
4487 +     * @param reducer a commutative associative combining function
4488 +     * @return the result of accumulating all entries
4489 +     */
4490 +    public Map.Entry<K,V> reduceEntriesInParallel
4491 +        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4492 +        return ForkJoinTasks.reduceEntries
4493 +            (this, reducer).invoke();
4494 +    }
4495 +
4496 +    /**
4497 +     * Returns the result of accumulating the given transformation
4498 +     * of all entries using the given reducer to combine values,
4499 +     * or null if none.
4500 +     *
4501 +     * @param transformer a function returning the transformation
4502 +     * for an element, or null if there is no transformation (in
4503 +     * which case it is not combined)
4504 +     * @param reducer a commutative associative combining function
4505 +     * @return the result of accumulating the given transformation
4506 +     * of all entries
4507 +     */
4508 +    public <U> U reduceEntriesInParallel
4509 +        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4510 +         BiFun<? super U, ? super U, ? extends U> reducer) {
4511 +        return ForkJoinTasks.reduceEntries
4512 +            (this, transformer, reducer).invoke();
4513 +    }
4514 +
4515 +    /**
4516 +     * Returns the result of accumulating the given transformation
4517 +     * of all entries using the given reducer to combine values,
4518 +     * and the given basis as an identity value.
4519 +     *
4520 +     * @param transformer a function returning the transformation
4521 +     * for an element
4522 +     * @param basis the identity (initial default value) for the reduction
4523 +     * @param reducer a commutative associative combining function
4524 +     * @return the result of accumulating the given transformation
4525 +     * of all entries
4526 +     */
4527 +    public double reduceEntriesToDoubleInParallel
4528 +        (ObjectToDouble<Map.Entry<K,V>> transformer,
4529 +         double basis,
4530 +         DoubleByDoubleToDouble reducer) {
4531 +        return ForkJoinTasks.reduceEntriesToDouble
4532 +            (this, transformer, basis, reducer).invoke();
4533 +    }
4534 +
4535 +    /**
4536 +     * Returns the result of accumulating the given transformation
4537 +     * of all entries using the given reducer to combine values,
4538 +     * and the given basis as an identity value.
4539 +     *
4540 +     * @param transformer a function returning the transformation
4541 +     * for an element
4542 +     * @param basis the identity (initial default value) for the reduction
4543 +     * @param reducer a commutative associative combining function
4544 +     * @return  the result of accumulating the given transformation
4545 +     * of all entries
4546 +     */
4547 +    public long reduceEntriesToLongInParallel
4548 +        (ObjectToLong<Map.Entry<K,V>> transformer,
4549 +         long basis,
4550 +         LongByLongToLong reducer) {
4551 +        return ForkJoinTasks.reduceEntriesToLong
4552 +            (this, transformer, basis, reducer).invoke();
4553 +    }
4554 +
4555 +    /**
4556 +     * Returns the result of accumulating the given transformation
4557 +     * of all entries using the given reducer to combine values,
4558 +     * and the given basis as an identity value.
4559 +     *
4560 +     * @param transformer a function returning the transformation
4561 +     * for an element
4562 +     * @param basis the identity (initial default value) for the reduction
4563 +     * @param reducer a commutative associative combining function
4564 +     * @return the result of accumulating the given transformation
4565 +     * of all entries
4566 +     */
4567 +    public int reduceEntriesToIntInParallel
4568 +        (ObjectToInt<Map.Entry<K,V>> transformer,
4569 +         int basis,
4570 +         IntByIntToInt reducer) {
4571 +        return ForkJoinTasks.reduceEntriesToInt
4572 +            (this, transformer, basis, reducer).invoke();
4573 +    }
4574 +
4575 +
4576 +    /* ----------------Views -------------- */
4577 +
4578 +    /**
4579 +     * Base class for views.
4580 +     */
4581 +    abstract static class CHMView<K, V> {
4582 +        final ConcurrentHashMapV8<K, V> map;
4583 +        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4584  
4585          /**
4586 <         * Performs the given action for each non-null transformation
3905 <         * of each value.
4586 >         * Returns the map backing this view.
4587           *
4588 <         * @param transformer a function returning the transformation
3908 <         * for an element, or null of there is no transformation (in
3909 <         * which case the action is not applied).
4588 >         * @return the map backing this view
4589           */
4590 <        public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4591 <                                     Action<U> action) {
4592 <            fjp.invoke(ForkJoinTasks.forEachValue
4593 <                       (ConcurrentHashMapV8.this, transformer, action));
4590 >        public ConcurrentHashMapV8<K,V> getMap() { return map; }
4591 >
4592 >        public final int size()                 { return map.size(); }
4593 >        public final boolean isEmpty()          { return map.isEmpty(); }
4594 >        public final void clear()               { map.clear(); }
4595 >
4596 >        // implementations below rely on concrete classes supplying these
4597 >        public abstract Iterator<?> iterator();
4598 >        public abstract boolean contains(Object o);
4599 >        public abstract boolean remove(Object o);
4600 >
4601 >        private static final String oomeMsg = "Required array size too large";
4602 >
4603 >        public final Object[] toArray() {
4604 >            long sz = map.mappingCount();
4605 >            if (sz > (long)(MAX_ARRAY_SIZE))
4606 >                throw new OutOfMemoryError(oomeMsg);
4607 >            int n = (int)sz;
4608 >            Object[] r = new Object[n];
4609 >            int i = 0;
4610 >            Iterator<?> it = iterator();
4611 >            while (it.hasNext()) {
4612 >                if (i == n) {
4613 >                    if (n >= MAX_ARRAY_SIZE)
4614 >                        throw new OutOfMemoryError(oomeMsg);
4615 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4616 >                        n = MAX_ARRAY_SIZE;
4617 >                    else
4618 >                        n += (n >>> 1) + 1;
4619 >                    r = Arrays.copyOf(r, n);
4620 >                }
4621 >                r[i++] = it.next();
4622 >            }
4623 >            return (i == n) ? r : Arrays.copyOf(r, i);
4624          }
4625  
4626 <        /**
4627 <         * Returns a non-null result from applying the given search
4628 <         * function on each value, or null if none.  Upon success,
4629 <         * further element processing is suppressed and the results of
4630 <         * any other parallel invocations of the search function are
4631 <         * ignored.
4632 <         *
4633 <         * @param searchFunction a function returning a non-null
4634 <         * result on success, else null
4635 <         * @return a non-null result from applying the given search
4636 <         * function on each value, or null if none
4637 <         *
4638 <         */
4639 <        public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4640 <            return fjp.invoke(ForkJoinTasks.searchValues
4641 <                              (ConcurrentHashMapV8.this, searchFunction));
4626 >        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4627 >            long sz = map.mappingCount();
4628 >            if (sz > (long)(MAX_ARRAY_SIZE))
4629 >                throw new OutOfMemoryError(oomeMsg);
4630 >            int m = (int)sz;
4631 >            T[] r = (a.length >= m) ? a :
4632 >                (T[])java.lang.reflect.Array
4633 >                .newInstance(a.getClass().getComponentType(), m);
4634 >            int n = r.length;
4635 >            int i = 0;
4636 >            Iterator<?> it = iterator();
4637 >            while (it.hasNext()) {
4638 >                if (i == n) {
4639 >                    if (n >= MAX_ARRAY_SIZE)
4640 >                        throw new OutOfMemoryError(oomeMsg);
4641 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4642 >                        n = MAX_ARRAY_SIZE;
4643 >                    else
4644 >                        n += (n >>> 1) + 1;
4645 >                    r = Arrays.copyOf(r, n);
4646 >                }
4647 >                r[i++] = (T)it.next();
4648 >            }
4649 >            if (a == r && i < n) {
4650 >                r[i] = null; // null-terminate
4651 >                return r;
4652 >            }
4653 >            return (i == n) ? r : Arrays.copyOf(r, i);
4654          }
4655  
4656 <        /**
4657 <         * Returns the result of accumulating all values using the
4658 <         * given reducer to combine values, or null if none.
4659 <         *
4660 <         * @param reducer a commutative associative combining function
3940 <         * @return  the result of accumulating all values
3941 <         */
3942 <        public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3943 <            return fjp.invoke(ForkJoinTasks.reduceValues
3944 <                              (ConcurrentHashMapV8.this, reducer));
4656 >        public final int hashCode() {
4657 >            int h = 0;
4658 >            for (Iterator<?> it = iterator(); it.hasNext();)
4659 >                h += it.next().hashCode();
4660 >            return h;
4661          }
4662  
4663 <        /**
4664 <         * Returns the result of accumulating the given transformation
4665 <         * of all values using the given reducer to combine values, or
4666 <         * null if none.
4667 <         *
4668 <         * @param transformer a function returning the transformation
4669 <         * for an element, or null of there is no transformation (in
4670 <         * which case it is not combined).
4671 <         * @param reducer a commutative associative combining function
4672 <         * @return the result of accumulating the given transformation
4673 <         * of all values
4674 <         */
4675 <        public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4676 <                                  BiFun<? super U, ? super U, ? extends U> reducer) {
3961 <            return fjp.invoke(ForkJoinTasks.reduceValues
3962 <                              (ConcurrentHashMapV8.this, transformer, reducer));
4663 >        public final String toString() {
4664 >            StringBuilder sb = new StringBuilder();
4665 >            sb.append('[');
4666 >            Iterator<?> it = iterator();
4667 >            if (it.hasNext()) {
4668 >                for (;;) {
4669 >                    Object e = it.next();
4670 >                    sb.append(e == this ? "(this Collection)" : e);
4671 >                    if (!it.hasNext())
4672 >                        break;
4673 >                    sb.append(',').append(' ');
4674 >                }
4675 >            }
4676 >            return sb.append(']').toString();
4677          }
4678  
4679 <        /**
4680 <         * Returns the result of accumulating the given transformation
4681 <         * of all values using the given reducer to combine values,
4682 <         * and the given basis as an identity value.
4683 <         *
4684 <         * @param transformer a function returning the transformation
4685 <         * for an element
4686 <         * @param basis the identity (initial default value) for the reduction
4687 <         * @param reducer a commutative associative combining function
3974 <         * @return the result of accumulating the given transformation
3975 <         * of all values
3976 <         */
3977 <        public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3978 <                                           double basis,
3979 <                                           DoubleByDoubleToDouble reducer) {
3980 <            return fjp.invoke(ForkJoinTasks.reduceValuesToDouble
3981 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4679 >        public final boolean containsAll(Collection<?> c) {
4680 >            if (c != this) {
4681 >                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4682 >                    Object e = it.next();
4683 >                    if (e == null || !contains(e))
4684 >                        return false;
4685 >                }
4686 >            }
4687 >            return true;
4688          }
4689  
4690 <        /**
4691 <         * Returns the result of accumulating the given transformation
4692 <         * of all values using the given reducer to combine values,
4693 <         * and the given basis as an identity value.
4694 <         *
4695 <         * @param transformer a function returning the transformation
4696 <         * for an element
4697 <         * @param basis the identity (initial default value) for the reduction
4698 <         * @param reducer a commutative associative combining function
3993 <         * @return the result of accumulating the given transformation
3994 <         * of all values
3995 <         */
3996 <        public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3997 <                                       long basis,
3998 <                                       LongByLongToLong reducer) {
3999 <            return fjp.invoke(ForkJoinTasks.reduceValuesToLong
4000 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4690 >        public final boolean removeAll(Collection<?> c) {
4691 >            boolean modified = false;
4692 >            for (Iterator<?> it = iterator(); it.hasNext();) {
4693 >                if (c.contains(it.next())) {
4694 >                    it.remove();
4695 >                    modified = true;
4696 >                }
4697 >            }
4698 >            return modified;
4699          }
4700  
4701 <        /**
4702 <         * Returns the result of accumulating the given transformation
4703 <         * of all values using the given reducer to combine values,
4704 <         * and the given basis as an identity value.
4705 <         *
4706 <         * @param transformer a function returning the transformation
4707 <         * for an element
4708 <         * @param basis the identity (initial default value) for the reduction
4709 <         * @param reducer a commutative associative combining function
4012 <         * @return the result of accumulating the given transformation
4013 <         * of all values
4014 <         */
4015 <        public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4016 <                                     int basis,
4017 <                                     IntByIntToInt reducer) {
4018 <            return fjp.invoke(ForkJoinTasks.reduceValuesToInt
4019 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4701 >        public final boolean retainAll(Collection<?> c) {
4702 >            boolean modified = false;
4703 >            for (Iterator<?> it = iterator(); it.hasNext();) {
4704 >                if (!c.contains(it.next())) {
4705 >                    it.remove();
4706 >                    modified = true;
4707 >                }
4708 >            }
4709 >            return modified;
4710          }
4711  
4712 <        /**
4713 <         * Performs the given action for each entry.
4714 <         *
4715 <         * @param action the action
4716 <         */
4717 <        public void forEachEntry(Action<Map.Entry<K,V>> action) {
4718 <            fjp.invoke(ForkJoinTasks.forEachEntry
4719 <                       (ConcurrentHashMapV8.this, action));
4712 >    }
4713 >
4714 >    /**
4715 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4716 >     * which additions may optionally be enabled by mapping to a
4717 >     * common value.  This class cannot be directly instantiated. See
4718 >     * {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()},
4719 >     * {@link #newKeySet(int)}.
4720 >     */
4721 >    public static class KeySetView<K,V> extends CHMView<K,V>
4722 >        implements Set<K>, java.io.Serializable {
4723 >        private static final long serialVersionUID = 7249069246763182397L;
4724 >        private final V value;
4725 >        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4726 >            super(map);
4727 >            this.value = value;
4728          }
4729  
4730          /**
4731 <         * Performs the given action for each non-null transformation
4732 <         * of each entry.
4731 >         * Returns the default mapped value for additions,
4732 >         * or {@code null} if additions are not supported.
4733           *
4734 <         * @param transformer a function returning the transformation
4735 <         * for an element, or null of there is no transformation (in
4038 <         * which case the action is not applied).
4039 <         * @param action the action
4734 >         * @return the default mapped value for additions, or {@code null}
4735 >         * if not supported
4736           */
4737 <        public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4738 <                                     Action<U> action) {
4739 <            fjp.invoke(ForkJoinTasks.forEachEntry
4740 <                       (ConcurrentHashMapV8.this, transformer, action));
4741 <        }
4737 >        public V getMappedValue() { return value; }
4738 >
4739 >        // implement Set API
4740 >
4741 >        public boolean contains(Object o) { return map.containsKey(o); }
4742 >        public boolean remove(Object o)   { return map.remove(o) != null; }
4743  
4744          /**
4745 <         * Returns a non-null result from applying the given search
4746 <         * function on each entry, or null if none.  Upon success,
4747 <         * further element processing is suppressed and the results of
4748 <         * any other parallel invocations of the search function are
4749 <         * ignored.
4745 >         * Returns a "weakly consistent" iterator that will never
4746 >         * throw {@link ConcurrentModificationException}, and
4747 >         * guarantees to traverse elements as they existed upon
4748 >         * construction of the iterator, and may (but is not
4749 >         * guaranteed to) reflect any modifications subsequent to
4750 >         * construction.
4751           *
4752 <         * @param searchFunction a function returning a non-null
4055 <         * result on success, else null
4056 <         * @return a non-null result from applying the given search
4057 <         * function on each entry, or null if none
4752 >         * @return an iterator over the keys of this map
4753           */
4754 <        public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4755 <            return fjp.invoke(ForkJoinTasks.searchEntries
4756 <                              (ConcurrentHashMapV8.this, searchFunction));
4754 >        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4755 >        public boolean add(K e) {
4756 >            V v;
4757 >            if ((v = value) == null)
4758 >                throw new UnsupportedOperationException();
4759 >            if (e == null)
4760 >                throw new NullPointerException();
4761 >            return map.internalPut(e, v, true) == null;
4762          }
4763 +        public boolean addAll(Collection<? extends K> c) {
4764 +            boolean added = false;
4765 +            V v;
4766 +            if ((v = value) == null)
4767 +                throw new UnsupportedOperationException();
4768 +            for (K e : c) {
4769 +                if (e == null)
4770 +                    throw new NullPointerException();
4771 +                if (map.internalPut(e, v, true) == null)
4772 +                    added = true;
4773 +            }
4774 +            return added;
4775 +        }
4776 +        public boolean equals(Object o) {
4777 +            Set<?> c;
4778 +            return ((o instanceof Set) &&
4779 +                    ((c = (Set<?>)o) == this ||
4780 +                     (containsAll(c) && c.containsAll(this))));
4781 +        }
4782 +    }
4783  
4784 <        /**
4785 <         * Returns the result of accumulating all entries using the
4786 <         * given reducer to combine values, or null if none.
4787 <         *
4788 <         * @param reducer a commutative associative combining function
4789 <         * @return the result of accumulating all entries
4790 <         */
4791 <        public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4792 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4793 <                              (ConcurrentHashMapV8.this, reducer));
4784 >    /**
4785 >     * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4786 >     * values, in which additions are disabled. This class cannot be
4787 >     * directly instantiated. See {@link #values()}.
4788 >     *
4789 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4790 >     * that will never throw {@link ConcurrentModificationException},
4791 >     * and guarantees to traverse elements as they existed upon
4792 >     * construction of the iterator, and may (but is not guaranteed to)
4793 >     * reflect any modifications subsequent to construction.
4794 >     */
4795 >    public static final class ValuesView<K,V> extends CHMView<K,V>
4796 >        implements Collection<V> {
4797 >        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4798 >        public final boolean contains(Object o) { return map.containsValue(o); }
4799 >        public final boolean remove(Object o) {
4800 >            if (o != null) {
4801 >                Iterator<V> it = new ValueIterator<K,V>(map);
4802 >                while (it.hasNext()) {
4803 >                    if (o.equals(it.next())) {
4804 >                        it.remove();
4805 >                        return true;
4806 >                    }
4807 >                }
4808 >            }
4809 >            return false;
4810          }
4811  
4812          /**
4813 <         * Returns the result of accumulating the given transformation
4814 <         * of all entries using the given reducer to combine values,
4815 <         * or null if none.
4813 >         * Returns a "weakly consistent" iterator that will never
4814 >         * throw {@link ConcurrentModificationException}, and
4815 >         * guarantees to traverse elements as they existed upon
4816 >         * construction of the iterator, and may (but is not
4817 >         * guaranteed to) reflect any modifications subsequent to
4818 >         * construction.
4819           *
4820 <         * @param transformer a function returning the transformation
4082 <         * for an element, or null of there is no transformation (in
4083 <         * which case it is not combined).
4084 <         * @param reducer a commutative associative combining function
4085 <         * @return the result of accumulating the given transformation
4086 <         * of all entries
4820 >         * @return an iterator over the values of this map
4821           */
4822 <        public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4823 <                                   BiFun<? super U, ? super U, ? extends U> reducer) {
4824 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4825 <                              (ConcurrentHashMapV8.this, transformer, reducer));
4822 >        public final Iterator<V> iterator() {
4823 >            return new ValueIterator<K,V>(map);
4824 >        }
4825 >        public final boolean add(V e) {
4826 >            throw new UnsupportedOperationException();
4827 >        }
4828 >        public final boolean addAll(Collection<? extends V> c) {
4829 >            throw new UnsupportedOperationException();
4830          }
4831  
4832 <        /**
4833 <         * Returns the result of accumulating the given transformation
4834 <         * of all entries using the given reducer to combine values,
4835 <         * and the given basis as an identity value.
4836 <         *
4837 <         * @param transformer a function returning the transformation
4838 <         * for an element
4839 <         * @param basis the identity (initial default value) for the reduction
4840 <         * @param reducer a commutative associative combining function
4841 <         * @return the result of accumulating the given transformation
4842 <         * of all entries
4843 <         */
4844 <        public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4845 <                                            double basis,
4846 <                                            DoubleByDoubleToDouble reducer) {
4847 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToDouble
4848 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4832 >    }
4833 >
4834 >    /**
4835 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4836 >     * entries.  This class cannot be directly instantiated. See
4837 >     * {@link #entrySet()}.
4838 >     */
4839 >    public static final class EntrySetView<K,V> extends CHMView<K,V>
4840 >        implements Set<Map.Entry<K,V>> {
4841 >        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4842 >        public final boolean contains(Object o) {
4843 >            Object k, v, r; Map.Entry<?,?> e;
4844 >            return ((o instanceof Map.Entry) &&
4845 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4846 >                    (r = map.get(k)) != null &&
4847 >                    (v = e.getValue()) != null &&
4848 >                    (v == r || v.equals(r)));
4849 >        }
4850 >        public final boolean remove(Object o) {
4851 >            Object k, v; Map.Entry<?,?> e;
4852 >            return ((o instanceof Map.Entry) &&
4853 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4854 >                    (v = e.getValue()) != null &&
4855 >                    map.remove(k, v));
4856          }
4857  
4858          /**
4859 <         * Returns the result of accumulating the given transformation
4860 <         * of all entries using the given reducer to combine values,
4861 <         * and the given basis as an identity value.
4859 >         * Returns a "weakly consistent" iterator that will never
4860 >         * throw {@link ConcurrentModificationException}, and
4861 >         * guarantees to traverse elements as they existed upon
4862 >         * construction of the iterator, and may (but is not
4863 >         * guaranteed to) reflect any modifications subsequent to
4864 >         * construction.
4865           *
4866 <         * @param transformer a function returning the transformation
4119 <         * for an element
4120 <         * @param basis the identity (initial default value) for the reduction
4121 <         * @param reducer a commutative associative combining function
4122 <         * @return  the result of accumulating the given transformation
4123 <         * of all entries
4866 >         * @return an iterator over the entries of this map
4867           */
4868 <        public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4869 <                                        long basis,
4127 <                                        LongByLongToLong reducer) {
4128 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToLong
4129 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4868 >        public final Iterator<Map.Entry<K,V>> iterator() {
4869 >            return new EntryIterator<K,V>(map);
4870          }
4871  
4872 <        /**
4873 <         * Returns the result of accumulating the given transformation
4874 <         * of all entries using the given reducer to combine values,
4875 <         * and the given basis as an identity value.
4876 <         *
4877 <         * @param transformer a function returning the transformation
4878 <         * for an element
4879 <         * @param basis the identity (initial default value) for the reduction
4880 <         * @param reducer a commutative associative combining function
4881 <         * @return the result of accumulating the given transformation
4882 <         * of all entries
4883 <         */
4884 <        public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4885 <                                      int basis,
4886 <                                      IntByIntToInt reducer) {
4887 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToInt
4148 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4872 >        public final boolean add(Entry<K,V> e) {
4873 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4874 >        }
4875 >        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4876 >            boolean added = false;
4877 >            for (Entry<K,V> e : c) {
4878 >                if (add(e))
4879 >                    added = true;
4880 >            }
4881 >            return added;
4882 >        }
4883 >        public boolean equals(Object o) {
4884 >            Set<?> c;
4885 >            return ((o instanceof Set) &&
4886 >                    ((c = (Set<?>)o) == this ||
4887 >                     (containsAll(c) && c.containsAll(this))));
4888          }
4889      }
4890  
# Line 4153 | Line 4892 | public class ConcurrentHashMapV8<K, V>
4892  
4893      /**
4894       * Predefined tasks for performing bulk parallel operations on
4895 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
4896 <     * in class {@link Parallel}. Each method has the same name, but
4897 <     * returns a task rather than invoking it. These methods may be
4898 <     * useful in custom applications such as submitting a task without
4899 <     * waiting for completion, or combining with other tasks.
4895 >     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4896 >     * for bulk operations. Each method has the same name, but returns
4897 >     * a task rather than invoking it. These methods may be useful in
4898 >     * custom applications such as submitting a task without waiting
4899 >     * for completion, using a custom pool, or combining with other
4900 >     * tasks.
4901       */
4902      public static class ForkJoinTasks {
4903          private ForkJoinTasks() {}
# Line 4174 | Line 4914 | public class ConcurrentHashMapV8<K, V>
4914              (ConcurrentHashMapV8<K,V> map,
4915               BiAction<K,V> action) {
4916              if (action == null) throw new NullPointerException();
4917 <            return new ForEachMappingTask<K,V>(map, action);
4917 >            return new ForEachMappingTask<K,V>(map, null, -1, action);
4918          }
4919  
4920          /**
# Line 4183 | Line 4923 | public class ConcurrentHashMapV8<K, V>
4923           *
4924           * @param map the map
4925           * @param transformer a function returning the transformation
4926 <         * for an element, or null of there is no transformation (in
4927 <         * which case the action is not applied).
4926 >         * for an element, or null if there is no transformation (in
4927 >         * which case the action is not applied)
4928           * @param action the action
4929           * @return the task
4930           */
# Line 4195 | Line 4935 | public class ConcurrentHashMapV8<K, V>
4935              if (transformer == null || action == null)
4936                  throw new NullPointerException();
4937              return new ForEachTransformedMappingTask<K,V,U>
4938 <                (map, transformer, action);
4938 >                (map, null, -1, transformer, action);
4939          }
4940  
4941          /**
# Line 4215 | Line 4955 | public class ConcurrentHashMapV8<K, V>
4955               BiFun<? super K, ? super V, ? extends U> searchFunction) {
4956              if (searchFunction == null) throw new NullPointerException();
4957              return new SearchMappingsTask<K,V,U>
4958 <                (map, searchFunction,
4958 >                (map, null, -1, searchFunction,
4959                   new AtomicReference<U>());
4960          }
4961  
# Line 4226 | Line 4966 | public class ConcurrentHashMapV8<K, V>
4966           *
4967           * @param map the map
4968           * @param transformer a function returning the transformation
4969 <         * for an element, or null of there is no transformation (in
4970 <         * which case it is not combined).
4969 >         * for an element, or null if there is no transformation (in
4970 >         * which case it is not combined)
4971           * @param reducer a commutative associative combining function
4972           * @return the task
4973           */
# Line 4238 | Line 4978 | public class ConcurrentHashMapV8<K, V>
4978              if (transformer == null || reducer == null)
4979                  throw new NullPointerException();
4980              return new MapReduceMappingsTask<K,V,U>
4981 <                (map, transformer, reducer);
4981 >                (map, null, -1, null, transformer, reducer);
4982          }
4983  
4984          /**
# Line 4262 | Line 5002 | public class ConcurrentHashMapV8<K, V>
5002              if (transformer == null || reducer == null)
5003                  throw new NullPointerException();
5004              return new MapReduceMappingsToDoubleTask<K,V>
5005 <                (map, transformer, basis, reducer);
5005 >                (map, null, -1, null, transformer, basis, reducer);
5006          }
5007  
5008          /**
# Line 4286 | Line 5026 | public class ConcurrentHashMapV8<K, V>
5026              if (transformer == null || reducer == null)
5027                  throw new NullPointerException();
5028              return new MapReduceMappingsToLongTask<K,V>
5029 <                (map, transformer, basis, reducer);
5029 >                (map, null, -1, null, transformer, basis, reducer);
5030          }
5031  
5032          /**
# Line 4309 | Line 5049 | public class ConcurrentHashMapV8<K, V>
5049              if (transformer == null || reducer == null)
5050                  throw new NullPointerException();
5051              return new MapReduceMappingsToIntTask<K,V>
5052 <                (map, transformer, basis, reducer);
5052 >                (map, null, -1, null, transformer, basis, reducer);
5053          }
5054  
5055          /**
# Line 4324 | Line 5064 | public class ConcurrentHashMapV8<K, V>
5064              (ConcurrentHashMapV8<K,V> map,
5065               Action<K> action) {
5066              if (action == null) throw new NullPointerException();
5067 <            return new ForEachKeyTask<K,V>(map, action);
5067 >            return new ForEachKeyTask<K,V>(map, null, -1, action);
5068          }
5069  
5070          /**
# Line 4333 | Line 5073 | public class ConcurrentHashMapV8<K, V>
5073           *
5074           * @param map the map
5075           * @param transformer a function returning the transformation
5076 <         * for an element, or null of there is no transformation (in
5077 <         * which case the action is not applied).
5076 >         * for an element, or null if there is no transformation (in
5077 >         * which case the action is not applied)
5078           * @param action the action
5079           * @return the task
5080           */
# Line 4345 | Line 5085 | public class ConcurrentHashMapV8<K, V>
5085              if (transformer == null || action == null)
5086                  throw new NullPointerException();
5087              return new ForEachTransformedKeyTask<K,V,U>
5088 <                (map, transformer, action);
5088 >                (map, null, -1, transformer, action);
5089          }
5090  
5091          /**
# Line 4365 | Line 5105 | public class ConcurrentHashMapV8<K, V>
5105               Fun<? super K, ? extends U> searchFunction) {
5106              if (searchFunction == null) throw new NullPointerException();
5107              return new SearchKeysTask<K,V,U>
5108 <                (map, searchFunction,
5108 >                (map, null, -1, searchFunction,
5109                   new AtomicReference<U>());
5110          }
5111  
# Line 4383 | Line 5123 | public class ConcurrentHashMapV8<K, V>
5123               BiFun<? super K, ? super K, ? extends K> reducer) {
5124              if (reducer == null) throw new NullPointerException();
5125              return new ReduceKeysTask<K,V>
5126 <                (map, reducer);
5126 >                (map, null, -1, null, reducer);
5127          }
5128  
5129          /**
# Line 4393 | Line 5133 | public class ConcurrentHashMapV8<K, V>
5133           *
5134           * @param map the map
5135           * @param transformer a function returning the transformation
5136 <         * for an element, or null of there is no transformation (in
5137 <         * which case it is not combined).
5136 >         * for an element, or null if there is no transformation (in
5137 >         * which case it is not combined)
5138           * @param reducer a commutative associative combining function
5139           * @return the task
5140           */
# Line 4405 | Line 5145 | public class ConcurrentHashMapV8<K, V>
5145              if (transformer == null || reducer == null)
5146                  throw new NullPointerException();
5147              return new MapReduceKeysTask<K,V,U>
5148 <                (map, transformer, reducer);
5148 >                (map, null, -1, null, transformer, reducer);
5149          }
5150  
5151          /**
# Line 4429 | Line 5169 | public class ConcurrentHashMapV8<K, V>
5169              if (transformer == null || reducer == null)
5170                  throw new NullPointerException();
5171              return new MapReduceKeysToDoubleTask<K,V>
5172 <                (map, transformer, basis, reducer);
5172 >                (map, null, -1, null, transformer, basis, reducer);
5173          }
5174  
5175          /**
# Line 4453 | Line 5193 | public class ConcurrentHashMapV8<K, V>
5193              if (transformer == null || reducer == null)
5194                  throw new NullPointerException();
5195              return new MapReduceKeysToLongTask<K,V>
5196 <                (map, transformer, basis, reducer);
5196 >                (map, null, -1, null, transformer, basis, reducer);
5197          }
5198  
5199          /**
# Line 4477 | Line 5217 | public class ConcurrentHashMapV8<K, V>
5217              if (transformer == null || reducer == null)
5218                  throw new NullPointerException();
5219              return new MapReduceKeysToIntTask<K,V>
5220 <                (map, transformer, basis, reducer);
5220 >                (map, null, -1, null, transformer, basis, reducer);
5221          }
5222  
5223          /**
# Line 4491 | Line 5231 | public class ConcurrentHashMapV8<K, V>
5231              (ConcurrentHashMapV8<K,V> map,
5232               Action<V> action) {
5233              if (action == null) throw new NullPointerException();
5234 <            return new ForEachValueTask<K,V>(map, action);
5234 >            return new ForEachValueTask<K,V>(map, null, -1, action);
5235          }
5236  
5237          /**
# Line 4500 | Line 5240 | public class ConcurrentHashMapV8<K, V>
5240           *
5241           * @param map the map
5242           * @param transformer a function returning the transformation
5243 <         * for an element, or null of there is no transformation (in
5244 <         * which case the action is not applied).
5243 >         * for an element, or null if there is no transformation (in
5244 >         * which case the action is not applied)
5245           * @param action the action
5246           */
5247          public static <K,V,U> ForkJoinTask<Void> forEachValue
# Line 4511 | Line 5251 | public class ConcurrentHashMapV8<K, V>
5251              if (transformer == null || action == null)
5252                  throw new NullPointerException();
5253              return new ForEachTransformedValueTask<K,V,U>
5254 <                (map, transformer, action);
5254 >                (map, null, -1, transformer, action);
5255          }
5256  
5257          /**
# Line 4525 | Line 5265 | public class ConcurrentHashMapV8<K, V>
5265           * @param searchFunction a function returning a non-null
5266           * result on success, else null
5267           * @return the task
4528         *
5268           */
5269          public static <K,V,U> ForkJoinTask<U> searchValues
5270              (ConcurrentHashMapV8<K,V> map,
5271               Fun<? super V, ? extends U> searchFunction) {
5272              if (searchFunction == null) throw new NullPointerException();
5273              return new SearchValuesTask<K,V,U>
5274 <                (map, searchFunction,
5274 >                (map, null, -1, searchFunction,
5275                   new AtomicReference<U>());
5276          }
5277  
# Line 4550 | Line 5289 | public class ConcurrentHashMapV8<K, V>
5289               BiFun<? super V, ? super V, ? extends V> reducer) {
5290              if (reducer == null) throw new NullPointerException();
5291              return new ReduceValuesTask<K,V>
5292 <                (map, reducer);
5292 >                (map, null, -1, null, reducer);
5293          }
5294  
5295          /**
# Line 4560 | Line 5299 | public class ConcurrentHashMapV8<K, V>
5299           *
5300           * @param map the map
5301           * @param transformer a function returning the transformation
5302 <         * for an element, or null of there is no transformation (in
5303 <         * which case it is not combined).
5302 >         * for an element, or null if there is no transformation (in
5303 >         * which case it is not combined)
5304           * @param reducer a commutative associative combining function
5305           * @return the task
5306           */
# Line 4572 | Line 5311 | public class ConcurrentHashMapV8<K, V>
5311              if (transformer == null || reducer == null)
5312                  throw new NullPointerException();
5313              return new MapReduceValuesTask<K,V,U>
5314 <                (map, transformer, reducer);
5314 >                (map, null, -1, null, transformer, reducer);
5315          }
5316  
5317          /**
# Line 4596 | Line 5335 | public class ConcurrentHashMapV8<K, V>
5335              if (transformer == null || reducer == null)
5336                  throw new NullPointerException();
5337              return new MapReduceValuesToDoubleTask<K,V>
5338 <                (map, transformer, basis, reducer);
5338 >                (map, null, -1, null, transformer, basis, reducer);
5339          }
5340  
5341          /**
# Line 4620 | Line 5359 | public class ConcurrentHashMapV8<K, V>
5359              if (transformer == null || reducer == null)
5360                  throw new NullPointerException();
5361              return new MapReduceValuesToLongTask<K,V>
5362 <                (map, transformer, basis, reducer);
5362 >                (map, null, -1, null, transformer, basis, reducer);
5363          }
5364  
5365          /**
# Line 4644 | Line 5383 | public class ConcurrentHashMapV8<K, V>
5383              if (transformer == null || reducer == null)
5384                  throw new NullPointerException();
5385              return new MapReduceValuesToIntTask<K,V>
5386 <                (map, transformer, basis, reducer);
5386 >                (map, null, -1, null, transformer, basis, reducer);
5387          }
5388  
5389          /**
# Line 4658 | Line 5397 | public class ConcurrentHashMapV8<K, V>
5397              (ConcurrentHashMapV8<K,V> map,
5398               Action<Map.Entry<K,V>> action) {
5399              if (action == null) throw new NullPointerException();
5400 <            return new ForEachEntryTask<K,V>(map, action);
5400 >            return new ForEachEntryTask<K,V>(map, null, -1, action);
5401          }
5402  
5403          /**
# Line 4667 | Line 5406 | public class ConcurrentHashMapV8<K, V>
5406           *
5407           * @param map the map
5408           * @param transformer a function returning the transformation
5409 <         * for an element, or null of there is no transformation (in
5410 <         * which case the action is not applied).
5409 >         * for an element, or null if there is no transformation (in
5410 >         * which case the action is not applied)
5411           * @param action the action
5412           */
5413          public static <K,V,U> ForkJoinTask<Void> forEachEntry
# Line 4678 | Line 5417 | public class ConcurrentHashMapV8<K, V>
5417              if (transformer == null || action == null)
5418                  throw new NullPointerException();
5419              return new ForEachTransformedEntryTask<K,V,U>
5420 <                (map, transformer, action);
5420 >                (map, null, -1, transformer, action);
5421          }
5422  
5423          /**
# Line 4692 | Line 5431 | public class ConcurrentHashMapV8<K, V>
5431           * @param searchFunction a function returning a non-null
5432           * result on success, else null
5433           * @return the task
4695         *
5434           */
5435          public static <K,V,U> ForkJoinTask<U> searchEntries
5436              (ConcurrentHashMapV8<K,V> map,
5437               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5438              if (searchFunction == null) throw new NullPointerException();
5439              return new SearchEntriesTask<K,V,U>
5440 <                (map, searchFunction,
5440 >                (map, null, -1, searchFunction,
5441                   new AtomicReference<U>());
5442          }
5443  
# Line 4717 | Line 5455 | public class ConcurrentHashMapV8<K, V>
5455               BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5456              if (reducer == null) throw new NullPointerException();
5457              return new ReduceEntriesTask<K,V>
5458 <                (map, reducer);
5458 >                (map, null, -1, null, reducer);
5459          }
5460  
5461          /**
# Line 4727 | Line 5465 | public class ConcurrentHashMapV8<K, V>
5465           *
5466           * @param map the map
5467           * @param transformer a function returning the transformation
5468 <         * for an element, or null of there is no transformation (in
5469 <         * which case it is not combined).
5468 >         * for an element, or null if there is no transformation (in
5469 >         * which case it is not combined)
5470           * @param reducer a commutative associative combining function
5471           * @return the task
5472           */
# Line 4739 | Line 5477 | public class ConcurrentHashMapV8<K, V>
5477              if (transformer == null || reducer == null)
5478                  throw new NullPointerException();
5479              return new MapReduceEntriesTask<K,V,U>
5480 <                (map, transformer, reducer);
5480 >                (map, null, -1, null, transformer, reducer);
5481          }
5482  
5483          /**
# Line 4763 | Line 5501 | public class ConcurrentHashMapV8<K, V>
5501              if (transformer == null || reducer == null)
5502                  throw new NullPointerException();
5503              return new MapReduceEntriesToDoubleTask<K,V>
5504 <                (map, transformer, basis, reducer);
5504 >                (map, null, -1, null, transformer, basis, reducer);
5505          }
5506  
5507          /**
# Line 4787 | Line 5525 | public class ConcurrentHashMapV8<K, V>
5525              if (transformer == null || reducer == null)
5526                  throw new NullPointerException();
5527              return new MapReduceEntriesToLongTask<K,V>
5528 <                (map, transformer, basis, reducer);
5528 >                (map, null, -1, null, transformer, basis, reducer);
5529          }
5530  
5531          /**
# Line 4811 | Line 5549 | public class ConcurrentHashMapV8<K, V>
5549              if (transformer == null || reducer == null)
5550                  throw new NullPointerException();
5551              return new MapReduceEntriesToIntTask<K,V>
5552 <                (map, transformer, basis, reducer);
5552 >                (map, null, -1, null, transformer, basis, reducer);
5553          }
5554      }
5555  
5556      // -------------------------------------------------------
5557  
4820    /**
4821     * Base for FJ tasks for bulk operations. This adds a variant of
4822     * CountedCompleters and some split and merge bookkeeping to
4823     * iterator functionality. The forEach and reduce methods are
4824     * similar to those illustrated in CountedCompleter documentation,
4825     * except that bottom-up reduction completions perform them within
4826     * their compute methods. The search methods are like forEach
4827     * except they continually poll for success and exit early.  Also,
4828     * exceptions are handled in a simpler manner, by just trying to
4829     * complete root task exceptionally.
4830     */
4831    @SuppressWarnings("serial")
4832    static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4833        final BulkTask<K,V,?> parent;  // completion target
4834        int batch;                     // split control
4835        int pending;                   // completion control
4836
4837        /** Constructor for root tasks */
4838        BulkTask(ConcurrentHashMapV8<K,V> map) {
4839            super(map);
4840            this.parent = null;
4841            this.batch = -1; // force call to batch() on execution
4842        }
4843
4844        /** Constructor for subtasks */
4845        BulkTask(BulkTask<K,V,?> parent, int batch, boolean split) {
4846            super(parent, split);
4847            this.parent = parent;
4848            this.batch = batch;
4849        }
4850
4851        // FJ methods
4852
4853        /**
4854         * Propagates completion. Note that all reduce actions
4855         * bypass this method to combine while completing.
4856         */
4857        final void tryComplete() {
4858            BulkTask<K,V,?> a = this, s = a;
4859            for (int c;;) {
4860                if ((c = a.pending) == 0) {
4861                    if ((a = (s = a).parent) == null) {
4862                        s.quietlyComplete();
4863                        break;
4864                    }
4865                }
4866                else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
4867                    break;
4868            }
4869        }
4870
4871        /**
4872         * Forces root task to throw exception unless already complete.
4873         */
4874        final void tryAbortComputation(Throwable ex) {
4875            for (BulkTask<K,V,?> a = this;;) {
4876                BulkTask<K,V,?> p = a.parent;
4877                if (p == null) {
4878                    a.completeExceptionally(ex);
4879                    break;
4880                }
4881                a = p;
4882            }
4883        }
4884
4885        public final boolean exec() {
4886            try {
4887                compute();
4888            }
4889            catch (Throwable ex) {
4890                tryAbortComputation(ex);
4891            }
4892            return false;
4893        }
4894
4895        public abstract void compute();
4896
4897        // utilities
4898
4899        /** CompareAndSet pending count */
4900        final boolean casPending(int cmp, int val) {
4901            return U.compareAndSwapInt(this, PENDING, cmp, val);
4902        }
4903
4904        /**
4905         * Returns approx exp2 of the number of times (minus one) to
4906         * split task by two before executing leaf action. This value
4907         * is faster to compute and more convenient to use as a guide
4908         * to splitting than is the depth, since it is used while
4909         * dividing by two anyway.
4910         */
4911        final int batch() {
4912            int b = batch;
4913            if (b < 0) {
4914                long n = map.counter.sum();
4915                int sp = getPool().getParallelism() << 3; // slack of 8
4916                b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4917            }
4918            return b;
4919        }
4920
4921        /**
4922         * Error message for hoisted null checks of functions
4923         */
4924        static final String NullFunctionMessage =
4925            "Unexpected null function";
4926
4927        /**
4928         * Returns exportable snapshot entry.
4929         */
4930        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4931            return new AbstractMap.SimpleEntry<K,V>(k, v);
4932        }
4933
4934        // Unsafe mechanics
4935        private static final sun.misc.Unsafe U;
4936        private static final long PENDING;
4937        static {
4938            try {
4939                U = getUnsafe();
4940                PENDING = U.objectFieldOffset
4941                    (BulkTask.class.getDeclaredField("pending"));
4942            } catch (Exception e) {
4943                throw new Error(e);
4944            }
4945        }
4946    }
4947
5558      /*
5559       * Task classes. Coded in a regular but ugly format/style to
5560       * simplify checks that each variant differs in the right way from
5561 <     * others.
5561 >     * others. The null screenings exist because compilers cannot tell
5562 >     * that we've already null-checked task arguments, so we force
5563 >     * simplest hoisted bypass to help avoid convoluted traps.
5564       */
5565  
5566 <    @SuppressWarnings("serial")
5567 <    static final class ForEachKeyTask<K,V>
4956 <        extends BulkTask<K,V,Void> {
5566 >    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5567 >        extends Traverser<K,V,Void> {
5568          final Action<K> action;
5569          ForEachKeyTask
5570 <            (ConcurrentHashMapV8<K,V> m,
4960 <             Action<K> action) {
4961 <            super(m);
4962 <            this.action = action;
4963 <        }
4964 <        ForEachKeyTask
4965 <            (BulkTask<K,V,?> p, int b, boolean split,
5570 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5571               Action<K> action) {
5572 <            super(p, b, split);
5572 >            super(m, p, b);
5573              this.action = action;
5574          }
5575          @SuppressWarnings("unchecked") public final void compute() {
5576 <            final Action<K> action = this.action;
5577 <            if (action == null)
5578 <                throw new Error(NullFunctionMessage);
5579 <            int b = batch(), c;
5580 <            while (b > 1 && baseIndex != baseLimit) {
5581 <                do {} while (!casPending(c = pending, c+1));
5582 <                new ForEachKeyTask<K,V>(this, b >>>= 1, true, action).fork();
5583 <            }
4979 <            while (advance() != null)
4980 <                action.apply((K)nextKey);
4981 <            tryComplete();
5576 >            final Action<K> action;
5577 >            if ((action = this.action) != null) {
5578 >                for (int b; (b = preSplit()) > 0;)
5579 >                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
5580 >                while (advance() != null)
5581 >                    action.apply((K)nextKey);
5582 >                propagateCompletion();
5583 >            }
5584          }
5585      }
5586  
5587 <    @SuppressWarnings("serial")
5588 <    static final class ForEachValueTask<K,V>
4987 <        extends BulkTask<K,V,Void> {
5587 >    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5588 >        extends Traverser<K,V,Void> {
5589          final Action<V> action;
5590          ForEachValueTask
5591 <            (ConcurrentHashMapV8<K,V> m,
4991 <             Action<V> action) {
4992 <            super(m);
4993 <            this.action = action;
4994 <        }
4995 <        ForEachValueTask
4996 <            (BulkTask<K,V,?> p, int b, boolean split,
5591 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5592               Action<V> action) {
5593 <            super(p, b, split);
5593 >            super(m, p, b);
5594              this.action = action;
5595          }
5596          @SuppressWarnings("unchecked") public final void compute() {
5597 <            final Action<V> action = this.action;
5598 <            if (action == null)
5599 <                throw new Error(NullFunctionMessage);
5600 <            int b = batch(), c;
5601 <            while (b > 1 && baseIndex != baseLimit) {
5602 <                do {} while (!casPending(c = pending, c+1));
5603 <                new ForEachValueTask<K,V>(this, b >>>= 1, true, action).fork();
5604 <            }
5605 <            Object v;
5011 <            while ((v = advance()) != null)
5012 <                action.apply((V)v);
5013 <            tryComplete();
5597 >            final Action<V> action;
5598 >            if ((action = this.action) != null) {
5599 >                for (int b; (b = preSplit()) > 0;)
5600 >                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5601 >                V v;
5602 >                while ((v = advance()) != null)
5603 >                    action.apply(v);
5604 >                propagateCompletion();
5605 >            }
5606          }
5607      }
5608  
5609 <    @SuppressWarnings("serial")
5610 <    static final class ForEachEntryTask<K,V>
5019 <        extends BulkTask<K,V,Void> {
5609 >    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5610 >        extends Traverser<K,V,Void> {
5611          final Action<Entry<K,V>> action;
5612          ForEachEntryTask
5613 <            (ConcurrentHashMapV8<K,V> m,
5613 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5614               Action<Entry<K,V>> action) {
5615 <            super(m);
5025 <            this.action = action;
5026 <        }
5027 <        ForEachEntryTask
5028 <            (BulkTask<K,V,?> p, int b, boolean split,
5029 <             Action<Entry<K,V>> action) {
5030 <            super(p, b, split);
5615 >            super(m, p, b);
5616              this.action = action;
5617          }
5618          @SuppressWarnings("unchecked") public final void compute() {
5619 <            final Action<Entry<K,V>> action = this.action;
5620 <            if (action == null)
5621 <                throw new Error(NullFunctionMessage);
5622 <            int b = batch(), c;
5623 <            while (b > 1 && baseIndex != baseLimit) {
5624 <                do {} while (!casPending(c = pending, c+1));
5625 <                new ForEachEntryTask<K,V>(this, b >>>= 1, true, action).fork();
5626 <            }
5627 <            Object v;
5043 <            while ((v = advance()) != null)
5044 <                action.apply(entryFor((K)nextKey, (V)v));
5045 <            tryComplete();
5619 >            final Action<Entry<K,V>> action;
5620 >            if ((action = this.action) != null) {
5621 >                for (int b; (b = preSplit()) > 0;)
5622 >                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5623 >                V v;
5624 >                while ((v = advance()) != null)
5625 >                    action.apply(entryFor((K)nextKey, v));
5626 >                propagateCompletion();
5627 >            }
5628          }
5629      }
5630  
5631 <    @SuppressWarnings("serial")
5632 <    static final class ForEachMappingTask<K,V>
5051 <        extends BulkTask<K,V,Void> {
5631 >    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5632 >        extends Traverser<K,V,Void> {
5633          final BiAction<K,V> action;
5634          ForEachMappingTask
5635 <            (ConcurrentHashMapV8<K,V> m,
5055 <             BiAction<K,V> action) {
5056 <            super(m);
5057 <            this.action = action;
5058 <        }
5059 <        ForEachMappingTask
5060 <            (BulkTask<K,V,?> p, int b, boolean split,
5635 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5636               BiAction<K,V> action) {
5637 <            super(p, b, split);
5637 >            super(m, p, b);
5638              this.action = action;
5639          }
5065
5640          @SuppressWarnings("unchecked") public final void compute() {
5641 <            final BiAction<K,V> action = this.action;
5642 <            if (action == null)
5643 <                throw new Error(NullFunctionMessage);
5644 <            int b = batch(), c;
5645 <            while (b > 1 && baseIndex != baseLimit) {
5646 <                do {} while (!casPending(c = pending, c+1));
5647 <                new ForEachMappingTask<K,V>(this, b >>>= 1, true,
5648 <                                            action).fork();
5649 <            }
5076 <            Object v;
5077 <            while ((v = advance()) != null)
5078 <                action.apply((K)nextKey, (V)v);
5079 <            tryComplete();
5641 >            final BiAction<K,V> action;
5642 >            if ((action = this.action) != null) {
5643 >                for (int b; (b = preSplit()) > 0;)
5644 >                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5645 >                V v;
5646 >                while ((v = advance()) != null)
5647 >                    action.apply((K)nextKey, v);
5648 >                propagateCompletion();
5649 >            }
5650          }
5651      }
5652  
5653 <    @SuppressWarnings("serial")
5654 <    static final class ForEachTransformedKeyTask<K,V,U>
5085 <        extends BulkTask<K,V,Void> {
5653 >    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5654 >        extends Traverser<K,V,Void> {
5655          final Fun<? super K, ? extends U> transformer;
5656          final Action<U> action;
5657          ForEachTransformedKeyTask
5658 <            (ConcurrentHashMapV8<K,V> m,
5659 <             Fun<? super K, ? extends U> transformer,
5660 <             Action<U> action) {
5661 <            super(m);
5093 <            this.transformer = transformer;
5094 <            this.action = action;
5095 <
5096 <        }
5097 <        ForEachTransformedKeyTask
5098 <            (BulkTask<K,V,?> p, int b, boolean split,
5099 <             Fun<? super K, ? extends U> transformer,
5100 <             Action<U> action) {
5101 <            super(p, b, split);
5102 <            this.transformer = transformer;
5103 <            this.action = action;
5658 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5659 >             Fun<? super K, ? extends U> transformer, Action<U> action) {
5660 >            super(m, p, b);
5661 >            this.transformer = transformer; this.action = action;
5662          }
5663          @SuppressWarnings("unchecked") public final void compute() {
5664 <            final Fun<? super K, ? extends U> transformer =
5665 <                this.transformer;
5666 <            final Action<U> action = this.action;
5667 <            if (transformer == null || action == null)
5668 <                throw new Error(NullFunctionMessage);
5669 <            int b = batch(), c;
5670 <            while (b > 1 && baseIndex != baseLimit) {
5671 <                do {} while (!casPending(c = pending, c+1));
5672 <                new ForEachTransformedKeyTask<K,V,U>
5673 <                    (this, b >>>= 1, true, transformer, action).fork();
5674 <            }
5675 <            U u;
5676 <            while (advance() != null) {
5119 <                if ((u = transformer.apply((K)nextKey)) != null)
5120 <                    action.apply(u);
5664 >            final Fun<? super K, ? extends U> transformer;
5665 >            final Action<U> action;
5666 >            if ((transformer = this.transformer) != null &&
5667 >                (action = this.action) != null) {
5668 >                for (int b; (b = preSplit()) > 0;)
5669 >                    new ForEachTransformedKeyTask<K,V,U>
5670 >                        (map, this, b, transformer, action).fork();
5671 >                U u;
5672 >                while (advance() != null) {
5673 >                    if ((u = transformer.apply((K)nextKey)) != null)
5674 >                        action.apply(u);
5675 >                }
5676 >                propagateCompletion();
5677              }
5122            tryComplete();
5678          }
5679      }
5680  
5681 <    @SuppressWarnings("serial")
5682 <    static final class ForEachTransformedValueTask<K,V,U>
5128 <        extends BulkTask<K,V,Void> {
5681 >    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5682 >        extends Traverser<K,V,Void> {
5683          final Fun<? super V, ? extends U> transformer;
5684          final Action<U> action;
5685          ForEachTransformedValueTask
5686 <            (ConcurrentHashMapV8<K,V> m,
5687 <             Fun<? super V, ? extends U> transformer,
5688 <             Action<U> action) {
5689 <            super(m);
5136 <            this.transformer = transformer;
5137 <            this.action = action;
5138 <
5139 <        }
5140 <        ForEachTransformedValueTask
5141 <            (BulkTask<K,V,?> p, int b, boolean split,
5142 <             Fun<? super V, ? extends U> transformer,
5143 <             Action<U> action) {
5144 <            super(p, b, split);
5145 <            this.transformer = transformer;
5146 <            this.action = action;
5686 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5687 >             Fun<? super V, ? extends U> transformer, Action<U> action) {
5688 >            super(m, p, b);
5689 >            this.transformer = transformer; this.action = action;
5690          }
5691          @SuppressWarnings("unchecked") public final void compute() {
5692 <            final Fun<? super V, ? extends U> transformer =
5693 <                this.transformer;
5694 <            final Action<U> action = this.action;
5695 <            if (transformer == null || action == null)
5696 <                throw new Error(NullFunctionMessage);
5697 <            int b = batch(), c;
5698 <            while (b > 1 && baseIndex != baseLimit) {
5699 <                do {} while (!casPending(c = pending, c+1));
5700 <                new ForEachTransformedValueTask<K,V,U>
5701 <                    (this, b >>>= 1, true, transformer, action).fork();
5702 <            }
5703 <            Object v; U u;
5704 <            while ((v = advance()) != null) {
5162 <                if ((u = transformer.apply((V)v)) != null)
5163 <                    action.apply(u);
5692 >            final Fun<? super V, ? extends U> transformer;
5693 >            final Action<U> action;
5694 >            if ((transformer = this.transformer) != null &&
5695 >                (action = this.action) != null) {
5696 >                for (int b; (b = preSplit()) > 0;)
5697 >                    new ForEachTransformedValueTask<K,V,U>
5698 >                        (map, this, b, transformer, action).fork();
5699 >                V v; U u;
5700 >                while ((v = advance()) != null) {
5701 >                    if ((u = transformer.apply(v)) != null)
5702 >                        action.apply(u);
5703 >                }
5704 >                propagateCompletion();
5705              }
5165            tryComplete();
5706          }
5707      }
5708  
5709 <    @SuppressWarnings("serial")
5710 <    static final class ForEachTransformedEntryTask<K,V,U>
5171 <        extends BulkTask<K,V,Void> {
5709 >    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5710 >        extends Traverser<K,V,Void> {
5711          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5712          final Action<U> action;
5713          ForEachTransformedEntryTask
5714 <            (ConcurrentHashMapV8<K,V> m,
5715 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5716 <             Action<U> action) {
5717 <            super(m);
5179 <            this.transformer = transformer;
5180 <            this.action = action;
5181 <
5182 <        }
5183 <        ForEachTransformedEntryTask
5184 <            (BulkTask<K,V,?> p, int b, boolean split,
5185 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5186 <             Action<U> action) {
5187 <            super(p, b, split);
5188 <            this.transformer = transformer;
5189 <            this.action = action;
5714 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5715 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
5716 >            super(m, p, b);
5717 >            this.transformer = transformer; this.action = action;
5718          }
5719          @SuppressWarnings("unchecked") public final void compute() {
5720 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5721 <                this.transformer;
5722 <            final Action<U> action = this.action;
5723 <            if (transformer == null || action == null)
5724 <                throw new Error(NullFunctionMessage);
5725 <            int b = batch(), c;
5726 <            while (b > 1 && baseIndex != baseLimit) {
5727 <                do {} while (!casPending(c = pending, c+1));
5728 <                new ForEachTransformedEntryTask<K,V,U>
5729 <                    (this, b >>>= 1, true, transformer, action).fork();
5730 <            }
5731 <            Object v; U u;
5732 <            while ((v = advance()) != null) {
5733 <                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5206 <                    action.apply(u);
5720 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5721 >            final Action<U> action;
5722 >            if ((transformer = this.transformer) != null &&
5723 >                (action = this.action) != null) {
5724 >                for (int b; (b = preSplit()) > 0;)
5725 >                    new ForEachTransformedEntryTask<K,V,U>
5726 >                        (map, this, b, transformer, action).fork();
5727 >                V v; U u;
5728 >                while ((v = advance()) != null) {
5729 >                    if ((u = transformer.apply(entryFor((K)nextKey,
5730 >                                                        v))) != null)
5731 >                        action.apply(u);
5732 >                }
5733 >                propagateCompletion();
5734              }
5208            tryComplete();
5735          }
5736      }
5737  
5738 <    @SuppressWarnings("serial")
5739 <    static final class ForEachTransformedMappingTask<K,V,U>
5214 <        extends BulkTask<K,V,Void> {
5738 >    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5739 >        extends Traverser<K,V,Void> {
5740          final BiFun<? super K, ? super V, ? extends U> transformer;
5741          final Action<U> action;
5742          ForEachTransformedMappingTask
5743 <            (ConcurrentHashMapV8<K,V> m,
5219 <             BiFun<? super K, ? super V, ? extends U> transformer,
5220 <             Action<U> action) {
5221 <            super(m);
5222 <            this.transformer = transformer;
5223 <            this.action = action;
5224 <
5225 <        }
5226 <        ForEachTransformedMappingTask
5227 <            (BulkTask<K,V,?> p, int b, boolean split,
5743 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5744               BiFun<? super K, ? super V, ? extends U> transformer,
5745               Action<U> action) {
5746 <            super(p, b, split);
5747 <            this.transformer = transformer;
5232 <            this.action = action;
5746 >            super(m, p, b);
5747 >            this.transformer = transformer; this.action = action;
5748          }
5749          @SuppressWarnings("unchecked") public final void compute() {
5750 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5751 <                this.transformer;
5752 <            final Action<U> action = this.action;
5753 <            if (transformer == null || action == null)
5754 <                throw new Error(NullFunctionMessage);
5755 <            int b = batch(), c;
5756 <            while (b > 1 && baseIndex != baseLimit) {
5757 <                do {} while (!casPending(c = pending, c+1));
5758 <                new ForEachTransformedMappingTask<K,V,U>
5759 <                    (this, b >>>= 1, true, transformer, action).fork();
5760 <            }
5761 <            Object v; U u;
5762 <            while ((v = advance()) != null) {
5248 <                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5249 <                    action.apply(u);
5750 >            final BiFun<? super K, ? super V, ? extends U> transformer;
5751 >            final Action<U> action;
5752 >            if ((transformer = this.transformer) != null &&
5753 >                (action = this.action) != null) {
5754 >                for (int b; (b = preSplit()) > 0;)
5755 >                    new ForEachTransformedMappingTask<K,V,U>
5756 >                        (map, this, b, transformer, action).fork();
5757 >                V v; U u;
5758 >                while ((v = advance()) != null) {
5759 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
5760 >                        action.apply(u);
5761 >                }
5762 >                propagateCompletion();
5763              }
5251            tryComplete();
5764          }
5765      }
5766  
5767 <    @SuppressWarnings("serial")
5768 <    static final class SearchKeysTask<K,V,U>
5257 <        extends BulkTask<K,V,U> {
5767 >    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5768 >        extends Traverser<K,V,U> {
5769          final Fun<? super K, ? extends U> searchFunction;
5770          final AtomicReference<U> result;
5771          SearchKeysTask
5772 <            (ConcurrentHashMapV8<K,V> m,
5262 <             Fun<? super K, ? extends U> searchFunction,
5263 <             AtomicReference<U> result) {
5264 <            super(m);
5265 <            this.searchFunction = searchFunction; this.result = result;
5266 <        }
5267 <        SearchKeysTask
5268 <            (BulkTask<K,V,?> p, int b, boolean split,
5772 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5773               Fun<? super K, ? extends U> searchFunction,
5774               AtomicReference<U> result) {
5775 <            super(p, b, split);
5775 >            super(m, p, b);
5776              this.searchFunction = searchFunction; this.result = result;
5777          }
5778 +        public final U getRawResult() { return result.get(); }
5779          @SuppressWarnings("unchecked") public final void compute() {
5780 <            AtomicReference<U> result = this.result;
5781 <            final Fun<? super K, ? extends U> searchFunction =
5782 <                this.searchFunction;
5783 <            if (searchFunction == null || result == null)
5784 <                throw new Error(NullFunctionMessage);
5785 <            int b = batch(), c;
5786 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5787 <                do {} while (!casPending(c = pending, c+1));
5788 <                new SearchKeysTask<K,V,U>(this, b >>>= 1, true,
5789 <                                          searchFunction, result).fork();
5790 <            }
5791 <            U u;
5792 <            while (result.get() == null && advance() != null) {
5793 <                if ((u = searchFunction.apply((K)nextKey)) != null) {
5794 <                    if (result.compareAndSet(null, u)) {
5795 <                        for (BulkTask<K,V,?> a = this, p;;) {
5796 <                            if ((p = a.parent) == null) {
5797 <                                a.quietlyComplete();
5798 <                                break;
5799 <                            }
5800 <                            a = p;
5801 <                        }
5780 >            final Fun<? super K, ? extends U> searchFunction;
5781 >            final AtomicReference<U> result;
5782 >            if ((searchFunction = this.searchFunction) != null &&
5783 >                (result = this.result) != null) {
5784 >                for (int b;;) {
5785 >                    if (result.get() != null)
5786 >                        return;
5787 >                    if ((b = preSplit()) <= 0)
5788 >                        break;
5789 >                    new SearchKeysTask<K,V,U>
5790 >                        (map, this, b, searchFunction, result).fork();
5791 >                }
5792 >                while (result.get() == null) {
5793 >                    U u;
5794 >                    if (advance() == null) {
5795 >                        propagateCompletion();
5796 >                        break;
5797 >                    }
5798 >                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5799 >                        if (result.compareAndSet(null, u))
5800 >                            quietlyCompleteRoot();
5801 >                        break;
5802                      }
5298                    break;
5803                  }
5804              }
5301            tryComplete();
5805          }
5303        public final U getRawResult() { return result.get(); }
5806      }
5807  
5808 <    @SuppressWarnings("serial")
5809 <    static final class SearchValuesTask<K,V,U>
5308 <        extends BulkTask<K,V,U> {
5808 >    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5809 >        extends Traverser<K,V,U> {
5810          final Fun<? super V, ? extends U> searchFunction;
5811          final AtomicReference<U> result;
5812          SearchValuesTask
5813 <            (ConcurrentHashMapV8<K,V> m,
5313 <             Fun<? super V, ? extends U> searchFunction,
5314 <             AtomicReference<U> result) {
5315 <            super(m);
5316 <            this.searchFunction = searchFunction; this.result = result;
5317 <        }
5318 <        SearchValuesTask
5319 <            (BulkTask<K,V,?> p, int b, boolean split,
5813 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5814               Fun<? super V, ? extends U> searchFunction,
5815               AtomicReference<U> result) {
5816 <            super(p, b, split);
5816 >            super(m, p, b);
5817              this.searchFunction = searchFunction; this.result = result;
5818          }
5819 +        public final U getRawResult() { return result.get(); }
5820          @SuppressWarnings("unchecked") public final void compute() {
5821 <            AtomicReference<U> result = this.result;
5822 <            final Fun<? super V, ? extends U> searchFunction =
5823 <                this.searchFunction;
5824 <            if (searchFunction == null || result == null)
5825 <                throw new Error(NullFunctionMessage);
5826 <            int b = batch(), c;
5827 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5828 <                do {} while (!casPending(c = pending, c+1));
5829 <                new SearchValuesTask<K,V,U>(this, b >>>= 1, true,
5830 <                                            searchFunction, result).fork();
5831 <            }
5832 <            Object v; U u;
5833 <            while (result.get() == null && (v = advance()) != null) {
5834 <                if ((u = searchFunction.apply((V)v)) != null) {
5835 <                    if (result.compareAndSet(null, u)) {
5836 <                        for (BulkTask<K,V,?> a = this, p;;) {
5837 <                            if ((p = a.parent) == null) {
5838 <                                a.quietlyComplete();
5839 <                                break;
5840 <                            }
5841 <                            a = p;
5842 <                        }
5821 >            final Fun<? super V, ? extends U> searchFunction;
5822 >            final AtomicReference<U> result;
5823 >            if ((searchFunction = this.searchFunction) != null &&
5824 >                (result = this.result) != null) {
5825 >                for (int b;;) {
5826 >                    if (result.get() != null)
5827 >                        return;
5828 >                    if ((b = preSplit()) <= 0)
5829 >                        break;
5830 >                    new SearchValuesTask<K,V,U>
5831 >                        (map, this, b, searchFunction, result).fork();
5832 >                }
5833 >                while (result.get() == null) {
5834 >                    V v; U u;
5835 >                    if ((v = advance()) == null) {
5836 >                        propagateCompletion();
5837 >                        break;
5838 >                    }
5839 >                    if ((u = searchFunction.apply(v)) != null) {
5840 >                        if (result.compareAndSet(null, u))
5841 >                            quietlyCompleteRoot();
5842 >                        break;
5843                      }
5349                    break;
5844                  }
5845              }
5352            tryComplete();
5846          }
5354        public final U getRawResult() { return result.get(); }
5847      }
5848  
5849 <    @SuppressWarnings("serial")
5850 <    static final class SearchEntriesTask<K,V,U>
5359 <        extends BulkTask<K,V,U> {
5849 >    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5850 >        extends Traverser<K,V,U> {
5851          final Fun<Entry<K,V>, ? extends U> searchFunction;
5852          final AtomicReference<U> result;
5853          SearchEntriesTask
5854 <            (ConcurrentHashMapV8<K,V> m,
5854 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5855               Fun<Entry<K,V>, ? extends U> searchFunction,
5856               AtomicReference<U> result) {
5857 <            super(m);
5367 <            this.searchFunction = searchFunction; this.result = result;
5368 <        }
5369 <        SearchEntriesTask
5370 <            (BulkTask<K,V,?> p, int b, boolean split,
5371 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5372 <             AtomicReference<U> result) {
5373 <            super(p, b, split);
5857 >            super(m, p, b);
5858              this.searchFunction = searchFunction; this.result = result;
5859          }
5860 +        public final U getRawResult() { return result.get(); }
5861          @SuppressWarnings("unchecked") public final void compute() {
5862 <            AtomicReference<U> result = this.result;
5863 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5864 <                this.searchFunction;
5865 <            if (searchFunction == null || result == null)
5866 <                throw new Error(NullFunctionMessage);
5867 <            int b = batch(), c;
5868 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5869 <                do {} while (!casPending(c = pending, c+1));
5870 <                new SearchEntriesTask<K,V,U>(this, b >>>= 1, true,
5871 <                                             searchFunction, result).fork();
5872 <            }
5873 <            Object v; U u;
5874 <            while (result.get() == null && (v = advance()) != null) {
5875 <                if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5876 <                    if (result.compareAndSet(null, u)) {
5877 <                        for (BulkTask<K,V,?> a = this, p;;) {
5878 <                            if ((p = a.parent) == null) {
5879 <                                a.quietlyComplete();
5880 <                                break;
5881 <                            }
5882 <                            a = p;
5883 <                        }
5862 >            final Fun<Entry<K,V>, ? extends U> searchFunction;
5863 >            final AtomicReference<U> result;
5864 >            if ((searchFunction = this.searchFunction) != null &&
5865 >                (result = this.result) != null) {
5866 >                for (int b;;) {
5867 >                    if (result.get() != null)
5868 >                        return;
5869 >                    if ((b = preSplit()) <= 0)
5870 >                        break;
5871 >                    new SearchEntriesTask<K,V,U>
5872 >                        (map, this, b, searchFunction, result).fork();
5873 >                }
5874 >                while (result.get() == null) {
5875 >                    V v; U u;
5876 >                    if ((v = advance()) == null) {
5877 >                        propagateCompletion();
5878 >                        break;
5879 >                    }
5880 >                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5881 >                                                           v))) != null) {
5882 >                        if (result.compareAndSet(null, u))
5883 >                            quietlyCompleteRoot();
5884 >                        return;
5885                      }
5400                    break;
5886                  }
5887              }
5403            tryComplete();
5888          }
5405        public final U getRawResult() { return result.get(); }
5889      }
5890  
5891 <    @SuppressWarnings("serial")
5892 <    static final class SearchMappingsTask<K,V,U>
5410 <        extends BulkTask<K,V,U> {
5891 >    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5892 >        extends Traverser<K,V,U> {
5893          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5894          final AtomicReference<U> result;
5895          SearchMappingsTask
5896 <            (ConcurrentHashMapV8<K,V> m,
5896 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5897               BiFun<? super K, ? super V, ? extends U> searchFunction,
5898               AtomicReference<U> result) {
5899 <            super(m);
5418 <            this.searchFunction = searchFunction; this.result = result;
5419 <        }
5420 <        SearchMappingsTask
5421 <            (BulkTask<K,V,?> p, int b, boolean split,
5422 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5423 <             AtomicReference<U> result) {
5424 <            super(p, b, split);
5899 >            super(m, p, b);
5900              this.searchFunction = searchFunction; this.result = result;
5901          }
5902 +        public final U getRawResult() { return result.get(); }
5903          @SuppressWarnings("unchecked") public final void compute() {
5904 <            AtomicReference<U> result = this.result;
5905 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5906 <                this.searchFunction;
5907 <            if (searchFunction == null || result == null)
5908 <                throw new Error(NullFunctionMessage);
5909 <            int b = batch(), c;
5910 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5911 <                do {} while (!casPending(c = pending, c+1));
5912 <                new SearchMappingsTask<K,V,U>(this, b >>>= 1, true,
5913 <                                              searchFunction, result).fork();
5914 <            }
5915 <            Object v; U u;
5916 <            while (result.get() == null && (v = advance()) != null) {
5917 <                if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5918 <                    if (result.compareAndSet(null, u)) {
5919 <                        for (BulkTask<K,V,?> a = this, p;;) {
5920 <                            if ((p = a.parent) == null) {
5921 <                                a.quietlyComplete();
5922 <                                break;
5923 <                            }
5924 <                            a = p;
5925 <                        }
5904 >            final BiFun<? super K, ? super V, ? extends U> searchFunction;
5905 >            final AtomicReference<U> result;
5906 >            if ((searchFunction = this.searchFunction) != null &&
5907 >                (result = this.result) != null) {
5908 >                for (int b;;) {
5909 >                    if (result.get() != null)
5910 >                        return;
5911 >                    if ((b = preSplit()) <= 0)
5912 >                        break;
5913 >                    new SearchMappingsTask<K,V,U>
5914 >                        (map, this, b, searchFunction, result).fork();
5915 >                }
5916 >                while (result.get() == null) {
5917 >                    V v; U u;
5918 >                    if ((v = advance()) == null) {
5919 >                        propagateCompletion();
5920 >                        break;
5921 >                    }
5922 >                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5923 >                        if (result.compareAndSet(null, u))
5924 >                            quietlyCompleteRoot();
5925 >                        break;
5926                      }
5451                    break;
5927                  }
5928              }
5454            tryComplete();
5929          }
5456        public final U getRawResult() { return result.get(); }
5930      }
5931  
5932 <    @SuppressWarnings("serial")
5933 <    static final class ReduceKeysTask<K,V>
5461 <        extends BulkTask<K,V,K> {
5932 >    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5933 >        extends Traverser<K,V,K> {
5934          final BiFun<? super K, ? super K, ? extends K> reducer;
5935          K result;
5936 <        ReduceKeysTask<K,V> sibling;
5465 <        ReduceKeysTask
5466 <            (ConcurrentHashMapV8<K,V> m,
5467 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5468 <            super(m);
5469 <            this.reducer = reducer;
5470 <        }
5936 >        ReduceKeysTask<K,V> rights, nextRight;
5937          ReduceKeysTask
5938 <            (BulkTask<K,V,?> p, int b, boolean split,
5938 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5939 >             ReduceKeysTask<K,V> nextRight,
5940               BiFun<? super K, ? super K, ? extends K> reducer) {
5941 <            super(p, b, split);
5941 >            super(m, p, b); this.nextRight = nextRight;
5942              this.reducer = reducer;
5943          }
5944 <
5944 >        public final K getRawResult() { return result; }
5945          @SuppressWarnings("unchecked") public final void compute() {
5946 <            ReduceKeysTask<K,V> t = this;
5947 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5948 <                this.reducer;
5949 <            if (reducer == null)
5950 <                throw new Error(NullFunctionMessage);
5951 <            int b = batch();
5952 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5953 <                b >>>= 1;
5954 <                t.pending = 1;
5488 <                ReduceKeysTask<K,V> rt =
5489 <                    new ReduceKeysTask<K,V>
5490 <                    (t, b, true, reducer);
5491 <                t = new ReduceKeysTask<K,V>
5492 <                    (t, b, false, reducer);
5493 <                t.sibling = rt;
5494 <                rt.sibling = t;
5495 <                rt.fork();
5496 <            }
5497 <            K r = null;
5498 <            while (t.advance() != null) {
5499 <                K u = (K)t.nextKey;
5500 <                r = (r == null) ? u : reducer.apply(r, u);
5501 <            }
5502 <            t.result = r;
5503 <            for (;;) {
5504 <                int c; BulkTask<K,V,?> par; ReduceKeysTask<K,V> s, p; K u;
5505 <                if ((par = t.parent) == null ||
5506 <                    !(par instanceof ReduceKeysTask)) {
5507 <                    t.quietlyComplete();
5508 <                    break;
5946 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5947 >            if ((reducer = this.reducer) != null) {
5948 >                for (int b; (b = preSplit()) > 0;)
5949 >                    (rights = new ReduceKeysTask<K,V>
5950 >                     (map, this, b, rights, reducer)).fork();
5951 >                K r = null;
5952 >                while (advance() != null) {
5953 >                    K u = (K)nextKey;
5954 >                    r = (r == null) ? u : reducer.apply(r, u);
5955                  }
5956 <                else if ((c = (p = (ReduceKeysTask<K,V>)par).pending) == 0) {
5957 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5958 <                        r = (r == null) ? u : reducer.apply(r, u);
5959 <                    (t = p).result = r;
5956 >                result = r;
5957 >                CountedCompleter<?> c;
5958 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5959 >                    ReduceKeysTask<K,V>
5960 >                        t = (ReduceKeysTask<K,V>)c,
5961 >                        s = t.rights;
5962 >                    while (s != null) {
5963 >                        K tr, sr;
5964 >                        if ((sr = s.result) != null)
5965 >                            t.result = (((tr = t.result) == null) ? sr :
5966 >                                        reducer.apply(tr, sr));
5967 >                        s = t.rights = s.nextRight;
5968 >                    }
5969                  }
5515                else if (p.casPending(c, 0))
5516                    break;
5970              }
5971          }
5519        public final K getRawResult() { return result; }
5972      }
5973  
5974 <    @SuppressWarnings("serial")
5975 <    static final class ReduceValuesTask<K,V>
5524 <        extends BulkTask<K,V,V> {
5974 >    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5975 >        extends Traverser<K,V,V> {
5976          final BiFun<? super V, ? super V, ? extends V> reducer;
5977          V result;
5978 <        ReduceValuesTask<K,V> sibling;
5528 <        ReduceValuesTask
5529 <            (ConcurrentHashMapV8<K,V> m,
5530 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5531 <            super(m);
5532 <            this.reducer = reducer;
5533 <        }
5978 >        ReduceValuesTask<K,V> rights, nextRight;
5979          ReduceValuesTask
5980 <            (BulkTask<K,V,?> p, int b, boolean split,
5980 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5981 >             ReduceValuesTask<K,V> nextRight,
5982               BiFun<? super V, ? super V, ? extends V> reducer) {
5983 <            super(p, b, split);
5983 >            super(m, p, b); this.nextRight = nextRight;
5984              this.reducer = reducer;
5985          }
5986 <
5986 >        public final V getRawResult() { return result; }
5987          @SuppressWarnings("unchecked") public final void compute() {
5988 <            ReduceValuesTask<K,V> t = this;
5989 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5990 <                this.reducer;
5991 <            if (reducer == null)
5992 <                throw new Error(NullFunctionMessage);
5993 <            int b = batch();
5994 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5995 <                b >>>= 1;
5996 <                t.pending = 1;
5997 <                ReduceValuesTask<K,V> rt =
5552 <                    new ReduceValuesTask<K,V>
5553 <                    (t, b, true, reducer);
5554 <                t = new ReduceValuesTask<K,V>
5555 <                    (t, b, false, reducer);
5556 <                t.sibling = rt;
5557 <                rt.sibling = t;
5558 <                rt.fork();
5559 <            }
5560 <            V r = null;
5561 <            Object v;
5562 <            while ((v = t.advance()) != null) {
5563 <                V u = (V)v;
5564 <                r = (r == null) ? u : reducer.apply(r, u);
5565 <            }
5566 <            t.result = r;
5567 <            for (;;) {
5568 <                int c; BulkTask<K,V,?> par; ReduceValuesTask<K,V> s, p; V u;
5569 <                if ((par = t.parent) == null ||
5570 <                    !(par instanceof ReduceValuesTask)) {
5571 <                    t.quietlyComplete();
5572 <                    break;
5988 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5989 >            if ((reducer = this.reducer) != null) {
5990 >                for (int b; (b = preSplit()) > 0;)
5991 >                    (rights = new ReduceValuesTask<K,V>
5992 >                     (map, this, b, rights, reducer)).fork();
5993 >                V r = null;
5994 >                V v;
5995 >                while ((v = advance()) != null) {
5996 >                    V u = v;
5997 >                    r = (r == null) ? u : reducer.apply(r, u);
5998                  }
5999 <                else if ((c = (p = (ReduceValuesTask<K,V>)par).pending) == 0) {
6000 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6001 <                        r = (r == null) ? u : reducer.apply(r, u);
6002 <                    (t = p).result = r;
5999 >                result = r;
6000 >                CountedCompleter<?> c;
6001 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6002 >                    ReduceValuesTask<K,V>
6003 >                        t = (ReduceValuesTask<K,V>)c,
6004 >                        s = t.rights;
6005 >                    while (s != null) {
6006 >                        V tr, sr;
6007 >                        if ((sr = s.result) != null)
6008 >                            t.result = (((tr = t.result) == null) ? sr :
6009 >                                        reducer.apply(tr, sr));
6010 >                        s = t.rights = s.nextRight;
6011 >                    }
6012                  }
5579                else if (p.casPending(c, 0))
5580                    break;
6013              }
6014          }
5583        public final V getRawResult() { return result; }
6015      }
6016  
6017 <    @SuppressWarnings("serial")
6018 <    static final class ReduceEntriesTask<K,V>
5588 <        extends BulkTask<K,V,Map.Entry<K,V>> {
6017 >    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6018 >        extends Traverser<K,V,Map.Entry<K,V>> {
6019          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6020          Map.Entry<K,V> result;
6021 <        ReduceEntriesTask<K,V> sibling;
6021 >        ReduceEntriesTask<K,V> rights, nextRight;
6022          ReduceEntriesTask
6023 <            (ConcurrentHashMapV8<K,V> m,
6023 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6024 >             ReduceEntriesTask<K,V> nextRight,
6025               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6026 <            super(m);
5596 <            this.reducer = reducer;
5597 <        }
5598 <        ReduceEntriesTask
5599 <            (BulkTask<K,V,?> p, int b, boolean split,
5600 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5601 <            super(p, b, split);
6026 >            super(m, p, b); this.nextRight = nextRight;
6027              this.reducer = reducer;
6028          }
6029 <
6029 >        public final Map.Entry<K,V> getRawResult() { return result; }
6030          @SuppressWarnings("unchecked") public final void compute() {
6031 <            ReduceEntriesTask<K,V> t = this;
6032 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
6033 <                this.reducer;
6034 <            if (reducer == null)
6035 <                throw new Error(NullFunctionMessage);
6036 <            int b = batch();
6037 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6038 <                b >>>= 1;
6039 <                t.pending = 1;
6040 <                ReduceEntriesTask<K,V> rt =
5616 <                    new ReduceEntriesTask<K,V>
5617 <                    (t, b, true, reducer);
5618 <                t = new ReduceEntriesTask<K,V>
5619 <                    (t, b, false, reducer);
5620 <                t.sibling = rt;
5621 <                rt.sibling = t;
5622 <                rt.fork();
5623 <            }
5624 <            Map.Entry<K,V> r = null;
5625 <            Object v;
5626 <            while ((v = t.advance()) != null) {
5627 <                Map.Entry<K,V> u = entryFor((K)t.nextKey, (V)v);
5628 <                r = (r == null) ? u : reducer.apply(r, u);
5629 <            }
5630 <            t.result = r;
5631 <            for (;;) {
5632 <                int c; BulkTask<K,V,?> par; ReduceEntriesTask<K,V> s, p;
5633 <                Map.Entry<K,V> u;
5634 <                if ((par = t.parent) == null ||
5635 <                    !(par instanceof ReduceEntriesTask)) {
5636 <                    t.quietlyComplete();
5637 <                    break;
6031 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6032 >            if ((reducer = this.reducer) != null) {
6033 >                for (int b; (b = preSplit()) > 0;)
6034 >                    (rights = new ReduceEntriesTask<K,V>
6035 >                     (map, this, b, rights, reducer)).fork();
6036 >                Map.Entry<K,V> r = null;
6037 >                V v;
6038 >                while ((v = advance()) != null) {
6039 >                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6040 >                    r = (r == null) ? u : reducer.apply(r, u);
6041                  }
6042 <                else if ((c = (p = (ReduceEntriesTask<K,V>)par).pending) == 0) {
6043 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6044 <                        r = (r == null) ? u : reducer.apply(r, u);
6045 <                    (t = p).result = r;
6042 >                result = r;
6043 >                CountedCompleter<?> c;
6044 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6045 >                    ReduceEntriesTask<K,V>
6046 >                        t = (ReduceEntriesTask<K,V>)c,
6047 >                        s = t.rights;
6048 >                    while (s != null) {
6049 >                        Map.Entry<K,V> tr, sr;
6050 >                        if ((sr = s.result) != null)
6051 >                            t.result = (((tr = t.result) == null) ? sr :
6052 >                                        reducer.apply(tr, sr));
6053 >                        s = t.rights = s.nextRight;
6054 >                    }
6055                  }
5644                else if (p.casPending(c, 0))
5645                    break;
6056              }
6057          }
5648        public final Map.Entry<K,V> getRawResult() { return result; }
6058      }
6059  
6060 <    @SuppressWarnings("serial")
6061 <    static final class MapReduceKeysTask<K,V,U>
5653 <        extends BulkTask<K,V,U> {
6060 >    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6061 >        extends Traverser<K,V,U> {
6062          final Fun<? super K, ? extends U> transformer;
6063          final BiFun<? super U, ? super U, ? extends U> reducer;
6064          U result;
6065 <        MapReduceKeysTask<K,V,U> sibling;
5658 <        MapReduceKeysTask
5659 <            (ConcurrentHashMapV8<K,V> m,
5660 <             Fun<? super K, ? extends U> transformer,
5661 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5662 <            super(m);
5663 <            this.transformer = transformer;
5664 <            this.reducer = reducer;
5665 <        }
6065 >        MapReduceKeysTask<K,V,U> rights, nextRight;
6066          MapReduceKeysTask
6067 <            (BulkTask<K,V,?> p, int b, boolean split,
6067 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6068 >             MapReduceKeysTask<K,V,U> nextRight,
6069               Fun<? super K, ? extends U> transformer,
6070               BiFun<? super U, ? super U, ? extends U> reducer) {
6071 <            super(p, b, split);
6071 >            super(m, p, b); this.nextRight = nextRight;
6072              this.transformer = transformer;
6073              this.reducer = reducer;
6074          }
6075 +        public final U getRawResult() { return result; }
6076          @SuppressWarnings("unchecked") public final void compute() {
6077 <            MapReduceKeysTask<K,V,U> t = this;
6078 <            final Fun<? super K, ? extends U> transformer =
6079 <                this.transformer;
6080 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6081 <                this.reducer;
6082 <            if (transformer == null || reducer == null)
6083 <                throw new Error(NullFunctionMessage);
6084 <            int b = batch();
6085 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6086 <                b >>>= 1;
5685 <                t.pending = 1;
5686 <                MapReduceKeysTask<K,V,U> rt =
5687 <                    new MapReduceKeysTask<K,V,U>
5688 <                    (t, b, true, transformer, reducer);
5689 <                t = new MapReduceKeysTask<K,V,U>
5690 <                    (t, b, false, transformer, reducer);
5691 <                t.sibling = rt;
5692 <                rt.sibling = t;
5693 <                rt.fork();
5694 <            }
5695 <            U r = null, u;
5696 <            while (t.advance() != null) {
5697 <                if ((u = transformer.apply((K)t.nextKey)) != null)
5698 <                    r = (r == null) ? u : reducer.apply(r, u);
5699 <            }
5700 <            t.result = r;
5701 <            for (;;) {
5702 <                int c; BulkTask<K,V,?> par; MapReduceKeysTask<K,V,U> s, p;
5703 <                if ((par = t.parent) == null ||
5704 <                    !(par instanceof MapReduceKeysTask)) {
5705 <                    t.quietlyComplete();
5706 <                    break;
5707 <                }
5708 <                else if ((c = (p = (MapReduceKeysTask<K,V,U>)par).pending) == 0) {
5709 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6077 >            final Fun<? super K, ? extends U> transformer;
6078 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6079 >            if ((transformer = this.transformer) != null &&
6080 >                (reducer = this.reducer) != null) {
6081 >                for (int b; (b = preSplit()) > 0;)
6082 >                    (rights = new MapReduceKeysTask<K,V,U>
6083 >                     (map, this, b, rights, transformer, reducer)).fork();
6084 >                U r = null, u;
6085 >                while (advance() != null) {
6086 >                    if ((u = transformer.apply((K)nextKey)) != null)
6087                          r = (r == null) ? u : reducer.apply(r, u);
5711                    (t = p).result = r;
6088                  }
6089 <                else if (p.casPending(c, 0))
6090 <                    break;
6089 >                result = r;
6090 >                CountedCompleter<?> c;
6091 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6092 >                    MapReduceKeysTask<K,V,U>
6093 >                        t = (MapReduceKeysTask<K,V,U>)c,
6094 >                        s = t.rights;
6095 >                    while (s != null) {
6096 >                        U tr, sr;
6097 >                        if ((sr = s.result) != null)
6098 >                            t.result = (((tr = t.result) == null) ? sr :
6099 >                                        reducer.apply(tr, sr));
6100 >                        s = t.rights = s.nextRight;
6101 >                    }
6102 >                }
6103              }
6104          }
5717        public final U getRawResult() { return result; }
6105      }
6106  
6107 <    @SuppressWarnings("serial")
6108 <    static final class MapReduceValuesTask<K,V,U>
5722 <        extends BulkTask<K,V,U> {
6107 >    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6108 >        extends Traverser<K,V,U> {
6109          final Fun<? super V, ? extends U> transformer;
6110          final BiFun<? super U, ? super U, ? extends U> reducer;
6111          U result;
6112 <        MapReduceValuesTask<K,V,U> sibling;
5727 <        MapReduceValuesTask
5728 <            (ConcurrentHashMapV8<K,V> m,
5729 <             Fun<? super V, ? extends U> transformer,
5730 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5731 <            super(m);
5732 <            this.transformer = transformer;
5733 <            this.reducer = reducer;
5734 <        }
6112 >        MapReduceValuesTask<K,V,U> rights, nextRight;
6113          MapReduceValuesTask
6114 <            (BulkTask<K,V,?> p, int b, boolean split,
6114 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6115 >             MapReduceValuesTask<K,V,U> nextRight,
6116               Fun<? super V, ? extends U> transformer,
6117               BiFun<? super U, ? super U, ? extends U> reducer) {
6118 <            super(p, b, split);
6118 >            super(m, p, b); this.nextRight = nextRight;
6119              this.transformer = transformer;
6120              this.reducer = reducer;
6121          }
6122 +        public final U getRawResult() { return result; }
6123          @SuppressWarnings("unchecked") public final void compute() {
6124 <            MapReduceValuesTask<K,V,U> t = this;
6125 <            final Fun<? super V, ? extends U> transformer =
6126 <                this.transformer;
6127 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6128 <                this.reducer;
6129 <            if (transformer == null || reducer == null)
6130 <                throw new Error(NullFunctionMessage);
6131 <            int b = batch();
6132 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6133 <                b >>>= 1;
6134 <                t.pending = 1;
5755 <                MapReduceValuesTask<K,V,U> rt =
5756 <                    new MapReduceValuesTask<K,V,U>
5757 <                    (t, b, true, transformer, reducer);
5758 <                t = new MapReduceValuesTask<K,V,U>
5759 <                    (t, b, false, transformer, reducer);
5760 <                t.sibling = rt;
5761 <                rt.sibling = t;
5762 <                rt.fork();
5763 <            }
5764 <            U r = null, u;
5765 <            Object v;
5766 <            while ((v = t.advance()) != null) {
5767 <                if ((u = transformer.apply((V)v)) != null)
5768 <                    r = (r == null) ? u : reducer.apply(r, u);
5769 <            }
5770 <            t.result = r;
5771 <            for (;;) {
5772 <                int c; BulkTask<K,V,?> par; MapReduceValuesTask<K,V,U> s, p;
5773 <                if ((par = t.parent) == null ||
5774 <                    !(par instanceof MapReduceValuesTask)) {
5775 <                    t.quietlyComplete();
5776 <                    break;
5777 <                }
5778 <                else if ((c = (p = (MapReduceValuesTask<K,V,U>)par).pending) == 0) {
5779 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6124 >            final Fun<? super V, ? extends U> transformer;
6125 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6126 >            if ((transformer = this.transformer) != null &&
6127 >                (reducer = this.reducer) != null) {
6128 >                for (int b; (b = preSplit()) > 0;)
6129 >                    (rights = new MapReduceValuesTask<K,V,U>
6130 >                     (map, this, b, rights, transformer, reducer)).fork();
6131 >                U r = null, u;
6132 >                V v;
6133 >                while ((v = advance()) != null) {
6134 >                    if ((u = transformer.apply(v)) != null)
6135                          r = (r == null) ? u : reducer.apply(r, u);
5781                    (t = p).result = r;
6136                  }
6137 <                else if (p.casPending(c, 0))
6138 <                    break;
6137 >                result = r;
6138 >                CountedCompleter<?> c;
6139 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6140 >                    MapReduceValuesTask<K,V,U>
6141 >                        t = (MapReduceValuesTask<K,V,U>)c,
6142 >                        s = t.rights;
6143 >                    while (s != null) {
6144 >                        U tr, sr;
6145 >                        if ((sr = s.result) != null)
6146 >                            t.result = (((tr = t.result) == null) ? sr :
6147 >                                        reducer.apply(tr, sr));
6148 >                        s = t.rights = s.nextRight;
6149 >                    }
6150 >                }
6151              }
6152          }
5787        public final U getRawResult() { return result; }
6153      }
6154  
6155 <    @SuppressWarnings("serial")
6156 <    static final class MapReduceEntriesTask<K,V,U>
5792 <        extends BulkTask<K,V,U> {
6155 >    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6156 >        extends Traverser<K,V,U> {
6157          final Fun<Map.Entry<K,V>, ? extends U> transformer;
6158          final BiFun<? super U, ? super U, ? extends U> reducer;
6159          U result;
6160 <        MapReduceEntriesTask<K,V,U> sibling;
5797 <        MapReduceEntriesTask
5798 <            (ConcurrentHashMapV8<K,V> m,
5799 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5800 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5801 <            super(m);
5802 <            this.transformer = transformer;
5803 <            this.reducer = reducer;
5804 <        }
6160 >        MapReduceEntriesTask<K,V,U> rights, nextRight;
6161          MapReduceEntriesTask
6162 <            (BulkTask<K,V,?> p, int b, boolean split,
6162 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6163 >             MapReduceEntriesTask<K,V,U> nextRight,
6164               Fun<Map.Entry<K,V>, ? extends U> transformer,
6165               BiFun<? super U, ? super U, ? extends U> reducer) {
6166 <            super(p, b, split);
6166 >            super(m, p, b); this.nextRight = nextRight;
6167              this.transformer = transformer;
6168              this.reducer = reducer;
6169          }
6170 +        public final U getRawResult() { return result; }
6171          @SuppressWarnings("unchecked") public final void compute() {
6172 <            MapReduceEntriesTask<K,V,U> t = this;
6173 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
6174 <                this.transformer;
6175 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6176 <                this.reducer;
6177 <            if (transformer == null || reducer == null)
6178 <                throw new Error(NullFunctionMessage);
6179 <            int b = batch();
6180 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6181 <                b >>>= 1;
6182 <                t.pending = 1;
6183 <                MapReduceEntriesTask<K,V,U> rt =
5826 <                    new MapReduceEntriesTask<K,V,U>
5827 <                    (t, b, true, transformer, reducer);
5828 <                t = new MapReduceEntriesTask<K,V,U>
5829 <                    (t, b, false, transformer, reducer);
5830 <                t.sibling = rt;
5831 <                rt.sibling = t;
5832 <                rt.fork();
5833 <            }
5834 <            U r = null, u;
5835 <            Object v;
5836 <            while ((v = t.advance()) != null) {
5837 <                if ((u = transformer.apply(entryFor((K)t.nextKey, (V)v))) != null)
5838 <                    r = (r == null) ? u : reducer.apply(r, u);
5839 <            }
5840 <            t.result = r;
5841 <            for (;;) {
5842 <                int c; BulkTask<K,V,?> par; MapReduceEntriesTask<K,V,U> s, p;
5843 <                if ((par = t.parent) == null ||
5844 <                    !(par instanceof MapReduceEntriesTask)) {
5845 <                    t.quietlyComplete();
5846 <                    break;
5847 <                }
5848 <                else if ((c = (p = (MapReduceEntriesTask<K,V,U>)par).pending) == 0) {
5849 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6172 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
6173 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6174 >            if ((transformer = this.transformer) != null &&
6175 >                (reducer = this.reducer) != null) {
6176 >                for (int b; (b = preSplit()) > 0;)
6177 >                    (rights = new MapReduceEntriesTask<K,V,U>
6178 >                     (map, this, b, rights, transformer, reducer)).fork();
6179 >                U r = null, u;
6180 >                V v;
6181 >                while ((v = advance()) != null) {
6182 >                    if ((u = transformer.apply(entryFor((K)nextKey,
6183 >                                                        v))) != null)
6184                          r = (r == null) ? u : reducer.apply(r, u);
5851                    (t = p).result = r;
6185                  }
6186 <                else if (p.casPending(c, 0))
6187 <                    break;
6186 >                result = r;
6187 >                CountedCompleter<?> c;
6188 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6189 >                    MapReduceEntriesTask<K,V,U>
6190 >                        t = (MapReduceEntriesTask<K,V,U>)c,
6191 >                        s = t.rights;
6192 >                    while (s != null) {
6193 >                        U tr, sr;
6194 >                        if ((sr = s.result) != null)
6195 >                            t.result = (((tr = t.result) == null) ? sr :
6196 >                                        reducer.apply(tr, sr));
6197 >                        s = t.rights = s.nextRight;
6198 >                    }
6199 >                }
6200              }
6201          }
5857        public final U getRawResult() { return result; }
6202      }
6203  
6204 <    @SuppressWarnings("serial")
6205 <    static final class MapReduceMappingsTask<K,V,U>
5862 <        extends BulkTask<K,V,U> {
6204 >    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6205 >        extends Traverser<K,V,U> {
6206          final BiFun<? super K, ? super V, ? extends U> transformer;
6207          final BiFun<? super U, ? super U, ? extends U> reducer;
6208          U result;
6209 <        MapReduceMappingsTask<K,V,U> sibling;
5867 <        MapReduceMappingsTask
5868 <            (ConcurrentHashMapV8<K,V> m,
5869 <             BiFun<? super K, ? super V, ? extends U> transformer,
5870 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5871 <            super(m);
5872 <            this.transformer = transformer;
5873 <            this.reducer = reducer;
5874 <        }
6209 >        MapReduceMappingsTask<K,V,U> rights, nextRight;
6210          MapReduceMappingsTask
6211 <            (BulkTask<K,V,?> p, int b, boolean split,
6211 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6212 >             MapReduceMappingsTask<K,V,U> nextRight,
6213               BiFun<? super K, ? super V, ? extends U> transformer,
6214               BiFun<? super U, ? super U, ? extends U> reducer) {
6215 <            super(p, b, split);
6215 >            super(m, p, b); this.nextRight = nextRight;
6216              this.transformer = transformer;
6217              this.reducer = reducer;
6218          }
6219 +        public final U getRawResult() { return result; }
6220          @SuppressWarnings("unchecked") public final void compute() {
6221 <            MapReduceMappingsTask<K,V,U> t = this;
6222 <            final BiFun<? super K, ? super V, ? extends U> transformer =
6223 <                this.transformer;
6224 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6225 <                this.reducer;
6226 <            if (transformer == null || reducer == null)
6227 <                throw new Error(NullFunctionMessage);
6228 <            int b = batch();
6229 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6230 <                b >>>= 1;
6231 <                t.pending = 1;
5895 <                MapReduceMappingsTask<K,V,U> rt =
5896 <                    new MapReduceMappingsTask<K,V,U>
5897 <                    (t, b, true, transformer, reducer);
5898 <                t = new MapReduceMappingsTask<K,V,U>
5899 <                    (t, b, false, transformer, reducer);
5900 <                t.sibling = rt;
5901 <                rt.sibling = t;
5902 <                rt.fork();
5903 <            }
5904 <            U r = null, u;
5905 <            Object v;
5906 <            while ((v = t.advance()) != null) {
5907 <                if ((u = transformer.apply((K)t.nextKey, (V)v)) != null)
5908 <                    r = (r == null) ? u : reducer.apply(r, u);
5909 <            }
5910 <            for (;;) {
5911 <                int c; BulkTask<K,V,?> par; MapReduceMappingsTask<K,V,U> s, p;
5912 <                if ((par = t.parent) == null ||
5913 <                    !(par instanceof MapReduceMappingsTask)) {
5914 <                    t.quietlyComplete();
5915 <                    break;
5916 <                }
5917 <                else if ((c = (p = (MapReduceMappingsTask<K,V,U>)par).pending) == 0) {
5918 <                    if ((s = t.sibling) != null && (u = s.result) != null)
6221 >            final BiFun<? super K, ? super V, ? extends U> transformer;
6222 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6223 >            if ((transformer = this.transformer) != null &&
6224 >                (reducer = this.reducer) != null) {
6225 >                for (int b; (b = preSplit()) > 0;)
6226 >                    (rights = new MapReduceMappingsTask<K,V,U>
6227 >                     (map, this, b, rights, transformer, reducer)).fork();
6228 >                U r = null, u;
6229 >                V v;
6230 >                while ((v = advance()) != null) {
6231 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
6232                          r = (r == null) ? u : reducer.apply(r, u);
5920                    (t = p).result = r;
6233                  }
6234 <                else if (p.casPending(c, 0))
6235 <                    break;
6234 >                result = r;
6235 >                CountedCompleter<?> c;
6236 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6237 >                    MapReduceMappingsTask<K,V,U>
6238 >                        t = (MapReduceMappingsTask<K,V,U>)c,
6239 >                        s = t.rights;
6240 >                    while (s != null) {
6241 >                        U tr, sr;
6242 >                        if ((sr = s.result) != null)
6243 >                            t.result = (((tr = t.result) == null) ? sr :
6244 >                                        reducer.apply(tr, sr));
6245 >                        s = t.rights = s.nextRight;
6246 >                    }
6247 >                }
6248              }
6249          }
5926        public final U getRawResult() { return result; }
6250      }
6251  
6252 <    @SuppressWarnings("serial")
6253 <    static final class MapReduceKeysToDoubleTask<K,V>
5931 <        extends BulkTask<K,V,Double> {
6252 >    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6253 >        extends Traverser<K,V,Double> {
6254          final ObjectToDouble<? super K> transformer;
6255          final DoubleByDoubleToDouble reducer;
6256          final double basis;
6257          double result;
6258 <        MapReduceKeysToDoubleTask<K,V> sibling;
5937 <        MapReduceKeysToDoubleTask
5938 <            (ConcurrentHashMapV8<K,V> m,
5939 <             ObjectToDouble<? super K> transformer,
5940 <             double basis,
5941 <             DoubleByDoubleToDouble reducer) {
5942 <            super(m);
5943 <            this.transformer = transformer;
5944 <            this.basis = basis; this.reducer = reducer;
5945 <        }
6258 >        MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6259          MapReduceKeysToDoubleTask
6260 <            (BulkTask<K,V,?> p, int b, boolean split,
6260 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6261 >             MapReduceKeysToDoubleTask<K,V> nextRight,
6262               ObjectToDouble<? super K> transformer,
6263               double basis,
6264               DoubleByDoubleToDouble reducer) {
6265 <            super(p, b, split);
6265 >            super(m, p, b); this.nextRight = nextRight;
6266              this.transformer = transformer;
6267              this.basis = basis; this.reducer = reducer;
6268          }
6269 +        public final Double getRawResult() { return result; }
6270          @SuppressWarnings("unchecked") public final void compute() {
6271 <            MapReduceKeysToDoubleTask<K,V> t = this;
6272 <            final ObjectToDouble<? super K> transformer =
6273 <                this.transformer;
6274 <            final DoubleByDoubleToDouble reducer = this.reducer;
6275 <            if (transformer == null || reducer == null)
6276 <                throw new Error(NullFunctionMessage);
6277 <            final double id = this.basis;
6278 <            int b = batch();
6279 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6280 <                b >>>= 1;
6281 <                t.pending = 1;
6282 <                MapReduceKeysToDoubleTask<K,V> rt =
6283 <                    new MapReduceKeysToDoubleTask<K,V>
6284 <                    (t, b, true, transformer, id, reducer);
6285 <                t = new MapReduceKeysToDoubleTask<K,V>
6286 <                    (t, b, false, transformer, id, reducer);
6287 <                t.sibling = rt;
6288 <                rt.sibling = t;
6289 <                rt.fork();
6290 <            }
5976 <            double r = id;
5977 <            while (t.advance() != null)
5978 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5979 <            t.result = r;
5980 <            for (;;) {
5981 <                int c; BulkTask<K,V,?> par; MapReduceKeysToDoubleTask<K,V> s, p;
5982 <                if ((par = t.parent) == null ||
5983 <                    !(par instanceof MapReduceKeysToDoubleTask)) {
5984 <                    t.quietlyComplete();
5985 <                    break;
5986 <                }
5987 <                else if ((c = (p = (MapReduceKeysToDoubleTask<K,V>)par).pending) == 0) {
5988 <                    if ((s = t.sibling) != null)
5989 <                        r = reducer.apply(r, s.result);
5990 <                    (t = p).result = r;
6271 >            final ObjectToDouble<? super K> transformer;
6272 >            final DoubleByDoubleToDouble reducer;
6273 >            if ((transformer = this.transformer) != null &&
6274 >                (reducer = this.reducer) != null) {
6275 >                double r = this.basis;
6276 >                for (int b; (b = preSplit()) > 0;)
6277 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
6278 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6279 >                while (advance() != null)
6280 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6281 >                result = r;
6282 >                CountedCompleter<?> c;
6283 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6284 >                    MapReduceKeysToDoubleTask<K,V>
6285 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
6286 >                        s = t.rights;
6287 >                    while (s != null) {
6288 >                        t.result = reducer.apply(t.result, s.result);
6289 >                        s = t.rights = s.nextRight;
6290 >                    }
6291                  }
5992                else if (p.casPending(c, 0))
5993                    break;
6292              }
6293          }
5996        public final Double getRawResult() { return result; }
6294      }
6295  
6296 <    @SuppressWarnings("serial")
6297 <    static final class MapReduceValuesToDoubleTask<K,V>
6001 <        extends BulkTask<K,V,Double> {
6296 >    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6297 >        extends Traverser<K,V,Double> {
6298          final ObjectToDouble<? super V> transformer;
6299          final DoubleByDoubleToDouble reducer;
6300          final double basis;
6301          double result;
6302 <        MapReduceValuesToDoubleTask<K,V> sibling;
6007 <        MapReduceValuesToDoubleTask
6008 <            (ConcurrentHashMapV8<K,V> m,
6009 <             ObjectToDouble<? super V> transformer,
6010 <             double basis,
6011 <             DoubleByDoubleToDouble reducer) {
6012 <            super(m);
6013 <            this.transformer = transformer;
6014 <            this.basis = basis; this.reducer = reducer;
6015 <        }
6302 >        MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6303          MapReduceValuesToDoubleTask
6304 <            (BulkTask<K,V,?> p, int b, boolean split,
6304 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6305 >             MapReduceValuesToDoubleTask<K,V> nextRight,
6306               ObjectToDouble<? super V> transformer,
6307               double basis,
6308               DoubleByDoubleToDouble reducer) {
6309 <            super(p, b, split);
6309 >            super(m, p, b); this.nextRight = nextRight;
6310              this.transformer = transformer;
6311              this.basis = basis; this.reducer = reducer;
6312          }
6313 +        public final Double getRawResult() { return result; }
6314          @SuppressWarnings("unchecked") public final void compute() {
6315 <            MapReduceValuesToDoubleTask<K,V> t = this;
6316 <            final ObjectToDouble<? super V> transformer =
6317 <                this.transformer;
6318 <            final DoubleByDoubleToDouble reducer = this.reducer;
6319 <            if (transformer == null || reducer == null)
6320 <                throw new Error(NullFunctionMessage);
6321 <            final double id = this.basis;
6322 <            int b = batch();
6323 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6324 <                b >>>= 1;
6325 <                t.pending = 1;
6326 <                MapReduceValuesToDoubleTask<K,V> rt =
6327 <                    new MapReduceValuesToDoubleTask<K,V>
6328 <                    (t, b, true, transformer, id, reducer);
6329 <                t = new MapReduceValuesToDoubleTask<K,V>
6330 <                    (t, b, false, transformer, id, reducer);
6331 <                t.sibling = rt;
6332 <                rt.sibling = t;
6333 <                rt.fork();
6334 <            }
6335 <            double r = id;
6047 <            Object v;
6048 <            while ((v = t.advance()) != null)
6049 <                r = reducer.apply(r, transformer.apply((V)v));
6050 <            t.result = r;
6051 <            for (;;) {
6052 <                int c; BulkTask<K,V,?> par; MapReduceValuesToDoubleTask<K,V> s, p;
6053 <                if ((par = t.parent) == null ||
6054 <                    !(par instanceof MapReduceValuesToDoubleTask)) {
6055 <                    t.quietlyComplete();
6056 <                    break;
6057 <                }
6058 <                else if ((c = (p = (MapReduceValuesToDoubleTask<K,V>)par).pending) == 0) {
6059 <                    if ((s = t.sibling) != null)
6060 <                        r = reducer.apply(r, s.result);
6061 <                    (t = p).result = r;
6315 >            final ObjectToDouble<? super V> transformer;
6316 >            final DoubleByDoubleToDouble reducer;
6317 >            if ((transformer = this.transformer) != null &&
6318 >                (reducer = this.reducer) != null) {
6319 >                double r = this.basis;
6320 >                for (int b; (b = preSplit()) > 0;)
6321 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
6322 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6323 >                V v;
6324 >                while ((v = advance()) != null)
6325 >                    r = reducer.apply(r, transformer.apply(v));
6326 >                result = r;
6327 >                CountedCompleter<?> c;
6328 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6329 >                    MapReduceValuesToDoubleTask<K,V>
6330 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
6331 >                        s = t.rights;
6332 >                    while (s != null) {
6333 >                        t.result = reducer.apply(t.result, s.result);
6334 >                        s = t.rights = s.nextRight;
6335 >                    }
6336                  }
6063                else if (p.casPending(c, 0))
6064                    break;
6337              }
6338          }
6067        public final Double getRawResult() { return result; }
6339      }
6340  
6341 <    @SuppressWarnings("serial")
6342 <    static final class MapReduceEntriesToDoubleTask<K,V>
6072 <        extends BulkTask<K,V,Double> {
6341 >    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6342 >        extends Traverser<K,V,Double> {
6343          final ObjectToDouble<Map.Entry<K,V>> transformer;
6344          final DoubleByDoubleToDouble reducer;
6345          final double basis;
6346          double result;
6347 <        MapReduceEntriesToDoubleTask<K,V> sibling;
6078 <        MapReduceEntriesToDoubleTask
6079 <            (ConcurrentHashMapV8<K,V> m,
6080 <             ObjectToDouble<Map.Entry<K,V>> transformer,
6081 <             double basis,
6082 <             DoubleByDoubleToDouble reducer) {
6083 <            super(m);
6084 <            this.transformer = transformer;
6085 <            this.basis = basis; this.reducer = reducer;
6086 <        }
6347 >        MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6348          MapReduceEntriesToDoubleTask
6349 <            (BulkTask<K,V,?> p, int b, boolean split,
6349 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6350 >             MapReduceEntriesToDoubleTask<K,V> nextRight,
6351               ObjectToDouble<Map.Entry<K,V>> transformer,
6352               double basis,
6353               DoubleByDoubleToDouble reducer) {
6354 <            super(p, b, split);
6354 >            super(m, p, b); this.nextRight = nextRight;
6355              this.transformer = transformer;
6356              this.basis = basis; this.reducer = reducer;
6357          }
6358 +        public final Double getRawResult() { return result; }
6359          @SuppressWarnings("unchecked") public final void compute() {
6360 <            MapReduceEntriesToDoubleTask<K,V> t = this;
6361 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
6362 <                this.transformer;
6363 <            final DoubleByDoubleToDouble reducer = this.reducer;
6364 <            if (transformer == null || reducer == null)
6365 <                throw new Error(NullFunctionMessage);
6366 <            final double id = this.basis;
6367 <            int b = batch();
6368 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6369 <                b >>>= 1;
6370 <                t.pending = 1;
6371 <                MapReduceEntriesToDoubleTask<K,V> rt =
6372 <                    new MapReduceEntriesToDoubleTask<K,V>
6373 <                    (t, b, true, transformer, id, reducer);
6374 <                t = new MapReduceEntriesToDoubleTask<K,V>
6375 <                    (t, b, false, transformer, id, reducer);
6376 <                t.sibling = rt;
6377 <                rt.sibling = t;
6378 <                rt.fork();
6379 <            }
6380 <            double r = id;
6381 <            Object v;
6119 <            while ((v = t.advance()) != null)
6120 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6121 <            t.result = r;
6122 <            for (;;) {
6123 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToDoubleTask<K,V> s, p;
6124 <                if ((par = t.parent) == null ||
6125 <                    !(par instanceof MapReduceEntriesToDoubleTask)) {
6126 <                    t.quietlyComplete();
6127 <                    break;
6128 <                }
6129 <                else if ((c = (p = (MapReduceEntriesToDoubleTask<K,V>)par).pending) == 0) {
6130 <                    if ((s = t.sibling) != null)
6131 <                        r = reducer.apply(r, s.result);
6132 <                    (t = p).result = r;
6360 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
6361 >            final DoubleByDoubleToDouble reducer;
6362 >            if ((transformer = this.transformer) != null &&
6363 >                (reducer = this.reducer) != null) {
6364 >                double r = this.basis;
6365 >                for (int b; (b = preSplit()) > 0;)
6366 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
6367 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6368 >                V v;
6369 >                while ((v = advance()) != null)
6370 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6371 >                                                                    v)));
6372 >                result = r;
6373 >                CountedCompleter<?> c;
6374 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6375 >                    MapReduceEntriesToDoubleTask<K,V>
6376 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
6377 >                        s = t.rights;
6378 >                    while (s != null) {
6379 >                        t.result = reducer.apply(t.result, s.result);
6380 >                        s = t.rights = s.nextRight;
6381 >                    }
6382                  }
6134                else if (p.casPending(c, 0))
6135                    break;
6383              }
6384          }
6138        public final Double getRawResult() { return result; }
6385      }
6386  
6387 <    @SuppressWarnings("serial")
6388 <    static final class MapReduceMappingsToDoubleTask<K,V>
6143 <        extends BulkTask<K,V,Double> {
6387 >    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6388 >        extends Traverser<K,V,Double> {
6389          final ObjectByObjectToDouble<? super K, ? super V> transformer;
6390          final DoubleByDoubleToDouble reducer;
6391          final double basis;
6392          double result;
6393 <        MapReduceMappingsToDoubleTask<K,V> sibling;
6393 >        MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6394          MapReduceMappingsToDoubleTask
6395 <            (ConcurrentHashMapV8<K,V> m,
6395 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6396 >             MapReduceMappingsToDoubleTask<K,V> nextRight,
6397               ObjectByObjectToDouble<? super K, ? super V> transformer,
6398               double basis,
6399               DoubleByDoubleToDouble reducer) {
6400 <            super(m);
6155 <            this.transformer = transformer;
6156 <            this.basis = basis; this.reducer = reducer;
6157 <        }
6158 <        MapReduceMappingsToDoubleTask
6159 <            (BulkTask<K,V,?> p, int b, boolean split,
6160 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
6161 <             double basis,
6162 <             DoubleByDoubleToDouble reducer) {
6163 <            super(p, b, split);
6400 >            super(m, p, b); this.nextRight = nextRight;
6401              this.transformer = transformer;
6402              this.basis = basis; this.reducer = reducer;
6403          }
6404 +        public final Double getRawResult() { return result; }
6405          @SuppressWarnings("unchecked") public final void compute() {
6406 <            MapReduceMappingsToDoubleTask<K,V> t = this;
6407 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
6408 <                this.transformer;
6409 <            final DoubleByDoubleToDouble reducer = this.reducer;
6410 <            if (transformer == null || reducer == null)
6411 <                throw new Error(NullFunctionMessage);
6412 <            final double id = this.basis;
6413 <            int b = batch();
6414 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6415 <                b >>>= 1;
6416 <                t.pending = 1;
6417 <                MapReduceMappingsToDoubleTask<K,V> rt =
6418 <                    new MapReduceMappingsToDoubleTask<K,V>
6419 <                    (t, b, true, transformer, id, reducer);
6420 <                t = new MapReduceMappingsToDoubleTask<K,V>
6421 <                    (t, b, false, transformer, id, reducer);
6422 <                t.sibling = rt;
6423 <                rt.sibling = t;
6424 <                rt.fork();
6425 <            }
6426 <            double r = id;
6189 <            Object v;
6190 <            while ((v = t.advance()) != null)
6191 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6192 <            t.result = r;
6193 <            for (;;) {
6194 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToDoubleTask<K,V> s, p;
6195 <                if ((par = t.parent) == null ||
6196 <                    !(par instanceof MapReduceMappingsToDoubleTask)) {
6197 <                    t.quietlyComplete();
6198 <                    break;
6199 <                }
6200 <                else if ((c = (p = (MapReduceMappingsToDoubleTask<K,V>)par).pending) == 0) {
6201 <                    if ((s = t.sibling) != null)
6202 <                        r = reducer.apply(r, s.result);
6203 <                    (t = p).result = r;
6406 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
6407 >            final DoubleByDoubleToDouble reducer;
6408 >            if ((transformer = this.transformer) != null &&
6409 >                (reducer = this.reducer) != null) {
6410 >                double r = this.basis;
6411 >                for (int b; (b = preSplit()) > 0;)
6412 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
6413 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6414 >                V v;
6415 >                while ((v = advance()) != null)
6416 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6417 >                result = r;
6418 >                CountedCompleter<?> c;
6419 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6420 >                    MapReduceMappingsToDoubleTask<K,V>
6421 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
6422 >                        s = t.rights;
6423 >                    while (s != null) {
6424 >                        t.result = reducer.apply(t.result, s.result);
6425 >                        s = t.rights = s.nextRight;
6426 >                    }
6427                  }
6205                else if (p.casPending(c, 0))
6206                    break;
6428              }
6429          }
6209        public final Double getRawResult() { return result; }
6430      }
6431  
6432 <    @SuppressWarnings("serial")
6433 <    static final class MapReduceKeysToLongTask<K,V>
6214 <        extends BulkTask<K,V,Long> {
6432 >    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6433 >        extends Traverser<K,V,Long> {
6434          final ObjectToLong<? super K> transformer;
6435          final LongByLongToLong reducer;
6436          final long basis;
6437          long result;
6438 <        MapReduceKeysToLongTask<K,V> sibling;
6220 <        MapReduceKeysToLongTask
6221 <            (ConcurrentHashMapV8<K,V> m,
6222 <             ObjectToLong<? super K> transformer,
6223 <             long basis,
6224 <             LongByLongToLong reducer) {
6225 <            super(m);
6226 <            this.transformer = transformer;
6227 <            this.basis = basis; this.reducer = reducer;
6228 <        }
6438 >        MapReduceKeysToLongTask<K,V> rights, nextRight;
6439          MapReduceKeysToLongTask
6440 <            (BulkTask<K,V,?> p, int b, boolean split,
6440 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6441 >             MapReduceKeysToLongTask<K,V> nextRight,
6442               ObjectToLong<? super K> transformer,
6443               long basis,
6444               LongByLongToLong reducer) {
6445 <            super(p, b, split);
6445 >            super(m, p, b); this.nextRight = nextRight;
6446              this.transformer = transformer;
6447              this.basis = basis; this.reducer = reducer;
6448          }
6449 +        public final Long getRawResult() { return result; }
6450          @SuppressWarnings("unchecked") public final void compute() {
6451 <            MapReduceKeysToLongTask<K,V> t = this;
6452 <            final ObjectToLong<? super K> transformer =
6453 <                this.transformer;
6454 <            final LongByLongToLong reducer = this.reducer;
6455 <            if (transformer == null || reducer == null)
6456 <                throw new Error(NullFunctionMessage);
6457 <            final long id = this.basis;
6458 <            int b = batch();
6459 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6460 <                b >>>= 1;
6461 <                t.pending = 1;
6462 <                MapReduceKeysToLongTask<K,V> rt =
6463 <                    new MapReduceKeysToLongTask<K,V>
6464 <                    (t, b, true, transformer, id, reducer);
6465 <                t = new MapReduceKeysToLongTask<K,V>
6466 <                    (t, b, false, transformer, id, reducer);
6467 <                t.sibling = rt;
6468 <                rt.sibling = t;
6469 <                rt.fork();
6470 <            }
6259 <            long r = id;
6260 <            while (t.advance() != null)
6261 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
6262 <            t.result = r;
6263 <            for (;;) {
6264 <                int c; BulkTask<K,V,?> par; MapReduceKeysToLongTask<K,V> s, p;
6265 <                if ((par = t.parent) == null ||
6266 <                    !(par instanceof MapReduceKeysToLongTask)) {
6267 <                    t.quietlyComplete();
6268 <                    break;
6269 <                }
6270 <                else if ((c = (p = (MapReduceKeysToLongTask<K,V>)par).pending) == 0) {
6271 <                    if ((s = t.sibling) != null)
6272 <                        r = reducer.apply(r, s.result);
6273 <                    (t = p).result = r;
6451 >            final ObjectToLong<? super K> transformer;
6452 >            final LongByLongToLong reducer;
6453 >            if ((transformer = this.transformer) != null &&
6454 >                (reducer = this.reducer) != null) {
6455 >                long r = this.basis;
6456 >                for (int b; (b = preSplit()) > 0;)
6457 >                    (rights = new MapReduceKeysToLongTask<K,V>
6458 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6459 >                while (advance() != null)
6460 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6461 >                result = r;
6462 >                CountedCompleter<?> c;
6463 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6464 >                    MapReduceKeysToLongTask<K,V>
6465 >                        t = (MapReduceKeysToLongTask<K,V>)c,
6466 >                        s = t.rights;
6467 >                    while (s != null) {
6468 >                        t.result = reducer.apply(t.result, s.result);
6469 >                        s = t.rights = s.nextRight;
6470 >                    }
6471                  }
6275                else if (p.casPending(c, 0))
6276                    break;
6472              }
6473          }
6279        public final Long getRawResult() { return result; }
6474      }
6475  
6476 <    @SuppressWarnings("serial")
6477 <    static final class MapReduceValuesToLongTask<K,V>
6284 <        extends BulkTask<K,V,Long> {
6476 >    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6477 >        extends Traverser<K,V,Long> {
6478          final ObjectToLong<? super V> transformer;
6479          final LongByLongToLong reducer;
6480          final long basis;
6481          long result;
6482 <        MapReduceValuesToLongTask<K,V> sibling;
6290 <        MapReduceValuesToLongTask
6291 <            (ConcurrentHashMapV8<K,V> m,
6292 <             ObjectToLong<? super V> transformer,
6293 <             long basis,
6294 <             LongByLongToLong reducer) {
6295 <            super(m);
6296 <            this.transformer = transformer;
6297 <            this.basis = basis; this.reducer = reducer;
6298 <        }
6482 >        MapReduceValuesToLongTask<K,V> rights, nextRight;
6483          MapReduceValuesToLongTask
6484 <            (BulkTask<K,V,?> p, int b, boolean split,
6484 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6485 >             MapReduceValuesToLongTask<K,V> nextRight,
6486               ObjectToLong<? super V> transformer,
6487               long basis,
6488               LongByLongToLong reducer) {
6489 <            super(p, b, split);
6489 >            super(m, p, b); this.nextRight = nextRight;
6490              this.transformer = transformer;
6491              this.basis = basis; this.reducer = reducer;
6492          }
6493 +        public final Long getRawResult() { return result; }
6494          @SuppressWarnings("unchecked") public final void compute() {
6495 <            MapReduceValuesToLongTask<K,V> t = this;
6496 <            final ObjectToLong<? super V> transformer =
6497 <                this.transformer;
6498 <            final LongByLongToLong reducer = this.reducer;
6499 <            if (transformer == null || reducer == null)
6500 <                throw new Error(NullFunctionMessage);
6501 <            final long id = this.basis;
6502 <            int b = batch();
6503 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6504 <                b >>>= 1;
6505 <                t.pending = 1;
6506 <                MapReduceValuesToLongTask<K,V> rt =
6507 <                    new MapReduceValuesToLongTask<K,V>
6508 <                    (t, b, true, transformer, id, reducer);
6509 <                t = new MapReduceValuesToLongTask<K,V>
6510 <                    (t, b, false, transformer, id, reducer);
6511 <                t.sibling = rt;
6512 <                rt.sibling = t;
6513 <                rt.fork();
6514 <            }
6515 <            long r = id;
6330 <            Object v;
6331 <            while ((v = t.advance()) != null)
6332 <                r = reducer.apply(r, transformer.apply((V)v));
6333 <            t.result = r;
6334 <            for (;;) {
6335 <                int c; BulkTask<K,V,?> par; MapReduceValuesToLongTask<K,V> s, p;
6336 <                if ((par = t.parent) == null ||
6337 <                    !(par instanceof MapReduceValuesToLongTask)) {
6338 <                    t.quietlyComplete();
6339 <                    break;
6340 <                }
6341 <                else if ((c = (p = (MapReduceValuesToLongTask<K,V>)par).pending) == 0) {
6342 <                    if ((s = t.sibling) != null)
6343 <                        r = reducer.apply(r, s.result);
6344 <                    (t = p).result = r;
6495 >            final ObjectToLong<? super V> transformer;
6496 >            final LongByLongToLong reducer;
6497 >            if ((transformer = this.transformer) != null &&
6498 >                (reducer = this.reducer) != null) {
6499 >                long r = this.basis;
6500 >                for (int b; (b = preSplit()) > 0;)
6501 >                    (rights = new MapReduceValuesToLongTask<K,V>
6502 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6503 >                V v;
6504 >                while ((v = advance()) != null)
6505 >                    r = reducer.apply(r, transformer.apply(v));
6506 >                result = r;
6507 >                CountedCompleter<?> c;
6508 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6509 >                    MapReduceValuesToLongTask<K,V>
6510 >                        t = (MapReduceValuesToLongTask<K,V>)c,
6511 >                        s = t.rights;
6512 >                    while (s != null) {
6513 >                        t.result = reducer.apply(t.result, s.result);
6514 >                        s = t.rights = s.nextRight;
6515 >                    }
6516                  }
6346                else if (p.casPending(c, 0))
6347                    break;
6517              }
6518          }
6350        public final Long getRawResult() { return result; }
6519      }
6520  
6521 <    @SuppressWarnings("serial")
6522 <    static final class MapReduceEntriesToLongTask<K,V>
6355 <        extends BulkTask<K,V,Long> {
6521 >    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6522 >        extends Traverser<K,V,Long> {
6523          final ObjectToLong<Map.Entry<K,V>> transformer;
6524          final LongByLongToLong reducer;
6525          final long basis;
6526          long result;
6527 <        MapReduceEntriesToLongTask<K,V> sibling;
6361 <        MapReduceEntriesToLongTask
6362 <            (ConcurrentHashMapV8<K,V> m,
6363 <             ObjectToLong<Map.Entry<K,V>> transformer,
6364 <             long basis,
6365 <             LongByLongToLong reducer) {
6366 <            super(m);
6367 <            this.transformer = transformer;
6368 <            this.basis = basis; this.reducer = reducer;
6369 <        }
6527 >        MapReduceEntriesToLongTask<K,V> rights, nextRight;
6528          MapReduceEntriesToLongTask
6529 <            (BulkTask<K,V,?> p, int b, boolean split,
6529 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6530 >             MapReduceEntriesToLongTask<K,V> nextRight,
6531               ObjectToLong<Map.Entry<K,V>> transformer,
6532               long basis,
6533               LongByLongToLong reducer) {
6534 <            super(p, b, split);
6534 >            super(m, p, b); this.nextRight = nextRight;
6535              this.transformer = transformer;
6536              this.basis = basis; this.reducer = reducer;
6537          }
6538 +        public final Long getRawResult() { return result; }
6539          @SuppressWarnings("unchecked") public final void compute() {
6540 <            MapReduceEntriesToLongTask<K,V> t = this;
6541 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6542 <                this.transformer;
6543 <            final LongByLongToLong reducer = this.reducer;
6544 <            if (transformer == null || reducer == null)
6545 <                throw new Error(NullFunctionMessage);
6546 <            final long id = this.basis;
6547 <            int b = batch();
6548 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6549 <                b >>>= 1;
6550 <                t.pending = 1;
6551 <                MapReduceEntriesToLongTask<K,V> rt =
6552 <                    new MapReduceEntriesToLongTask<K,V>
6553 <                    (t, b, true, transformer, id, reducer);
6554 <                t = new MapReduceEntriesToLongTask<K,V>
6555 <                    (t, b, false, transformer, id, reducer);
6556 <                t.sibling = rt;
6557 <                rt.sibling = t;
6558 <                rt.fork();
6559 <            }
6560 <            long r = id;
6561 <            Object v;
6402 <            while ((v = t.advance()) != null)
6403 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6404 <            t.result = r;
6405 <            for (;;) {
6406 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToLongTask<K,V> s, p;
6407 <                if ((par = t.parent) == null ||
6408 <                    !(par instanceof MapReduceEntriesToLongTask)) {
6409 <                    t.quietlyComplete();
6410 <                    break;
6411 <                }
6412 <                else if ((c = (p = (MapReduceEntriesToLongTask<K,V>)par).pending) == 0) {
6413 <                    if ((s = t.sibling) != null)
6414 <                        r = reducer.apply(r, s.result);
6415 <                    (t = p).result = r;
6540 >            final ObjectToLong<Map.Entry<K,V>> transformer;
6541 >            final LongByLongToLong reducer;
6542 >            if ((transformer = this.transformer) != null &&
6543 >                (reducer = this.reducer) != null) {
6544 >                long r = this.basis;
6545 >                for (int b; (b = preSplit()) > 0;)
6546 >                    (rights = new MapReduceEntriesToLongTask<K,V>
6547 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6548 >                V v;
6549 >                while ((v = advance()) != null)
6550 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6551 >                                                                    v)));
6552 >                result = r;
6553 >                CountedCompleter<?> c;
6554 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6555 >                    MapReduceEntriesToLongTask<K,V>
6556 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6557 >                        s = t.rights;
6558 >                    while (s != null) {
6559 >                        t.result = reducer.apply(t.result, s.result);
6560 >                        s = t.rights = s.nextRight;
6561 >                    }
6562                  }
6417                else if (p.casPending(c, 0))
6418                    break;
6563              }
6564          }
6421        public final Long getRawResult() { return result; }
6565      }
6566  
6567 <    @SuppressWarnings("serial")
6568 <    static final class MapReduceMappingsToLongTask<K,V>
6426 <        extends BulkTask<K,V,Long> {
6567 >    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6568 >        extends Traverser<K,V,Long> {
6569          final ObjectByObjectToLong<? super K, ? super V> transformer;
6570          final LongByLongToLong reducer;
6571          final long basis;
6572          long result;
6573 <        MapReduceMappingsToLongTask<K,V> sibling;
6432 <        MapReduceMappingsToLongTask
6433 <            (ConcurrentHashMapV8<K,V> m,
6434 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6435 <             long basis,
6436 <             LongByLongToLong reducer) {
6437 <            super(m);
6438 <            this.transformer = transformer;
6439 <            this.basis = basis; this.reducer = reducer;
6440 <        }
6573 >        MapReduceMappingsToLongTask<K,V> rights, nextRight;
6574          MapReduceMappingsToLongTask
6575 <            (BulkTask<K,V,?> p, int b, boolean split,
6575 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6576 >             MapReduceMappingsToLongTask<K,V> nextRight,
6577               ObjectByObjectToLong<? super K, ? super V> transformer,
6578               long basis,
6579               LongByLongToLong reducer) {
6580 <            super(p, b, split);
6580 >            super(m, p, b); this.nextRight = nextRight;
6581              this.transformer = transformer;
6582              this.basis = basis; this.reducer = reducer;
6583          }
6584 +        public final Long getRawResult() { return result; }
6585          @SuppressWarnings("unchecked") public final void compute() {
6586 <            MapReduceMappingsToLongTask<K,V> t = this;
6587 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6588 <                this.transformer;
6589 <            final LongByLongToLong reducer = this.reducer;
6590 <            if (transformer == null || reducer == null)
6591 <                throw new Error(NullFunctionMessage);
6592 <            final long id = this.basis;
6593 <            int b = batch();
6594 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6595 <                b >>>= 1;
6596 <                t.pending = 1;
6597 <                MapReduceMappingsToLongTask<K,V> rt =
6598 <                    new MapReduceMappingsToLongTask<K,V>
6599 <                    (t, b, true, transformer, id, reducer);
6600 <                t = new MapReduceMappingsToLongTask<K,V>
6601 <                    (t, b, false, transformer, id, reducer);
6602 <                t.sibling = rt;
6603 <                rt.sibling = t;
6604 <                rt.fork();
6605 <            }
6606 <            long r = id;
6472 <            Object v;
6473 <            while ((v = t.advance()) != null)
6474 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6475 <            t.result = r;
6476 <            for (;;) {
6477 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToLongTask<K,V> s, p;
6478 <                if ((par = t.parent) == null ||
6479 <                    !(par instanceof MapReduceMappingsToLongTask)) {
6480 <                    t.quietlyComplete();
6481 <                    break;
6482 <                }
6483 <                else if ((c = (p = (MapReduceMappingsToLongTask<K,V>)par).pending) == 0) {
6484 <                    if ((s = t.sibling) != null)
6485 <                        r = reducer.apply(r, s.result);
6486 <                    (t = p).result = r;
6586 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
6587 >            final LongByLongToLong reducer;
6588 >            if ((transformer = this.transformer) != null &&
6589 >                (reducer = this.reducer) != null) {
6590 >                long r = this.basis;
6591 >                for (int b; (b = preSplit()) > 0;)
6592 >                    (rights = new MapReduceMappingsToLongTask<K,V>
6593 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6594 >                V v;
6595 >                while ((v = advance()) != null)
6596 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6597 >                result = r;
6598 >                CountedCompleter<?> c;
6599 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6600 >                    MapReduceMappingsToLongTask<K,V>
6601 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6602 >                        s = t.rights;
6603 >                    while (s != null) {
6604 >                        t.result = reducer.apply(t.result, s.result);
6605 >                        s = t.rights = s.nextRight;
6606 >                    }
6607                  }
6488                else if (p.casPending(c, 0))
6489                    break;
6608              }
6609          }
6492        public final Long getRawResult() { return result; }
6610      }
6611  
6612 <    @SuppressWarnings("serial")
6613 <    static final class MapReduceKeysToIntTask<K,V>
6497 <        extends BulkTask<K,V,Integer> {
6612 >    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6613 >        extends Traverser<K,V,Integer> {
6614          final ObjectToInt<? super K> transformer;
6615          final IntByIntToInt reducer;
6616          final int basis;
6617          int result;
6618 <        MapReduceKeysToIntTask<K,V> sibling;
6503 <        MapReduceKeysToIntTask
6504 <            (ConcurrentHashMapV8<K,V> m,
6505 <             ObjectToInt<? super K> transformer,
6506 <             int basis,
6507 <             IntByIntToInt reducer) {
6508 <            super(m);
6509 <            this.transformer = transformer;
6510 <            this.basis = basis; this.reducer = reducer;
6511 <        }
6618 >        MapReduceKeysToIntTask<K,V> rights, nextRight;
6619          MapReduceKeysToIntTask
6620 <            (BulkTask<K,V,?> p, int b, boolean split,
6620 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6621 >             MapReduceKeysToIntTask<K,V> nextRight,
6622               ObjectToInt<? super K> transformer,
6623               int basis,
6624               IntByIntToInt reducer) {
6625 <            super(p, b, split);
6625 >            super(m, p, b); this.nextRight = nextRight;
6626              this.transformer = transformer;
6627              this.basis = basis; this.reducer = reducer;
6628          }
6629 +        public final Integer getRawResult() { return result; }
6630          @SuppressWarnings("unchecked") public final void compute() {
6631 <            MapReduceKeysToIntTask<K,V> t = this;
6632 <            final ObjectToInt<? super K> transformer =
6633 <                this.transformer;
6634 <            final IntByIntToInt reducer = this.reducer;
6635 <            if (transformer == null || reducer == null)
6636 <                throw new Error(NullFunctionMessage);
6637 <            final int id = this.basis;
6638 <            int b = batch();
6639 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6640 <                b >>>= 1;
6641 <                t.pending = 1;
6642 <                MapReduceKeysToIntTask<K,V> rt =
6643 <                    new MapReduceKeysToIntTask<K,V>
6644 <                    (t, b, true, transformer, id, reducer);
6645 <                t = new MapReduceKeysToIntTask<K,V>
6646 <                    (t, b, false, transformer, id, reducer);
6647 <                t.sibling = rt;
6648 <                rt.sibling = t;
6649 <                rt.fork();
6650 <            }
6542 <            int r = id;
6543 <            while (t.advance() != null)
6544 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
6545 <            t.result = r;
6546 <            for (;;) {
6547 <                int c; BulkTask<K,V,?> par; MapReduceKeysToIntTask<K,V> s, p;
6548 <                if ((par = t.parent) == null ||
6549 <                    !(par instanceof MapReduceKeysToIntTask)) {
6550 <                    t.quietlyComplete();
6551 <                    break;
6552 <                }
6553 <                else if ((c = (p = (MapReduceKeysToIntTask<K,V>)par).pending) == 0) {
6554 <                    if ((s = t.sibling) != null)
6555 <                        r = reducer.apply(r, s.result);
6556 <                    (t = p).result = r;
6631 >            final ObjectToInt<? super K> transformer;
6632 >            final IntByIntToInt reducer;
6633 >            if ((transformer = this.transformer) != null &&
6634 >                (reducer = this.reducer) != null) {
6635 >                int r = this.basis;
6636 >                for (int b; (b = preSplit()) > 0;)
6637 >                    (rights = new MapReduceKeysToIntTask<K,V>
6638 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6639 >                while (advance() != null)
6640 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6641 >                result = r;
6642 >                CountedCompleter<?> c;
6643 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6644 >                    MapReduceKeysToIntTask<K,V>
6645 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6646 >                        s = t.rights;
6647 >                    while (s != null) {
6648 >                        t.result = reducer.apply(t.result, s.result);
6649 >                        s = t.rights = s.nextRight;
6650 >                    }
6651                  }
6558                else if (p.casPending(c, 0))
6559                    break;
6652              }
6653          }
6562        public final Integer getRawResult() { return result; }
6654      }
6655  
6656 <    @SuppressWarnings("serial")
6657 <    static final class MapReduceValuesToIntTask<K,V>
6567 <        extends BulkTask<K,V,Integer> {
6656 >    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6657 >        extends Traverser<K,V,Integer> {
6658          final ObjectToInt<? super V> transformer;
6659          final IntByIntToInt reducer;
6660          final int basis;
6661          int result;
6662 <        MapReduceValuesToIntTask<K,V> sibling;
6573 <        MapReduceValuesToIntTask
6574 <            (ConcurrentHashMapV8<K,V> m,
6575 <             ObjectToInt<? super V> transformer,
6576 <             int basis,
6577 <             IntByIntToInt reducer) {
6578 <            super(m);
6579 <            this.transformer = transformer;
6580 <            this.basis = basis; this.reducer = reducer;
6581 <        }
6662 >        MapReduceValuesToIntTask<K,V> rights, nextRight;
6663          MapReduceValuesToIntTask
6664 <            (BulkTask<K,V,?> p, int b, boolean split,
6664 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6665 >             MapReduceValuesToIntTask<K,V> nextRight,
6666               ObjectToInt<? super V> transformer,
6667               int basis,
6668               IntByIntToInt reducer) {
6669 <            super(p, b, split);
6669 >            super(m, p, b); this.nextRight = nextRight;
6670              this.transformer = transformer;
6671              this.basis = basis; this.reducer = reducer;
6672          }
6673 +        public final Integer getRawResult() { return result; }
6674          @SuppressWarnings("unchecked") public final void compute() {
6675 <            MapReduceValuesToIntTask<K,V> t = this;
6676 <            final ObjectToInt<? super V> transformer =
6677 <                this.transformer;
6678 <            final IntByIntToInt reducer = this.reducer;
6679 <            if (transformer == null || reducer == null)
6680 <                throw new Error(NullFunctionMessage);
6681 <            final int id = this.basis;
6682 <            int b = batch();
6683 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6684 <                b >>>= 1;
6685 <                t.pending = 1;
6686 <                MapReduceValuesToIntTask<K,V> rt =
6687 <                    new MapReduceValuesToIntTask<K,V>
6688 <                    (t, b, true, transformer, id, reducer);
6689 <                t = new MapReduceValuesToIntTask<K,V>
6690 <                    (t, b, false, transformer, id, reducer);
6691 <                t.sibling = rt;
6692 <                rt.sibling = t;
6693 <                rt.fork();
6694 <            }
6695 <            int r = id;
6613 <            Object v;
6614 <            while ((v = t.advance()) != null)
6615 <                r = reducer.apply(r, transformer.apply((V)v));
6616 <            t.result = r;
6617 <            for (;;) {
6618 <                int c; BulkTask<K,V,?> par; MapReduceValuesToIntTask<K,V> s, p;
6619 <                if ((par = t.parent) == null ||
6620 <                    !(par instanceof MapReduceValuesToIntTask)) {
6621 <                    t.quietlyComplete();
6622 <                    break;
6623 <                }
6624 <                else if ((c = (p = (MapReduceValuesToIntTask<K,V>)par).pending) == 0) {
6625 <                    if ((s = t.sibling) != null)
6626 <                        r = reducer.apply(r, s.result);
6627 <                    (t = p).result = r;
6675 >            final ObjectToInt<? super V> transformer;
6676 >            final IntByIntToInt reducer;
6677 >            if ((transformer = this.transformer) != null &&
6678 >                (reducer = this.reducer) != null) {
6679 >                int r = this.basis;
6680 >                for (int b; (b = preSplit()) > 0;)
6681 >                    (rights = new MapReduceValuesToIntTask<K,V>
6682 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6683 >                V v;
6684 >                while ((v = advance()) != null)
6685 >                    r = reducer.apply(r, transformer.apply(v));
6686 >                result = r;
6687 >                CountedCompleter<?> c;
6688 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6689 >                    MapReduceValuesToIntTask<K,V>
6690 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6691 >                        s = t.rights;
6692 >                    while (s != null) {
6693 >                        t.result = reducer.apply(t.result, s.result);
6694 >                        s = t.rights = s.nextRight;
6695 >                    }
6696                  }
6629                else if (p.casPending(c, 0))
6630                    break;
6697              }
6698          }
6633        public final Integer getRawResult() { return result; }
6699      }
6700  
6701 <    @SuppressWarnings("serial")
6702 <    static final class MapReduceEntriesToIntTask<K,V>
6638 <        extends BulkTask<K,V,Integer> {
6701 >    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6702 >        extends Traverser<K,V,Integer> {
6703          final ObjectToInt<Map.Entry<K,V>> transformer;
6704          final IntByIntToInt reducer;
6705          final int basis;
6706          int result;
6707 <        MapReduceEntriesToIntTask<K,V> sibling;
6644 <        MapReduceEntriesToIntTask
6645 <            (ConcurrentHashMapV8<K,V> m,
6646 <             ObjectToInt<Map.Entry<K,V>> transformer,
6647 <             int basis,
6648 <             IntByIntToInt reducer) {
6649 <            super(m);
6650 <            this.transformer = transformer;
6651 <            this.basis = basis; this.reducer = reducer;
6652 <        }
6707 >        MapReduceEntriesToIntTask<K,V> rights, nextRight;
6708          MapReduceEntriesToIntTask
6709 <            (BulkTask<K,V,?> p, int b, boolean split,
6709 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6710 >             MapReduceEntriesToIntTask<K,V> nextRight,
6711               ObjectToInt<Map.Entry<K,V>> transformer,
6712               int basis,
6713               IntByIntToInt reducer) {
6714 <            super(p, b, split);
6714 >            super(m, p, b); this.nextRight = nextRight;
6715              this.transformer = transformer;
6716              this.basis = basis; this.reducer = reducer;
6717          }
6718 +        public final Integer getRawResult() { return result; }
6719          @SuppressWarnings("unchecked") public final void compute() {
6720 <            MapReduceEntriesToIntTask<K,V> t = this;
6721 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6722 <                this.transformer;
6723 <            final IntByIntToInt reducer = this.reducer;
6724 <            if (transformer == null || reducer == null)
6725 <                throw new Error(NullFunctionMessage);
6726 <            final int id = this.basis;
6727 <            int b = batch();
6728 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6729 <                b >>>= 1;
6730 <                t.pending = 1;
6731 <                MapReduceEntriesToIntTask<K,V> rt =
6732 <                    new MapReduceEntriesToIntTask<K,V>
6733 <                    (t, b, true, transformer, id, reducer);
6734 <                t = new MapReduceEntriesToIntTask<K,V>
6735 <                    (t, b, false, transformer, id, reducer);
6736 <                t.sibling = rt;
6737 <                rt.sibling = t;
6738 <                rt.fork();
6739 <            }
6740 <            int r = id;
6741 <            Object v;
6685 <            while ((v = t.advance()) != null)
6686 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6687 <            t.result = r;
6688 <            for (;;) {
6689 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToIntTask<K,V> s, p;
6690 <                if ((par = t.parent) == null ||
6691 <                    !(par instanceof MapReduceEntriesToIntTask)) {
6692 <                    t.quietlyComplete();
6693 <                    break;
6694 <                }
6695 <                else if ((c = (p = (MapReduceEntriesToIntTask<K,V>)par).pending) == 0) {
6696 <                    if ((s = t.sibling) != null)
6697 <                        r = reducer.apply(r, s.result);
6698 <                    (t = p).result = r;
6720 >            final ObjectToInt<Map.Entry<K,V>> transformer;
6721 >            final IntByIntToInt reducer;
6722 >            if ((transformer = this.transformer) != null &&
6723 >                (reducer = this.reducer) != null) {
6724 >                int r = this.basis;
6725 >                for (int b; (b = preSplit()) > 0;)
6726 >                    (rights = new MapReduceEntriesToIntTask<K,V>
6727 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6728 >                V v;
6729 >                while ((v = advance()) != null)
6730 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6731 >                                                                    v)));
6732 >                result = r;
6733 >                CountedCompleter<?> c;
6734 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6735 >                    MapReduceEntriesToIntTask<K,V>
6736 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6737 >                        s = t.rights;
6738 >                    while (s != null) {
6739 >                        t.result = reducer.apply(t.result, s.result);
6740 >                        s = t.rights = s.nextRight;
6741 >                    }
6742                  }
6700                else if (p.casPending(c, 0))
6701                    break;
6743              }
6744          }
6704        public final Integer getRawResult() { return result; }
6745      }
6746  
6747 <    @SuppressWarnings("serial")
6748 <    static final class MapReduceMappingsToIntTask<K,V>
6709 <        extends BulkTask<K,V,Integer> {
6747 >    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6748 >        extends Traverser<K,V,Integer> {
6749          final ObjectByObjectToInt<? super K, ? super V> transformer;
6750          final IntByIntToInt reducer;
6751          final int basis;
6752          int result;
6753 <        MapReduceMappingsToIntTask<K,V> sibling;
6753 >        MapReduceMappingsToIntTask<K,V> rights, nextRight;
6754          MapReduceMappingsToIntTask
6755 <            (ConcurrentHashMapV8<K,V> m,
6755 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6756 >             MapReduceMappingsToIntTask<K,V> nextRight,
6757               ObjectByObjectToInt<? super K, ? super V> transformer,
6758               int basis,
6759               IntByIntToInt reducer) {
6760 <            super(m);
6721 <            this.transformer = transformer;
6722 <            this.basis = basis; this.reducer = reducer;
6723 <        }
6724 <        MapReduceMappingsToIntTask
6725 <            (BulkTask<K,V,?> p, int b, boolean split,
6726 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6727 <             int basis,
6728 <             IntByIntToInt reducer) {
6729 <            super(p, b, split);
6760 >            super(m, p, b); this.nextRight = nextRight;
6761              this.transformer = transformer;
6762              this.basis = basis; this.reducer = reducer;
6763          }
6764 +        public final Integer getRawResult() { return result; }
6765          @SuppressWarnings("unchecked") public final void compute() {
6766 <            MapReduceMappingsToIntTask<K,V> t = this;
6767 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6768 <                this.transformer;
6769 <            final IntByIntToInt reducer = this.reducer;
6770 <            if (transformer == null || reducer == null)
6771 <                throw new Error(NullFunctionMessage);
6772 <            final int id = this.basis;
6773 <            int b = batch();
6774 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6775 <                b >>>= 1;
6776 <                t.pending = 1;
6777 <                MapReduceMappingsToIntTask<K,V> rt =
6778 <                    new MapReduceMappingsToIntTask<K,V>
6779 <                    (t, b, true, transformer, id, reducer);
6780 <                t = new MapReduceMappingsToIntTask<K,V>
6781 <                    (t, b, false, transformer, id, reducer);
6782 <                t.sibling = rt;
6783 <                rt.sibling = t;
6784 <                rt.fork();
6785 <            }
6786 <            int r = id;
6755 <            Object v;
6756 <            while ((v = t.advance()) != null)
6757 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6758 <            t.result = r;
6759 <            for (;;) {
6760 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToIntTask<K,V> s, p;
6761 <                if ((par = t.parent) == null ||
6762 <                    !(par instanceof MapReduceMappingsToIntTask)) {
6763 <                    t.quietlyComplete();
6764 <                    break;
6765 <                }
6766 <                else if ((c = (p = (MapReduceMappingsToIntTask<K,V>)par).pending) == 0) {
6767 <                    if ((s = t.sibling) != null)
6768 <                        r = reducer.apply(r, s.result);
6769 <                    (t = p).result = r;
6766 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
6767 >            final IntByIntToInt reducer;
6768 >            if ((transformer = this.transformer) != null &&
6769 >                (reducer = this.reducer) != null) {
6770 >                int r = this.basis;
6771 >                for (int b; (b = preSplit()) > 0;)
6772 >                    (rights = new MapReduceMappingsToIntTask<K,V>
6773 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6774 >                V v;
6775 >                while ((v = advance()) != null)
6776 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6777 >                result = r;
6778 >                CountedCompleter<?> c;
6779 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6780 >                    MapReduceMappingsToIntTask<K,V>
6781 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6782 >                        s = t.rights;
6783 >                    while (s != null) {
6784 >                        t.result = reducer.apply(t.result, s.result);
6785 >                        s = t.rights = s.nextRight;
6786 >                    }
6787                  }
6771                else if (p.casPending(c, 0))
6772                    break;
6788              }
6789          }
6775        public final Integer getRawResult() { return result; }
6790      }
6791  
6778
6792      // Unsafe mechanics
6793 <    private static final sun.misc.Unsafe UNSAFE;
6794 <    private static final long counterOffset;
6795 <    private static final long sizeCtlOffset;
6793 >    private static final sun.misc.Unsafe U;
6794 >    private static final long SIZECTL;
6795 >    private static final long TRANSFERINDEX;
6796 >    private static final long TRANSFERORIGIN;
6797 >    private static final long BASECOUNT;
6798 >    private static final long COUNTERBUSY;
6799 >    private static final long CELLVALUE;
6800      private static final long ABASE;
6801      private static final int ASHIFT;
6802  
6803      static {
6787        int ss;
6804          try {
6805 <            UNSAFE = getUnsafe();
6805 >            U = getUnsafe();
6806              Class<?> k = ConcurrentHashMapV8.class;
6807 <            counterOffset = UNSAFE.objectFieldOffset
6792 <                (k.getDeclaredField("counter"));
6793 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6807 >            SIZECTL = U.objectFieldOffset
6808                  (k.getDeclaredField("sizeCtl"));
6809 +            TRANSFERINDEX = U.objectFieldOffset
6810 +                (k.getDeclaredField("transferIndex"));
6811 +            TRANSFERORIGIN = U.objectFieldOffset
6812 +                (k.getDeclaredField("transferOrigin"));
6813 +            BASECOUNT = U.objectFieldOffset
6814 +                (k.getDeclaredField("baseCount"));
6815 +            COUNTERBUSY = U.objectFieldOffset
6816 +                (k.getDeclaredField("counterBusy"));
6817 +            Class<?> ck = CounterCell.class;
6818 +            CELLVALUE = U.objectFieldOffset
6819 +                (ck.getDeclaredField("value"));
6820              Class<?> sc = Node[].class;
6821 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6822 <            ss = UNSAFE.arrayIndexScale(sc);
6821 >            ABASE = U.arrayBaseOffset(sc);
6822 >            int scale = U.arrayIndexScale(sc);
6823 >            if ((scale & (scale - 1)) != 0)
6824 >                throw new Error("data type scale not a power of two");
6825 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6826          } catch (Exception e) {
6827              throw new Error(e);
6828          }
6801        if ((ss & (ss-1)) != 0)
6802            throw new Error("data type scale not a power of two");
6803        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6829      }
6830  
6831      /**
# Line 6813 | Line 6838 | public class ConcurrentHashMapV8<K, V>
6838      private static sun.misc.Unsafe getUnsafe() {
6839          try {
6840              return sun.misc.Unsafe.getUnsafe();
6841 <        } catch (SecurityException se) {
6842 <            try {
6843 <                return java.security.AccessController.doPrivileged
6844 <                    (new java.security
6845 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6846 <                        public sun.misc.Unsafe run() throws Exception {
6847 <                            java.lang.reflect.Field f = sun.misc
6848 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6849 <                            f.setAccessible(true);
6850 <                            return (sun.misc.Unsafe) f.get(null);
6851 <                        }});
6852 <            } catch (java.security.PrivilegedActionException e) {
6853 <                throw new RuntimeException("Could not initialize intrinsics",
6854 <                                           e.getCause());
6855 <            }
6841 >        } catch (SecurityException tryReflectionInstead) {}
6842 >        try {
6843 >            return java.security.AccessController.doPrivileged
6844 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6845 >                public sun.misc.Unsafe run() throws Exception {
6846 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6847 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6848 >                        f.setAccessible(true);
6849 >                        Object x = f.get(null);
6850 >                        if (k.isInstance(x))
6851 >                            return k.cast(x);
6852 >                    }
6853 >                    throw new NoSuchFieldError("the Unsafe");
6854 >                }});
6855 >        } catch (java.security.PrivilegedActionException e) {
6856 >            throw new RuntimeException("Could not initialize intrinsics",
6857 >                                       e.getCause());
6858          }
6859      }
6860   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines