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.71 by dl, Tue Oct 30 14:23:03 2012 UTC vs.
Revision 1.84 by dl, Sat Dec 15 20:21:25 2012 UTC

# Line 21 | Line 21 | import java.util.Enumeration;
21   import java.util.ConcurrentModificationException;
22   import java.util.NoSuchElementException;
23   import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.ThreadLocalRandom;
25 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;
28
27   import java.io.Serializable;
28  
29   /**
# Line 40 | 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 61 | 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 82 | 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
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
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
# Line 99 | Line 97 | import java.io.Serializable;
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 parallel operations using the {@link
104 < * ForkJoinPool#commonPool}. (Task that may be used in other contexts
105 < * are available in class {@link ForkJoinTasks}). These operations are
106 < * designed to be safely, and often sensibly, applied even with maps
107 < * that are being concurrently updated by other threads; for example,
108 < * when computing a snapshot summary of the values in a shared
109 < * registry.  There are three kinds of operation, each with four
110 < * forms, accepting functions with Keys, Values, Entries, and (Key,
111 < * Value) arguments and/or return values. Because the elements of a
112 < * ConcurrentHashMapV8 are not ordered in any particular way, and may be
113 < * processed in different orders in different parallel executions, the
114 < * correctness of supplied functions should not depend on any
115 < * ordering, or on any other objects or values that may transiently
116 < * change while computation is in progress; and except for forEach
117 < * actions, should ideally be side-effect-free.
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.
# Line 182 | Line 182 | import java.io.Serializable;
182   * arguments can be supplied using {@code new
183   * AbstractMap.SimpleEntry(k,v)}.
184   *
185 < * <p> Bulk operations may complete abruptly, throwing an
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>Parallel speedups for bulk operations compared to sequential
193 < * processing are common but not guaranteed.  Operations involving
194 < * brief functions on small maps may execute more slowly than
195 < * sequential loops if the underlying work to parallelize the
196 < * computation is more expensive than the computation
197 < * itself. Similarly, parallelization may not lead to much actual
198 < * parallelism if all processors are busy performing unrelated tasks.
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.
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>
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">
# Line 223 | 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 285 | Line 285 | public class ConcurrentHashMapV8<K, V>
285          Spliterator<T> split();
286      }
287  
288    /**
289     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
290     * which additions may optionally be enabled by mapping to a
291     * common value.  This class cannot be directly instantiated. See
292     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
293     * {@link #newKeySet(int)}.
294     *
295     * <p>The view's {@code iterator} is a "weakly consistent" iterator
296     * that will never throw {@link ConcurrentModificationException},
297     * and guarantees to traverse elements as they existed upon
298     * construction of the iterator, and may (but is not guaranteed to)
299     * reflect any modifications subsequent to construction.
300     */
301    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
302        private static final long serialVersionUID = 7249069246763182397L;
303        private final V value;
304        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
305            super(map);
306            this.value = value;
307        }
308
309        /**
310         * Returns the map backing this view.
311         *
312         * @return the map backing this view
313         */
314        public ConcurrentHashMapV8<K,V> getMap() { return map; }
315
316        /**
317         * Returns the default mapped value for additions,
318         * or {@code null} if additions are not supported.
319         *
320         * @return the default mapped value for additions, or {@code null}
321         * if not supported.
322         */
323        public V getMappedValue() { return value; }
324
325        // implement Set API
326
327        public boolean contains(Object o) { return map.containsKey(o); }
328        public boolean remove(Object o)   { return map.remove(o) != null; }
329        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
330        public boolean add(K e) {
331            V v;
332            if ((v = value) == null)
333                throw new UnsupportedOperationException();
334            if (e == null)
335                throw new NullPointerException();
336            return map.internalPutIfAbsent(e, v) == null;
337        }
338        public boolean addAll(Collection<? extends K> c) {
339            boolean added = false;
340            V v;
341            if ((v = value) == null)
342                throw new UnsupportedOperationException();
343            for (K e : c) {
344                if (e == null)
345                    throw new NullPointerException();
346                if (map.internalPutIfAbsent(e, v) == null)
347                    added = true;
348            }
349            return added;
350        }
351        public boolean equals(Object o) {
352            Set<?> c;
353            return ((o instanceof Set) &&
354                    ((c = (Set<?>)o) == this ||
355                     (containsAll(c) && c.containsAll(this))));
356        }
357    }
358
288      /*
289       * Overview:
290       *
# Line 366 | 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
378 <     * variants of put-related operations). The validation-based
379 <     * 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 390 | 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
399 <     *  11 - Locked and may have a thread waiting for lock
400 <     *  10 - Node is a forwarding node
401 <     *
402 <     * The lower 30 bits of each Node's hash field contain a
403 <     * transformation of the key's hash code, except for forwarding
404 <     * nodes, for which the lower bits are zero (and so always have
405 <     * 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 411 | 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
416 <     * construction, so we overlay these by using bits of the Node
417 <     * hash field for lock control (see above), and so normally use
418 <     * builtin monitors only for blocking and signalling using
419 <     * 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 478 | 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 529 | 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 593 | Line 509 | public class ConcurrentHashMapV8<K, V>
509      private static final float LOAD_FACTOR = 0.75f;
510  
511      /**
596     * The buffer size for skipped bins during transfers. The
597     * value is arbitrary but should be large enough to avoid
598     * most locking stalls during resizes.
599     */
600    private static final int TRANSFER_BUFFER_SIZE = 32;
601
602    /**
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
611 <     * 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 621 | 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 KeySetView<K,V> keySet;
627 <    private transient Values<K,V> values;
628 <    private transient EntrySet<K,V> entrySet;
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 659 | 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 683 | 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          }
698
699        /** CompareAndSet the hash field */
700        final boolean casHash(int cmp, int val) {
701            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
702        }
703
704        /** The number of spins before blocking for a lock */
705        static final int MAX_SPINS =
706            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
707
708        /**
709         * Spins a while if LOCKED bit set and this node is the first
710         * of its bin, and then sets WAITING bits on hash field and
711         * blocks (once) if they are still set.  It is OK for this
712         * method to return even if lock is not available upon exit,
713         * which enables these simple single-wait mechanics.
714         *
715         * The corresponding signalling operation is performed within
716         * callers: Upon detecting that WAITING has been set when
717         * unlocking lock (via a failed CAS from non-waiting LOCKED
718         * state), unlockers acquire the sync lock and perform a
719         * notifyAll.
720         *
721         * The initial sanity check on tab and bounds is not currently
722         * necessary in the only usages of this method, but enables
723         * use in other future contexts.
724         */
725        final void tryAwaitLock(Node[] tab, int i) {
726            if (tab != null && i >= 0 && i < tab.length) { // sanity check
727                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
728                int spins = MAX_SPINS, h;
729                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
730                    if (spins >= 0) {
731                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
732                        if (r >= 0 && --spins == 0)
733                            Thread.yield();  // yield before block
734                    }
735                    else if (casHash(h, h | WAITING)) {
736                        synchronized (this) {
737                            if (tabAt(tab, i) == this &&
738                                (hash & WAITING) == WAITING) {
739                                try {
740                                    wait();
741                                } catch (InterruptedException ie) {
742                                    Thread.currentThread().interrupt();
743                                }
744                            }
745                            else
746                                notifyAll(); // possibly won race vs signaller
747                        }
748                        break;
749                    }
750                }
751            }
752        }
753
754        // Unsafe mechanics for casHash
755        private static final sun.misc.Unsafe UNSAFE;
756        private static final long hashOffset;
757
758        static {
759            try {
760                UNSAFE = getUnsafe();
761                Class<?> k = Node.class;
762                hashOffset = UNSAFE.objectFieldOffset
763                    (k.getDeclaredField("hash"));
764            } catch (Exception e) {
765                throw new Error(e);
766            }
767        }
686      }
687  
688      /* ---------------- TreeBins -------------- */
# Line 772 | 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 828 | 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 862 | 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 879 | 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 899 | 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") final TreeNode getTreeNode
821 <            (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 910 | 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                          }
919                        else if ((pr = p.right) != null && h >= pr.hash)
920                            s = pr;
921                        if (s != null && (r = getTreeNode(h, k, s)) != null)
922                            return r;
842                      }
843                  }
844                  else
# Line 934 | 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 946 | 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 960 | Line 879 | public class ConcurrentHashMapV8<K, V>
879           * Finds or adds a node.
880           * @return null if added
881           */
882 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
883 <            (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 974 | 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 991 | 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 1006 | 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 1030 | 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 1052 | 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 1067 | 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 1116 | 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 1135 | 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 1153 | 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 1165 | 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 1181 | 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 1191 | 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 1203 | 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 1233 | 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 1251 | 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)
1263 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1264 <            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 1295 | 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 1329 | 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) {
1342 <                checkForResize();               // try resizing if can't get lock
1343 <                f.tryAwaitLock(tab, i);
1344 <            }
1345 <            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 1371 | Line 1290 | public class ConcurrentHashMapV8<K, V>
1290                                  break;
1291                          }
1292                      }
1374                } finally {
1375                    if (!f.casHash(fh | LOCKED, fh)) {
1376                        f.hash = fh;
1377                        synchronized (f) { f.notifyAll(); };
1378                    }
1293                  }
1294                  if (validated) {
1295                      if (deleted)
1296 <                        counter.add(-1L);
1296 >                        addCount(-1L, -1);
1297                      break;
1298                  }
1299              }
# Line 1388 | 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
1393 <     * 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.
1407 <     *  * compute uses the same function-call mechanics, but without
1408 <     *    the prescans
1409 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1410 <     *    update function if present
1411 <     *  * putAll attempts to pre-allocate enough table space
1412 <     *    and more lazily performs count updates and checks.
1413 <     *
1414 <     * Someday when details settle down a bit more, it might be worth
1415 <     * 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;
1462 <                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                      }
1483                } finally {                  // unlock and signal if needed
1484                    if (!f.casHash(fh | LOCKED, fh)) {
1485                        f.hash = fh;
1486                        synchronized (f) { f.notifyAll(); };
1487                    }
1390                  }
1391 <                if (count != 0) {
1391 >                if (len != 0) {
1392                      if (oldVal != null)
1393                          return oldVal;
1492                    if (tab.length <= 64)
1493                        count = 2;
1394                      break;
1395                  }
1396              }
1397          }
1398 <        counter.add(1L);
1499 <        if (count > 1)
1500 <            checkForResize();
1501 <        return null;
1502 <    }
1503 <
1504 <    /** Implementation for putIfAbsent */
1505 <    private final Object internalPutIfAbsent(Object k, Object v) {
1506 <        int h = spread(k.hashCode());
1507 <        int count = 0;
1508 <        for (Node[] tab = table;;) {
1509 <            int i; Node f; int fh; Object fk, fv;
1510 <            if (tab == null)
1511 <                tab = initTable();
1512 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1513 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1514 <                    break;
1515 <            }
1516 <            else if ((fh = f.hash) == MOVED) {
1517 <                if ((fk = f.key) instanceof TreeBin) {
1518 <                    TreeBin t = (TreeBin)fk;
1519 <                    Object oldVal = null;
1520 <                    t.acquire(0);
1521 <                    try {
1522 <                        if (tabAt(tab, i) == f) {
1523 <                            count = 2;
1524 <                            TreeNode p = t.putTreeNode(h, k, v);
1525 <                            if (p != null)
1526 <                                oldVal = p.val;
1527 <                        }
1528 <                    } finally {
1529 <                        t.release(0);
1530 <                    }
1531 <                    if (count != 0) {
1532 <                        if (oldVal != null)
1533 <                            return oldVal;
1534 <                        break;
1535 <                    }
1536 <                }
1537 <                else
1538 <                    tab = (Node[])fk;
1539 <            }
1540 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1541 <                     ((fk = f.key) == k || k.equals(fk)))
1542 <                return fv;
1543 <            else {
1544 <                Node g = f.next;
1545 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1546 <                    for (Node e = g;;) {
1547 <                        Object ek, ev;
1548 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1549 <                            ((ek = e.key) == k || k.equals(ek)))
1550 <                            return ev;
1551 <                        if ((e = e.next) == null) {
1552 <                            checkForResize();
1553 <                            break;
1554 <                        }
1555 <                    }
1556 <                }
1557 <                if (((fh = f.hash) & LOCKED) != 0) {
1558 <                    checkForResize();
1559 <                    f.tryAwaitLock(tab, i);
1560 <                }
1561 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1562 <                    Object oldVal = null;
1563 <                    try {
1564 <                        if (tabAt(tab, i) == f) {
1565 <                            count = 1;
1566 <                            for (Node e = f;; ++count) {
1567 <                                Object ek, ev;
1568 <                                if ((e.hash & HASH_BITS) == h &&
1569 <                                    (ev = e.val) != null &&
1570 <                                    ((ek = e.key) == k || k.equals(ek))) {
1571 <                                    oldVal = ev;
1572 <                                    break;
1573 <                                }
1574 <                                Node last = e;
1575 <                                if ((e = e.next) == null) {
1576 <                                    last.next = new Node(h, k, v, null);
1577 <                                    if (count >= TREE_THRESHOLD)
1578 <                                        replaceWithTreeBin(tab, i, k);
1579 <                                    break;
1580 <                                }
1581 <                            }
1582 <                        }
1583 <                    } finally {
1584 <                        if (!f.casHash(fh | LOCKED, fh)) {
1585 <                            f.hash = fh;
1586 <                            synchronized (f) { f.notifyAll(); };
1587 <                        }
1588 <                    }
1589 <                    if (count != 0) {
1590 <                        if (oldVal != null)
1591 <                            return oldVal;
1592 <                        if (tab.length <= 64)
1593 <                            count = 2;
1594 <                        break;
1595 <                    }
1596 <                }
1597 <            }
1598 <        }
1599 <        counter.add(1L);
1600 <        if (count > 1)
1601 <            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)) {
1626 <                            node.hash = h;
1627 <                            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              }
1663            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1664                     ((fk = f.key) == k || k.equals(fk)))
1665                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 &&
1672 <                            ((ek = e.key) == k || k.equals(ek)))
1673 <                            return ev;
1674 <                        if ((e = e.next) == null) {
1675 <                            checkForResize();
1676 <                            break;
1677 <                        }
1678 <                    }
1679 <                }
1680 <                if (((fh = f.hash) & LOCKED) != 0) {
1681 <                    checkForResize();
1682 <                    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)
1703 <                                            replaceWithTreeBin(tab, i, k);
1704 <                                    }
1705 <                                    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                          }
1709                    } finally {
1710                        if (!f.casHash(fh | LOCKED, fh)) {
1711                            f.hash = fh;
1712                            synchronized (f) { f.notifyAll(); };
1713                        }
1714                    }
1715                    if (count != 0) {
1716                        if (!added)
1717                            return val;
1718                        if (tab.length <= 64)
1719                            count = 2;
1720                        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);
1727 <            if (count > 1)
1728 <                checkForResize();
1729 <        }
1499 >        if (val != null)
1500 >            addCount(1L, len);
1501          return val;
1502      }
1503  
1504      /** Implementation for compute */
1505 <    @SuppressWarnings("unchecked") private final Object internalCompute
1506 <        (K k, boolean onlyIfPresent, 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)) {
1759 <                            node.hash = h;
1760 <                            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 1790 | 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();
1801 <                f.tryAwaitLock(tab, i);
1802 <            }
1803 <            else if (f.casHash(fh, fh | LOCKED)) {
1804 <                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 1824 | 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                      }
1837                } finally {
1838                    if (!f.casHash(fh | LOCKED, fh)) {
1839                        f.hash = fh;
1840                        synchronized (f) { f.notifyAll(); };
1841                    }
1608                  }
1609 <                if (count != 0) {
1844 <                    if (tab.length <= 64)
1845 <                        count = 2;
1609 >                if (len != 0)
1610                      break;
1847                }
1611              }
1612          }
1613 <        if (delta != 0) {
1614 <            counter.add((long)delta);
1852 <            if (count > 1)
1853 <                checkForResize();
1854 <        }
1613 >        if (delta != 0)
1614 >            addCount((long)delta, len);
1615          return val;
1616      }
1617  
1618      /** Implementation for merge */
1619 <    @SuppressWarnings("unchecked") private final Object internalMerge
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 1899 | 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;
1907 <            }
1908 <            else if ((fh & LOCKED) != 0) {
1909 <                checkForResize();
1910 <                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 1934 | 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                      }
1945                } finally {
1946                    if (!f.casHash(fh | LOCKED, fh)) {
1947                        f.hash = fh;
1948                        synchronized (f) { f.notifyAll(); };
1949                    }
1703                  }
1704 <                if (count != 0) {
1952 <                    if (tab.length <= 64)
1953 <                        count = 2;
1704 >                if (len != 0)
1705                      break;
1955                }
1706              }
1707          }
1708 <        if (delta != 0) {
1709 <            counter.add((long)delta);
1960 <            if (count > 1)
1961 <                checkForResize();
1962 <        }
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 2010 | 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;
2018 <                        checkForResize();
2019 <                        f.tryAwaitLock(tab, i);
2020 <                    }
2021 <                    else if (f.casHash(fh, fh | LOCKED)) {
2022 <                        int count = 0;
2023 <                        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                              }
2044                        } finally {
2045                            if (!f.casHash(fh | LOCKED, fh)) {
2046                                f.hash = fh;
2047                                synchronized (f) { f.notifyAll(); };
2048                            }
1786                          }
1787 <                        if (count != 0) {
1788 <                            if (count > 1) {
1789 <                                counter.add(delta);
2053 <                                delta = 0L;
2054 <                                checkForResize();
2055 <                            }
1787 >                        if (len != 0) {
1788 >                            if (len > 1)
1789 >                                addCount(delta, len);
1790                              break;
1791                          }
1792                      }
1793                  }
1794              }
1795          } finally {
1796 <            if (delta != 0)
1797 <                counter.add(delta);
1796 >            if (delta != 0L)
1797 >                addCount(delta, 2);
1798          }
1799          if (npe)
1800              throw new NullPointerException();
1801      }
1802  
1803 +    /**
1804 +     * Implementation for clear. Steps through each bin, removing all
1805 +     * nodes.
1806 +     */
1807 +    @SuppressWarnings("unchecked") private final void internalClear() {
1808 +        long delta = 0L; // negative number of deletions
1809 +        int i = 0;
1810 +        Node<V>[] tab = table;
1811 +        while (tab != null && i < tab.length) {
1812 +            Node<V> f = tabAt(tab, i);
1813 +            if (f == null)
1814 +                ++i;
1815 +            else if (f.hash < 0) {
1816 +                Object fk;
1817 +                if ((fk = f.key) instanceof TreeBin) {
1818 +                    TreeBin<V> t = (TreeBin<V>)fk;
1819 +                    t.acquire(0);
1820 +                    try {
1821 +                        if (tabAt(tab, i) == f) {
1822 +                            for (Node<V> p = t.first; p != null; p = p.next) {
1823 +                                if (p.val != null) { // (currently always true)
1824 +                                    p.val = null;
1825 +                                    --delta;
1826 +                                }
1827 +                            }
1828 +                            t.first = null;
1829 +                            t.root = null;
1830 +                            ++i;
1831 +                        }
1832 +                    } finally {
1833 +                        t.release(0);
1834 +                    }
1835 +                }
1836 +                else
1837 +                    tab = (Node<V>[])fk;
1838 +            }
1839 +            else {
1840 +                synchronized (f) {
1841 +                    if (tabAt(tab, i) == f) {
1842 +                        for (Node<V> e = f; e != null; e = e.next) {
1843 +                            if (e.val != null) {  // (currently always true)
1844 +                                e.val = null;
1845 +                                --delta;
1846 +                            }
1847 +                        }
1848 +                        setTabAt(tab, i, null);
1849 +                        ++i;
1850 +                    }
1851 +                }
1852 +            }
1853 +        }
1854 +        if (delta != 0L)
1855 +            addCount(delta, -1);
1856 +    }
1857 +
1858      /* ---------------- Table Initialization and Resizing -------------- */
1859  
1860      /**
# Line 2085 | Line 1874 | public class ConcurrentHashMapV8<K, V>
1874      /**
1875       * Initializes table, using the size recorded in sizeCtl.
1876       */
1877 <    private final Node[] initTable() {
1878 <        Node[] tab; int sc;
1877 >    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
1878 >        Node<V>[] tab; int sc;
1879          while ((tab = table) == null) {
1880              if ((sc = sizeCtl) < 0)
1881                  Thread.yield(); // lost initialization race; just spin
1882 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1882 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1883                  try {
1884                      if ((tab = table) == null) {
1885                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1886 <                        tab = table = new Node[n];
1886 >                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1887 >                        table = tab = (Node<V>[])tb;
1888                          sc = n - (n >>> 2);
1889                      }
1890                  } finally {
# Line 2107 | Line 1897 | public class ConcurrentHashMapV8<K, V>
1897      }
1898  
1899      /**
1900 <     * If table is too small and not already resizing, creates next
1901 <     * table and transfers bins.  Rechecks occupancy after a transfer
1902 <     * to see if another resize is already needed because resizings
1903 <     * are lagging additions.
1904 <     */
1905 <    private final void checkForResize() {
1906 <        Node[] tab; int n, sc;
1907 <        while ((tab = table) != null &&
1908 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1909 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1910 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1911 <            try {
1912 <                if (tab == table) {
1913 <                    table = rebuild(tab);
1914 <                    sc = (n << 1) - (n >>> 1);
1900 >     * Adds to count, and if table is too small and not already
1901 >     * resizing, initiates transfer. If already resizing, helps
1902 >     * perform transfer if work is available.  Rechecks occupancy
1903 >     * after a transfer to see if another resize is already needed
1904 >     * because resizings are lagging additions.
1905 >     *
1906 >     * @param x the count to add
1907 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1908 >     */
1909 >    private final void addCount(long x, int check) {
1910 >        CounterCell[] as; long b, s;
1911 >        if ((as = counterCells) != null ||
1912 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1913 >            CounterHashCode hc; CounterCell a; long v; int m;
1914 >            boolean uncontended = true;
1915 >            if ((hc = threadCounterHashCode.get()) == null ||
1916 >                as == null || (m = as.length - 1) < 0 ||
1917 >                (a = as[m & hc.code]) == null ||
1918 >                !(uncontended =
1919 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1920 >                fullAddCount(x, hc, uncontended);
1921 >                return;
1922 >            }
1923 >            if (check <= 1)
1924 >                return;
1925 >            s = sumCount();
1926 >        }
1927 >        if (check >= 0) {
1928 >            Node<V>[] tab, nt; int sc;
1929 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1930 >                   tab.length < MAXIMUM_CAPACITY) {
1931 >                if (sc < 0) {
1932 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1933 >                        (nt = nextTable) == null)
1934 >                        break;
1935 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1936 >                        transfer(tab, nt);
1937                  }
1938 <            } finally {
1939 <                sizeCtl = sc;
1938 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1939 >                    transfer(tab, null);
1940 >                s = sumCount();
1941              }
1942          }
1943      }
# Line 2134 | Line 1947 | public class ConcurrentHashMapV8<K, V>
1947       *
1948       * @param size number of elements (doesn't need to be perfectly accurate)
1949       */
1950 <    private final void tryPresize(int size) {
1950 >    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
1951          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1952              tableSizeFor(size + (size >>> 1) + 1);
1953          int sc;
1954          while ((sc = sizeCtl) >= 0) {
1955 <            Node[] tab = table; int n;
1955 >            Node<V>[] tab = table; int n;
1956              if (tab == null || (n = tab.length) == 0) {
1957                  n = (sc > c) ? sc : c;
1958 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1958 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1959                      try {
1960                          if (table == tab) {
1961 <                            table = new Node[n];
1961 >                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1962 >                            table = (Node<V>[])tb;
1963                              sc = n - (n >>> 2);
1964                          }
1965                      } finally {
# Line 2155 | Line 1969 | public class ConcurrentHashMapV8<K, V>
1969              }
1970              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1971                  break;
1972 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1973 <                try {
1974 <                    if (table == tab) {
2161 <                        table = rebuild(tab);
2162 <                        sc = (n << 1) - (n >>> 1);
2163 <                    }
2164 <                } finally {
2165 <                    sizeCtl = sc;
2166 <                }
2167 <            }
1972 >            else if (tab == table &&
1973 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1974 >                transfer(tab, null);
1975          }
1976      }
1977  
1978      /*
1979       * Moves and/or copies the nodes in each bin to new table. See
1980       * above for explanation.
2174     *
2175     * @return the new table
1981       */
1982 <    private static final Node[] rebuild(Node[] tab) {
1983 <        int n = tab.length;
1984 <        Node[] nextTab = new Node[n << 1];
1985 <        Node fwd = new Node(MOVED, nextTab, null, null);
1986 <        int[] buffer = null;       // holds bins to revisit; null until needed
1987 <        Node rev = null;           // reverse forwarder; null until needed
1988 <        int nbuffered = 0;         // the number of bins in buffer list
1989 <        int bufferIndex = 0;       // buffer index of current buffered bin
1990 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1991 <
1992 <        for (int i = bin;;) {      // start upwards sweep
1993 <            int fh; Node f;
1994 <            if ((f = tabAt(tab, i)) == null) {
1995 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
1996 <                    if (!casTabAt(tab, i, f, fwd))
1997 <                        continue;
1998 <                }
1999 <                else {             // transiently use a locked forwarding node
2000 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2001 <                    if (!casTabAt(tab, i, f, g))
2002 <                        continue;
1982 >    @SuppressWarnings("unchecked") private final void transfer
1983 >        (Node<V>[] tab, Node<V>[] nextTab) {
1984 >        int n = tab.length, stride;
1985 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1986 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1987 >        if (nextTab == null) {            // initiating
1988 >            try {
1989 >                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
1990 >                nextTab = (Node<V>[])tb;
1991 >            } catch (Throwable ex) {      // try to cope with OOME
1992 >                sizeCtl = Integer.MAX_VALUE;
1993 >                return;
1994 >            }
1995 >            nextTable = nextTab;
1996 >            transferOrigin = n;
1997 >            transferIndex = n;
1998 >            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1999 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2000 >                int nextk = (k > stride) ? k - stride : 0;
2001 >                for (int m = nextk; m < k; ++m)
2002 >                    nextTab[m] = rev;
2003 >                for (int m = n + nextk; m < n + k; ++m)
2004 >                    nextTab[m] = rev;
2005 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2006 >            }
2007 >        }
2008 >        int nextn = nextTab.length;
2009 >        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2010 >        boolean advance = true;
2011 >        for (int i = 0, bound = 0;;) {
2012 >            int nextIndex, nextBound; Node<V> f; Object fk;
2013 >            while (advance) {
2014 >                if (--i >= bound)
2015 >                    advance = false;
2016 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2017 >                    i = -1;
2018 >                    advance = false;
2019 >                }
2020 >                else if (U.compareAndSwapInt
2021 >                         (this, TRANSFERINDEX, nextIndex,
2022 >                          nextBound = (nextIndex > stride ?
2023 >                                       nextIndex - stride : 0))) {
2024 >                    bound = nextBound;
2025 >                    i = nextIndex - 1;
2026 >                    advance = false;
2027 >                }
2028 >            }
2029 >            if (i < 0 || i >= n || i + n >= nextn) {
2030 >                for (int sc;;) {
2031 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2032 >                        if (sc == -1) {
2033 >                            nextTable = null;
2034 >                            table = nextTab;
2035 >                            sizeCtl = (n << 1) - (n >>> 1);
2036 >                        }
2037 >                        return;
2038 >                    }
2039 >                }
2040 >            }
2041 >            else if ((f = tabAt(tab, i)) == null) {
2042 >                if (casTabAt(tab, i, null, fwd)) {
2043                      setTabAt(nextTab, i, null);
2044                      setTabAt(nextTab, i + n, null);
2045 <                    setTabAt(tab, i, fwd);
2201 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2202 <                        g.hash = MOVED;
2203 <                        synchronized (g) { g.notifyAll(); }
2204 <                    }
2045 >                    advance = true;
2046                  }
2047              }
2048 <            else if ((fh = f.hash) == MOVED) {
2049 <                Object fk = f.key;
2050 <                if (fk instanceof TreeBin) {
2051 <                    TreeBin t = (TreeBin)fk;
2052 <                    boolean validated = false;
2053 <                    t.acquire(0);
2054 <                    try {
2055 <                        if (tabAt(tab, i) == f) {
2056 <                            validated = true;
2057 <                            splitTreeBin(nextTab, i, t);
2058 <                            setTabAt(tab, i, fwd);
2048 >            else if (f.hash >= 0) {
2049 >                synchronized (f) {
2050 >                    if (tabAt(tab, i) == f) {
2051 >                        int runBit = f.hash & n;
2052 >                        Node<V> lastRun = f, lo = null, hi = null;
2053 >                        for (Node<V> p = f.next; p != null; p = p.next) {
2054 >                            int b = p.hash & n;
2055 >                            if (b != runBit) {
2056 >                                runBit = b;
2057 >                                lastRun = p;
2058 >                            }
2059                          }
2060 <                    } finally {
2061 <                        t.release(0);
2060 >                        if (runBit == 0)
2061 >                            lo = lastRun;
2062 >                        else
2063 >                            hi = lastRun;
2064 >                        for (Node<V> p = f; p != lastRun; p = p.next) {
2065 >                            int ph = p.hash;
2066 >                            Object pk = p.key; V pv = p.val;
2067 >                            if ((ph & n) == 0)
2068 >                                lo = new Node<V>(ph, pk, pv, lo);
2069 >                            else
2070 >                                hi = new Node<V>(ph, pk, pv, hi);
2071 >                        }
2072 >                        setTabAt(nextTab, i, lo);
2073 >                        setTabAt(nextTab, i + n, hi);
2074 >                        setTabAt(tab, i, fwd);
2075 >                        advance = true;
2076                      }
2222                    if (!validated)
2223                        continue;
2077                  }
2078              }
2079 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2080 <                boolean validated = false;
2081 <                try {              // split to lo and hi lists; copying as needed
2079 >            else if ((fk = f.key) instanceof TreeBin) {
2080 >                TreeBin<V> t = (TreeBin<V>)fk;
2081 >                t.acquire(0);
2082 >                try {
2083                      if (tabAt(tab, i) == f) {
2084 <                        validated = true;
2085 <                        splitBin(nextTab, i, f);
2084 >                        TreeBin<V> lt = new TreeBin<V>();
2085 >                        TreeBin<V> ht = new TreeBin<V>();
2086 >                        int lc = 0, hc = 0;
2087 >                        for (Node<V> e = t.first; e != null; e = e.next) {
2088 >                            int h = e.hash;
2089 >                            Object k = e.key; V v = e.val;
2090 >                            if ((h & n) == 0) {
2091 >                                ++lc;
2092 >                                lt.putTreeNode(h, k, v);
2093 >                            }
2094 >                            else {
2095 >                                ++hc;
2096 >                                ht.putTreeNode(h, k, v);
2097 >                            }
2098 >                        }
2099 >                        Node<V> ln, hn; // throw away trees if too small
2100 >                        if (lc < TREE_THRESHOLD) {
2101 >                            ln = null;
2102 >                            for (Node<V> p = lt.first; p != null; p = p.next)
2103 >                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2104 >                        }
2105 >                        else
2106 >                            ln = new Node<V>(MOVED, lt, null, null);
2107 >                        setTabAt(nextTab, i, ln);
2108 >                        if (hc < TREE_THRESHOLD) {
2109 >                            hn = null;
2110 >                            for (Node<V> p = ht.first; p != null; p = p.next)
2111 >                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2112 >                        }
2113 >                        else
2114 >                            hn = new Node<V>(MOVED, ht, null, null);
2115 >                        setTabAt(nextTab, i + n, hn);
2116                          setTabAt(tab, i, fwd);
2117 +                        advance = true;
2118                      }
2119                  } finally {
2120 <                    if (!f.casHash(fh | LOCKED, fh)) {
2236 <                        f.hash = fh;
2237 <                        synchronized (f) { f.notifyAll(); };
2238 <                    }
2120 >                    t.release(0);
2121                  }
2240                if (!validated)
2241                    continue;
2242            }
2243            else {
2244                if (buffer == null) // initialize buffer for revisits
2245                    buffer = new int[TRANSFER_BUFFER_SIZE];
2246                if (bin < 0 && bufferIndex > 0) {
2247                    int j = buffer[--bufferIndex];
2248                    buffer[bufferIndex] = i;
2249                    i = j;         // swap with another bin
2250                    continue;
2251                }
2252                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2253                    f.tryAwaitLock(tab, i);
2254                    continue;      // no other options -- block
2255                }
2256                if (rev == null)   // initialize reverse-forwarder
2257                    rev = new Node(MOVED, tab, null, null);
2258                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2259                    continue;      // recheck before adding to list
2260                buffer[nbuffered++] = i;
2261                setTabAt(nextTab, i, rev);     // install place-holders
2262                setTabAt(nextTab, i + n, rev);
2263            }
2264
2265            if (bin > 0)
2266                i = --bin;
2267            else if (buffer != null && nbuffered > 0) {
2268                bin = -1;
2269                i = buffer[bufferIndex = --nbuffered];
2122              }
2123              else
2124 <                return nextTab;
2124 >                advance = true; // already processed
2125          }
2126      }
2127  
2128 <    /**
2129 <     * Splits a normal bin with list headed by e into lo and hi parts;
2130 <     * installs in given table.
2131 <     */
2132 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2133 <        int bit = nextTab.length >>> 1; // bit to split on
2134 <        int runBit = e.hash & bit;
2135 <        Node lastRun = e, lo = null, hi = null;
2136 <        for (Node p = e.next; p != null; p = p.next) {
2285 <            int b = p.hash & bit;
2286 <            if (b != runBit) {
2287 <                runBit = b;
2288 <                lastRun = p;
2128 >    /* ---------------- Counter support -------------- */
2129 >
2130 >    final long sumCount() {
2131 >        CounterCell[] as = counterCells; CounterCell a;
2132 >        long sum = baseCount;
2133 >        if (as != null) {
2134 >            for (int i = 0; i < as.length; ++i) {
2135 >                if ((a = as[i]) != null)
2136 >                    sum += a.value;
2137              }
2138          }
2139 <        if (runBit == 0)
2292 <            lo = lastRun;
2293 <        else
2294 <            hi = lastRun;
2295 <        for (Node p = e; p != lastRun; p = p.next) {
2296 <            int ph = p.hash & HASH_BITS;
2297 <            Object pk = p.key, pv = p.val;
2298 <            if ((ph & bit) == 0)
2299 <                lo = new Node(ph, pk, pv, lo);
2300 <            else
2301 <                hi = new Node(ph, pk, pv, hi);
2302 <        }
2303 <        setTabAt(nextTab, i, lo);
2304 <        setTabAt(nextTab, i + bit, hi);
2139 >        return sum;
2140      }
2141  
2142 <    /**
2143 <     * Splits a tree bin into lo and hi parts; installs in given table.
2144 <     */
2145 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2146 <        int bit = nextTab.length >>> 1;
2147 <        TreeBin lt = new TreeBin();
2148 <        TreeBin ht = new TreeBin();
2149 <        int lc = 0, hc = 0;
2150 <        for (Node e = t.first; e != null; e = e.next) {
2316 <            int h = e.hash & HASH_BITS;
2317 <            Object k = e.key, v = e.val;
2318 <            if ((h & bit) == 0) {
2319 <                ++lc;
2320 <                lt.putTreeNode(h, k, v);
2321 <            }
2322 <            else {
2323 <                ++hc;
2324 <                ht.putTreeNode(h, k, v);
2325 <            }
2326 <        }
2327 <        Node ln, hn; // throw away trees if too small
2328 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2329 <            ln = null;
2330 <            for (Node p = lt.first; p != null; p = p.next)
2331 <                ln = new Node(p.hash, p.key, p.val, ln);
2332 <        }
2333 <        else
2334 <            ln = new Node(MOVED, lt, null, null);
2335 <        setTabAt(nextTab, i, ln);
2336 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2337 <            hn = null;
2338 <            for (Node p = ht.first; p != null; p = p.next)
2339 <                hn = new Node(p.hash, p.key, p.val, hn);
2142 >    // See LongAdder version for explanation
2143 >    private final void fullAddCount(long x, CounterHashCode hc,
2144 >                                    boolean wasUncontended) {
2145 >        int h;
2146 >        if (hc == null) {
2147 >            hc = new CounterHashCode();
2148 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2149 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2150 >            threadCounterHashCode.set(hc);
2151          }
2152          else
2153 <            hn = new Node(MOVED, ht, null, null);
2154 <        setTabAt(nextTab, i + bit, hn);
2155 <    }
2156 <
2157 <    /**
2158 <     * Implementation for clear. Steps through each bin, removing all
2159 <     * nodes.
2160 <     */
2161 <    private final void internalClear() {
2162 <        long delta = 0L; // negative number of deletions
2163 <        int i = 0;
2164 <        Node[] tab = table;
2165 <        while (tab != null && i < tab.length) {
2166 <            int fh; Object fk;
2167 <            Node f = tabAt(tab, i);
2168 <            if (f == null)
2169 <                ++i;
2170 <            else if ((fh = f.hash) == MOVED) {
2360 <                if ((fk = f.key) instanceof TreeBin) {
2361 <                    TreeBin t = (TreeBin)fk;
2362 <                    t.acquire(0);
2363 <                    try {
2364 <                        if (tabAt(tab, i) == f) {
2365 <                            for (Node p = t.first; p != null; p = p.next) {
2366 <                                if (p.val != null) { // (currently always true)
2367 <                                    p.val = null;
2368 <                                    --delta;
2153 >            h = hc.code;
2154 >        boolean collide = false;                // True if last slot nonempty
2155 >        for (;;) {
2156 >            CounterCell[] as; CounterCell a; int n; long v;
2157 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2158 >                if ((a = as[(n - 1) & h]) == null) {
2159 >                    if (counterBusy == 0) {            // Try to attach new Cell
2160 >                        CounterCell r = new CounterCell(x); // Optimistic create
2161 >                        if (counterBusy == 0 &&
2162 >                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2163 >                            boolean created = false;
2164 >                            try {               // Recheck under lock
2165 >                                CounterCell[] rs; int m, j;
2166 >                                if ((rs = counterCells) != null &&
2167 >                                    (m = rs.length) > 0 &&
2168 >                                    rs[j = (m - 1) & h] == null) {
2169 >                                    rs[j] = r;
2170 >                                    created = true;
2171                                  }
2172 +                            } finally {
2173 +                                counterBusy = 0;
2174                              }
2175 <                            t.first = null;
2176 <                            t.root = null;
2177 <                            ++i;
2175 >                            if (created)
2176 >                                break;
2177 >                            continue;           // Slot is now non-empty
2178                          }
2375                    } finally {
2376                        t.release(0);
2179                      }
2180 +                    collide = false;
2181                  }
2182 <                else
2183 <                    tab = (Node[])fk;
2184 <            }
2185 <            else if ((fh & LOCKED) != 0) {
2186 <                counter.add(delta); // opportunistically update count
2187 <                delta = 0L;
2188 <                f.tryAwaitLock(tab, i);
2189 <            }
2190 <            else if (f.casHash(fh, fh | LOCKED)) {
2191 <                try {
2192 <                    if (tabAt(tab, i) == f) {
2193 <                        for (Node e = f; e != null; e = e.next) {
2194 <                            if (e.val != null) {  // (currently always true)
2195 <                                e.val = null;
2196 <                                --delta;
2197 <                            }
2182 >                else if (!wasUncontended)       // CAS already known to fail
2183 >                    wasUncontended = true;      // Continue after rehash
2184 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2185 >                    break;
2186 >                else if (counterCells != as || n >= NCPU)
2187 >                    collide = false;            // At max size or stale
2188 >                else if (!collide)
2189 >                    collide = true;
2190 >                else if (counterBusy == 0 &&
2191 >                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2192 >                    try {
2193 >                        if (counterCells == as) {// Expand table unless stale
2194 >                            CounterCell[] rs = new CounterCell[n << 1];
2195 >                            for (int i = 0; i < n; ++i)
2196 >                                rs[i] = as[i];
2197 >                            counterCells = rs;
2198                          }
2199 <                        setTabAt(tab, i, null);
2200 <                        ++i;
2199 >                    } finally {
2200 >                        counterBusy = 0;
2201                      }
2202 <                } finally {
2203 <                    if (!f.casHash(fh | LOCKED, fh)) {
2204 <                        f.hash = fh;
2205 <                        synchronized (f) { f.notifyAll(); };
2202 >                    collide = false;
2203 >                    continue;                   // Retry with expanded table
2204 >                }
2205 >                h ^= h << 13;                   // Rehash
2206 >                h ^= h >>> 17;
2207 >                h ^= h << 5;
2208 >            }
2209 >            else if (counterBusy == 0 && counterCells == as &&
2210 >                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2211 >                boolean init = false;
2212 >                try {                           // Initialize table
2213 >                    if (counterCells == as) {
2214 >                        CounterCell[] rs = new CounterCell[2];
2215 >                        rs[h & 1] = new CounterCell(x);
2216 >                        counterCells = rs;
2217 >                        init = true;
2218                      }
2219 +                } finally {
2220 +                    counterBusy = 0;
2221                  }
2222 +                if (init)
2223 +                    break;
2224              }
2225 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2226 +                break;                          // Fall back on using base
2227          }
2228 <        if (delta != 0)
2408 <            counter.add(delta);
2228 >        hc.code = h;                            // Record index for next time
2229      }
2230  
2231      /* ----------------Table Traversal -------------- */
# Line 2448 | Line 2268 | public class ConcurrentHashMapV8<K, V>
2268       * across threads, iteration terminates if a bounds checks fails
2269       * for a table read.
2270       *
2271 <     * This class extends ForkJoinTask to streamline parallel
2272 <     * iteration in bulk operations (see BulkTask). This adds only an
2273 <     * int of space overhead, which is close enough to negligible in
2274 <     * cases where it is not needed to not worry about it.  Because
2275 <     * ForkJoinTask is Serializable, but iterators need not be, we
2276 <     * need to add warning suppressions.
2271 >     * This class extends CountedCompleter to streamline parallel
2272 >     * iteration in bulk operations. This adds only a few fields of
2273 >     * space overhead, which is small enough in cases where it is not
2274 >     * needed to not worry about it.  Because CountedCompleter is
2275 >     * Serializable, but iterators need not be, we need to add warning
2276 >     * suppressions.
2277       */
2278 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2278 >    @SuppressWarnings("serial") static class Traverser<K,V,R>
2279 >        extends CountedCompleter<R> {
2280          final ConcurrentHashMapV8<K, V> map;
2281 <        Node next;           // the next entry to use
2281 >        Node<V> next;        // the next entry to use
2282          Object nextKey;      // cached key field of next
2283 <        Object nextVal;      // cached val field of next
2284 <        Node[] tab;          // current table; updated if resized
2283 >        V nextVal;           // cached val field of next
2284 >        Node<V>[] tab;       // current table; updated if resized
2285          int index;           // index of bin to use next
2286          int baseIndex;       // current index of initial table
2287          int baseLimit;       // index bound for initial table
2288          int baseSize;        // initial table size
2289 +        int batch;           // split control
2290  
2291          /** Creates iterator for all entries in the table. */
2292          Traverser(ConcurrentHashMapV8<K, V> map) {
2293              this.map = map;
2294          }
2295  
2296 <        /** Creates iterator for split() methods */
2297 <        Traverser(Traverser<K,V,?> it) {
2298 <            ConcurrentHashMapV8<K, V> m; Node[] t;
2299 <            if ((m = this.map = it.map) == null)
2300 <                t = null;
2301 <            else if ((t = it.tab) == null && // force parent tab initialization
2302 <                     (t = it.tab = m.table) != null)
2303 <                it.baseLimit = it.baseSize = t.length;
2304 <            this.tab = t;
2305 <            this.baseSize = it.baseSize;
2306 <            it.baseLimit = this.index = this.baseIndex =
2307 <                ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1;
2296 >        /** Creates iterator for split() methods and task constructors */
2297 >        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2298 >            super(it);
2299 >            this.batch = batch;
2300 >            if ((this.map = map) != null && it != null) { // split parent
2301 >                Node<V>[] t;
2302 >                if ((t = it.tab) == null &&
2303 >                    (t = it.tab = map.table) != null)
2304 >                    it.baseLimit = it.baseSize = t.length;
2305 >                this.tab = t;
2306 >                this.baseSize = it.baseSize;
2307 >                int hi = this.baseLimit = it.baseLimit;
2308 >                it.baseLimit = this.index = this.baseIndex =
2309 >                    (hi + it.baseIndex + 1) >>> 1;
2310 >            }
2311          }
2312  
2313          /**
2314           * Advances next; returns nextVal or null if terminated.
2315           * See above for explanation.
2316           */
2317 <        final Object advance() {
2318 <            Node e = next;
2319 <            Object ev = null;
2317 >        @SuppressWarnings("unchecked") final V advance() {
2318 >            Node<V> e = next;
2319 >            V ev = null;
2320              outer: do {
2321                  if (e != null)                  // advance past used/skipped node
2322                      e = e.next;
2323                  while (e == null) {             // get to next non-null bin
2324                      ConcurrentHashMapV8<K, V> m;
2325 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2325 >                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2326                      if ((t = tab) != null)
2327                          n = t.length;
2328                      else if ((m = map) != null && (t = tab = m.table) != null)
# Line 2507 | Line 2332 | public class ConcurrentHashMapV8<K, V>
2332                      if ((b = baseIndex) >= baseLimit ||
2333                          (i = index) < 0 || i >= n)
2334                          break outer;
2335 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2335 >                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2336                          if ((ek = e.key) instanceof TreeBin)
2337 <                            e = ((TreeBin)ek).first;
2337 >                            e = ((TreeBin<V>)ek).first;
2338                          else {
2339 <                            tab = (Node[])ek;
2339 >                            tab = (Node<V>[])ek;
2340                              continue;           // restarts due to null val
2341                          }
2342                      }                           // visit upper slots if present
# Line 2535 | Line 2360 | public class ConcurrentHashMapV8<K, V>
2360          }
2361  
2362          public final boolean hasMoreElements() { return hasNext(); }
2363 <        public final void setRawResult(Object x) { }
2364 <        public R getRawResult() { return null; }
2365 <        public boolean exec() { return true; }
2363 >
2364 >        public void compute() { } // default no-op CountedCompleter body
2365 >
2366 >        /**
2367 >         * Returns a batch value > 0 if this task should (and must) be
2368 >         * split, if so, adding to pending count, and in any case
2369 >         * updating batch value. The initial batch value is approx
2370 >         * exp2 of the number of times (minus one) to split task by
2371 >         * two before executing leaf action. This value is faster to
2372 >         * compute and more convenient to use as a guide to splitting
2373 >         * than is the depth, since it is used while dividing by two
2374 >         * anyway.
2375 >         */
2376 >        final int preSplit() {
2377 >            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2378 >            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2379 >                if ((t = tab) == null && (t = tab = m.table) != null)
2380 >                    baseLimit = baseSize = t.length;
2381 >                if (t != null) {
2382 >                    long n = m.sumCount();
2383 >                    int par = ((pool = getPool()) == null) ?
2384 >                        ForkJoinPool.getCommonPoolParallelism() :
2385 >                        pool.getParallelism();
2386 >                    int sp = par << 3; // slack of 8
2387 >                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2388 >                }
2389 >            }
2390 >            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2391 >            if ((batch = b) > 0)
2392 >                addToPendingCount(1);
2393 >            return b;
2394 >        }
2395 >
2396      }
2397  
2398      /* ---------------- Public operations -------------- */
# Line 2546 | Line 2401 | public class ConcurrentHashMapV8<K, V>
2401       * Creates a new, empty map with the default initial table size (16).
2402       */
2403      public ConcurrentHashMapV8() {
2549        this.counter = new LongAdder();
2404      }
2405  
2406      /**
# Line 2565 | Line 2419 | public class ConcurrentHashMapV8<K, V>
2419          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2420                     MAXIMUM_CAPACITY :
2421                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2568        this.counter = new LongAdder();
2422          this.sizeCtl = cap;
2423      }
2424  
# Line 2575 | Line 2428 | public class ConcurrentHashMapV8<K, V>
2428       * @param m the map
2429       */
2430      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2578        this.counter = new LongAdder();
2431          this.sizeCtl = DEFAULT_CAPACITY;
2432          internalPutAll(m);
2433      }
# Line 2626 | Line 2478 | public class ConcurrentHashMapV8<K, V>
2478          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2479          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2480              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2629        this.counter = new LongAdder();
2481          this.sizeCtl = cap;
2482      }
2483  
# Line 2652 | Line 2503 | public class ConcurrentHashMapV8<K, V>
2503       * @return the new set
2504       */
2505      public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2506 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(initialCapacity),
2507 <                                      Boolean.TRUE);
2506 >        return new KeySetView<K,Boolean>
2507 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2508      }
2509  
2510      /**
2511       * {@inheritDoc}
2512       */
2513      public boolean isEmpty() {
2514 <        return counter.sum() <= 0L; // ignore transient negative values
2514 >        return sumCount() <= 0L; // ignore transient negative values
2515      }
2516  
2517      /**
2518       * {@inheritDoc}
2519       */
2520      public int size() {
2521 <        long n = counter.sum();
2521 >        long n = sumCount();
2522          return ((n < 0L) ? 0 :
2523                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2524                  (int)n);
# Line 2677 | Line 2528 | public class ConcurrentHashMapV8<K, V>
2528       * Returns the number of mappings. This method should be used
2529       * instead of {@link #size} because a ConcurrentHashMapV8 may
2530       * contain more mappings than can be represented as an int. The
2531 <     * value returned is a snapshot; the actual count may differ if
2532 <     * there are ongoing concurrent insertions or removals.
2531 >     * value returned is an estimate; the actual count may differ if
2532 >     * there are concurrent insertions or removals.
2533       *
2534       * @return the number of mappings
2535       */
2536      public long mappingCount() {
2537 <        long n = counter.sum();
2537 >        long n = sumCount();
2538          return (n < 0L) ? 0L : n; // ignore transient negative values
2539      }
2540  
# Line 2698 | Line 2549 | public class ConcurrentHashMapV8<K, V>
2549       *
2550       * @throws NullPointerException if the specified key is null
2551       */
2552 <    @SuppressWarnings("unchecked") public V get(Object key) {
2553 <        if (key == null)
2703 <            throw new NullPointerException();
2704 <        return (V)internalGet(key);
2552 >    public V get(Object key) {
2553 >        return internalGet(key);
2554      }
2555  
2556      /**
# Line 2714 | Line 2563 | public class ConcurrentHashMapV8<K, V>
2563       * @return the mapping for the key, if present; else the defaultValue
2564       * @throws NullPointerException if the specified key is null
2565       */
2566 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
2567 <        if (key == null)
2568 <            throw new NullPointerException();
2720 <        V v = (V) internalGet(key);
2721 <        return v == null ? defaultValue : v;
2566 >    public V getValueOrDefault(Object key, V defaultValue) {
2567 >        V v;
2568 >        return (v = internalGet(key)) == null ? defaultValue : v;
2569      }
2570  
2571      /**
# Line 2731 | Line 2578 | public class ConcurrentHashMapV8<K, V>
2578       * @throws NullPointerException if the specified key is null
2579       */
2580      public boolean containsKey(Object key) {
2734        if (key == null)
2735            throw new NullPointerException();
2581          return internalGet(key) != null;
2582      }
2583  
# Line 2749 | Line 2594 | public class ConcurrentHashMapV8<K, V>
2594      public boolean containsValue(Object value) {
2595          if (value == null)
2596              throw new NullPointerException();
2597 <        Object v;
2597 >        V v;
2598          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2599          while ((v = it.advance()) != null) {
2600              if (v == value || value.equals(v))
# Line 2773 | Line 2618 | public class ConcurrentHashMapV8<K, V>
2618       *         {@code false} otherwise
2619       * @throws NullPointerException if the specified value is null
2620       */
2621 <    public boolean contains(Object value) {
2621 >    @Deprecated public boolean contains(Object value) {
2622          return containsValue(value);
2623      }
2624  
# Line 2781 | Line 2626 | public class ConcurrentHashMapV8<K, V>
2626       * Maps the specified key to the specified value in this table.
2627       * Neither the key nor the value can be null.
2628       *
2629 <     * <p> The value can be retrieved by calling the {@code get} method
2629 >     * <p>The value can be retrieved by calling the {@code get} method
2630       * with a key that is equal to the original key.
2631       *
2632       * @param key key with which the specified value is to be associated
# Line 2790 | Line 2635 | public class ConcurrentHashMapV8<K, V>
2635       *         {@code null} if there was no mapping for {@code key}
2636       * @throws NullPointerException if the specified key or value is null
2637       */
2638 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
2639 <        if (key == null || value == null)
2795 <            throw new NullPointerException();
2796 <        return (V)internalPut(key, value);
2638 >    public V put(K key, V value) {
2639 >        return internalPut(key, value, false);
2640      }
2641  
2642      /**
# Line 2803 | Line 2646 | public class ConcurrentHashMapV8<K, V>
2646       *         or {@code null} if there was no mapping for the key
2647       * @throws NullPointerException if the specified key or value is null
2648       */
2649 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
2650 <        if (key == null || value == null)
2808 <            throw new NullPointerException();
2809 <        return (V)internalPutIfAbsent(key, value);
2649 >    public V putIfAbsent(K key, V value) {
2650 >        return internalPut(key, value, true);
2651      }
2652  
2653      /**
# Line 2859 | Line 2700 | public class ConcurrentHashMapV8<K, V>
2700       * @throws RuntimeException or Error if the mappingFunction does so,
2701       *         in which case the mapping is left unestablished
2702       */
2703 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2703 >    public V computeIfAbsent
2704          (K key, Fun<? super K, ? extends V> mappingFunction) {
2705 <        if (key == null || mappingFunction == null)
2865 <            throw new NullPointerException();
2866 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2705 >        return internalComputeIfAbsent(key, mappingFunction);
2706      }
2707  
2708      /**
# Line 2900 | Line 2739 | public class ConcurrentHashMapV8<K, V>
2739       * @throws RuntimeException or Error if the remappingFunction does so,
2740       *         in which case the mapping is unchanged
2741       */
2742 <    @SuppressWarnings("unchecked") public V computeIfPresent
2742 >    public V computeIfPresent
2743          (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2744 <        if (key == null || remappingFunction == null)
2906 <            throw new NullPointerException();
2907 <        return (V)internalCompute(key, true, remappingFunction);
2744 >        return internalCompute(key, true, remappingFunction);
2745      }
2746  
2747      /**
# Line 2947 | Line 2784 | public class ConcurrentHashMapV8<K, V>
2784       * @throws RuntimeException or Error if the remappingFunction does so,
2785       *         in which case the mapping is unchanged
2786       */
2787 <    @SuppressWarnings("unchecked") public V compute
2787 >    public V compute
2788          (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2789 <        if (key == null || remappingFunction == null)
2953 <            throw new NullPointerException();
2954 <        return (V)internalCompute(key, false, remappingFunction);
2789 >        return internalCompute(key, false, remappingFunction);
2790      }
2791  
2792      /**
# Line 2979 | Line 2814 | public class ConcurrentHashMapV8<K, V>
2814       * so the computation should be short and simple, and must not
2815       * attempt to update any other mappings of this Map.
2816       */
2817 <    @SuppressWarnings("unchecked") public V merge
2818 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2819 <        if (key == null || value == null || remappingFunction == null)
2820 <            throw new NullPointerException();
2986 <        return (V)internalMerge(key, value, remappingFunction);
2817 >    public V merge
2818 >        (K key, V value,
2819 >         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2820 >        return internalMerge(key, value, remappingFunction);
2821      }
2822  
2823      /**
# Line 2995 | Line 2829 | public class ConcurrentHashMapV8<K, V>
2829       *         {@code null} if there was no mapping for {@code key}
2830       * @throws NullPointerException if the specified key is null
2831       */
2832 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2833 <        if (key == null)
3000 <            throw new NullPointerException();
3001 <        return (V)internalReplace(key, null, null);
2832 >    public V remove(Object key) {
2833 >        return internalReplace(key, null, null);
2834      }
2835  
2836      /**
# Line 3007 | Line 2839 | public class ConcurrentHashMapV8<K, V>
2839       * @throws NullPointerException if the specified key is null
2840       */
2841      public boolean remove(Object key, Object value) {
2842 <        if (key == null)
3011 <            throw new NullPointerException();
3012 <        if (value == null)
3013 <            return false;
3014 <        return internalReplace(key, null, value) != null;
2842 >        return value != null && internalReplace(key, null, value) != null;
2843      }
2844  
2845      /**
# Line 3032 | Line 2860 | public class ConcurrentHashMapV8<K, V>
2860       *         or {@code null} if there was no mapping for the key
2861       * @throws NullPointerException if the specified key or value is null
2862       */
2863 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2863 >    public V replace(K key, V value) {
2864          if (key == null || value == null)
2865              throw new NullPointerException();
2866 <        return (V)internalReplace(key, value, null);
2866 >        return internalReplace(key, value, null);
2867      }
2868  
2869      /**
# Line 3078 | Line 2906 | public class ConcurrentHashMapV8<K, V>
2906      /**
2907       * Returns a {@link Collection} view of the values contained in this map.
2908       * The collection is backed by the map, so changes to the map are
2909 <     * reflected in the collection, and vice-versa.  The collection
3082 <     * supports element removal, which removes the corresponding
3083 <     * mapping from this map, via the {@code Iterator.remove},
3084 <     * {@code Collection.remove}, {@code removeAll},
3085 <     * {@code retainAll}, and {@code clear} operations.  It does not
3086 <     * support the {@code add} or {@code addAll} operations.
3087 <     *
3088 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3089 <     * that will never throw {@link ConcurrentModificationException},
3090 <     * and guarantees to traverse elements as they existed upon
3091 <     * construction of the iterator, and may (but is not guaranteed to)
3092 <     * reflect any modifications subsequent to construction.
2909 >     * reflected in the collection, and vice-versa.
2910       */
2911 <    public Collection<V> values() {
2912 <        Values<K,V> vs = values;
2913 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
2911 >    public ValuesView<K,V> values() {
2912 >        ValuesView<K,V> vs = values;
2913 >        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2914      }
2915  
2916      /**
# Line 3113 | Line 2930 | public class ConcurrentHashMapV8<K, V>
2930       * reflect any modifications subsequent to construction.
2931       */
2932      public Set<Map.Entry<K,V>> entrySet() {
2933 <        EntrySet<K,V> es = entrySet;
2934 <        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2933 >        EntrySetView<K,V> es = entrySet;
2934 >        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2935      }
2936  
2937      /**
# Line 3174 | Line 2991 | public class ConcurrentHashMapV8<K, V>
2991      public int hashCode() {
2992          int h = 0;
2993          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2994 <        Object v;
2994 >        V v;
2995          while ((v = it.advance()) != null) {
2996              h += it.nextKey.hashCode() ^ v.hashCode();
2997          }
# Line 3196 | Line 3013 | public class ConcurrentHashMapV8<K, V>
3013          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3014          StringBuilder sb = new StringBuilder();
3015          sb.append('{');
3016 <        Object v;
3016 >        V v;
3017          if ((v = it.advance()) != null) {
3018              for (;;) {
3019                  Object k = it.nextKey;
# Line 3227 | Line 3044 | public class ConcurrentHashMapV8<K, V>
3044                  return false;
3045              Map<?,?> m = (Map<?,?>) o;
3046              Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3047 <            Object val;
3047 >            V val;
3048              while ((val = it.advance()) != null) {
3049                  Object v = m.get(it.nextKey);
3050                  if (v == null || (v != val && !v.equals(val)))
# Line 3247 | Line 3064 | public class ConcurrentHashMapV8<K, V>
3064  
3065      /* ----------------Iterators -------------- */
3066  
3067 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3067 >    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3068 >        extends Traverser<K,V,Object>
3069          implements Spliterator<K>, Enumeration<K> {
3070          KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3071 <        KeyIterator(Traverser<K,V,Object> it) {
3072 <            super(it);
3071 >        KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3072 >            super(map, it, -1);
3073          }
3074          public KeyIterator<K,V> split() {
3075              if (nextKey != null)
3076                  throw new IllegalStateException();
3077 <            return new KeyIterator<K,V>(this);
3077 >            return new KeyIterator<K,V>(map, this);
3078          }
3079          @SuppressWarnings("unchecked") public final K next() {
3080              if (nextVal == null && advance() == null)
# Line 3269 | Line 3087 | public class ConcurrentHashMapV8<K, V>
3087          public final K nextElement() { return next(); }
3088      }
3089  
3090 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3090 >    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3091 >        extends Traverser<K,V,Object>
3092          implements Spliterator<V>, Enumeration<V> {
3093          ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3094 <        ValueIterator(Traverser<K,V,Object> it) {
3095 <            super(it);
3094 >        ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3095 >            super(map, it, -1);
3096          }
3097          public ValueIterator<K,V> split() {
3098              if (nextKey != null)
3099                  throw new IllegalStateException();
3100 <            return new ValueIterator<K,V>(this);
3100 >            return new ValueIterator<K,V>(map, this);
3101          }
3102  
3103 <        @SuppressWarnings("unchecked") public final V next() {
3104 <            Object v;
3103 >        public final V next() {
3104 >            V v;
3105              if ((v = nextVal) == null && (v = advance()) == null)
3106                  throw new NoSuchElementException();
3107              nextVal = null;
3108 <            return (V) v;
3108 >            return v;
3109          }
3110  
3111          public final V nextElement() { return next(); }
3112      }
3113  
3114 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3114 >    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3115 >        extends Traverser<K,V,Object>
3116          implements Spliterator<Map.Entry<K,V>> {
3117          EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3118 <        EntryIterator(Traverser<K,V,Object> it) {
3119 <            super(it);
3118 >        EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3119 >            super(map, it, -1);
3120          }
3121          public EntryIterator<K,V> split() {
3122              if (nextKey != null)
3123                  throw new IllegalStateException();
3124 <            return new EntryIterator<K,V>(this);
3124 >            return new EntryIterator<K,V>(map, this);
3125          }
3126  
3127          @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3128 <            Object v;
3128 >            V v;
3129              if ((v = nextVal) == null && (v = advance()) == null)
3130                  throw new NoSuchElementException();
3131              Object k = nextKey;
3132              nextVal = null;
3133 <            return new MapEntry<K,V>((K)k, (V)v, map);
3133 >            return new MapEntry<K,V>((K)k, v, map);
3134          }
3135      }
3136  
# Line 3357 | Line 3177 | public class ConcurrentHashMapV8<K, V>
3177          }
3178      }
3179  
3360    /* ----------------Views -------------- */
3361
3180      /**
3181 <     * Base class for views.
3181 >     * Returns exportable snapshot entry for the given key and value
3182 >     * when write-through can't or shouldn't be used.
3183       */
3184 <    static abstract class CHMView<K, V> {
3185 <        final ConcurrentHashMapV8<K, V> map;
3367 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
3368 <        public final int size()                 { return map.size(); }
3369 <        public final boolean isEmpty()          { return map.isEmpty(); }
3370 <        public final void clear()               { map.clear(); }
3371 <
3372 <        // implementations below rely on concrete classes supplying these
3373 <        abstract public Iterator<?> iterator();
3374 <        abstract public boolean contains(Object o);
3375 <        abstract public boolean remove(Object o);
3376 <
3377 <        private static final String oomeMsg = "Required array size too large";
3378 <
3379 <        public final Object[] toArray() {
3380 <            long sz = map.mappingCount();
3381 <            if (sz > (long)(MAX_ARRAY_SIZE))
3382 <                throw new OutOfMemoryError(oomeMsg);
3383 <            int n = (int)sz;
3384 <            Object[] r = new Object[n];
3385 <            int i = 0;
3386 <            Iterator<?> it = iterator();
3387 <            while (it.hasNext()) {
3388 <                if (i == n) {
3389 <                    if (n >= MAX_ARRAY_SIZE)
3390 <                        throw new OutOfMemoryError(oomeMsg);
3391 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3392 <                        n = MAX_ARRAY_SIZE;
3393 <                    else
3394 <                        n += (n >>> 1) + 1;
3395 <                    r = Arrays.copyOf(r, n);
3396 <                }
3397 <                r[i++] = it.next();
3398 <            }
3399 <            return (i == n) ? r : Arrays.copyOf(r, i);
3400 <        }
3401 <
3402 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
3403 <            long sz = map.mappingCount();
3404 <            if (sz > (long)(MAX_ARRAY_SIZE))
3405 <                throw new OutOfMemoryError(oomeMsg);
3406 <            int m = (int)sz;
3407 <            T[] r = (a.length >= m) ? a :
3408 <                (T[])java.lang.reflect.Array
3409 <                .newInstance(a.getClass().getComponentType(), m);
3410 <            int n = r.length;
3411 <            int i = 0;
3412 <            Iterator<?> it = iterator();
3413 <            while (it.hasNext()) {
3414 <                if (i == n) {
3415 <                    if (n >= MAX_ARRAY_SIZE)
3416 <                        throw new OutOfMemoryError(oomeMsg);
3417 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3418 <                        n = MAX_ARRAY_SIZE;
3419 <                    else
3420 <                        n += (n >>> 1) + 1;
3421 <                    r = Arrays.copyOf(r, n);
3422 <                }
3423 <                r[i++] = (T)it.next();
3424 <            }
3425 <            if (a == r && i < n) {
3426 <                r[i] = null; // null-terminate
3427 <                return r;
3428 <            }
3429 <            return (i == n) ? r : Arrays.copyOf(r, i);
3430 <        }
3431 <
3432 <        public final int hashCode() {
3433 <            int h = 0;
3434 <            for (Iterator<?> it = iterator(); it.hasNext();)
3435 <                h += it.next().hashCode();
3436 <            return h;
3437 <        }
3438 <
3439 <        public final String toString() {
3440 <            StringBuilder sb = new StringBuilder();
3441 <            sb.append('[');
3442 <            Iterator<?> it = iterator();
3443 <            if (it.hasNext()) {
3444 <                for (;;) {
3445 <                    Object e = it.next();
3446 <                    sb.append(e == this ? "(this Collection)" : e);
3447 <                    if (!it.hasNext())
3448 <                        break;
3449 <                    sb.append(',').append(' ');
3450 <                }
3451 <            }
3452 <            return sb.append(']').toString();
3453 <        }
3454 <
3455 <        public final boolean containsAll(Collection<?> c) {
3456 <            if (c != this) {
3457 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3458 <                    Object e = it.next();
3459 <                    if (e == null || !contains(e))
3460 <                        return false;
3461 <                }
3462 <            }
3463 <            return true;
3464 <        }
3465 <
3466 <        public final boolean removeAll(Collection<?> c) {
3467 <            boolean modified = false;
3468 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3469 <                if (c.contains(it.next())) {
3470 <                    it.remove();
3471 <                    modified = true;
3472 <                }
3473 <            }
3474 <            return modified;
3475 <        }
3476 <
3477 <        public final boolean retainAll(Collection<?> c) {
3478 <            boolean modified = false;
3479 <            for (Iterator<?> it = iterator(); it.hasNext();) {
3480 <                if (!c.contains(it.next())) {
3481 <                    it.remove();
3482 <                    modified = true;
3483 <                }
3484 <            }
3485 <            return modified;
3486 <        }
3487 <
3488 <    }
3489 <
3490 <    static final class Values<K,V> extends CHMView<K,V>
3491 <        implements Collection<V> {
3492 <        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
3493 <        public final boolean contains(Object o) { return map.containsValue(o); }
3494 <        public final boolean remove(Object o) {
3495 <            if (o != null) {
3496 <                Iterator<V> it = new ValueIterator<K,V>(map);
3497 <                while (it.hasNext()) {
3498 <                    if (o.equals(it.next())) {
3499 <                        it.remove();
3500 <                        return true;
3501 <                    }
3502 <                }
3503 <            }
3504 <            return false;
3505 <        }
3506 <        public final Iterator<V> iterator() {
3507 <            return new ValueIterator<K,V>(map);
3508 <        }
3509 <        public final boolean add(V e) {
3510 <            throw new UnsupportedOperationException();
3511 <        }
3512 <        public final boolean addAll(Collection<? extends V> c) {
3513 <            throw new UnsupportedOperationException();
3514 <        }
3515 <
3516 <    }
3517 <
3518 <    static final class EntrySet<K,V> extends CHMView<K,V>
3519 <        implements Set<Map.Entry<K,V>> {
3520 <        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
3521 <        public final boolean contains(Object o) {
3522 <            Object k, v, r; Map.Entry<?,?> e;
3523 <            return ((o instanceof Map.Entry) &&
3524 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3525 <                    (r = map.get(k)) != null &&
3526 <                    (v = e.getValue()) != null &&
3527 <                    (v == r || v.equals(r)));
3528 <        }
3529 <        public final boolean remove(Object o) {
3530 <            Object k, v; Map.Entry<?,?> e;
3531 <            return ((o instanceof Map.Entry) &&
3532 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3533 <                    (v = e.getValue()) != null &&
3534 <                    map.remove(k, v));
3535 <        }
3536 <        public final Iterator<Map.Entry<K,V>> iterator() {
3537 <            return new EntryIterator<K,V>(map);
3538 <        }
3539 <        public final boolean add(Entry<K,V> e) {
3540 <            throw new UnsupportedOperationException();
3541 <        }
3542 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3543 <            throw new UnsupportedOperationException();
3544 <        }
3545 <        public boolean equals(Object o) {
3546 <            Set<?> c;
3547 <            return ((o instanceof Set) &&
3548 <                    ((c = (Set<?>)o) == this ||
3549 <                     (containsAll(c) && c.containsAll(this))));
3550 <        }
3184 >    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3185 >        return new AbstractMap.SimpleEntry<K,V>(k, v);
3186      }
3187  
3188      /* ---------------- Serialization Support -------------- */
# Line 3571 | Line 3206 | public class ConcurrentHashMapV8<K, V>
3206       * for each key-value mapping, followed by a null pair.
3207       * The key-value mappings are emitted in no particular order.
3208       */
3209 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3209 >    @SuppressWarnings("unchecked") private void writeObject
3210 >        (java.io.ObjectOutputStream s)
3211          throws java.io.IOException {
3212          if (segments == null) { // for serialization compatibility
3213              segments = (Segment<K,V>[])
# Line 3581 | Line 3217 | public class ConcurrentHashMapV8<K, V>
3217          }
3218          s.defaultWriteObject();
3219          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3220 <        Object v;
3220 >        V v;
3221          while ((v = it.advance()) != null) {
3222              s.writeObject(it.nextKey);
3223              s.writeObject(v);
# Line 3595 | Line 3231 | public class ConcurrentHashMapV8<K, V>
3231       * Reconstitutes the instance from a stream (that is, deserializes it).
3232       * @param s the stream
3233       */
3234 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3234 >    @SuppressWarnings("unchecked") private void readObject
3235 >        (java.io.ObjectInputStream s)
3236          throws java.io.IOException, ClassNotFoundException {
3237          s.defaultReadObject();
3238          this.segments = null; // unneeded
3602        // initialize transient final field
3603        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3239  
3240          // Create all nodes, then place in table once size is known
3241          long size = 0L;
3242 <        Node p = null;
3242 >        Node<V> p = null;
3243          for (;;) {
3244              K k = (K) s.readObject();
3245              V v = (V) s.readObject();
3246              if (k != null && v != null) {
3247                  int h = spread(k.hashCode());
3248 <                p = new Node(h, k, v, p);
3248 >                p = new Node<V>(h, k, v, p);
3249                  ++size;
3250              }
3251              else
# Line 3628 | Line 3263 | public class ConcurrentHashMapV8<K, V>
3263              int sc = sizeCtl;
3264              boolean collide = false;
3265              if (n > sc &&
3266 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3266 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3267                  try {
3268                      if (table == null) {
3269                          init = true;
3270 <                        Node[] tab = new Node[n];
3270 >                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3271 >                        Node<V>[] tab = (Node<V>[])rt;
3272                          int mask = n - 1;
3273                          while (p != null) {
3274                              int j = p.hash & mask;
3275 <                            Node next = p.next;
3276 <                            Node q = p.next = tabAt(tab, j);
3275 >                            Node<V> next = p.next;
3276 >                            Node<V> q = p.next = tabAt(tab, j);
3277                              setTabAt(tab, j, p);
3278                              if (!collide && q != null && q.hash == p.hash)
3279                                  collide = true;
3280                              p = next;
3281                          }
3282                          table = tab;
3283 <                        counter.add(size);
3283 >                        addCount(size, -1);
3284                          sc = n - (n >>> 2);
3285                      }
3286                  } finally {
3287                      sizeCtl = sc;
3288                  }
3289                  if (collide) { // rescan and convert to TreeBins
3290 <                    Node[] tab = table;
3290 >                    Node<V>[] tab = table;
3291                      for (int i = 0; i < tab.length; ++i) {
3292                          int c = 0;
3293 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3293 >                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3294                              if (++c > TREE_THRESHOLD &&
3295                                  (e.key instanceof Comparable)) {
3296                                  replaceWithTreeBin(tab, i, e.key);
# Line 3666 | Line 3302 | public class ConcurrentHashMapV8<K, V>
3302              }
3303              if (!init) { // Can only happen if unsafely published.
3304                  while (p != null) {
3305 <                    internalPut(p.key, p.val);
3305 >                    internalPut((K)p.key, p.val, false);
3306                      p = p.next;
3307                  }
3308              }
3309          }
3310      }
3311  
3676
3312      // -------------------------------------------------------
3313  
3314      // Sams
# Line 3715 | Line 3350 | public class ConcurrentHashMapV8<K, V>
3350  
3351      // -------------------------------------------------------
3352  
3353 +    // Sequential bulk operations
3354 +
3355 +    /**
3356 +     * Performs the given action for each (key, value).
3357 +     *
3358 +     * @param action the action
3359 +     */
3360 +    @SuppressWarnings("unchecked") public void forEachSequentially
3361 +        (BiAction<K,V> action) {
3362 +        if (action == null) throw new NullPointerException();
3363 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3364 +        V v;
3365 +        while ((v = it.advance()) != null)
3366 +            action.apply((K)it.nextKey, v);
3367 +    }
3368 +
3369 +    /**
3370 +     * Performs the given action for each non-null transformation
3371 +     * of each (key, value).
3372 +     *
3373 +     * @param transformer a function returning the transformation
3374 +     * for an element, or null of there is no transformation (in
3375 +     * which case the action is not applied).
3376 +     * @param action the action
3377 +     */
3378 +    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3379 +        (BiFun<? super K, ? super V, ? extends U> transformer,
3380 +         Action<U> action) {
3381 +        if (transformer == null || action == null)
3382 +            throw new NullPointerException();
3383 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3384 +        V v; U u;
3385 +        while ((v = it.advance()) != null) {
3386 +            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3387 +                action.apply(u);
3388 +        }
3389 +    }
3390 +
3391 +    /**
3392 +     * Returns a non-null result from applying the given search
3393 +     * function on each (key, value), or null if none.
3394 +     *
3395 +     * @param searchFunction a function returning a non-null
3396 +     * result on success, else null
3397 +     * @return a non-null result from applying the given search
3398 +     * function on each (key, value), or null if none
3399 +     */
3400 +    @SuppressWarnings("unchecked") public <U> U searchSequentially
3401 +        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3402 +        if (searchFunction == null) throw new NullPointerException();
3403 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3404 +        V v; U u;
3405 +        while ((v = it.advance()) != null) {
3406 +            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3407 +                return u;
3408 +        }
3409 +        return null;
3410 +    }
3411 +
3412 +    /**
3413 +     * Returns the result of accumulating the given transformation
3414 +     * of all (key, value) pairs using the given reducer to
3415 +     * combine values, or null if none.
3416 +     *
3417 +     * @param transformer a function returning the transformation
3418 +     * for an element, or null of there is no transformation (in
3419 +     * which case it is not combined).
3420 +     * @param reducer a commutative associative combining function
3421 +     * @return the result of accumulating the given transformation
3422 +     * of all (key, value) pairs
3423 +     */
3424 +    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3425 +        (BiFun<? super K, ? super V, ? extends U> transformer,
3426 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3427 +        if (transformer == null || reducer == null)
3428 +            throw new NullPointerException();
3429 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3430 +        U r = null, u; V v;
3431 +        while ((v = it.advance()) != null) {
3432 +            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3433 +                r = (r == null) ? u : reducer.apply(r, u);
3434 +        }
3435 +        return r;
3436 +    }
3437 +
3438 +    /**
3439 +     * Returns the result of accumulating the given transformation
3440 +     * of all (key, value) pairs using the given reducer to
3441 +     * combine values, and the given basis as an identity value.
3442 +     *
3443 +     * @param transformer a function returning the transformation
3444 +     * for an element
3445 +     * @param basis the identity (initial default value) for the reduction
3446 +     * @param reducer a commutative associative combining function
3447 +     * @return the result of accumulating the given transformation
3448 +     * of all (key, value) pairs
3449 +     */
3450 +    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3451 +        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3452 +         double basis,
3453 +         DoubleByDoubleToDouble reducer) {
3454 +        if (transformer == null || reducer == null)
3455 +            throw new NullPointerException();
3456 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3457 +        double r = basis; V v;
3458 +        while ((v = it.advance()) != null)
3459 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3460 +        return r;
3461 +    }
3462 +
3463 +    /**
3464 +     * Returns the result of accumulating the given transformation
3465 +     * of all (key, value) pairs using the given reducer to
3466 +     * combine values, and the given basis as an identity value.
3467 +     *
3468 +     * @param transformer a function returning the transformation
3469 +     * for an element
3470 +     * @param basis the identity (initial default value) for the reduction
3471 +     * @param reducer a commutative associative combining function
3472 +     * @return the result of accumulating the given transformation
3473 +     * of all (key, value) pairs
3474 +     */
3475 +    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3476 +        (ObjectByObjectToLong<? super K, ? super V> transformer,
3477 +         long basis,
3478 +         LongByLongToLong reducer) {
3479 +        if (transformer == null || reducer == null)
3480 +            throw new NullPointerException();
3481 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3482 +        long r = basis; V v;
3483 +        while ((v = it.advance()) != null)
3484 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3485 +        return r;
3486 +    }
3487 +
3488 +    /**
3489 +     * Returns the result of accumulating the given transformation
3490 +     * of all (key, value) pairs using the given reducer to
3491 +     * combine values, and the given basis as an identity value.
3492 +     *
3493 +     * @param transformer a function returning the transformation
3494 +     * for an element
3495 +     * @param basis the identity (initial default value) for the reduction
3496 +     * @param reducer a commutative associative combining function
3497 +     * @return the result of accumulating the given transformation
3498 +     * of all (key, value) pairs
3499 +     */
3500 +    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3501 +        (ObjectByObjectToInt<? super K, ? super V> transformer,
3502 +         int basis,
3503 +         IntByIntToInt reducer) {
3504 +        if (transformer == null || reducer == null)
3505 +            throw new NullPointerException();
3506 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3507 +        int r = basis; V v;
3508 +        while ((v = it.advance()) != null)
3509 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3510 +        return r;
3511 +    }
3512 +
3513 +    /**
3514 +     * Performs the given action for each key.
3515 +     *
3516 +     * @param action the action
3517 +     */
3518 +    @SuppressWarnings("unchecked") public void forEachKeySequentially
3519 +        (Action<K> action) {
3520 +        if (action == null) throw new NullPointerException();
3521 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3522 +        while (it.advance() != null)
3523 +            action.apply((K)it.nextKey);
3524 +    }
3525 +
3526 +    /**
3527 +     * Performs the given action for each non-null transformation
3528 +     * of each key.
3529 +     *
3530 +     * @param transformer a function returning the transformation
3531 +     * for an element, or null of there is no transformation (in
3532 +     * which case the action is not applied).
3533 +     * @param action the action
3534 +     */
3535 +    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3536 +        (Fun<? super K, ? extends U> transformer,
3537 +         Action<U> action) {
3538 +        if (transformer == null || action == null)
3539 +            throw new NullPointerException();
3540 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3541 +        U u;
3542 +        while (it.advance() != null) {
3543 +            if ((u = transformer.apply((K)it.nextKey)) != null)
3544 +                action.apply(u);
3545 +        }
3546 +        ForkJoinTasks.forEachKey
3547 +            (this, transformer, action).invoke();
3548 +    }
3549 +
3550 +    /**
3551 +     * Returns a non-null result from applying the given search
3552 +     * function on each key, or null if none.
3553 +     *
3554 +     * @param searchFunction a function returning a non-null
3555 +     * result on success, else null
3556 +     * @return a non-null result from applying the given search
3557 +     * function on each key, or null if none
3558 +     */
3559 +    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3560 +        (Fun<? super K, ? extends U> searchFunction) {
3561 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3562 +        U u;
3563 +        while (it.advance() != null) {
3564 +            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3565 +                return u;
3566 +        }
3567 +        return null;
3568 +    }
3569 +
3570 +    /**
3571 +     * Returns the result of accumulating all keys using the given
3572 +     * reducer to combine values, or null if none.
3573 +     *
3574 +     * @param reducer a commutative associative combining function
3575 +     * @return the result of accumulating all keys using the given
3576 +     * reducer to combine values, or null if none
3577 +     */
3578 +    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3579 +        (BiFun<? super K, ? super K, ? extends K> reducer) {
3580 +        if (reducer == null) throw new NullPointerException();
3581 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3582 +        K r = null;
3583 +        while (it.advance() != null) {
3584 +            K u = (K)it.nextKey;
3585 +            r = (r == null) ? u : reducer.apply(r, u);
3586 +        }
3587 +        return r;
3588 +    }
3589 +
3590 +    /**
3591 +     * Returns the result of accumulating the given transformation
3592 +     * of all keys using the given reducer to combine values, or
3593 +     * null if none.
3594 +     *
3595 +     * @param transformer a function returning the transformation
3596 +     * for an element, or null of there is no transformation (in
3597 +     * which case it is not combined).
3598 +     * @param reducer a commutative associative combining function
3599 +     * @return the result of accumulating the given transformation
3600 +     * of all keys
3601 +     */
3602 +    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3603 +        (Fun<? super K, ? extends U> transformer,
3604 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3605 +        if (transformer == null || reducer == null)
3606 +            throw new NullPointerException();
3607 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3608 +        U r = null, u;
3609 +        while (it.advance() != null) {
3610 +            if ((u = transformer.apply((K)it.nextKey)) != null)
3611 +                r = (r == null) ? u : reducer.apply(r, u);
3612 +        }
3613 +        return r;
3614 +    }
3615 +
3616 +    /**
3617 +     * Returns the result of accumulating the given transformation
3618 +     * of all keys using the given reducer to combine values, and
3619 +     * the given basis as an identity value.
3620 +     *
3621 +     * @param transformer a function returning the transformation
3622 +     * for an element
3623 +     * @param basis the identity (initial default value) for the reduction
3624 +     * @param reducer a commutative associative combining function
3625 +     * @return  the result of accumulating the given transformation
3626 +     * of all keys
3627 +     */
3628 +    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3629 +        (ObjectToDouble<? super K> transformer,
3630 +         double basis,
3631 +         DoubleByDoubleToDouble reducer) {
3632 +        if (transformer == null || reducer == null)
3633 +            throw new NullPointerException();
3634 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3635 +        double r = basis;
3636 +        while (it.advance() != null)
3637 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3638 +        return r;
3639 +    }
3640 +
3641 +    /**
3642 +     * Returns the result of accumulating the given transformation
3643 +     * of all keys using the given reducer to combine values, and
3644 +     * the given basis as an identity value.
3645 +     *
3646 +     * @param transformer a function returning the transformation
3647 +     * for an element
3648 +     * @param basis the identity (initial default value) for the reduction
3649 +     * @param reducer a commutative associative combining function
3650 +     * @return the result of accumulating the given transformation
3651 +     * of all keys
3652 +     */
3653 +    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3654 +        (ObjectToLong<? super K> transformer,
3655 +         long basis,
3656 +         LongByLongToLong reducer) {
3657 +        if (transformer == null || reducer == null)
3658 +            throw new NullPointerException();
3659 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3660 +        long r = basis;
3661 +        while (it.advance() != null)
3662 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3663 +        return r;
3664 +    }
3665 +
3666 +    /**
3667 +     * Returns the result of accumulating the given transformation
3668 +     * of all keys using the given reducer to combine values, and
3669 +     * the given basis as an identity value.
3670 +     *
3671 +     * @param transformer a function returning the transformation
3672 +     * for an element
3673 +     * @param basis the identity (initial default value) for the reduction
3674 +     * @param reducer a commutative associative combining function
3675 +     * @return the result of accumulating the given transformation
3676 +     * of all keys
3677 +     */
3678 +    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3679 +        (ObjectToInt<? super K> transformer,
3680 +         int basis,
3681 +         IntByIntToInt reducer) {
3682 +        if (transformer == null || reducer == null)
3683 +            throw new NullPointerException();
3684 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3685 +        int r = basis;
3686 +        while (it.advance() != null)
3687 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3688 +        return r;
3689 +    }
3690 +
3691 +    /**
3692 +     * Performs the given action for each value.
3693 +     *
3694 +     * @param action the action
3695 +     */
3696 +    public void forEachValueSequentially(Action<V> action) {
3697 +        if (action == null) throw new NullPointerException();
3698 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3699 +        V v;
3700 +        while ((v = it.advance()) != null)
3701 +            action.apply(v);
3702 +    }
3703 +
3704 +    /**
3705 +     * Performs the given action for each non-null transformation
3706 +     * of each value.
3707 +     *
3708 +     * @param transformer a function returning the transformation
3709 +     * for an element, or null of there is no transformation (in
3710 +     * which case the action is not applied).
3711 +     */
3712 +    public <U> void forEachValueSequentially
3713 +        (Fun<? super V, ? extends U> transformer,
3714 +         Action<U> action) {
3715 +        if (transformer == null || action == null)
3716 +            throw new NullPointerException();
3717 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3718 +        V v; U u;
3719 +        while ((v = it.advance()) != null) {
3720 +            if ((u = transformer.apply(v)) != null)
3721 +                action.apply(u);
3722 +        }
3723 +    }
3724 +
3725 +    /**
3726 +     * Returns a non-null result from applying the given search
3727 +     * function on each value, or null if none.
3728 +     *
3729 +     * @param searchFunction a function returning a non-null
3730 +     * result on success, else null
3731 +     * @return a non-null result from applying the given search
3732 +     * function on each value, or null if none
3733 +     *
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 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 of 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 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 of 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 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 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 +     * 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 of 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 forEach(BiAction<K,V> action) {
4049 >    public void forEachInParallel(BiAction<K,V> action) {
4050          ForkJoinTasks.forEach
4051              (this, action).invoke();
4052      }
# Line 3734 | Line 4060 | public class ConcurrentHashMapV8<K, V>
4060       * which case the action is not applied).
4061       * @param action the action
4062       */
4063 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
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();
# Line 3752 | Line 4079 | public class ConcurrentHashMapV8<K, V>
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 search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
4082 >    public <U> U searchInParallel
4083 >        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4084          return ForkJoinTasks.search
4085              (this, searchFunction).invoke();
4086      }
# Line 3769 | Line 4097 | public class ConcurrentHashMapV8<K, V>
4097       * @return the result of accumulating the given transformation
4098       * of all (key, value) pairs
4099       */
4100 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
4101 <                        BiFun<? super U, ? super U, ? extends U> reducer) {
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      }
# Line 3787 | Line 4116 | public class ConcurrentHashMapV8<K, V>
4116       * @return the result of accumulating the given transformation
4117       * of all (key, value) pairs
4118       */
4119 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
4120 <                                 double basis,
4121 <                                 DoubleByDoubleToDouble reducer) {
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      }
# Line 3806 | Line 4136 | public class ConcurrentHashMapV8<K, V>
4136       * @return the result of accumulating the given transformation
4137       * of all (key, value) pairs
4138       */
4139 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
4140 <                             long basis,
4141 <                             LongByLongToLong reducer) {
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      }
# Line 3825 | Line 4156 | public class ConcurrentHashMapV8<K, V>
4156       * @return the result of accumulating the given transformation
4157       * of all (key, value) pairs
4158       */
4159 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
4160 <                           int basis,
4161 <                           IntByIntToInt reducer) {
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      }
# Line 3837 | Line 4169 | public class ConcurrentHashMapV8<K, V>
4169       *
4170       * @param action the action
4171       */
4172 <    public void forEachKey(Action<K> action) {
4172 >    public void forEachKeyInParallel(Action<K> action) {
4173          ForkJoinTasks.forEachKey
4174              (this, action).invoke();
4175      }
# Line 3851 | Line 4183 | public class ConcurrentHashMapV8<K, V>
4183       * which case the action is not applied).
4184       * @param action the action
4185       */
4186 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
4187 <                               Action<U> action) {
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      }
# Line 3869 | Line 4202 | public class ConcurrentHashMapV8<K, V>
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 searchKeys(Fun<? super K, ? extends U> searchFunction) {
4205 >    public <U> U searchKeysInParallel
4206 >        (Fun<? super K, ? extends U> searchFunction) {
4207          return ForkJoinTasks.searchKeys
4208              (this, searchFunction).invoke();
4209      }
# Line 3882 | Line 4216 | public class ConcurrentHashMapV8<K, V>
4216       * @return the result of accumulating all keys using the given
4217       * reducer to combine values, or null if none
4218       */
4219 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
4219 >    public K reduceKeysInParallel
4220 >        (BiFun<? super K, ? super K, ? extends K> reducer) {
4221          return ForkJoinTasks.reduceKeys
4222              (this, reducer).invoke();
4223      }
# Line 3899 | Line 4234 | public class ConcurrentHashMapV8<K, V>
4234       * @return the result of accumulating the given transformation
4235       * of all keys
4236       */
4237 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
4238 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
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      }
# Line 3917 | Line 4253 | public class ConcurrentHashMapV8<K, V>
4253       * @return  the result of accumulating the given transformation
4254       * of all keys
4255       */
4256 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
4257 <                                     double basis,
4258 <                                     DoubleByDoubleToDouble reducer) {
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      }
# Line 3936 | Line 4273 | public class ConcurrentHashMapV8<K, V>
4273       * @return the result of accumulating the given transformation
4274       * of all keys
4275       */
4276 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
4277 <                                 long basis,
4278 <                                 LongByLongToLong reducer) {
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      }
# Line 3955 | Line 4293 | public class ConcurrentHashMapV8<K, V>
4293       * @return the result of accumulating the given transformation
4294       * of all keys
4295       */
4296 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
4297 <                               int basis,
4298 <                               IntByIntToInt reducer) {
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      }
# Line 3967 | Line 4306 | public class ConcurrentHashMapV8<K, V>
4306       *
4307       * @param action the action
4308       */
4309 <    public void forEachValue(Action<V> action) {
4309 >    public void forEachValueInParallel(Action<V> action) {
4310          ForkJoinTasks.forEachValue
4311              (this, action).invoke();
4312      }
# Line 3980 | Line 4319 | public class ConcurrentHashMapV8<K, V>
4319       * for an element, or null of there is no transformation (in
4320       * which case the action is not applied).
4321       */
4322 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
4323 <                                 Action<U> action) {
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      }
# Line 3999 | Line 4339 | public class ConcurrentHashMapV8<K, V>
4339       * function on each value, or null if none
4340       *
4341       */
4342 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4342 >    public <U> U searchValuesInParallel
4343 >        (Fun<? super V, ? extends U> searchFunction) {
4344          return ForkJoinTasks.searchValues
4345              (this, searchFunction).invoke();
4346      }
# Line 4011 | Line 4352 | public class ConcurrentHashMapV8<K, V>
4352       * @param reducer a commutative associative combining function
4353       * @return  the result of accumulating all values
4354       */
4355 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4355 >    public V reduceValuesInParallel
4356 >        (BiFun<? super V, ? super V, ? extends V> reducer) {
4357          return ForkJoinTasks.reduceValues
4358              (this, reducer).invoke();
4359      }
# Line 4028 | Line 4370 | public class ConcurrentHashMapV8<K, V>
4370       * @return the result of accumulating the given transformation
4371       * of all values
4372       */
4373 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4374 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4373 >    public <U> U reduceValuesInParallel
4374 >        (Fun<? super V, ? extends U> transformer,
4375 >         BiFun<? super U, ? super U, ? extends U> reducer) {
4376          return ForkJoinTasks.reduceValues
4377              (this, transformer, reducer).invoke();
4378      }
# Line 4046 | Line 4389 | public class ConcurrentHashMapV8<K, V>
4389       * @return the result of accumulating the given transformation
4390       * of all values
4391       */
4392 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4393 <                                       double basis,
4394 <                                       DoubleByDoubleToDouble reducer) {
4392 >    public double reduceValuesToDoubleInParallel
4393 >        (ObjectToDouble<? super V> transformer,
4394 >         double basis,
4395 >         DoubleByDoubleToDouble reducer) {
4396          return ForkJoinTasks.reduceValuesToDouble
4397              (this, transformer, basis, reducer).invoke();
4398      }
# Line 4065 | Line 4409 | public class ConcurrentHashMapV8<K, V>
4409       * @return the result of accumulating the given transformation
4410       * of all values
4411       */
4412 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4413 <                                   long basis,
4414 <                                   LongByLongToLong reducer) {
4412 >    public long reduceValuesToLongInParallel
4413 >        (ObjectToLong<? super V> transformer,
4414 >         long basis,
4415 >         LongByLongToLong reducer) {
4416          return ForkJoinTasks.reduceValuesToLong
4417              (this, transformer, basis, reducer).invoke();
4418      }
# Line 4084 | Line 4429 | public class ConcurrentHashMapV8<K, V>
4429       * @return the result of accumulating the given transformation
4430       * of all values
4431       */
4432 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4433 <                                 int basis,
4434 <                                 IntByIntToInt reducer) {
4432 >    public int reduceValuesToIntInParallel
4433 >        (ObjectToInt<? super V> transformer,
4434 >         int basis,
4435 >         IntByIntToInt reducer) {
4436          return ForkJoinTasks.reduceValuesToInt
4437              (this, transformer, basis, reducer).invoke();
4438      }
# Line 4096 | Line 4442 | public class ConcurrentHashMapV8<K, V>
4442       *
4443       * @param action the action
4444       */
4445 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4445 >    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4446          ForkJoinTasks.forEachEntry
4447              (this, action).invoke();
4448      }
# Line 4110 | Line 4456 | public class ConcurrentHashMapV8<K, V>
4456       * which case the action is not applied).
4457       * @param action the action
4458       */
4459 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4460 <                                 Action<U> action) {
4459 >    public <U> void forEachEntryInParallel
4460 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4461 >         Action<U> action) {
4462          ForkJoinTasks.forEachEntry
4463              (this, transformer, action).invoke();
4464      }
# Line 4128 | Line 4475 | public class ConcurrentHashMapV8<K, V>
4475       * @return a non-null result from applying the given search
4476       * function on each entry, or null if none
4477       */
4478 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4478 >    public <U> U searchEntriesInParallel
4479 >        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4480          return ForkJoinTasks.searchEntries
4481              (this, searchFunction).invoke();
4482      }
# Line 4140 | Line 4488 | public class ConcurrentHashMapV8<K, V>
4488       * @param reducer a commutative associative combining function
4489       * @return the result of accumulating all entries
4490       */
4491 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4491 >    public Map.Entry<K,V> reduceEntriesInParallel
4492 >        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4493          return ForkJoinTasks.reduceEntries
4494              (this, reducer).invoke();
4495      }
# Line 4157 | Line 4506 | public class ConcurrentHashMapV8<K, V>
4506       * @return the result of accumulating the given transformation
4507       * of all entries
4508       */
4509 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4510 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4509 >    public <U> U reduceEntriesInParallel
4510 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4511 >         BiFun<? super U, ? super U, ? extends U> reducer) {
4512          return ForkJoinTasks.reduceEntries
4513              (this, transformer, reducer).invoke();
4514      }
# Line 4175 | Line 4525 | public class ConcurrentHashMapV8<K, V>
4525       * @return the result of accumulating the given transformation
4526       * of all entries
4527       */
4528 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4529 <                                        double basis,
4530 <                                        DoubleByDoubleToDouble reducer) {
4528 >    public double reduceEntriesToDoubleInParallel
4529 >        (ObjectToDouble<Map.Entry<K,V>> transformer,
4530 >         double basis,
4531 >         DoubleByDoubleToDouble reducer) {
4532          return ForkJoinTasks.reduceEntriesToDouble
4533              (this, transformer, basis, reducer).invoke();
4534      }
# Line 4194 | Line 4545 | public class ConcurrentHashMapV8<K, V>
4545       * @return  the result of accumulating the given transformation
4546       * of all entries
4547       */
4548 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4549 <                                    long basis,
4550 <                                    LongByLongToLong reducer) {
4548 >    public long reduceEntriesToLongInParallel
4549 >        (ObjectToLong<Map.Entry<K,V>> transformer,
4550 >         long basis,
4551 >         LongByLongToLong reducer) {
4552          return ForkJoinTasks.reduceEntriesToLong
4553              (this, transformer, basis, reducer).invoke();
4554      }
# Line 4213 | Line 4565 | public class ConcurrentHashMapV8<K, V>
4565       * @return the result of accumulating the given transformation
4566       * of all entries
4567       */
4568 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4569 <                                  int basis,
4570 <                                  IntByIntToInt reducer) {
4568 >    public int reduceEntriesToIntInParallel
4569 >        (ObjectToInt<Map.Entry<K,V>> transformer,
4570 >         int basis,
4571 >         IntByIntToInt reducer) {
4572          return ForkJoinTasks.reduceEntriesToInt
4573              (this, transformer, basis, reducer).invoke();
4574      }
4575  
4576 +
4577 +    /* ----------------Views -------------- */
4578 +
4579 +    /**
4580 +     * Base class for views.
4581 +     */
4582 +    static abstract class CHMView<K, V> {
4583 +        final ConcurrentHashMapV8<K, V> map;
4584 +        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4585 +
4586 +        /**
4587 +         * Returns the map backing this view.
4588 +         *
4589 +         * @return the map backing this view
4590 +         */
4591 +        public ConcurrentHashMapV8<K,V> getMap() { return map; }
4592 +
4593 +        public final int size()                 { return map.size(); }
4594 +        public final boolean isEmpty()          { return map.isEmpty(); }
4595 +        public final void clear()               { map.clear(); }
4596 +
4597 +        // implementations below rely on concrete classes supplying these
4598 +        abstract public Iterator<?> iterator();
4599 +        abstract public boolean contains(Object o);
4600 +        abstract public boolean remove(Object o);
4601 +
4602 +        private static final String oomeMsg = "Required array size too large";
4603 +
4604 +        public final Object[] toArray() {
4605 +            long sz = map.mappingCount();
4606 +            if (sz > (long)(MAX_ARRAY_SIZE))
4607 +                throw new OutOfMemoryError(oomeMsg);
4608 +            int n = (int)sz;
4609 +            Object[] r = new Object[n];
4610 +            int i = 0;
4611 +            Iterator<?> it = iterator();
4612 +            while (it.hasNext()) {
4613 +                if (i == n) {
4614 +                    if (n >= MAX_ARRAY_SIZE)
4615 +                        throw new OutOfMemoryError(oomeMsg);
4616 +                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4617 +                        n = MAX_ARRAY_SIZE;
4618 +                    else
4619 +                        n += (n >>> 1) + 1;
4620 +                    r = Arrays.copyOf(r, n);
4621 +                }
4622 +                r[i++] = it.next();
4623 +            }
4624 +            return (i == n) ? r : Arrays.copyOf(r, i);
4625 +        }
4626 +
4627 +        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4628 +            long sz = map.mappingCount();
4629 +            if (sz > (long)(MAX_ARRAY_SIZE))
4630 +                throw new OutOfMemoryError(oomeMsg);
4631 +            int m = (int)sz;
4632 +            T[] r = (a.length >= m) ? a :
4633 +                (T[])java.lang.reflect.Array
4634 +                .newInstance(a.getClass().getComponentType(), m);
4635 +            int n = r.length;
4636 +            int i = 0;
4637 +            Iterator<?> it = iterator();
4638 +            while (it.hasNext()) {
4639 +                if (i == n) {
4640 +                    if (n >= MAX_ARRAY_SIZE)
4641 +                        throw new OutOfMemoryError(oomeMsg);
4642 +                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4643 +                        n = MAX_ARRAY_SIZE;
4644 +                    else
4645 +                        n += (n >>> 1) + 1;
4646 +                    r = Arrays.copyOf(r, n);
4647 +                }
4648 +                r[i++] = (T)it.next();
4649 +            }
4650 +            if (a == r && i < n) {
4651 +                r[i] = null; // null-terminate
4652 +                return r;
4653 +            }
4654 +            return (i == n) ? r : Arrays.copyOf(r, i);
4655 +        }
4656 +
4657 +        public final int hashCode() {
4658 +            int h = 0;
4659 +            for (Iterator<?> it = iterator(); it.hasNext();)
4660 +                h += it.next().hashCode();
4661 +            return h;
4662 +        }
4663 +
4664 +        public final String toString() {
4665 +            StringBuilder sb = new StringBuilder();
4666 +            sb.append('[');
4667 +            Iterator<?> it = iterator();
4668 +            if (it.hasNext()) {
4669 +                for (;;) {
4670 +                    Object e = it.next();
4671 +                    sb.append(e == this ? "(this Collection)" : e);
4672 +                    if (!it.hasNext())
4673 +                        break;
4674 +                    sb.append(',').append(' ');
4675 +                }
4676 +            }
4677 +            return sb.append(']').toString();
4678 +        }
4679 +
4680 +        public final boolean containsAll(Collection<?> c) {
4681 +            if (c != this) {
4682 +                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4683 +                    Object e = it.next();
4684 +                    if (e == null || !contains(e))
4685 +                        return false;
4686 +                }
4687 +            }
4688 +            return true;
4689 +        }
4690 +
4691 +        public final boolean removeAll(Collection<?> c) {
4692 +            boolean modified = false;
4693 +            for (Iterator<?> it = iterator(); it.hasNext();) {
4694 +                if (c.contains(it.next())) {
4695 +                    it.remove();
4696 +                    modified = true;
4697 +                }
4698 +            }
4699 +            return modified;
4700 +        }
4701 +
4702 +        public final boolean retainAll(Collection<?> c) {
4703 +            boolean modified = false;
4704 +            for (Iterator<?> it = iterator(); it.hasNext();) {
4705 +                if (!c.contains(it.next())) {
4706 +                    it.remove();
4707 +                    modified = true;
4708 +                }
4709 +            }
4710 +            return modified;
4711 +        }
4712 +
4713 +    }
4714 +
4715 +    /**
4716 +     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4717 +     * which additions may optionally be enabled by mapping to a
4718 +     * common value.  This class cannot be directly instantiated. See
4719 +     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4720 +     * {@link #newKeySet(int)}.
4721 +     */
4722 +    public static class KeySetView<K,V> extends CHMView<K,V>
4723 +        implements Set<K>, java.io.Serializable {
4724 +        private static final long serialVersionUID = 7249069246763182397L;
4725 +        private final V value;
4726 +        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4727 +            super(map);
4728 +            this.value = value;
4729 +        }
4730 +
4731 +        /**
4732 +         * Returns the default mapped value for additions,
4733 +         * or {@code null} if additions are not supported.
4734 +         *
4735 +         * @return the default mapped value for additions, or {@code null}
4736 +         * if not supported.
4737 +         */
4738 +        public V getMappedValue() { return value; }
4739 +
4740 +        // implement Set API
4741 +
4742 +        public boolean contains(Object o) { return map.containsKey(o); }
4743 +        public boolean remove(Object o)   { return map.remove(o) != null; }
4744 +
4745 +        /**
4746 +         * Returns a "weakly consistent" iterator that will never
4747 +         * throw {@link ConcurrentModificationException}, and
4748 +         * guarantees to traverse elements as they existed upon
4749 +         * construction of the iterator, and may (but is not
4750 +         * guaranteed to) reflect any modifications subsequent to
4751 +         * construction.
4752 +         *
4753 +         * @return an iterator over the keys of this map
4754 +         */
4755 +        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4756 +        public boolean add(K e) {
4757 +            V v;
4758 +            if ((v = value) == null)
4759 +                throw new UnsupportedOperationException();
4760 +            if (e == null)
4761 +                throw new NullPointerException();
4762 +            return map.internalPut(e, v, true) == null;
4763 +        }
4764 +        public boolean addAll(Collection<? extends K> c) {
4765 +            boolean added = false;
4766 +            V v;
4767 +            if ((v = value) == null)
4768 +                throw new UnsupportedOperationException();
4769 +            for (K e : c) {
4770 +                if (e == null)
4771 +                    throw new NullPointerException();
4772 +                if (map.internalPut(e, v, true) == null)
4773 +                    added = true;
4774 +            }
4775 +            return added;
4776 +        }
4777 +        public boolean equals(Object o) {
4778 +            Set<?> c;
4779 +            return ((o instanceof Set) &&
4780 +                    ((c = (Set<?>)o) == this ||
4781 +                     (containsAll(c) && c.containsAll(this))));
4782 +        }
4783 +    }
4784 +
4785 +    /**
4786 +     * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4787 +     * values, in which additions are disabled. This class cannot be
4788 +     * directly instantiated. See {@link #values},
4789 +     *
4790 +     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4791 +     * that will never throw {@link ConcurrentModificationException},
4792 +     * and guarantees to traverse elements as they existed upon
4793 +     * construction of the iterator, and may (but is not guaranteed to)
4794 +     * reflect any modifications subsequent to construction.
4795 +     */
4796 +    public static final class ValuesView<K,V> extends CHMView<K,V>
4797 +        implements Collection<V> {
4798 +        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4799 +        public final boolean contains(Object o) { return map.containsValue(o); }
4800 +        public final boolean remove(Object o) {
4801 +            if (o != null) {
4802 +                Iterator<V> it = new ValueIterator<K,V>(map);
4803 +                while (it.hasNext()) {
4804 +                    if (o.equals(it.next())) {
4805 +                        it.remove();
4806 +                        return true;
4807 +                    }
4808 +                }
4809 +            }
4810 +            return false;
4811 +        }
4812 +
4813 +        /**
4814 +         * Returns a "weakly consistent" iterator that will never
4815 +         * throw {@link ConcurrentModificationException}, and
4816 +         * guarantees to traverse elements as they existed upon
4817 +         * construction of the iterator, and may (but is not
4818 +         * guaranteed to) reflect any modifications subsequent to
4819 +         * construction.
4820 +         *
4821 +         * @return an iterator over the values of this map
4822 +         */
4823 +        public final Iterator<V> iterator() {
4824 +            return new ValueIterator<K,V>(map);
4825 +        }
4826 +        public final boolean add(V e) {
4827 +            throw new UnsupportedOperationException();
4828 +        }
4829 +        public final boolean addAll(Collection<? extends V> c) {
4830 +            throw new UnsupportedOperationException();
4831 +        }
4832 +
4833 +    }
4834 +
4835 +    /**
4836 +     * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4837 +     * entries.  This class cannot be directly instantiated. See
4838 +     * {@link #entrySet}.
4839 +     */
4840 +    public static final class EntrySetView<K,V> extends CHMView<K,V>
4841 +        implements Set<Map.Entry<K,V>> {
4842 +        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4843 +        public final boolean contains(Object o) {
4844 +            Object k, v, r; Map.Entry<?,?> e;
4845 +            return ((o instanceof Map.Entry) &&
4846 +                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4847 +                    (r = map.get(k)) != null &&
4848 +                    (v = e.getValue()) != null &&
4849 +                    (v == r || v.equals(r)));
4850 +        }
4851 +        public final boolean remove(Object o) {
4852 +            Object k, v; Map.Entry<?,?> e;
4853 +            return ((o instanceof Map.Entry) &&
4854 +                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4855 +                    (v = e.getValue()) != null &&
4856 +                    map.remove(k, v));
4857 +        }
4858 +
4859 +        /**
4860 +         * Returns a "weakly consistent" iterator that will never
4861 +         * throw {@link ConcurrentModificationException}, and
4862 +         * guarantees to traverse elements as they existed upon
4863 +         * construction of the iterator, and may (but is not
4864 +         * guaranteed to) reflect any modifications subsequent to
4865 +         * construction.
4866 +         *
4867 +         * @return an iterator over the entries of this map
4868 +         */
4869 +        public final Iterator<Map.Entry<K,V>> iterator() {
4870 +            return new EntryIterator<K,V>(map);
4871 +        }
4872 +
4873 +        public final boolean add(Entry<K,V> e) {
4874 +            K key = e.getKey();
4875 +            V value = e.getValue();
4876 +            if (key == null || value == null)
4877 +                throw new NullPointerException();
4878 +            return map.internalPut(key, value, false) == null;
4879 +        }
4880 +        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4881 +            boolean added = false;
4882 +            for (Entry<K,V> e : c) {
4883 +                if (add(e))
4884 +                    added = true;
4885 +            }
4886 +            return added;
4887 +        }
4888 +        public boolean equals(Object o) {
4889 +            Set<?> c;
4890 +            return ((o instanceof Set) &&
4891 +                    ((c = (Set<?>)o) == this ||
4892 +                     (containsAll(c) && c.containsAll(this))));
4893 +        }
4894 +    }
4895 +
4896      // ---------------------------------------------------------------------
4897  
4898      /**
# Line 4246 | Line 4919 | public class ConcurrentHashMapV8<K, V>
4919              (ConcurrentHashMapV8<K,V> map,
4920               BiAction<K,V> action) {
4921              if (action == null) throw new NullPointerException();
4922 <            return new ForEachMappingTask<K,V>(map, null, -1, null, action);
4922 >            return new ForEachMappingTask<K,V>(map, null, -1, action);
4923          }
4924  
4925          /**
# Line 4267 | Line 4940 | public class ConcurrentHashMapV8<K, V>
4940              if (transformer == null || action == null)
4941                  throw new NullPointerException();
4942              return new ForEachTransformedMappingTask<K,V,U>
4943 <                (map, null, -1, null, transformer, action);
4943 >                (map, null, -1, transformer, action);
4944          }
4945  
4946          /**
# Line 4287 | Line 4960 | public class ConcurrentHashMapV8<K, V>
4960               BiFun<? super K, ? super V, ? extends U> searchFunction) {
4961              if (searchFunction == null) throw new NullPointerException();
4962              return new SearchMappingsTask<K,V,U>
4963 <                (map, null, -1, null, searchFunction,
4963 >                (map, null, -1, searchFunction,
4964                   new AtomicReference<U>());
4965          }
4966  
# Line 4396 | Line 5069 | public class ConcurrentHashMapV8<K, V>
5069              (ConcurrentHashMapV8<K,V> map,
5070               Action<K> action) {
5071              if (action == null) throw new NullPointerException();
5072 <            return new ForEachKeyTask<K,V>(map, null, -1, null, action);
5072 >            return new ForEachKeyTask<K,V>(map, null, -1, action);
5073          }
5074  
5075          /**
# Line 4417 | Line 5090 | public class ConcurrentHashMapV8<K, V>
5090              if (transformer == null || action == null)
5091                  throw new NullPointerException();
5092              return new ForEachTransformedKeyTask<K,V,U>
5093 <                (map, null, -1, null, transformer, action);
5093 >                (map, null, -1, transformer, action);
5094          }
5095  
5096          /**
# Line 4437 | Line 5110 | public class ConcurrentHashMapV8<K, V>
5110               Fun<? super K, ? extends U> searchFunction) {
5111              if (searchFunction == null) throw new NullPointerException();
5112              return new SearchKeysTask<K,V,U>
5113 <                (map, null, -1, null, searchFunction,
5113 >                (map, null, -1, searchFunction,
5114                   new AtomicReference<U>());
5115          }
5116  
# Line 4563 | Line 5236 | public class ConcurrentHashMapV8<K, V>
5236              (ConcurrentHashMapV8<K,V> map,
5237               Action<V> action) {
5238              if (action == null) throw new NullPointerException();
5239 <            return new ForEachValueTask<K,V>(map, null, -1, null, action);
5239 >            return new ForEachValueTask<K,V>(map, null, -1, action);
5240          }
5241  
5242          /**
# Line 4583 | Line 5256 | public class ConcurrentHashMapV8<K, V>
5256              if (transformer == null || action == null)
5257                  throw new NullPointerException();
5258              return new ForEachTransformedValueTask<K,V,U>
5259 <                (map, null, -1, null, transformer, action);
5259 >                (map, null, -1, transformer, action);
5260          }
5261  
5262          /**
# Line 4603 | Line 5276 | public class ConcurrentHashMapV8<K, V>
5276               Fun<? super V, ? extends U> searchFunction) {
5277              if (searchFunction == null) throw new NullPointerException();
5278              return new SearchValuesTask<K,V,U>
5279 <                (map, null, -1, null, searchFunction,
5279 >                (map, null, -1, searchFunction,
5280                   new AtomicReference<U>());
5281          }
5282  
# Line 4729 | Line 5402 | public class ConcurrentHashMapV8<K, V>
5402              (ConcurrentHashMapV8<K,V> map,
5403               Action<Map.Entry<K,V>> action) {
5404              if (action == null) throw new NullPointerException();
5405 <            return new ForEachEntryTask<K,V>(map, null, -1, null, action);
5405 >            return new ForEachEntryTask<K,V>(map, null, -1, action);
5406          }
5407  
5408          /**
# Line 4749 | Line 5422 | public class ConcurrentHashMapV8<K, V>
5422              if (transformer == null || action == null)
5423                  throw new NullPointerException();
5424              return new ForEachTransformedEntryTask<K,V,U>
5425 <                (map, null, -1, null, transformer, action);
5425 >                (map, null, -1, transformer, action);
5426          }
5427  
5428          /**
# Line 4769 | Line 5442 | public class ConcurrentHashMapV8<K, V>
5442               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5443              if (searchFunction == null) throw new NullPointerException();
5444              return new SearchEntriesTask<K,V,U>
5445 <                (map, null, -1, null, searchFunction,
5445 >                (map, null, -1, searchFunction,
5446                   new AtomicReference<U>());
5447          }
5448  
# Line 4887 | Line 5560 | public class ConcurrentHashMapV8<K, V>
5560  
5561      // -------------------------------------------------------
5562  
4890    /**
4891     * Base for FJ tasks for bulk operations. This adds a variant of
4892     * CountedCompleters and some split and merge bookkeeping to
4893     * iterator functionality. The forEach and reduce methods are
4894     * similar to those illustrated in CountedCompleter documentation,
4895     * except that bottom-up reduction completions perform them within
4896     * their compute methods. The search methods are like forEach
4897     * except they continually poll for success and exit early.  Also,
4898     * exceptions are handled in a simpler manner, by just trying to
4899     * complete root task exceptionally.
4900     */
4901    @SuppressWarnings("serial") static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4902        final BulkTask<K,V,?> parent;  // completion target
4903        int batch;                     // split control; -1 for unknown
4904        int pending;                   // completion control
4905
4906        BulkTask(ConcurrentHashMapV8<K,V> map, BulkTask<K,V,?> parent,
4907                 int batch) {
4908            super(map);
4909            this.parent = parent;
4910            this.batch = batch;
4911            if (parent != null && map != null) { // split parent
4912                Node[] t;
4913                if ((t = parent.tab) == null &&
4914                    (t = parent.tab = map.table) != null)
4915                    parent.baseLimit = parent.baseSize = t.length;
4916                this.tab = t;
4917                this.baseSize = parent.baseSize;
4918                int hi = this.baseLimit = parent.baseLimit;
4919                parent.baseLimit = this.index = this.baseIndex =
4920                    (hi + parent.baseIndex + 1) >>> 1;
4921            }
4922        }
4923
4924        /**
4925         * Forces root task to complete.
4926         * @param ex if null, complete normally, else exceptionally
4927         * @return false to simplify use
4928         */
4929        final boolean tryCompleteComputation(Throwable ex) {
4930            for (BulkTask<K,V,?> a = this;;) {
4931                BulkTask<K,V,?> p = a.parent;
4932                if (p == null) {
4933                    if (ex != null)
4934                        a.completeExceptionally(ex);
4935                    else
4936                        a.quietlyComplete();
4937                    return false;
4938                }
4939                a = p;
4940            }
4941        }
4942
4943        /**
4944         * Version of tryCompleteComputation for function screening checks
4945         */
4946        final boolean abortOnNullFunction() {
4947            return tryCompleteComputation(new Error("Unexpected null function"));
4948        }
4949
4950        // utilities
4951
4952        /** CompareAndSet pending count */
4953        final boolean casPending(int cmp, int val) {
4954            return U.compareAndSwapInt(this, PENDING, cmp, val);
4955        }
4956
4957        /**
4958         * Returns approx exp2 of the number of times (minus one) to
4959         * split task by two before executing leaf action. This value
4960         * is faster to compute and more convenient to use as a guide
4961         * to splitting than is the depth, since it is used while
4962         * dividing by two anyway.
4963         */
4964        final int batch() {
4965            ConcurrentHashMapV8<K, V> m; int b; Node[] t;  ForkJoinPool pool;
4966            if ((b = batch) < 0 && (m = map) != null) { // force initialization
4967                if ((t = tab) == null && (t = tab = m.table) != null)
4968                    baseLimit = baseSize = t.length;
4969                if (t != null) {
4970                    long n = m.counter.sum();
4971                    int par = (pool = getPool()) == null?
4972                        ForkJoinPool.getCommonPoolParallelism() :
4973                        pool.getParallelism();
4974                    int sp = par << 3; // slack of 8
4975                    b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4976                }
4977            }
4978            return b;
4979        }
4980
4981        /**
4982         * Returns exportable snapshot entry.
4983         */
4984        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4985            return new AbstractMap.SimpleEntry<K,V>(k, v);
4986        }
4987
4988        // Unsafe mechanics
4989        private static final sun.misc.Unsafe U;
4990        private static final long PENDING;
4991        static {
4992            try {
4993                U = getUnsafe();
4994                PENDING = U.objectFieldOffset
4995                    (BulkTask.class.getDeclaredField("pending"));
4996            } catch (Exception e) {
4997                throw new Error(e);
4998            }
4999        }
5000    }
5001
5002    /**
5003     * Base class for non-reductive actions
5004     */
5005    @SuppressWarnings("serial") static abstract class BulkAction<K,V,R> extends BulkTask<K,V,R> {
5006        BulkAction<K,V,?> nextTask;
5007        BulkAction(ConcurrentHashMapV8<K,V> map, BulkTask<K,V,?> parent,
5008                   int batch, BulkAction<K,V,?> nextTask) {
5009            super(map, parent, batch);
5010            this.nextTask = nextTask;
5011        }
5012
5013        /**
5014         * Try to complete task and upward parents. Upon hitting
5015         * non-completed parent, if a non-FJ task, try to help out the
5016         * computation.
5017         */
5018        final void tryComplete(BulkAction<K,V,?> subtasks) {
5019            BulkTask<K,V,?> a = this, s = a;
5020            for (int c;;) {
5021                if ((c = a.pending) == 0) {
5022                    if ((a = (s = a).parent) == null) {
5023                        s.quietlyComplete();
5024                        break;
5025                    }
5026                }
5027                else if (a.casPending(c, c - 1)) {
5028                    if (subtasks != null && !inForkJoinPool()) {
5029                        while ((s = a.parent) != null)
5030                            a = s;
5031                        while (!a.isDone()) {
5032                            BulkAction<K,V,?> next = subtasks.nextTask;
5033                            if (subtasks.tryUnfork())
5034                                subtasks.exec();
5035                            if ((subtasks = next) == null)
5036                                break;
5037                        }
5038                    }
5039                    break;
5040                }
5041            }
5042        }
5043
5044    }
5045
5563      /*
5564       * Task classes. Coded in a regular but ugly format/style to
5565       * simplify checks that each variant differs in the right way from
5566 <     * others.
5566 >     * others. The null screenings exist because compilers cannot tell
5567 >     * that we've already null-checked task arguments, so we force
5568 >     * simplest hoisted bypass to help avoid convoluted traps.
5569       */
5570  
5571      @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5572 <        extends BulkAction<K,V,Void> {
5572 >        extends Traverser<K,V,Void> {
5573          final Action<K> action;
5574          ForEachKeyTask
5575 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5057 <             ForEachKeyTask<K,V> nextTask,
5575 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5576               Action<K> action) {
5577 <            super(m, p, b, nextTask);
5577 >            super(m, p, b);
5578              this.action = action;
5579          }
5580 <        @SuppressWarnings("unchecked") public final boolean exec() {
5581 <            final Action<K> action = this.action;
5582 <            if (action == null)
5583 <                return abortOnNullFunction();
5584 <            ForEachKeyTask<K,V> subtasks = null;
5067 <            try {
5068 <                int b = batch(), c;
5069 <                while (b > 1 && baseIndex != baseLimit) {
5070 <                    do {} while (!casPending(c = pending, c+1));
5071 <                    (subtasks = new ForEachKeyTask<K,V>
5072 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5073 <                }
5580 >        @SuppressWarnings("unchecked") public final void compute() {
5581 >            final Action<K> action;
5582 >            if ((action = this.action) != null) {
5583 >                for (int b; (b = preSplit()) > 0;)
5584 >                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
5585                  while (advance() != null)
5586                      action.apply((K)nextKey);
5587 <            } catch (Throwable ex) {
5077 <                return tryCompleteComputation(ex);
5587 >                propagateCompletion();
5588              }
5079            tryComplete(subtasks);
5080            return false;
5589          }
5590      }
5591  
5592      @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5593 <        extends BulkAction<K,V,Void> {
5593 >        extends Traverser<K,V,Void> {
5594          final Action<V> action;
5595          ForEachValueTask
5596 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5089 <             ForEachValueTask<K,V> nextTask,
5596 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5597               Action<V> action) {
5598 <            super(m, p, b, nextTask);
5598 >            super(m, p, b);
5599              this.action = action;
5600          }
5601 <        @SuppressWarnings("unchecked") public final boolean exec() {
5602 <            final Action<V> action = this.action;
5603 <            if (action == null)
5604 <                return abortOnNullFunction();
5605 <            ForEachValueTask<K,V> subtasks = null;
5606 <            try {
5100 <                int b = batch(), c;
5101 <                while (b > 1 && baseIndex != baseLimit) {
5102 <                    do {} while (!casPending(c = pending, c+1));
5103 <                    (subtasks = new ForEachValueTask<K,V>
5104 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5105 <                }
5106 <                Object v;
5601 >        @SuppressWarnings("unchecked") public final void compute() {
5602 >            final Action<V> action;
5603 >            if ((action = this.action) != null) {
5604 >                for (int b; (b = preSplit()) > 0;)
5605 >                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5606 >                V v;
5607                  while ((v = advance()) != null)
5608 <                    action.apply((V)v);
5609 <            } catch (Throwable ex) {
5110 <                return tryCompleteComputation(ex);
5608 >                    action.apply(v);
5609 >                propagateCompletion();
5610              }
5112            tryComplete(subtasks);
5113            return false;
5611          }
5612      }
5613  
5614      @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5615 <        extends BulkAction<K,V,Void> {
5615 >        extends Traverser<K,V,Void> {
5616          final Action<Entry<K,V>> action;
5617          ForEachEntryTask
5618 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5122 <             ForEachEntryTask<K,V> nextTask,
5618 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5619               Action<Entry<K,V>> action) {
5620 <            super(m, p, b, nextTask);
5620 >            super(m, p, b);
5621              this.action = action;
5622          }
5623 <        @SuppressWarnings("unchecked") public final boolean exec() {
5624 <            final Action<Entry<K,V>> action = this.action;
5625 <            if (action == null)
5626 <                return abortOnNullFunction();
5627 <            ForEachEntryTask<K,V> subtasks = null;
5628 <            try {
5133 <                int b = batch(), c;
5134 <                while (b > 1 && baseIndex != baseLimit) {
5135 <                    do {} while (!casPending(c = pending, c+1));
5136 <                    (subtasks = new ForEachEntryTask<K,V>
5137 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5138 <                }
5139 <                Object v;
5623 >        @SuppressWarnings("unchecked") public final void compute() {
5624 >            final Action<Entry<K,V>> action;
5625 >            if ((action = this.action) != null) {
5626 >                for (int b; (b = preSplit()) > 0;)
5627 >                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5628 >                V v;
5629                  while ((v = advance()) != null)
5630 <                    action.apply(entryFor((K)nextKey, (V)v));
5631 <            } catch (Throwable ex) {
5143 <                return tryCompleteComputation(ex);
5630 >                    action.apply(entryFor((K)nextKey, v));
5631 >                propagateCompletion();
5632              }
5145            tryComplete(subtasks);
5146            return false;
5633          }
5634      }
5635  
5636      @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5637 <        extends BulkAction<K,V,Void> {
5637 >        extends Traverser<K,V,Void> {
5638          final BiAction<K,V> action;
5639          ForEachMappingTask
5640 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5155 <             ForEachMappingTask<K,V> nextTask,
5640 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5641               BiAction<K,V> action) {
5642 <            super(m, p, b, nextTask);
5642 >            super(m, p, b);
5643              this.action = action;
5644          }
5645 <        @SuppressWarnings("unchecked") public final boolean exec() {
5646 <            final BiAction<K,V> action = this.action;
5647 <            if (action == null)
5648 <                return abortOnNullFunction();
5649 <            ForEachMappingTask<K,V> subtasks = null;
5650 <            try {
5166 <                int b = batch(), c;
5167 <                while (b > 1 && baseIndex != baseLimit) {
5168 <                    do {} while (!casPending(c = pending, c+1));
5169 <                    (subtasks = new ForEachMappingTask<K,V>
5170 <                     (map, this, b >>>= 1, subtasks, action)).fork();
5171 <                }
5172 <                Object v;
5645 >        @SuppressWarnings("unchecked") public final void compute() {
5646 >            final BiAction<K,V> action;
5647 >            if ((action = this.action) != null) {
5648 >                for (int b; (b = preSplit()) > 0;)
5649 >                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5650 >                V v;
5651                  while ((v = advance()) != null)
5652 <                    action.apply((K)nextKey, (V)v);
5653 <            } catch (Throwable ex) {
5176 <                return tryCompleteComputation(ex);
5652 >                    action.apply((K)nextKey, v);
5653 >                propagateCompletion();
5654              }
5178            tryComplete(subtasks);
5179            return false;
5655          }
5656      }
5657  
5658      @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5659 <        extends BulkAction<K,V,Void> {
5659 >        extends Traverser<K,V,Void> {
5660          final Fun<? super K, ? extends U> transformer;
5661          final Action<U> action;
5662          ForEachTransformedKeyTask
5663 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5664 <             ForEachTransformedKeyTask<K,V,U> nextTask,
5665 <             Fun<? super K, ? extends U> transformer,
5666 <             Action<U> action) {
5667 <            super(m, p, b, nextTask);
5668 <            this.transformer = transformer;
5669 <            this.action = action;
5670 <
5671 <        }
5672 <        @SuppressWarnings("unchecked") public final boolean exec() {
5673 <            final Fun<? super K, ? extends U> transformer =
5674 <                this.transformer;
5675 <            final Action<U> action = this.action;
5201 <            if (transformer == null || action == null)
5202 <                return abortOnNullFunction();
5203 <            ForEachTransformedKeyTask<K,V,U> subtasks = null;
5204 <            try {
5205 <                int b = batch(), c;
5206 <                while (b > 1 && baseIndex != baseLimit) {
5207 <                    do {} while (!casPending(c = pending, c+1));
5208 <                    (subtasks = new ForEachTransformedKeyTask<K,V,U>
5209 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5210 <                }
5663 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5664 >             Fun<? super K, ? extends U> transformer, Action<U> action) {
5665 >            super(m, p, b);
5666 >            this.transformer = transformer; this.action = action;
5667 >        }
5668 >        @SuppressWarnings("unchecked") public final void compute() {
5669 >            final Fun<? super K, ? extends U> transformer;
5670 >            final Action<U> action;
5671 >            if ((transformer = this.transformer) != null &&
5672 >                (action = this.action) != null) {
5673 >                for (int b; (b = preSplit()) > 0;)
5674 >                    new ForEachTransformedKeyTask<K,V,U>
5675 >                        (map, this, b, transformer, action).fork();
5676                  U u;
5677                  while (advance() != null) {
5678                      if ((u = transformer.apply((K)nextKey)) != null)
5679                          action.apply(u);
5680                  }
5681 <            } catch (Throwable ex) {
5217 <                return tryCompleteComputation(ex);
5681 >                propagateCompletion();
5682              }
5219            tryComplete(subtasks);
5220            return false;
5683          }
5684      }
5685  
5686      @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5687 <        extends BulkAction<K,V,Void> {
5687 >        extends Traverser<K,V,Void> {
5688          final Fun<? super V, ? extends U> transformer;
5689          final Action<U> action;
5690          ForEachTransformedValueTask
5691 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5692 <             ForEachTransformedValueTask<K,V,U> nextTask,
5693 <             Fun<? super V, ? extends U> transformer,
5694 <             Action<U> action) {
5695 <            super(m, p, b, nextTask);
5696 <            this.transformer = transformer;
5697 <            this.action = action;
5698 <
5699 <        }
5700 <        @SuppressWarnings("unchecked") public final boolean exec() {
5701 <            final Fun<? super V, ? extends U> transformer =
5702 <                this.transformer;
5703 <            final Action<U> action = this.action;
5704 <            if (transformer == null || action == null)
5243 <                return abortOnNullFunction();
5244 <            ForEachTransformedValueTask<K,V,U> subtasks = null;
5245 <            try {
5246 <                int b = batch(), c;
5247 <                while (b > 1 && baseIndex != baseLimit) {
5248 <                    do {} while (!casPending(c = pending, c+1));
5249 <                    (subtasks = new ForEachTransformedValueTask<K,V,U>
5250 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5251 <                }
5252 <                Object v; U u;
5691 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5692 >             Fun<? super V, ? extends U> transformer, Action<U> action) {
5693 >            super(m, p, b);
5694 >            this.transformer = transformer; this.action = action;
5695 >        }
5696 >        @SuppressWarnings("unchecked") public final void compute() {
5697 >            final Fun<? super V, ? extends U> transformer;
5698 >            final Action<U> action;
5699 >            if ((transformer = this.transformer) != null &&
5700 >                (action = this.action) != null) {
5701 >                for (int b; (b = preSplit()) > 0;)
5702 >                    new ForEachTransformedValueTask<K,V,U>
5703 >                        (map, this, b, transformer, action).fork();
5704 >                V v; U u;
5705                  while ((v = advance()) != null) {
5706 <                    if ((u = transformer.apply((V)v)) != null)
5706 >                    if ((u = transformer.apply(v)) != null)
5707                          action.apply(u);
5708                  }
5709 <            } catch (Throwable ex) {
5258 <                return tryCompleteComputation(ex);
5709 >                propagateCompletion();
5710              }
5260            tryComplete(subtasks);
5261            return false;
5711          }
5712      }
5713  
5714      @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5715 <        extends BulkAction<K,V,Void> {
5715 >        extends Traverser<K,V,Void> {
5716          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5717          final Action<U> action;
5718          ForEachTransformedEntryTask
5719 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5720 <             ForEachTransformedEntryTask<K,V,U> nextTask,
5721 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5722 <             Action<U> action) {
5723 <            super(m, p, b, nextTask);
5724 <            this.transformer = transformer;
5725 <            this.action = action;
5726 <
5727 <        }
5728 <        @SuppressWarnings("unchecked") public final boolean exec() {
5729 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5730 <                this.transformer;
5731 <            final Action<U> action = this.action;
5732 <            if (transformer == null || action == null)
5284 <                return abortOnNullFunction();
5285 <            ForEachTransformedEntryTask<K,V,U> subtasks = null;
5286 <            try {
5287 <                int b = batch(), c;
5288 <                while (b > 1 && baseIndex != baseLimit) {
5289 <                    do {} while (!casPending(c = pending, c+1));
5290 <                    (subtasks = new ForEachTransformedEntryTask<K,V,U>
5291 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5292 <                }
5293 <                Object v; U u;
5719 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5720 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
5721 >            super(m, p, b);
5722 >            this.transformer = transformer; this.action = action;
5723 >        }
5724 >        @SuppressWarnings("unchecked") public final void compute() {
5725 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5726 >            final Action<U> action;
5727 >            if ((transformer = this.transformer) != null &&
5728 >                (action = this.action) != null) {
5729 >                for (int b; (b = preSplit()) > 0;)
5730 >                    new ForEachTransformedEntryTask<K,V,U>
5731 >                        (map, this, b, transformer, action).fork();
5732 >                V v; U u;
5733                  while ((v = advance()) != null) {
5734 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5734 >                    if ((u = transformer.apply(entryFor((K)nextKey,
5735 >                                                        v))) != null)
5736                          action.apply(u);
5737                  }
5738 <            } catch (Throwable ex) {
5299 <                return tryCompleteComputation(ex);
5738 >                propagateCompletion();
5739              }
5301            tryComplete(subtasks);
5302            return false;
5740          }
5741      }
5742  
5743      @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5744 <        extends BulkAction<K,V,Void> {
5744 >        extends Traverser<K,V,Void> {
5745          final BiFun<? super K, ? super V, ? extends U> transformer;
5746          final Action<U> action;
5747          ForEachTransformedMappingTask
5748 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5312 <             ForEachTransformedMappingTask<K,V,U> nextTask,
5748 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5749               BiFun<? super K, ? super V, ? extends U> transformer,
5750               Action<U> action) {
5751 <            super(m, p, b, nextTask);
5752 <            this.transformer = transformer;
5317 <            this.action = action;
5318 <
5751 >            super(m, p, b);
5752 >            this.transformer = transformer; this.action = action;
5753          }
5754 <        @SuppressWarnings("unchecked") public final boolean exec() {
5755 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5756 <                this.transformer;
5757 <            final Action<U> action = this.action;
5758 <            if (transformer == null || action == null)
5759 <                return abortOnNullFunction();
5760 <            ForEachTransformedMappingTask<K,V,U> subtasks = null;
5761 <            try {
5762 <                int b = batch(), c;
5329 <                while (b > 1 && baseIndex != baseLimit) {
5330 <                    do {} while (!casPending(c = pending, c+1));
5331 <                    (subtasks = new ForEachTransformedMappingTask<K,V,U>
5332 <                     (map, this, b >>>= 1, subtasks, transformer, action)).fork();
5333 <                }
5334 <                Object v; U u;
5754 >        @SuppressWarnings("unchecked") public final void compute() {
5755 >            final BiFun<? super K, ? super V, ? extends U> transformer;
5756 >            final Action<U> action;
5757 >            if ((transformer = this.transformer) != null &&
5758 >                (action = this.action) != null) {
5759 >                for (int b; (b = preSplit()) > 0;)
5760 >                    new ForEachTransformedMappingTask<K,V,U>
5761 >                        (map, this, b, transformer, action).fork();
5762 >                V v; U u;
5763                  while ((v = advance()) != null) {
5764 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5764 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
5765                          action.apply(u);
5766                  }
5767 <            } catch (Throwable ex) {
5340 <                return tryCompleteComputation(ex);
5767 >                propagateCompletion();
5768              }
5342            tryComplete(subtasks);
5343            return false;
5769          }
5770      }
5771  
5772      @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5773 <        extends BulkAction<K,V,U> {
5773 >        extends Traverser<K,V,U> {
5774          final Fun<? super K, ? extends U> searchFunction;
5775          final AtomicReference<U> result;
5776          SearchKeysTask
5777 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5353 <             SearchKeysTask<K,V,U> nextTask,
5777 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5778               Fun<? super K, ? extends U> searchFunction,
5779               AtomicReference<U> result) {
5780 <            super(m, p, b, nextTask);
5780 >            super(m, p, b);
5781              this.searchFunction = searchFunction; this.result = result;
5782          }
5783 <        @SuppressWarnings("unchecked") public final boolean exec() {
5784 <            AtomicReference<U> result = this.result;
5785 <            final Fun<? super K, ? extends U> searchFunction =
5786 <                this.searchFunction;
5787 <            if (searchFunction == null || result == null)
5788 <                return abortOnNullFunction();
5789 <            SearchKeysTask<K,V,U> subtasks = null;
5790 <            try {
5791 <                int b = batch(), c;
5792 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5793 <                    do {} while (!casPending(c = pending, c+1));
5794 <                    (subtasks = new SearchKeysTask<K,V,U>
5795 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5783 >        public final U getRawResult() { return result.get(); }
5784 >        @SuppressWarnings("unchecked") public final void compute() {
5785 >            final Fun<? super K, ? extends U> searchFunction;
5786 >            final AtomicReference<U> result;
5787 >            if ((searchFunction = this.searchFunction) != null &&
5788 >                (result = this.result) != null) {
5789 >                for (int b;;) {
5790 >                    if (result.get() != null)
5791 >                        return;
5792 >                    if ((b = preSplit()) <= 0)
5793 >                        break;
5794 >                    new SearchKeysTask<K,V,U>
5795 >                        (map, this, b, searchFunction, result).fork();
5796                  }
5797 <                U u;
5798 <                while (result.get() == null && advance() != null) {
5797 >                while (result.get() == null) {
5798 >                    U u;
5799 >                    if (advance() == null) {
5800 >                        propagateCompletion();
5801 >                        break;
5802 >                    }
5803                      if ((u = searchFunction.apply((K)nextKey)) != null) {
5804                          if (result.compareAndSet(null, u))
5805 <                            tryCompleteComputation(null);
5805 >                            quietlyCompleteRoot();
5806                          break;
5807                      }
5808                  }
5381            } catch (Throwable ex) {
5382                return tryCompleteComputation(ex);
5809              }
5384            tryComplete(subtasks);
5385            return false;
5810          }
5387        public final U getRawResult() { return result.get(); }
5811      }
5812  
5813      @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5814 <        extends BulkAction<K,V,U> {
5814 >        extends Traverser<K,V,U> {
5815          final Fun<? super V, ? extends U> searchFunction;
5816          final AtomicReference<U> result;
5817          SearchValuesTask
5818 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5396 <             SearchValuesTask<K,V,U> nextTask,
5818 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5819               Fun<? super V, ? extends U> searchFunction,
5820               AtomicReference<U> result) {
5821 <            super(m, p, b, nextTask);
5821 >            super(m, p, b);
5822              this.searchFunction = searchFunction; this.result = result;
5823          }
5824 <        @SuppressWarnings("unchecked") public final boolean exec() {
5825 <            AtomicReference<U> result = this.result;
5826 <            final Fun<? super V, ? extends U> searchFunction =
5827 <                this.searchFunction;
5828 <            if (searchFunction == null || result == null)
5829 <                return abortOnNullFunction();
5830 <            SearchValuesTask<K,V,U> subtasks = null;
5831 <            try {
5832 <                int b = batch(), c;
5833 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5834 <                    do {} while (!casPending(c = pending, c+1));
5835 <                    (subtasks = new SearchValuesTask<K,V,U>
5836 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5837 <                }
5838 <                Object v; U u;
5839 <                while (result.get() == null && (v = advance()) != null) {
5840 <                    if ((u = searchFunction.apply((V)v)) != null) {
5824 >        public final U getRawResult() { return result.get(); }
5825 >        @SuppressWarnings("unchecked") public final void compute() {
5826 >            final Fun<? super V, ? extends U> searchFunction;
5827 >            final AtomicReference<U> result;
5828 >            if ((searchFunction = this.searchFunction) != null &&
5829 >                (result = this.result) != null) {
5830 >                for (int b;;) {
5831 >                    if (result.get() != null)
5832 >                        return;
5833 >                    if ((b = preSplit()) <= 0)
5834 >                        break;
5835 >                    new SearchValuesTask<K,V,U>
5836 >                        (map, this, b, searchFunction, result).fork();
5837 >                }
5838 >                while (result.get() == null) {
5839 >                    V v; U u;
5840 >                    if ((v = advance()) == null) {
5841 >                        propagateCompletion();
5842 >                        break;
5843 >                    }
5844 >                    if ((u = searchFunction.apply(v)) != null) {
5845                          if (result.compareAndSet(null, u))
5846 <                            tryCompleteComputation(null);
5846 >                            quietlyCompleteRoot();
5847                          break;
5848                      }
5849                  }
5424            } catch (Throwable ex) {
5425                return tryCompleteComputation(ex);
5850              }
5427            tryComplete(subtasks);
5428            return false;
5851          }
5430        public final U getRawResult() { return result.get(); }
5852      }
5853  
5854      @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5855 <        extends BulkAction<K,V,U> {
5855 >        extends Traverser<K,V,U> {
5856          final Fun<Entry<K,V>, ? extends U> searchFunction;
5857          final AtomicReference<U> result;
5858          SearchEntriesTask
5859 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5439 <             SearchEntriesTask<K,V,U> nextTask,
5859 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5860               Fun<Entry<K,V>, ? extends U> searchFunction,
5861               AtomicReference<U> result) {
5862 <            super(m, p, b, nextTask);
5862 >            super(m, p, b);
5863              this.searchFunction = searchFunction; this.result = result;
5864          }
5865 <        @SuppressWarnings("unchecked") public final boolean exec() {
5866 <            AtomicReference<U> result = this.result;
5867 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5868 <                this.searchFunction;
5869 <            if (searchFunction == null || result == null)
5870 <                return abortOnNullFunction();
5871 <            SearchEntriesTask<K,V,U> subtasks = null;
5872 <            try {
5873 <                int b = batch(), c;
5874 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5455 <                    do {} while (!casPending(c = pending, c+1));
5456 <                    (subtasks = new SearchEntriesTask<K,V,U>
5457 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5458 <                }
5459 <                Object v; U u;
5460 <                while (result.get() == null && (v = advance()) != null) {
5461 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5462 <                        if (result.compareAndSet(null, u))
5463 <                            tryCompleteComputation(null);
5865 >        public final U getRawResult() { return result.get(); }
5866 >        @SuppressWarnings("unchecked") public final void compute() {
5867 >            final Fun<Entry<K,V>, ? extends U> searchFunction;
5868 >            final AtomicReference<U> result;
5869 >            if ((searchFunction = this.searchFunction) != null &&
5870 >                (result = this.result) != null) {
5871 >                for (int b;;) {
5872 >                    if (result.get() != null)
5873 >                        return;
5874 >                    if ((b = preSplit()) <= 0)
5875                          break;
5876 +                    new SearchEntriesTask<K,V,U>
5877 +                        (map, this, b, searchFunction, result).fork();
5878 +                }
5879 +                while (result.get() == null) {
5880 +                    V v; U u;
5881 +                    if ((v = advance()) == null) {
5882 +                        propagateCompletion();
5883 +                        break;
5884 +                    }
5885 +                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5886 +                                                           v))) != null) {
5887 +                        if (result.compareAndSet(null, u))
5888 +                            quietlyCompleteRoot();
5889 +                        return;
5890                      }
5891                  }
5467            } catch (Throwable ex) {
5468                return tryCompleteComputation(ex);
5892              }
5470            tryComplete(subtasks);
5471            return false;
5893          }
5473        public final U getRawResult() { return result.get(); }
5894      }
5895  
5896      @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5897 <        extends BulkAction<K,V,U> {
5897 >        extends Traverser<K,V,U> {
5898          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5899          final AtomicReference<U> result;
5900          SearchMappingsTask
5901 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5482 <             SearchMappingsTask<K,V,U> nextTask,
5901 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5902               BiFun<? super K, ? super V, ? extends U> searchFunction,
5903               AtomicReference<U> result) {
5904 <            super(m, p, b, nextTask);
5904 >            super(m, p, b);
5905              this.searchFunction = searchFunction; this.result = result;
5906          }
5907 <        @SuppressWarnings("unchecked") public final boolean exec() {
5908 <            AtomicReference<U> result = this.result;
5909 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5910 <                this.searchFunction;
5911 <            if (searchFunction == null || result == null)
5912 <                return abortOnNullFunction();
5913 <            SearchMappingsTask<K,V,U> subtasks = null;
5914 <            try {
5915 <                int b = batch(), c;
5916 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5917 <                    do {} while (!casPending(c = pending, c+1));
5918 <                    (subtasks = new SearchMappingsTask<K,V,U>
5919 <                     (map, this, b >>>= 1, subtasks, searchFunction, result)).fork();
5920 <                }
5921 <                Object v; U u;
5922 <                while (result.get() == null && (v = advance()) != null) {
5923 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5907 >        public final U getRawResult() { return result.get(); }
5908 >        @SuppressWarnings("unchecked") public final void compute() {
5909 >            final BiFun<? super K, ? super V, ? extends U> searchFunction;
5910 >            final AtomicReference<U> result;
5911 >            if ((searchFunction = this.searchFunction) != null &&
5912 >                (result = this.result) != null) {
5913 >                for (int b;;) {
5914 >                    if (result.get() != null)
5915 >                        return;
5916 >                    if ((b = preSplit()) <= 0)
5917 >                        break;
5918 >                    new SearchMappingsTask<K,V,U>
5919 >                        (map, this, b, searchFunction, result).fork();
5920 >                }
5921 >                while (result.get() == null) {
5922 >                    V v; U u;
5923 >                    if ((v = advance()) == null) {
5924 >                        propagateCompletion();
5925 >                        break;
5926 >                    }
5927 >                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5928                          if (result.compareAndSet(null, u))
5929 <                            tryCompleteComputation(null);
5929 >                            quietlyCompleteRoot();
5930                          break;
5931                      }
5932                  }
5510            } catch (Throwable ex) {
5511                return tryCompleteComputation(ex);
5933              }
5513            tryComplete(subtasks);
5514            return false;
5934          }
5516        public final U getRawResult() { return result.get(); }
5935      }
5936  
5937      @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5938 <        extends BulkTask<K,V,K> {
5938 >        extends Traverser<K,V,K> {
5939          final BiFun<? super K, ? super K, ? extends K> reducer;
5940          K result;
5941          ReduceKeysTask<K,V> rights, nextRight;
5942          ReduceKeysTask
5943 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5943 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5944               ReduceKeysTask<K,V> nextRight,
5945               BiFun<? super K, ? super K, ? extends K> reducer) {
5946              super(m, p, b); this.nextRight = nextRight;
5947              this.reducer = reducer;
5948          }
5949 <        @SuppressWarnings("unchecked") public final boolean exec() {
5950 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5951 <                this.reducer;
5952 <            if (reducer == null)
5953 <                return abortOnNullFunction();
5536 <            try {
5537 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5538 <                    do {} while (!casPending(c = pending, c+1));
5949 >        public final K getRawResult() { return result; }
5950 >        @SuppressWarnings("unchecked") public final void compute() {
5951 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5952 >            if ((reducer = this.reducer) != null) {
5953 >                for (int b; (b = preSplit()) > 0;)
5954                      (rights = new ReduceKeysTask<K,V>
5955 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5541 <                }
5955 >                     (map, this, b, rights, reducer)).fork();
5956                  K r = null;
5957                  while (advance() != null) {
5958                      K u = (K)nextKey;
5959                      r = (r == null) ? u : reducer.apply(r, u);
5960                  }
5961                  result = r;
5962 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5963 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5964 <                    if ((c = t.pending) == 0) {
5965 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5966 <                            if ((sr = s.result) != null)
5967 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5968 <                        }
5969 <                        if ((par = t.parent) == null ||
5970 <                            !(par instanceof ReduceKeysTask)) {
5971 <                            t.quietlyComplete();
5972 <                            break;
5559 <                        }
5560 <                        t = (ReduceKeysTask<K,V>)par;
5962 >                CountedCompleter<?> c;
5963 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5964 >                    ReduceKeysTask<K,V>
5965 >                        t = (ReduceKeysTask<K,V>)c,
5966 >                        s = t.rights;
5967 >                    while (s != null) {
5968 >                        K tr, sr;
5969 >                        if ((sr = s.result) != null)
5970 >                            t.result = (((tr = t.result) == null) ? sr :
5971 >                                        reducer.apply(tr, sr));
5972 >                        s = t.rights = s.nextRight;
5973                      }
5562                    else if (t.casPending(c, c - 1))
5563                        break;
5974                  }
5565            } catch (Throwable ex) {
5566                return tryCompleteComputation(ex);
5567            }
5568            ReduceKeysTask<K,V> s = rights;
5569            if (s != null && !inForkJoinPool()) {
5570                do  {
5571                    if (s.tryUnfork())
5572                        s.exec();
5573                } while ((s = s.nextRight) != null);
5975              }
5575            return false;
5976          }
5577        public final K getRawResult() { return result; }
5977      }
5978  
5979      @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5980 <        extends BulkTask<K,V,V> {
5980 >        extends Traverser<K,V,V> {
5981          final BiFun<? super V, ? super V, ? extends V> reducer;
5982          V result;
5983          ReduceValuesTask<K,V> rights, nextRight;
5984          ReduceValuesTask
5985 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5985 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5986               ReduceValuesTask<K,V> nextRight,
5987               BiFun<? super V, ? super V, ? extends V> reducer) {
5988              super(m, p, b); this.nextRight = nextRight;
5989              this.reducer = reducer;
5990          }
5991 <        @SuppressWarnings("unchecked") public final boolean exec() {
5992 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5993 <                this.reducer;
5994 <            if (reducer == null)
5995 <                return abortOnNullFunction();
5597 <            try {
5598 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5599 <                    do {} while (!casPending(c = pending, c+1));
5991 >        public final V getRawResult() { return result; }
5992 >        @SuppressWarnings("unchecked") public final void compute() {
5993 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5994 >            if ((reducer = this.reducer) != null) {
5995 >                for (int b; (b = preSplit()) > 0;)
5996                      (rights = new ReduceValuesTask<K,V>
5997 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5602 <                }
5997 >                     (map, this, b, rights, reducer)).fork();
5998                  V r = null;
5999 <                Object v;
5999 >                V v;
6000                  while ((v = advance()) != null) {
6001 <                    V u = (V)v;
6001 >                    V u = v;
6002                      r = (r == null) ? u : reducer.apply(r, u);
6003                  }
6004                  result = r;
6005 <                for (ReduceValuesTask<K,V> t = this, s;;) {
6006 <                    int c; BulkTask<K,V,?> par; V tr, sr;
6007 <                    if ((c = t.pending) == 0) {
6008 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6009 <                            if ((sr = s.result) != null)
6010 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6011 <                        }
6012 <                        if ((par = t.parent) == null ||
6013 <                            !(par instanceof ReduceValuesTask)) {
6014 <                            t.quietlyComplete();
6015 <                            break;
5621 <                        }
5622 <                        t = (ReduceValuesTask<K,V>)par;
6005 >                CountedCompleter<?> c;
6006 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6007 >                    ReduceValuesTask<K,V>
6008 >                        t = (ReduceValuesTask<K,V>)c,
6009 >                        s = t.rights;
6010 >                    while (s != null) {
6011 >                        V tr, sr;
6012 >                        if ((sr = s.result) != null)
6013 >                            t.result = (((tr = t.result) == null) ? sr :
6014 >                                        reducer.apply(tr, sr));
6015 >                        s = t.rights = s.nextRight;
6016                      }
5624                    else if (t.casPending(c, c - 1))
5625                        break;
6017                  }
5627            } catch (Throwable ex) {
5628                return tryCompleteComputation(ex);
5629            }
5630            ReduceValuesTask<K,V> s = rights;
5631            if (s != null && !inForkJoinPool()) {
5632                do  {
5633                    if (s.tryUnfork())
5634                        s.exec();
5635                } while ((s = s.nextRight) != null);
6018              }
5637            return false;
6019          }
5639        public final V getRawResult() { return result; }
6020      }
6021  
6022      @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6023 <        extends BulkTask<K,V,Map.Entry<K,V>> {
6023 >        extends Traverser<K,V,Map.Entry<K,V>> {
6024          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6025          Map.Entry<K,V> result;
6026          ReduceEntriesTask<K,V> rights, nextRight;
6027          ReduceEntriesTask
6028 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6028 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6029               ReduceEntriesTask<K,V> nextRight,
6030               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6031              super(m, p, b); this.nextRight = nextRight;
6032              this.reducer = reducer;
6033          }
6034 <        @SuppressWarnings("unchecked") public final boolean exec() {
6035 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
6036 <                this.reducer;
6037 <            if (reducer == null)
6038 <                return abortOnNullFunction();
5659 <            try {
5660 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5661 <                    do {} while (!casPending(c = pending, c+1));
6034 >        public final Map.Entry<K,V> getRawResult() { return result; }
6035 >        @SuppressWarnings("unchecked") public final void compute() {
6036 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6037 >            if ((reducer = this.reducer) != null) {
6038 >                for (int b; (b = preSplit()) > 0;)
6039                      (rights = new ReduceEntriesTask<K,V>
6040 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5664 <                }
6040 >                     (map, this, b, rights, reducer)).fork();
6041                  Map.Entry<K,V> r = null;
6042 <                Object v;
6042 >                V v;
6043                  while ((v = advance()) != null) {
6044 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
6044 >                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6045                      r = (r == null) ? u : reducer.apply(r, u);
6046                  }
6047                  result = r;
6048 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
6049 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
6050 <                    if ((c = t.pending) == 0) {
6051 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6052 <                            if ((sr = s.result) != null)
6053 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6054 <                        }
6055 <                        if ((par = t.parent) == null ||
6056 <                            !(par instanceof ReduceEntriesTask)) {
6057 <                            t.quietlyComplete();
6058 <                            break;
5683 <                        }
5684 <                        t = (ReduceEntriesTask<K,V>)par;
6048 >                CountedCompleter<?> c;
6049 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6050 >                    ReduceEntriesTask<K,V>
6051 >                        t = (ReduceEntriesTask<K,V>)c,
6052 >                        s = t.rights;
6053 >                    while (s != null) {
6054 >                        Map.Entry<K,V> tr, sr;
6055 >                        if ((sr = s.result) != null)
6056 >                            t.result = (((tr = t.result) == null) ? sr :
6057 >                                        reducer.apply(tr, sr));
6058 >                        s = t.rights = s.nextRight;
6059                      }
5686                    else if (t.casPending(c, c - 1))
5687                        break;
6060                  }
5689            } catch (Throwable ex) {
5690                return tryCompleteComputation(ex);
5691            }
5692            ReduceEntriesTask<K,V> s = rights;
5693            if (s != null && !inForkJoinPool()) {
5694                do  {
5695                    if (s.tryUnfork())
5696                        s.exec();
5697                } while ((s = s.nextRight) != null);
6061              }
5699            return false;
6062          }
5701        public final Map.Entry<K,V> getRawResult() { return result; }
6063      }
6064  
6065      @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6066 <        extends BulkTask<K,V,U> {
6066 >        extends Traverser<K,V,U> {
6067          final Fun<? super K, ? extends U> transformer;
6068          final BiFun<? super U, ? super U, ? extends U> reducer;
6069          U result;
6070          MapReduceKeysTask<K,V,U> rights, nextRight;
6071          MapReduceKeysTask
6072 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6072 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6073               MapReduceKeysTask<K,V,U> nextRight,
6074               Fun<? super K, ? extends U> transformer,
6075               BiFun<? super U, ? super U, ? extends U> reducer) {
# Line 5716 | Line 6077 | public class ConcurrentHashMapV8<K, V>
6077              this.transformer = transformer;
6078              this.reducer = reducer;
6079          }
6080 <        @SuppressWarnings("unchecked") public final boolean exec() {
6081 <            final Fun<? super K, ? extends U> transformer =
6082 <                this.transformer;
6083 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6084 <                this.reducer;
6085 <            if (transformer == null || reducer == null)
6086 <                return abortOnNullFunction();
5726 <            try {
5727 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5728 <                    do {} while (!casPending(c = pending, c+1));
6080 >        public final U getRawResult() { return result; }
6081 >        @SuppressWarnings("unchecked") public final void compute() {
6082 >            final Fun<? super K, ? extends U> transformer;
6083 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6084 >            if ((transformer = this.transformer) != null &&
6085 >                (reducer = this.reducer) != null) {
6086 >                for (int b; (b = preSplit()) > 0;)
6087                      (rights = new MapReduceKeysTask<K,V,U>
6088 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5731 <                }
6088 >                     (map, this, b, rights, transformer, reducer)).fork();
6089                  U r = null, u;
6090                  while (advance() != null) {
6091                      if ((u = transformer.apply((K)nextKey)) != null)
6092                          r = (r == null) ? u : reducer.apply(r, u);
6093                  }
6094                  result = r;
6095 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
6096 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6097 <                    if ((c = t.pending) == 0) {
6098 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6099 <                            if ((sr = s.result) != null)
6100 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6101 <                        }
6102 <                        if ((par = t.parent) == null ||
6103 <                            !(par instanceof MapReduceKeysTask)) {
6104 <                            t.quietlyComplete();
6105 <                            break;
5749 <                        }
5750 <                        t = (MapReduceKeysTask<K,V,U>)par;
6095 >                CountedCompleter<?> c;
6096 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6097 >                    MapReduceKeysTask<K,V,U>
6098 >                        t = (MapReduceKeysTask<K,V,U>)c,
6099 >                        s = t.rights;
6100 >                    while (s != null) {
6101 >                        U tr, sr;
6102 >                        if ((sr = s.result) != null)
6103 >                            t.result = (((tr = t.result) == null) ? sr :
6104 >                                        reducer.apply(tr, sr));
6105 >                        s = t.rights = s.nextRight;
6106                      }
5752                    else if (t.casPending(c, c - 1))
5753                        break;
6107                  }
5755            } catch (Throwable ex) {
5756                return tryCompleteComputation(ex);
5757            }
5758            MapReduceKeysTask<K,V,U> s = rights;
5759            if (s != null && !inForkJoinPool()) {
5760                do  {
5761                    if (s.tryUnfork())
5762                        s.exec();
5763                } while ((s = s.nextRight) != null);
6108              }
5765            return false;
6109          }
5767        public final U getRawResult() { return result; }
6110      }
6111  
6112      @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6113 <        extends BulkTask<K,V,U> {
6113 >        extends Traverser<K,V,U> {
6114          final Fun<? super V, ? extends U> transformer;
6115          final BiFun<? super U, ? super U, ? extends U> reducer;
6116          U result;
6117          MapReduceValuesTask<K,V,U> rights, nextRight;
6118          MapReduceValuesTask
6119 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6119 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6120               MapReduceValuesTask<K,V,U> nextRight,
6121               Fun<? super V, ? extends U> transformer,
6122               BiFun<? super U, ? super U, ? extends U> reducer) {
# Line 5782 | Line 6124 | public class ConcurrentHashMapV8<K, V>
6124              this.transformer = transformer;
6125              this.reducer = reducer;
6126          }
6127 <        @SuppressWarnings("unchecked") public final boolean exec() {
6128 <            final Fun<? super V, ? extends U> transformer =
6129 <                this.transformer;
6130 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6131 <                this.reducer;
6132 <            if (transformer == null || reducer == null)
6133 <                return abortOnNullFunction();
5792 <            try {
5793 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5794 <                    do {} while (!casPending(c = pending, c+1));
6127 >        public final U getRawResult() { return result; }
6128 >        @SuppressWarnings("unchecked") public final void compute() {
6129 >            final Fun<? super V, ? extends U> transformer;
6130 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6131 >            if ((transformer = this.transformer) != null &&
6132 >                (reducer = this.reducer) != null) {
6133 >                for (int b; (b = preSplit()) > 0;)
6134                      (rights = new MapReduceValuesTask<K,V,U>
6135 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5797 <                }
6135 >                     (map, this, b, rights, transformer, reducer)).fork();
6136                  U r = null, u;
6137 <                Object v;
6137 >                V v;
6138                  while ((v = advance()) != null) {
6139 <                    if ((u = transformer.apply((V)v)) != null)
6139 >                    if ((u = transformer.apply(v)) != null)
6140                          r = (r == null) ? u : reducer.apply(r, u);
6141                  }
6142                  result = r;
6143 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
6144 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6145 <                    if ((c = t.pending) == 0) {
6146 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6147 <                            if ((sr = s.result) != null)
6148 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6149 <                        }
6150 <                        if ((par = t.parent) == null ||
6151 <                            !(par instanceof MapReduceValuesTask)) {
6152 <                            t.quietlyComplete();
6153 <                            break;
5816 <                        }
5817 <                        t = (MapReduceValuesTask<K,V,U>)par;
6143 >                CountedCompleter<?> c;
6144 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6145 >                    MapReduceValuesTask<K,V,U>
6146 >                        t = (MapReduceValuesTask<K,V,U>)c,
6147 >                        s = t.rights;
6148 >                    while (s != null) {
6149 >                        U tr, sr;
6150 >                        if ((sr = s.result) != null)
6151 >                            t.result = (((tr = t.result) == null) ? sr :
6152 >                                        reducer.apply(tr, sr));
6153 >                        s = t.rights = s.nextRight;
6154                      }
5819                    else if (t.casPending(c, c - 1))
5820                        break;
6155                  }
5822            } catch (Throwable ex) {
5823                return tryCompleteComputation(ex);
5824            }
5825            MapReduceValuesTask<K,V,U> s = rights;
5826            if (s != null && !inForkJoinPool()) {
5827                do  {
5828                    if (s.tryUnfork())
5829                        s.exec();
5830                } while ((s = s.nextRight) != null);
6156              }
5832            return false;
6157          }
5834        public final U getRawResult() { return result; }
6158      }
6159  
6160      @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6161 <        extends BulkTask<K,V,U> {
6161 >        extends Traverser<K,V,U> {
6162          final Fun<Map.Entry<K,V>, ? extends U> transformer;
6163          final BiFun<? super U, ? super U, ? extends U> reducer;
6164          U result;
6165          MapReduceEntriesTask<K,V,U> rights, nextRight;
6166          MapReduceEntriesTask
6167 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6167 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6168               MapReduceEntriesTask<K,V,U> nextRight,
6169               Fun<Map.Entry<K,V>, ? extends U> transformer,
6170               BiFun<? super U, ? super U, ? extends U> reducer) {
# Line 5849 | Line 6172 | public class ConcurrentHashMapV8<K, V>
6172              this.transformer = transformer;
6173              this.reducer = reducer;
6174          }
6175 <        @SuppressWarnings("unchecked") public final boolean exec() {
6176 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
6177 <                this.transformer;
6178 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6179 <                this.reducer;
6180 <            if (transformer == null || reducer == null)
6181 <                return abortOnNullFunction();
5859 <            try {
5860 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5861 <                    do {} while (!casPending(c = pending, c+1));
6175 >        public final U getRawResult() { return result; }
6176 >        @SuppressWarnings("unchecked") public final void compute() {
6177 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
6178 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6179 >            if ((transformer = this.transformer) != null &&
6180 >                (reducer = this.reducer) != null) {
6181 >                for (int b; (b = preSplit()) > 0;)
6182                      (rights = new MapReduceEntriesTask<K,V,U>
6183 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5864 <                }
6183 >                     (map, this, b, rights, transformer, reducer)).fork();
6184                  U r = null, u;
6185 <                Object v;
6185 >                V v;
6186                  while ((v = advance()) != null) {
6187 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
6187 >                    if ((u = transformer.apply(entryFor((K)nextKey,
6188 >                                                        v))) != null)
6189                          r = (r == null) ? u : reducer.apply(r, u);
6190                  }
6191                  result = r;
6192 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
6193 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6194 <                    if ((c = t.pending) == 0) {
6195 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6196 <                            if ((sr = s.result) != null)
6197 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6198 <                        }
6199 <                        if ((par = t.parent) == null ||
6200 <                            !(par instanceof MapReduceEntriesTask)) {
6201 <                            t.quietlyComplete();
6202 <                            break;
5883 <                        }
5884 <                        t = (MapReduceEntriesTask<K,V,U>)par;
6192 >                CountedCompleter<?> c;
6193 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6194 >                    MapReduceEntriesTask<K,V,U>
6195 >                        t = (MapReduceEntriesTask<K,V,U>)c,
6196 >                        s = t.rights;
6197 >                    while (s != null) {
6198 >                        U tr, sr;
6199 >                        if ((sr = s.result) != null)
6200 >                            t.result = (((tr = t.result) == null) ? sr :
6201 >                                        reducer.apply(tr, sr));
6202 >                        s = t.rights = s.nextRight;
6203                      }
5886                    else if (t.casPending(c, c - 1))
5887                        break;
6204                  }
5889            } catch (Throwable ex) {
5890                return tryCompleteComputation(ex);
6205              }
5892            MapReduceEntriesTask<K,V,U> s = rights;
5893            if (s != null && !inForkJoinPool()) {
5894                do  {
5895                    if (s.tryUnfork())
5896                        s.exec();
5897                } while ((s = s.nextRight) != null);
5898            }
5899            return false;
6206          }
5901        public final U getRawResult() { return result; }
6207      }
6208  
6209      @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6210 <        extends BulkTask<K,V,U> {
6210 >        extends Traverser<K,V,U> {
6211          final BiFun<? super K, ? super V, ? extends U> transformer;
6212          final BiFun<? super U, ? super U, ? extends U> reducer;
6213          U result;
6214          MapReduceMappingsTask<K,V,U> rights, nextRight;
6215          MapReduceMappingsTask
6216 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6216 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6217               MapReduceMappingsTask<K,V,U> nextRight,
6218               BiFun<? super K, ? super V, ? extends U> transformer,
6219               BiFun<? super U, ? super U, ? extends U> reducer) {
# Line 5916 | Line 6221 | public class ConcurrentHashMapV8<K, V>
6221              this.transformer = transformer;
6222              this.reducer = reducer;
6223          }
6224 <        @SuppressWarnings("unchecked") public final boolean exec() {
6225 <            final BiFun<? super K, ? super V, ? extends U> transformer =
6226 <                this.transformer;
6227 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6228 <                this.reducer;
6229 <            if (transformer == null || reducer == null)
6230 <                return abortOnNullFunction();
5926 <            try {
5927 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5928 <                    do {} while (!casPending(c = pending, c+1));
6224 >        public final U getRawResult() { return result; }
6225 >        @SuppressWarnings("unchecked") public final void compute() {
6226 >            final BiFun<? super K, ? super V, ? extends U> transformer;
6227 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6228 >            if ((transformer = this.transformer) != null &&
6229 >                (reducer = this.reducer) != null) {
6230 >                for (int b; (b = preSplit()) > 0;)
6231                      (rights = new MapReduceMappingsTask<K,V,U>
6232 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5931 <                }
6232 >                     (map, this, b, rights, transformer, reducer)).fork();
6233                  U r = null, u;
6234 <                Object v;
6234 >                V v;
6235                  while ((v = advance()) != null) {
6236 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
6236 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
6237                          r = (r == null) ? u : reducer.apply(r, u);
6238                  }
6239                  result = r;
6240 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
6241 <                    int c; BulkTask<K,V,?> par; U tr, sr;
6242 <                    if ((c = t.pending) == 0) {
6243 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6244 <                            if ((sr = s.result) != null)
6245 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
6246 <                        }
6247 <                        if ((par = t.parent) == null ||
6248 <                            !(par instanceof MapReduceMappingsTask)) {
6249 <                            t.quietlyComplete();
6250 <                            break;
5950 <                        }
5951 <                        t = (MapReduceMappingsTask<K,V,U>)par;
6240 >                CountedCompleter<?> c;
6241 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6242 >                    MapReduceMappingsTask<K,V,U>
6243 >                        t = (MapReduceMappingsTask<K,V,U>)c,
6244 >                        s = t.rights;
6245 >                    while (s != null) {
6246 >                        U tr, sr;
6247 >                        if ((sr = s.result) != null)
6248 >                            t.result = (((tr = t.result) == null) ? sr :
6249 >                                        reducer.apply(tr, sr));
6250 >                        s = t.rights = s.nextRight;
6251                      }
5953                    else if (t.casPending(c, c - 1))
5954                        break;
6252                  }
5956            } catch (Throwable ex) {
5957                return tryCompleteComputation(ex);
5958            }
5959            MapReduceMappingsTask<K,V,U> s = rights;
5960            if (s != null && !inForkJoinPool()) {
5961                do  {
5962                    if (s.tryUnfork())
5963                        s.exec();
5964                } while ((s = s.nextRight) != null);
6253              }
5966            return false;
6254          }
5968        public final U getRawResult() { return result; }
6255      }
6256  
6257      @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6258 <        extends BulkTask<K,V,Double> {
6258 >        extends Traverser<K,V,Double> {
6259          final ObjectToDouble<? super K> transformer;
6260          final DoubleByDoubleToDouble reducer;
6261          final double basis;
6262          double result;
6263          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6264          MapReduceKeysToDoubleTask
6265 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6265 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6266               MapReduceKeysToDoubleTask<K,V> nextRight,
6267               ObjectToDouble<? super K> transformer,
6268               double basis,
# Line 5985 | Line 6271 | public class ConcurrentHashMapV8<K, V>
6271              this.transformer = transformer;
6272              this.basis = basis; this.reducer = reducer;
6273          }
6274 <        @SuppressWarnings("unchecked") public final boolean exec() {
6275 <            final ObjectToDouble<? super K> transformer =
6276 <                this.transformer;
6277 <            final DoubleByDoubleToDouble reducer = this.reducer;
6278 <            if (transformer == null || reducer == null)
6279 <                return abortOnNullFunction();
6280 <            try {
6281 <                final double id = this.basis;
5996 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5997 <                    do {} while (!casPending(c = pending, c+1));
6274 >        public final Double getRawResult() { return result; }
6275 >        @SuppressWarnings("unchecked") public final void compute() {
6276 >            final ObjectToDouble<? super K> transformer;
6277 >            final DoubleByDoubleToDouble reducer;
6278 >            if ((transformer = this.transformer) != null &&
6279 >                (reducer = this.reducer) != null) {
6280 >                double r = this.basis;
6281 >                for (int b; (b = preSplit()) > 0;)
6282                      (rights = new MapReduceKeysToDoubleTask<K,V>
6283 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6000 <                }
6001 <                double r = id;
6283 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6284                  while (advance() != null)
6285                      r = reducer.apply(r, transformer.apply((K)nextKey));
6286                  result = r;
6287 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
6288 <                    int c; BulkTask<K,V,?> par;
6289 <                    if ((c = t.pending) == 0) {
6290 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6291 <                            t.result = reducer.apply(t.result, s.result);
6292 <                        }
6293 <                        if ((par = t.parent) == null ||
6294 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
6013 <                            t.quietlyComplete();
6014 <                            break;
6015 <                        }
6016 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
6287 >                CountedCompleter<?> c;
6288 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6289 >                    MapReduceKeysToDoubleTask<K,V>
6290 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
6291 >                        s = t.rights;
6292 >                    while (s != null) {
6293 >                        t.result = reducer.apply(t.result, s.result);
6294 >                        s = t.rights = s.nextRight;
6295                      }
6018                    else if (t.casPending(c, c - 1))
6019                        break;
6296                  }
6021            } catch (Throwable ex) {
6022                return tryCompleteComputation(ex);
6297              }
6024            MapReduceKeysToDoubleTask<K,V> s = rights;
6025            if (s != null && !inForkJoinPool()) {
6026                do  {
6027                    if (s.tryUnfork())
6028                        s.exec();
6029                } while ((s = s.nextRight) != null);
6030            }
6031            return false;
6298          }
6033        public final Double getRawResult() { return result; }
6299      }
6300  
6301      @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6302 <        extends BulkTask<K,V,Double> {
6302 >        extends Traverser<K,V,Double> {
6303          final ObjectToDouble<? super V> transformer;
6304          final DoubleByDoubleToDouble reducer;
6305          final double basis;
6306          double result;
6307          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6308          MapReduceValuesToDoubleTask
6309 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6309 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6310               MapReduceValuesToDoubleTask<K,V> nextRight,
6311               ObjectToDouble<? super V> transformer,
6312               double basis,
# Line 6050 | Line 6315 | public class ConcurrentHashMapV8<K, V>
6315              this.transformer = transformer;
6316              this.basis = basis; this.reducer = reducer;
6317          }
6318 <        @SuppressWarnings("unchecked") public final boolean exec() {
6319 <            final ObjectToDouble<? super V> transformer =
6320 <                this.transformer;
6321 <            final DoubleByDoubleToDouble reducer = this.reducer;
6322 <            if (transformer == null || reducer == null)
6323 <                return abortOnNullFunction();
6324 <            try {
6325 <                final double id = this.basis;
6061 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6062 <                    do {} while (!casPending(c = pending, c+1));
6318 >        public final Double getRawResult() { return result; }
6319 >        @SuppressWarnings("unchecked") public final void compute() {
6320 >            final ObjectToDouble<? super V> transformer;
6321 >            final DoubleByDoubleToDouble reducer;
6322 >            if ((transformer = this.transformer) != null &&
6323 >                (reducer = this.reducer) != null) {
6324 >                double r = this.basis;
6325 >                for (int b; (b = preSplit()) > 0;)
6326                      (rights = new MapReduceValuesToDoubleTask<K,V>
6327 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6328 <                }
6066 <                double r = id;
6067 <                Object v;
6327 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6328 >                V v;
6329                  while ((v = advance()) != null)
6330 <                    r = reducer.apply(r, transformer.apply((V)v));
6330 >                    r = reducer.apply(r, transformer.apply(v));
6331                  result = r;
6332 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
6333 <                    int c; BulkTask<K,V,?> par;
6334 <                    if ((c = t.pending) == 0) {
6335 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6336 <                            t.result = reducer.apply(t.result, s.result);
6337 <                        }
6338 <                        if ((par = t.parent) == null ||
6339 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
6079 <                            t.quietlyComplete();
6080 <                            break;
6081 <                        }
6082 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
6332 >                CountedCompleter<?> c;
6333 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6334 >                    MapReduceValuesToDoubleTask<K,V>
6335 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
6336 >                        s = t.rights;
6337 >                    while (s != null) {
6338 >                        t.result = reducer.apply(t.result, s.result);
6339 >                        s = t.rights = s.nextRight;
6340                      }
6084                    else if (t.casPending(c, c - 1))
6085                        break;
6341                  }
6087            } catch (Throwable ex) {
6088                return tryCompleteComputation(ex);
6089            }
6090            MapReduceValuesToDoubleTask<K,V> s = rights;
6091            if (s != null && !inForkJoinPool()) {
6092                do  {
6093                    if (s.tryUnfork())
6094                        s.exec();
6095                } while ((s = s.nextRight) != null);
6342              }
6097            return false;
6343          }
6099        public final Double getRawResult() { return result; }
6344      }
6345  
6346      @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6347 <        extends BulkTask<K,V,Double> {
6347 >        extends Traverser<K,V,Double> {
6348          final ObjectToDouble<Map.Entry<K,V>> transformer;
6349          final DoubleByDoubleToDouble reducer;
6350          final double basis;
6351          double result;
6352          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6353          MapReduceEntriesToDoubleTask
6354 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6354 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6355               MapReduceEntriesToDoubleTask<K,V> nextRight,
6356               ObjectToDouble<Map.Entry<K,V>> transformer,
6357               double basis,
# Line 6116 | Line 6360 | public class ConcurrentHashMapV8<K, V>
6360              this.transformer = transformer;
6361              this.basis = basis; this.reducer = reducer;
6362          }
6363 <        @SuppressWarnings("unchecked") public final boolean exec() {
6364 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
6365 <                this.transformer;
6366 <            final DoubleByDoubleToDouble reducer = this.reducer;
6367 <            if (transformer == null || reducer == null)
6368 <                return abortOnNullFunction();
6369 <            try {
6370 <                final double id = this.basis;
6127 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6128 <                    do {} while (!casPending(c = pending, c+1));
6363 >        public final Double getRawResult() { return result; }
6364 >        @SuppressWarnings("unchecked") public final void compute() {
6365 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
6366 >            final DoubleByDoubleToDouble reducer;
6367 >            if ((transformer = this.transformer) != null &&
6368 >                (reducer = this.reducer) != null) {
6369 >                double r = this.basis;
6370 >                for (int b; (b = preSplit()) > 0;)
6371                      (rights = new MapReduceEntriesToDoubleTask<K,V>
6372 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6373 <                }
6132 <                double r = id;
6133 <                Object v;
6372 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6373 >                V v;
6374                  while ((v = advance()) != null)
6375 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6375 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6376 >                                                                    v)));
6377                  result = r;
6378 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
6379 <                    int c; BulkTask<K,V,?> par;
6380 <                    if ((c = t.pending) == 0) {
6381 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6382 <                            t.result = reducer.apply(t.result, s.result);
6383 <                        }
6384 <                        if ((par = t.parent) == null ||
6385 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
6145 <                            t.quietlyComplete();
6146 <                            break;
6147 <                        }
6148 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
6378 >                CountedCompleter<?> c;
6379 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6380 >                    MapReduceEntriesToDoubleTask<K,V>
6381 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
6382 >                        s = t.rights;
6383 >                    while (s != null) {
6384 >                        t.result = reducer.apply(t.result, s.result);
6385 >                        s = t.rights = s.nextRight;
6386                      }
6150                    else if (t.casPending(c, c - 1))
6151                        break;
6387                  }
6153            } catch (Throwable ex) {
6154                return tryCompleteComputation(ex);
6388              }
6156            MapReduceEntriesToDoubleTask<K,V> s = rights;
6157            if (s != null && !inForkJoinPool()) {
6158                do  {
6159                    if (s.tryUnfork())
6160                        s.exec();
6161                } while ((s = s.nextRight) != null);
6162            }
6163            return false;
6389          }
6165        public final Double getRawResult() { return result; }
6390      }
6391  
6392      @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6393 <        extends BulkTask<K,V,Double> {
6393 >        extends Traverser<K,V,Double> {
6394          final ObjectByObjectToDouble<? super K, ? super V> transformer;
6395          final DoubleByDoubleToDouble reducer;
6396          final double basis;
6397          double result;
6398          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6399          MapReduceMappingsToDoubleTask
6400 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6400 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6401               MapReduceMappingsToDoubleTask<K,V> nextRight,
6402               ObjectByObjectToDouble<? super K, ? super V> transformer,
6403               double basis,
# Line 6182 | Line 6406 | public class ConcurrentHashMapV8<K, V>
6406              this.transformer = transformer;
6407              this.basis = basis; this.reducer = reducer;
6408          }
6409 <        @SuppressWarnings("unchecked") public final boolean exec() {
6410 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
6411 <                this.transformer;
6412 <            final DoubleByDoubleToDouble reducer = this.reducer;
6413 <            if (transformer == null || reducer == null)
6414 <                return abortOnNullFunction();
6415 <            try {
6416 <                final double id = this.basis;
6193 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6194 <                    do {} while (!casPending(c = pending, c+1));
6409 >        public final Double getRawResult() { return result; }
6410 >        @SuppressWarnings("unchecked") public final void compute() {
6411 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
6412 >            final DoubleByDoubleToDouble reducer;
6413 >            if ((transformer = this.transformer) != null &&
6414 >                (reducer = this.reducer) != null) {
6415 >                double r = this.basis;
6416 >                for (int b; (b = preSplit()) > 0;)
6417                      (rights = new MapReduceMappingsToDoubleTask<K,V>
6418 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6419 <                }
6198 <                double r = id;
6199 <                Object v;
6418 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6419 >                V v;
6420                  while ((v = advance()) != null)
6421 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6421 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6422                  result = r;
6423 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
6424 <                    int c; BulkTask<K,V,?> par;
6425 <                    if ((c = t.pending) == 0) {
6426 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6427 <                            t.result = reducer.apply(t.result, s.result);
6428 <                        }
6429 <                        if ((par = t.parent) == null ||
6430 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6211 <                            t.quietlyComplete();
6212 <                            break;
6213 <                        }
6214 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
6423 >                CountedCompleter<?> c;
6424 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6425 >                    MapReduceMappingsToDoubleTask<K,V>
6426 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
6427 >                        s = t.rights;
6428 >                    while (s != null) {
6429 >                        t.result = reducer.apply(t.result, s.result);
6430 >                        s = t.rights = s.nextRight;
6431                      }
6216                    else if (t.casPending(c, c - 1))
6217                        break;
6432                  }
6219            } catch (Throwable ex) {
6220                return tryCompleteComputation(ex);
6221            }
6222            MapReduceMappingsToDoubleTask<K,V> s = rights;
6223            if (s != null && !inForkJoinPool()) {
6224                do  {
6225                    if (s.tryUnfork())
6226                        s.exec();
6227                } while ((s = s.nextRight) != null);
6433              }
6229            return false;
6434          }
6231        public final Double getRawResult() { return result; }
6435      }
6436  
6437      @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6438 <        extends BulkTask<K,V,Long> {
6438 >        extends Traverser<K,V,Long> {
6439          final ObjectToLong<? super K> transformer;
6440          final LongByLongToLong reducer;
6441          final long basis;
6442          long result;
6443          MapReduceKeysToLongTask<K,V> rights, nextRight;
6444          MapReduceKeysToLongTask
6445 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6445 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6446               MapReduceKeysToLongTask<K,V> nextRight,
6447               ObjectToLong<? super K> transformer,
6448               long basis,
# Line 6248 | Line 6451 | public class ConcurrentHashMapV8<K, V>
6451              this.transformer = transformer;
6452              this.basis = basis; this.reducer = reducer;
6453          }
6454 <        @SuppressWarnings("unchecked") public final boolean exec() {
6455 <            final ObjectToLong<? super K> transformer =
6456 <                this.transformer;
6457 <            final LongByLongToLong reducer = this.reducer;
6458 <            if (transformer == null || reducer == null)
6459 <                return abortOnNullFunction();
6460 <            try {
6461 <                final long id = this.basis;
6259 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6260 <                    do {} while (!casPending(c = pending, c+1));
6454 >        public final Long getRawResult() { return result; }
6455 >        @SuppressWarnings("unchecked") public final void compute() {
6456 >            final ObjectToLong<? super K> transformer;
6457 >            final LongByLongToLong reducer;
6458 >            if ((transformer = this.transformer) != null &&
6459 >                (reducer = this.reducer) != null) {
6460 >                long r = this.basis;
6461 >                for (int b; (b = preSplit()) > 0;)
6462                      (rights = new MapReduceKeysToLongTask<K,V>
6463 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6263 <                }
6264 <                long r = id;
6463 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6464                  while (advance() != null)
6465                      r = reducer.apply(r, transformer.apply((K)nextKey));
6466                  result = r;
6467 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
6468 <                    int c; BulkTask<K,V,?> par;
6469 <                    if ((c = t.pending) == 0) {
6470 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6471 <                            t.result = reducer.apply(t.result, s.result);
6472 <                        }
6473 <                        if ((par = t.parent) == null ||
6474 <                            !(par instanceof MapReduceKeysToLongTask)) {
6276 <                            t.quietlyComplete();
6277 <                            break;
6278 <                        }
6279 <                        t = (MapReduceKeysToLongTask<K,V>)par;
6467 >                CountedCompleter<?> c;
6468 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6469 >                    MapReduceKeysToLongTask<K,V>
6470 >                        t = (MapReduceKeysToLongTask<K,V>)c,
6471 >                        s = t.rights;
6472 >                    while (s != null) {
6473 >                        t.result = reducer.apply(t.result, s.result);
6474 >                        s = t.rights = s.nextRight;
6475                      }
6281                    else if (t.casPending(c, c - 1))
6282                        break;
6476                  }
6284            } catch (Throwable ex) {
6285                return tryCompleteComputation(ex);
6286            }
6287            MapReduceKeysToLongTask<K,V> s = rights;
6288            if (s != null && !inForkJoinPool()) {
6289                do  {
6290                    if (s.tryUnfork())
6291                        s.exec();
6292                } while ((s = s.nextRight) != null);
6477              }
6294            return false;
6478          }
6296        public final Long getRawResult() { return result; }
6479      }
6480  
6481      @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6482 <        extends BulkTask<K,V,Long> {
6482 >        extends Traverser<K,V,Long> {
6483          final ObjectToLong<? super V> transformer;
6484          final LongByLongToLong reducer;
6485          final long basis;
6486          long result;
6487          MapReduceValuesToLongTask<K,V> rights, nextRight;
6488          MapReduceValuesToLongTask
6489 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6489 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6490               MapReduceValuesToLongTask<K,V> nextRight,
6491               ObjectToLong<? super V> transformer,
6492               long basis,
# Line 6313 | Line 6495 | public class ConcurrentHashMapV8<K, V>
6495              this.transformer = transformer;
6496              this.basis = basis; this.reducer = reducer;
6497          }
6498 <        @SuppressWarnings("unchecked") public final boolean exec() {
6499 <            final ObjectToLong<? super V> transformer =
6500 <                this.transformer;
6501 <            final LongByLongToLong reducer = this.reducer;
6502 <            if (transformer == null || reducer == null)
6503 <                return abortOnNullFunction();
6504 <            try {
6505 <                final long id = this.basis;
6324 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6325 <                    do {} while (!casPending(c = pending, c+1));
6498 >        public final Long getRawResult() { return result; }
6499 >        @SuppressWarnings("unchecked") public final void compute() {
6500 >            final ObjectToLong<? super V> transformer;
6501 >            final LongByLongToLong reducer;
6502 >            if ((transformer = this.transformer) != null &&
6503 >                (reducer = this.reducer) != null) {
6504 >                long r = this.basis;
6505 >                for (int b; (b = preSplit()) > 0;)
6506                      (rights = new MapReduceValuesToLongTask<K,V>
6507 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6508 <                }
6329 <                long r = id;
6330 <                Object v;
6507 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6508 >                V v;
6509                  while ((v = advance()) != null)
6510 <                    r = reducer.apply(r, transformer.apply((V)v));
6510 >                    r = reducer.apply(r, transformer.apply(v));
6511                  result = r;
6512 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
6513 <                    int c; BulkTask<K,V,?> par;
6514 <                    if ((c = t.pending) == 0) {
6515 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6516 <                            t.result = reducer.apply(t.result, s.result);
6517 <                        }
6518 <                        if ((par = t.parent) == null ||
6519 <                            !(par instanceof MapReduceValuesToLongTask)) {
6342 <                            t.quietlyComplete();
6343 <                            break;
6344 <                        }
6345 <                        t = (MapReduceValuesToLongTask<K,V>)par;
6512 >                CountedCompleter<?> c;
6513 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6514 >                    MapReduceValuesToLongTask<K,V>
6515 >                        t = (MapReduceValuesToLongTask<K,V>)c,
6516 >                        s = t.rights;
6517 >                    while (s != null) {
6518 >                        t.result = reducer.apply(t.result, s.result);
6519 >                        s = t.rights = s.nextRight;
6520                      }
6347                    else if (t.casPending(c, c - 1))
6348                        break;
6521                  }
6350            } catch (Throwable ex) {
6351                return tryCompleteComputation(ex);
6352            }
6353            MapReduceValuesToLongTask<K,V> s = rights;
6354            if (s != null && !inForkJoinPool()) {
6355                do  {
6356                    if (s.tryUnfork())
6357                        s.exec();
6358                } while ((s = s.nextRight) != null);
6522              }
6360            return false;
6523          }
6362        public final Long getRawResult() { return result; }
6524      }
6525  
6526      @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6527 <        extends BulkTask<K,V,Long> {
6527 >        extends Traverser<K,V,Long> {
6528          final ObjectToLong<Map.Entry<K,V>> transformer;
6529          final LongByLongToLong reducer;
6530          final long basis;
6531          long result;
6532          MapReduceEntriesToLongTask<K,V> rights, nextRight;
6533          MapReduceEntriesToLongTask
6534 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6534 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6535               MapReduceEntriesToLongTask<K,V> nextRight,
6536               ObjectToLong<Map.Entry<K,V>> transformer,
6537               long basis,
# Line 6379 | Line 6540 | public class ConcurrentHashMapV8<K, V>
6540              this.transformer = transformer;
6541              this.basis = basis; this.reducer = reducer;
6542          }
6543 <        @SuppressWarnings("unchecked") public final boolean exec() {
6544 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6545 <                this.transformer;
6546 <            final LongByLongToLong reducer = this.reducer;
6547 <            if (transformer == null || reducer == null)
6548 <                return abortOnNullFunction();
6549 <            try {
6550 <                final long id = this.basis;
6390 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6391 <                    do {} while (!casPending(c = pending, c+1));
6543 >        public final Long getRawResult() { return result; }
6544 >        @SuppressWarnings("unchecked") public final void compute() {
6545 >            final ObjectToLong<Map.Entry<K,V>> transformer;
6546 >            final LongByLongToLong reducer;
6547 >            if ((transformer = this.transformer) != null &&
6548 >                (reducer = this.reducer) != null) {
6549 >                long r = this.basis;
6550 >                for (int b; (b = preSplit()) > 0;)
6551                      (rights = new MapReduceEntriesToLongTask<K,V>
6552 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6553 <                }
6395 <                long r = id;
6396 <                Object v;
6552 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6553 >                V v;
6554                  while ((v = advance()) != null)
6555 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6555 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6556 >                                                                    v)));
6557                  result = r;
6558 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
6559 <                    int c; BulkTask<K,V,?> par;
6560 <                    if ((c = t.pending) == 0) {
6561 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6562 <                            t.result = reducer.apply(t.result, s.result);
6563 <                        }
6564 <                        if ((par = t.parent) == null ||
6565 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6408 <                            t.quietlyComplete();
6409 <                            break;
6410 <                        }
6411 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
6558 >                CountedCompleter<?> c;
6559 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6560 >                    MapReduceEntriesToLongTask<K,V>
6561 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6562 >                        s = t.rights;
6563 >                    while (s != null) {
6564 >                        t.result = reducer.apply(t.result, s.result);
6565 >                        s = t.rights = s.nextRight;
6566                      }
6413                    else if (t.casPending(c, c - 1))
6414                        break;
6567                  }
6416            } catch (Throwable ex) {
6417                return tryCompleteComputation(ex);
6568              }
6419            MapReduceEntriesToLongTask<K,V> s = rights;
6420            if (s != null && !inForkJoinPool()) {
6421                do  {
6422                    if (s.tryUnfork())
6423                        s.exec();
6424                } while ((s = s.nextRight) != null);
6425            }
6426            return false;
6569          }
6428        public final Long getRawResult() { return result; }
6570      }
6571  
6572      @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6573 <        extends BulkTask<K,V,Long> {
6573 >        extends Traverser<K,V,Long> {
6574          final ObjectByObjectToLong<? super K, ? super V> transformer;
6575          final LongByLongToLong reducer;
6576          final long basis;
6577          long result;
6578          MapReduceMappingsToLongTask<K,V> rights, nextRight;
6579          MapReduceMappingsToLongTask
6580 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6580 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6581               MapReduceMappingsToLongTask<K,V> nextRight,
6582               ObjectByObjectToLong<? super K, ? super V> transformer,
6583               long basis,
# Line 6445 | Line 6586 | public class ConcurrentHashMapV8<K, V>
6586              this.transformer = transformer;
6587              this.basis = basis; this.reducer = reducer;
6588          }
6589 <        @SuppressWarnings("unchecked") public final boolean exec() {
6590 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6591 <                this.transformer;
6592 <            final LongByLongToLong reducer = this.reducer;
6593 <            if (transformer == null || reducer == null)
6594 <                return abortOnNullFunction();
6595 <            try {
6596 <                final long id = this.basis;
6456 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6457 <                    do {} while (!casPending(c = pending, c+1));
6589 >        public final Long getRawResult() { return result; }
6590 >        @SuppressWarnings("unchecked") public final void compute() {
6591 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
6592 >            final LongByLongToLong reducer;
6593 >            if ((transformer = this.transformer) != null &&
6594 >                (reducer = this.reducer) != null) {
6595 >                long r = this.basis;
6596 >                for (int b; (b = preSplit()) > 0;)
6597                      (rights = new MapReduceMappingsToLongTask<K,V>
6598 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6599 <                }
6461 <                long r = id;
6462 <                Object v;
6598 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6599 >                V v;
6600                  while ((v = advance()) != null)
6601 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6601 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6602                  result = r;
6603 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
6604 <                    int c; BulkTask<K,V,?> par;
6605 <                    if ((c = t.pending) == 0) {
6606 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6607 <                            t.result = reducer.apply(t.result, s.result);
6608 <                        }
6609 <                        if ((par = t.parent) == null ||
6610 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6474 <                            t.quietlyComplete();
6475 <                            break;
6476 <                        }
6477 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
6603 >                CountedCompleter<?> c;
6604 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6605 >                    MapReduceMappingsToLongTask<K,V>
6606 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6607 >                        s = t.rights;
6608 >                    while (s != null) {
6609 >                        t.result = reducer.apply(t.result, s.result);
6610 >                        s = t.rights = s.nextRight;
6611                      }
6479                    else if (t.casPending(c, c - 1))
6480                        break;
6612                  }
6482            } catch (Throwable ex) {
6483                return tryCompleteComputation(ex);
6484            }
6485            MapReduceMappingsToLongTask<K,V> s = rights;
6486            if (s != null && !inForkJoinPool()) {
6487                do  {
6488                    if (s.tryUnfork())
6489                        s.exec();
6490                } while ((s = s.nextRight) != null);
6613              }
6492            return false;
6614          }
6494        public final Long getRawResult() { return result; }
6615      }
6616  
6617      @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6618 <        extends BulkTask<K,V,Integer> {
6618 >        extends Traverser<K,V,Integer> {
6619          final ObjectToInt<? super K> transformer;
6620          final IntByIntToInt reducer;
6621          final int basis;
6622          int result;
6623          MapReduceKeysToIntTask<K,V> rights, nextRight;
6624          MapReduceKeysToIntTask
6625 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6625 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6626               MapReduceKeysToIntTask<K,V> nextRight,
6627               ObjectToInt<? super K> transformer,
6628               int basis,
# Line 6511 | Line 6631 | public class ConcurrentHashMapV8<K, V>
6631              this.transformer = transformer;
6632              this.basis = basis; this.reducer = reducer;
6633          }
6634 <        @SuppressWarnings("unchecked") public final boolean exec() {
6635 <            final ObjectToInt<? super K> transformer =
6636 <                this.transformer;
6637 <            final IntByIntToInt reducer = this.reducer;
6638 <            if (transformer == null || reducer == null)
6639 <                return abortOnNullFunction();
6640 <            try {
6641 <                final int id = this.basis;
6522 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6523 <                    do {} while (!casPending(c = pending, c+1));
6634 >        public final Integer getRawResult() { return result; }
6635 >        @SuppressWarnings("unchecked") public final void compute() {
6636 >            final ObjectToInt<? super K> transformer;
6637 >            final IntByIntToInt reducer;
6638 >            if ((transformer = this.transformer) != null &&
6639 >                (reducer = this.reducer) != null) {
6640 >                int r = this.basis;
6641 >                for (int b; (b = preSplit()) > 0;)
6642                      (rights = new MapReduceKeysToIntTask<K,V>
6643 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6526 <                }
6527 <                int r = id;
6643 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6644                  while (advance() != null)
6645                      r = reducer.apply(r, transformer.apply((K)nextKey));
6646                  result = r;
6647 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
6648 <                    int c; BulkTask<K,V,?> par;
6649 <                    if ((c = t.pending) == 0) {
6650 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6651 <                            t.result = reducer.apply(t.result, s.result);
6652 <                        }
6653 <                        if ((par = t.parent) == null ||
6654 <                            !(par instanceof MapReduceKeysToIntTask)) {
6539 <                            t.quietlyComplete();
6540 <                            break;
6541 <                        }
6542 <                        t = (MapReduceKeysToIntTask<K,V>)par;
6647 >                CountedCompleter<?> c;
6648 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6649 >                    MapReduceKeysToIntTask<K,V>
6650 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6651 >                        s = t.rights;
6652 >                    while (s != null) {
6653 >                        t.result = reducer.apply(t.result, s.result);
6654 >                        s = t.rights = s.nextRight;
6655                      }
6544                    else if (t.casPending(c, c - 1))
6545                        break;
6656                  }
6547            } catch (Throwable ex) {
6548                return tryCompleteComputation(ex);
6657              }
6550            MapReduceKeysToIntTask<K,V> s = rights;
6551            if (s != null && !inForkJoinPool()) {
6552                do  {
6553                    if (s.tryUnfork())
6554                        s.exec();
6555                } while ((s = s.nextRight) != null);
6556            }
6557            return false;
6658          }
6559        public final Integer getRawResult() { return result; }
6659      }
6660  
6661      @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6662 <        extends BulkTask<K,V,Integer> {
6662 >        extends Traverser<K,V,Integer> {
6663          final ObjectToInt<? super V> transformer;
6664          final IntByIntToInt reducer;
6665          final int basis;
6666          int result;
6667          MapReduceValuesToIntTask<K,V> rights, nextRight;
6668          MapReduceValuesToIntTask
6669 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6669 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6670               MapReduceValuesToIntTask<K,V> nextRight,
6671               ObjectToInt<? super V> transformer,
6672               int basis,
# Line 6576 | Line 6675 | public class ConcurrentHashMapV8<K, V>
6675              this.transformer = transformer;
6676              this.basis = basis; this.reducer = reducer;
6677          }
6678 <        @SuppressWarnings("unchecked") public final boolean exec() {
6679 <            final ObjectToInt<? super V> transformer =
6680 <                this.transformer;
6681 <            final IntByIntToInt reducer = this.reducer;
6682 <            if (transformer == null || reducer == null)
6683 <                return abortOnNullFunction();
6684 <            try {
6685 <                final int id = this.basis;
6587 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6588 <                    do {} while (!casPending(c = pending, c+1));
6678 >        public final Integer getRawResult() { return result; }
6679 >        @SuppressWarnings("unchecked") public final void compute() {
6680 >            final ObjectToInt<? super V> transformer;
6681 >            final IntByIntToInt reducer;
6682 >            if ((transformer = this.transformer) != null &&
6683 >                (reducer = this.reducer) != null) {
6684 >                int r = this.basis;
6685 >                for (int b; (b = preSplit()) > 0;)
6686                      (rights = new MapReduceValuesToIntTask<K,V>
6687 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6688 <                }
6592 <                int r = id;
6593 <                Object v;
6687 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6688 >                V v;
6689                  while ((v = advance()) != null)
6690 <                    r = reducer.apply(r, transformer.apply((V)v));
6690 >                    r = reducer.apply(r, transformer.apply(v));
6691                  result = r;
6692 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
6693 <                    int c; BulkTask<K,V,?> par;
6694 <                    if ((c = t.pending) == 0) {
6695 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6696 <                            t.result = reducer.apply(t.result, s.result);
6697 <                        }
6698 <                        if ((par = t.parent) == null ||
6699 <                            !(par instanceof MapReduceValuesToIntTask)) {
6605 <                            t.quietlyComplete();
6606 <                            break;
6607 <                        }
6608 <                        t = (MapReduceValuesToIntTask<K,V>)par;
6692 >                CountedCompleter<?> c;
6693 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6694 >                    MapReduceValuesToIntTask<K,V>
6695 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6696 >                        s = t.rights;
6697 >                    while (s != null) {
6698 >                        t.result = reducer.apply(t.result, s.result);
6699 >                        s = t.rights = s.nextRight;
6700                      }
6610                    else if (t.casPending(c, c - 1))
6611                        break;
6701                  }
6613            } catch (Throwable ex) {
6614                return tryCompleteComputation(ex);
6702              }
6616            MapReduceValuesToIntTask<K,V> s = rights;
6617            if (s != null && !inForkJoinPool()) {
6618                do  {
6619                    if (s.tryUnfork())
6620                        s.exec();
6621                } while ((s = s.nextRight) != null);
6622            }
6623            return false;
6703          }
6625        public final Integer getRawResult() { return result; }
6704      }
6705  
6706      @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6707 <        extends BulkTask<K,V,Integer> {
6707 >        extends Traverser<K,V,Integer> {
6708          final ObjectToInt<Map.Entry<K,V>> transformer;
6709          final IntByIntToInt reducer;
6710          final int basis;
6711          int result;
6712          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6713          MapReduceEntriesToIntTask
6714 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6714 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6715               MapReduceEntriesToIntTask<K,V> nextRight,
6716               ObjectToInt<Map.Entry<K,V>> transformer,
6717               int basis,
# Line 6642 | Line 6720 | public class ConcurrentHashMapV8<K, V>
6720              this.transformer = transformer;
6721              this.basis = basis; this.reducer = reducer;
6722          }
6723 <        @SuppressWarnings("unchecked") public final boolean exec() {
6724 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6725 <                this.transformer;
6726 <            final IntByIntToInt reducer = this.reducer;
6727 <            if (transformer == null || reducer == null)
6728 <                return abortOnNullFunction();
6729 <            try {
6730 <                final int id = this.basis;
6653 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6654 <                    do {} while (!casPending(c = pending, c+1));
6723 >        public final Integer getRawResult() { return result; }
6724 >        @SuppressWarnings("unchecked") public final void compute() {
6725 >            final ObjectToInt<Map.Entry<K,V>> transformer;
6726 >            final IntByIntToInt reducer;
6727 >            if ((transformer = this.transformer) != null &&
6728 >                (reducer = this.reducer) != null) {
6729 >                int r = this.basis;
6730 >                for (int b; (b = preSplit()) > 0;)
6731                      (rights = new MapReduceEntriesToIntTask<K,V>
6732 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6733 <                }
6658 <                int r = id;
6659 <                Object v;
6732 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6733 >                V v;
6734                  while ((v = advance()) != null)
6735 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6735 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6736 >                                                                    v)));
6737                  result = r;
6738 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
6739 <                    int c; BulkTask<K,V,?> par;
6740 <                    if ((c = t.pending) == 0) {
6741 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6742 <                            t.result = reducer.apply(t.result, s.result);
6743 <                        }
6744 <                        if ((par = t.parent) == null ||
6745 <                            !(par instanceof MapReduceEntriesToIntTask)) {
6671 <                            t.quietlyComplete();
6672 <                            break;
6673 <                        }
6674 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
6738 >                CountedCompleter<?> c;
6739 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6740 >                    MapReduceEntriesToIntTask<K,V>
6741 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6742 >                        s = t.rights;
6743 >                    while (s != null) {
6744 >                        t.result = reducer.apply(t.result, s.result);
6745 >                        s = t.rights = s.nextRight;
6746                      }
6676                    else if (t.casPending(c, c - 1))
6677                        break;
6747                  }
6679            } catch (Throwable ex) {
6680                return tryCompleteComputation(ex);
6681            }
6682            MapReduceEntriesToIntTask<K,V> s = rights;
6683            if (s != null && !inForkJoinPool()) {
6684                do  {
6685                    if (s.tryUnfork())
6686                        s.exec();
6687                } while ((s = s.nextRight) != null);
6748              }
6689            return false;
6749          }
6691        public final Integer getRawResult() { return result; }
6750      }
6751  
6752      @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6753 <        extends BulkTask<K,V,Integer> {
6753 >        extends Traverser<K,V,Integer> {
6754          final ObjectByObjectToInt<? super K, ? super V> transformer;
6755          final IntByIntToInt reducer;
6756          final int basis;
6757          int result;
6758          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6759          MapReduceMappingsToIntTask
6760 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
6761 <             MapReduceMappingsToIntTask<K,V> rights,
6760 >            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6761 >             MapReduceMappingsToIntTask<K,V> nextRight,
6762               ObjectByObjectToInt<? super K, ? super V> transformer,
6763               int basis,
6764               IntByIntToInt reducer) {
# Line 6708 | Line 6766 | public class ConcurrentHashMapV8<K, V>
6766              this.transformer = transformer;
6767              this.basis = basis; this.reducer = reducer;
6768          }
6769 <        @SuppressWarnings("unchecked") public final boolean exec() {
6770 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6771 <                this.transformer;
6772 <            final IntByIntToInt reducer = this.reducer;
6773 <            if (transformer == null || reducer == null)
6774 <                return abortOnNullFunction();
6775 <            try {
6776 <                final int id = this.basis;
6719 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
6720 <                    do {} while (!casPending(c = pending, c+1));
6769 >        public final Integer getRawResult() { return result; }
6770 >        @SuppressWarnings("unchecked") public final void compute() {
6771 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
6772 >            final IntByIntToInt reducer;
6773 >            if ((transformer = this.transformer) != null &&
6774 >                (reducer = this.reducer) != null) {
6775 >                int r = this.basis;
6776 >                for (int b; (b = preSplit()) > 0;)
6777                      (rights = new MapReduceMappingsToIntTask<K,V>
6778 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
6779 <                }
6724 <                int r = id;
6725 <                Object v;
6778 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6779 >                V v;
6780                  while ((v = advance()) != null)
6781 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6781 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6782                  result = r;
6783 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
6784 <                    int c; BulkTask<K,V,?> par;
6785 <                    if ((c = t.pending) == 0) {
6786 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
6787 <                            t.result = reducer.apply(t.result, s.result);
6788 <                        }
6789 <                        if ((par = t.parent) == null ||
6790 <                            !(par instanceof MapReduceMappingsToIntTask)) {
6737 <                            t.quietlyComplete();
6738 <                            break;
6739 <                        }
6740 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6783 >                CountedCompleter<?> c;
6784 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6785 >                    MapReduceMappingsToIntTask<K,V>
6786 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6787 >                        s = t.rights;
6788 >                    while (s != null) {
6789 >                        t.result = reducer.apply(t.result, s.result);
6790 >                        s = t.rights = s.nextRight;
6791                      }
6742                    else if (t.casPending(c, c - 1))
6743                        break;
6792                  }
6745            } catch (Throwable ex) {
6746                return tryCompleteComputation(ex);
6747            }
6748            MapReduceMappingsToIntTask<K,V> s = rights;
6749            if (s != null && !inForkJoinPool()) {
6750                do  {
6751                    if (s.tryUnfork())
6752                        s.exec();
6753                } while ((s = s.nextRight) != null);
6793              }
6755            return false;
6794          }
6757        public final Integer getRawResult() { return result; }
6795      }
6796  
6760
6797      // Unsafe mechanics
6798 <    private static final sun.misc.Unsafe UNSAFE;
6799 <    private static final long counterOffset;
6800 <    private static final long sizeCtlOffset;
6798 >    private static final sun.misc.Unsafe U;
6799 >    private static final long SIZECTL;
6800 >    private static final long TRANSFERINDEX;
6801 >    private static final long TRANSFERORIGIN;
6802 >    private static final long BASECOUNT;
6803 >    private static final long COUNTERBUSY;
6804 >    private static final long CELLVALUE;
6805      private static final long ABASE;
6806      private static final int ASHIFT;
6807  
6808      static {
6809          int ss;
6810          try {
6811 <            UNSAFE = getUnsafe();
6811 >            U = getUnsafe();
6812              Class<?> k = ConcurrentHashMapV8.class;
6813 <            counterOffset = UNSAFE.objectFieldOffset
6774 <                (k.getDeclaredField("counter"));
6775 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6813 >            SIZECTL = U.objectFieldOffset
6814                  (k.getDeclaredField("sizeCtl"));
6815 +            TRANSFERINDEX = U.objectFieldOffset
6816 +                (k.getDeclaredField("transferIndex"));
6817 +            TRANSFERORIGIN = U.objectFieldOffset
6818 +                (k.getDeclaredField("transferOrigin"));
6819 +            BASECOUNT = U.objectFieldOffset
6820 +                (k.getDeclaredField("baseCount"));
6821 +            COUNTERBUSY = U.objectFieldOffset
6822 +                (k.getDeclaredField("counterBusy"));
6823 +            Class<?> ck = CounterCell.class;
6824 +            CELLVALUE = U.objectFieldOffset
6825 +                (ck.getDeclaredField("value"));
6826              Class<?> sc = Node[].class;
6827 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6828 <            ss = UNSAFE.arrayIndexScale(sc);
6827 >            ABASE = U.arrayBaseOffset(sc);
6828 >            ss = U.arrayIndexScale(sc);
6829 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6830          } catch (Exception e) {
6831              throw new Error(e);
6832          }
6833          if ((ss & (ss-1)) != 0)
6834              throw new Error("data type scale not a power of two");
6785        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6835      }
6836  
6837      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines