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.81 by dl, Sat Dec 8 14:10:38 2012 UTC vs.
Revision 1.98 by jsr166, Mon Feb 11 20:52:00 2013 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
29 import java.io.Serializable;
30
31 import java.util.Comparator;
32 import java.util.Arrays;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.Collection;
36 import java.util.AbstractMap;
37 import java.util.AbstractSet;
38 import java.util.AbstractCollection;
39 import java.util.Hashtable;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.Enumeration;
43 import java.util.ConcurrentModificationException;
44 import java.util.NoSuchElementException;
45 import java.util.concurrent.ConcurrentMap;
46 import java.util.concurrent.ThreadLocalRandom;
47 import java.util.concurrent.locks.LockSupport;
48 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
49 import java.util.concurrent.atomic.AtomicReference;
50
27   import java.io.Serializable;
28  
29   /**
# Line 124 | Line 100 | import java.io.Serializable;
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}. (Tasks 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. (The first three forms are
112 < * also available via the {@link #keySet()}, {@link #values()} and
113 < * {@link #entrySet()} views). Because the elements of a
114 < * ConcurrentHashMapV8 are not ordered in any particular way, and may be
115 < * processed in different orders in different parallel executions, the
116 < * correctness of supplied functions should not depend on any
117 < * ordering, or on any other objects or values that may transiently
118 < * change while computation is in progress; and except for forEach
119 < * 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 213 | Line 189 | import java.io.Serializable;
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 itself.
197 < * Similarly, parallelization may not lead to much actual parallelism
198 < * 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.
201   *
# Line 309 | Line 285 | public class ConcurrentHashMapV8<K, V>
285          Spliterator<T> split();
286      }
287  
312
288      /*
289       * Overview:
290       *
# Line 320 | 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
332 <     * variants of put-related operations). The validation-based
333 <     * 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 344 | 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
353 <     *  11 - Locked and may have a thread waiting for lock
354 <     *  10 - Node is a forwarding node
355 <     *
356 <     * The lower 30 bits of each Node's hash field contain a
357 <     * transformation of the key's hash code, except for forwarding
358 <     * nodes, for which the lower bits are zero (and so always have
359 <     * 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 365 | 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
370 <     * construction, so we overlay these by using bits of the Node
371 <     * hash field for lock control (see above), and so normally use
372 <     * builtin monitors only for blocking and signalling using
373 <     * 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 432 | 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 483 | 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 547 | Line 509 | public class ConcurrentHashMapV8<K, V>
509      private static final float LOAD_FACTOR = 0.75f;
510  
511      /**
550     * The buffer size for skipped bins during transfers. The
551     * value is arbitrary but should be large enough to avoid
552     * most locking stalls during resizes.
553     */
554    private static final int TRANSFER_BUFFER_SIZE = 32;
555
556    /**
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
565 <     * 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 575 | 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 ValuesView<K,V> values;
# Line 613 | 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 637 | 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          }
652
653        /** CompareAndSet the hash field */
654        final boolean casHash(int cmp, int val) {
655            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
656        }
657
658        /** The number of spins before blocking for a lock */
659        static final int MAX_SPINS =
660            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
661
662        /**
663         * Spins a while if LOCKED bit set and this node is the first
664         * of its bin, and then sets WAITING bits on hash field and
665         * blocks (once) if they are still set.  It is OK for this
666         * method to return even if lock is not available upon exit,
667         * which enables these simple single-wait mechanics.
668         *
669         * The corresponding signalling operation is performed within
670         * callers: Upon detecting that WAITING has been set when
671         * unlocking lock (via a failed CAS from non-waiting LOCKED
672         * state), unlockers acquire the sync lock and perform a
673         * notifyAll.
674         *
675         * The initial sanity check on tab and bounds is not currently
676         * necessary in the only usages of this method, but enables
677         * use in other future contexts.
678         */
679        final void tryAwaitLock(Node[] tab, int i) {
680            if (tab != null && i >= 0 && i < tab.length) { // sanity check
681                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
682                int spins = MAX_SPINS, h;
683                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
684                    if (spins >= 0) {
685                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
686                        if (r >= 0 && --spins == 0)
687                            Thread.yield();  // yield before block
688                    }
689                    else if (casHash(h, h | WAITING)) {
690                        synchronized (this) {
691                            if (tabAt(tab, i) == this &&
692                                (hash & WAITING) == WAITING) {
693                                try {
694                                    wait();
695                                } catch (InterruptedException ie) {
696                                    try {
697                                        Thread.currentThread().interrupt();
698                                    } catch (SecurityException ignore) {
699                                    }
700                                }
701                            }
702                            else
703                                notifyAll(); // possibly won race vs signaller
704                        }
705                        break;
706                    }
707                }
708            }
709        }
710
711        // Unsafe mechanics for casHash
712        private static final sun.misc.Unsafe UNSAFE;
713        private static final long hashOffset;
714
715        static {
716            try {
717                UNSAFE = getUnsafe();
718                Class<?> k = Node.class;
719                hashOffset = UNSAFE.objectFieldOffset
720                    (k.getDeclaredField("hash"));
721            } catch (Exception e) {
722                throw new Error(e);
723            }
724        }
686      }
687  
688      /* ---------------- TreeBins -------------- */
# Line 729 | 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 785 | 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 819 | 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 836 | 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 856 | 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 869 | Line 830 | public class ConcurrentHashMapV8<K, V>
830                          (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
831                          if ((dir = (c == pc) ? 0 :
832                               c.getName().compareTo(pc.getName())) == 0) {
833 <                            TreeNode r = null, pl, pr; // check both sides
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;
# Line 892 | 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 904 | 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 918 | 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 932 | 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 <                        TreeNode s = null, r = null, pr;
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 &&
# Line 952 | 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 967 | 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 991 | 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 1013 | 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 1028 | 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 1077 | 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 1096 | 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 1114 | 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 1126 | 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 1142 | 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 1152 | 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 1164 | 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 1194 | 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 1212 | 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)
1224 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1225 <            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 1256 | 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 1290 | 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) {
1303 <                checkForResize();               // try resizing if can't get lock
1304 <                f.tryAwaitLock(tab, i);
1305 <            }
1306 <            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 1332 | Line 1290 | public class ConcurrentHashMapV8<K, V>
1290                                  break;
1291                          }
1292                      }
1335                } finally {
1336                    if (!f.casHash(fh | LOCKED, fh)) {
1337                        f.hash = fh;
1338                        synchronized (f) { f.notifyAll(); };
1339                    }
1293                  }
1294                  if (validated) {
1295                      if (deleted)
1296 <                        counter.add(-1L);
1296 >                        addCount(-1L, -1);
1297                      break;
1298                  }
1299              }
# Line 1349 | 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
1354 <     * 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.
1368 <     *  * compute uses the same function-call mechanics, but without
1369 <     *    the prescans
1370 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1371 <     *    update function if present
1372 <     *  * putAll attempts to pre-allocate enough table space
1373 <     *    and more lazily performs count updates and checks.
1374 <     *
1375 <     * Someday when details settle down a bit more, it might be worth
1376 <     * 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;
1423 <                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                      }
1444                } finally {                  // unlock and signal if needed
1445                    if (!f.casHash(fh | LOCKED, fh)) {
1446                        f.hash = fh;
1447                        synchronized (f) { f.notifyAll(); };
1448                    }
1390                  }
1391 <                if (count != 0) {
1391 >                if (len != 0) {
1392                      if (oldVal != null)
1393                          return oldVal;
1453                    if (tab.length <= 64)
1454                        count = 2;
1394                      break;
1395                  }
1396              }
1397          }
1398 <        counter.add(1L);
1460 <        if (count > 1)
1461 <            checkForResize();
1462 <        return null;
1463 <    }
1464 <
1465 <    /** Implementation for putIfAbsent */
1466 <    private final Object internalPutIfAbsent(Object k, Object v) {
1467 <        int h = spread(k.hashCode());
1468 <        int count = 0;
1469 <        for (Node[] tab = table;;) {
1470 <            int i; Node f; int fh; Object fk, fv;
1471 <            if (tab == null)
1472 <                tab = initTable();
1473 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1474 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1475 <                    break;
1476 <            }
1477 <            else if ((fh = f.hash) == MOVED) {
1478 <                if ((fk = f.key) instanceof TreeBin) {
1479 <                    TreeBin t = (TreeBin)fk;
1480 <                    Object oldVal = null;
1481 <                    t.acquire(0);
1482 <                    try {
1483 <                        if (tabAt(tab, i) == f) {
1484 <                            count = 2;
1485 <                            TreeNode p = t.putTreeNode(h, k, v);
1486 <                            if (p != null)
1487 <                                oldVal = p.val;
1488 <                        }
1489 <                    } finally {
1490 <                        t.release(0);
1491 <                    }
1492 <                    if (count != 0) {
1493 <                        if (oldVal != null)
1494 <                            return oldVal;
1495 <                        break;
1496 <                    }
1497 <                }
1498 <                else
1499 <                    tab = (Node[])fk;
1500 <            }
1501 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1502 <                     ((fk = f.key) == k || k.equals(fk)))
1503 <                return fv;
1504 <            else {
1505 <                Node g = f.next;
1506 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1507 <                    for (Node e = g;;) {
1508 <                        Object ek, ev;
1509 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1510 <                            ((ek = e.key) == k || k.equals(ek)))
1511 <                            return ev;
1512 <                        if ((e = e.next) == null) {
1513 <                            checkForResize();
1514 <                            break;
1515 <                        }
1516 <                    }
1517 <                }
1518 <                if (((fh = f.hash) & LOCKED) != 0) {
1519 <                    checkForResize();
1520 <                    f.tryAwaitLock(tab, i);
1521 <                }
1522 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1523 <                    Object oldVal = null;
1524 <                    try {
1525 <                        if (tabAt(tab, i) == f) {
1526 <                            count = 1;
1527 <                            for (Node e = f;; ++count) {
1528 <                                Object ek, ev;
1529 <                                if ((e.hash & HASH_BITS) == h &&
1530 <                                    (ev = e.val) != null &&
1531 <                                    ((ek = e.key) == k || k.equals(ek))) {
1532 <                                    oldVal = ev;
1533 <                                    break;
1534 <                                }
1535 <                                Node last = e;
1536 <                                if ((e = e.next) == null) {
1537 <                                    last.next = new Node(h, k, v, null);
1538 <                                    if (count >= TREE_THRESHOLD)
1539 <                                        replaceWithTreeBin(tab, i, k);
1540 <                                    break;
1541 <                                }
1542 <                            }
1543 <                        }
1544 <                    } finally {
1545 <                        if (!f.casHash(fh | LOCKED, fh)) {
1546 <                            f.hash = fh;
1547 <                            synchronized (f) { f.notifyAll(); };
1548 <                        }
1549 <                    }
1550 <                    if (count != 0) {
1551 <                        if (oldVal != null)
1552 <                            return oldVal;
1553 <                        if (tab.length <= 64)
1554 <                            count = 2;
1555 <                        break;
1556 <                    }
1557 <                }
1558 <            }
1559 <        }
1560 <        counter.add(1L);
1561 <        if (count > 1)
1562 <            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)) {
1587 <                            node.hash = h;
1588 <                            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              }
1624            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1625                     ((fk = f.key) == k || k.equals(fk)))
1626                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 &&
1633 <                            ((ek = e.key) == k || k.equals(ek)))
1634 <                            return ev;
1635 <                        if ((e = e.next) == null) {
1636 <                            checkForResize();
1637 <                            break;
1638 <                        }
1639 <                    }
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 <                if (((fh = f.hash) & LOCKED) != 0) {
1468 <                    checkForResize();
1469 <                    f.tryAwaitLock(tab, i);
1470 <                }
1471 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1472 <                    boolean added = false;
1473 <                    try {
1474 <                        if (tabAt(tab, i) == f) {
1475 <                            count = 1;
1476 <                            for (Node e = f;; ++count) {
1477 <                                Object ek, ev;
1478 <                                if ((e.hash & HASH_BITS) == h &&
1479 <                                    (ev = e.val) != null &&
1480 <                                    ((ek = e.key) == k || k.equals(ek))) {
1481 <                                    val = ev;
1482 <                                    break;
1483 <                                }
1484 <                                Node last = e;
1485 <                                if ((e = e.next) == null) {
1660 <                                    if ((val = mf.apply(k)) != null) {
1661 <                                        added = true;
1662 <                                        last.next = new Node(h, k, val, null);
1663 <                                        if (count >= TREE_THRESHOLD)
1664 <                                            replaceWithTreeBin(tab, i, k);
1665 <                                    }
1666 <                                    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                          }
1670                    } finally {
1671                        if (!f.casHash(fh | LOCKED, fh)) {
1672                            f.hash = fh;
1673                            synchronized (f) { f.notifyAll(); };
1674                        }
1675                    }
1676                    if (count != 0) {
1677                        if (!added)
1678                            return val;
1679                        if (tab.length <= 64)
1680                            count = 2;
1681                        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);
1688 <            if (count > 1)
1689 <                checkForResize();
1690 <        }
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)) {
1720 <                            node.hash = h;
1721 <                            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 1751 | 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();
1762 <                f.tryAwaitLock(tab, i);
1763 <            }
1764 <            else if (f.casHash(fh, fh | LOCKED)) {
1765 <                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 1785 | 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                      }
1798                } finally {
1799                    if (!f.casHash(fh | LOCKED, fh)) {
1800                        f.hash = fh;
1801                        synchronized (f) { f.notifyAll(); };
1802                    }
1608                  }
1609 <                if (count != 0) {
1805 <                    if (tab.length <= 64)
1806 <                        count = 2;
1609 >                if (len != 0)
1610                      break;
1808                }
1611              }
1612          }
1613 <        if (delta != 0) {
1614 <            counter.add((long)delta);
1813 <            if (count > 1)
1814 <                checkForResize();
1815 <        }
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 1860 | 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;
1668 >                    tab = (Node<V>[])fk;
1669              }
1670 <            else if ((fh & LOCKED) != 0) {
1671 <                checkForResize();
1871 <                f.tryAwaitLock(tab, i);
1872 <            }
1873 <            else if (f.casHash(fh, fh | LOCKED)) {
1874 <                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 1895 | 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                      }
1906                } finally {
1907                    if (!f.casHash(fh | LOCKED, fh)) {
1908                        f.hash = fh;
1909                        synchronized (f) { f.notifyAll(); };
1910                    }
1703                  }
1704 <                if (count != 0) {
1913 <                    if (tab.length <= 64)
1914 <                        count = 2;
1704 >                if (len != 0)
1705                      break;
1916                }
1706              }
1707          }
1708 <        if (delta != 0) {
1709 <            counter.add((long)delta);
1921 <            if (count > 1)
1922 <                checkForResize();
1923 <        }
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 1971 | Line 1758 | public class ConcurrentHashMapV8<K, V>
1758                                  break;
1759                          }
1760                          else
1761 <                            tab = (Node[])fk;
1975 <                    }
1976 <                    else if ((fh & LOCKED) != 0) {
1977 <                        counter.add(delta);
1978 <                        delta = 0L;
1979 <                        checkForResize();
1980 <                        f.tryAwaitLock(tab, i);
1761 >                            tab = (Node<V>[])fk;
1762                      }
1763 <                    else if (f.casHash(fh, fh | LOCKED)) {
1764 <                        int count = 0;
1765 <                        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                              }
2005                        } finally {
2006                            if (!f.casHash(fh | LOCKED, fh)) {
2007                                f.hash = fh;
2008                                synchronized (f) { f.notifyAll(); };
2009                            }
1786                          }
1787 <                        if (count != 0) {
1788 <                            if (count > 1) {
1789 <                                counter.add(delta);
1787 >                        if (len != 0) {
1788 >                            if (len > 1) {
1789 >                                addCount(delta, len);
1790                                  delta = 0L;
2015                                checkForResize();
1791                              }
1792                              break;
1793                          }
# Line 2020 | Line 1795 | public class ConcurrentHashMapV8<K, V>
1795                  }
1796              }
1797          } finally {
1798 <            if (delta != 0)
1799 <                counter.add(delta);
1798 >            if (delta != 0L)
1799 >                addCount(delta, 2);
1800          }
1801          if (npe)
1802              throw new NullPointerException();
1803      }
1804  
1805 +    /**
1806 +     * Implementation for clear. Steps through each bin, removing all
1807 +     * nodes.
1808 +     */
1809 +    @SuppressWarnings("unchecked") private final void internalClear() {
1810 +        long delta = 0L; // negative number of deletions
1811 +        int i = 0;
1812 +        Node<V>[] tab = table;
1813 +        while (tab != null && i < tab.length) {
1814 +            Node<V> f = tabAt(tab, i);
1815 +            if (f == null)
1816 +                ++i;
1817 +            else if (f.hash < 0) {
1818 +                Object fk;
1819 +                if ((fk = f.key) instanceof TreeBin) {
1820 +                    TreeBin<V> t = (TreeBin<V>)fk;
1821 +                    t.acquire(0);
1822 +                    try {
1823 +                        if (tabAt(tab, i) == f) {
1824 +                            for (Node<V> p = t.first; p != null; p = p.next) {
1825 +                                if (p.val != null) { // (currently always true)
1826 +                                    p.val = null;
1827 +                                    --delta;
1828 +                                }
1829 +                            }
1830 +                            t.first = null;
1831 +                            t.root = null;
1832 +                            ++i;
1833 +                        }
1834 +                    } finally {
1835 +                        t.release(0);
1836 +                    }
1837 +                }
1838 +                else
1839 +                    tab = (Node<V>[])fk;
1840 +            }
1841 +            else {
1842 +                synchronized (f) {
1843 +                    if (tabAt(tab, i) == f) {
1844 +                        for (Node<V> e = f; e != null; e = e.next) {
1845 +                            if (e.val != null) {  // (currently always true)
1846 +                                e.val = null;
1847 +                                --delta;
1848 +                            }
1849 +                        }
1850 +                        setTabAt(tab, i, null);
1851 +                        ++i;
1852 +                    }
1853 +                }
1854 +            }
1855 +        }
1856 +        if (delta != 0L)
1857 +            addCount(delta, -1);
1858 +    }
1859 +
1860      /* ---------------- Table Initialization and Resizing -------------- */
1861  
1862      /**
# Line 2046 | Line 1876 | public class ConcurrentHashMapV8<K, V>
1876      /**
1877       * Initializes table, using the size recorded in sizeCtl.
1878       */
1879 <    private final Node[] initTable() {
1880 <        Node[] tab; int sc;
1879 >    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
1880 >        Node<V>[] tab; int sc;
1881          while ((tab = table) == null) {
1882              if ((sc = sizeCtl) < 0)
1883                  Thread.yield(); // lost initialization race; just spin
1884 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1884 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1885                  try {
1886                      if ((tab = table) == null) {
1887                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1888 <                        tab = table = new Node[n];
1888 >                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1889 >                        table = tab = (Node<V>[])tb;
1890                          sc = n - (n >>> 2);
1891                      }
1892                  } finally {
# Line 2068 | Line 1899 | public class ConcurrentHashMapV8<K, V>
1899      }
1900  
1901      /**
1902 <     * If table is too small and not already resizing, creates next
1903 <     * table and transfers bins.  Rechecks occupancy after a transfer
1904 <     * to see if another resize is already needed because resizings
1905 <     * are lagging additions.
1906 <     */
1907 <    private final void checkForResize() {
1908 <        Node[] tab; int n, sc;
1909 <        while ((tab = table) != null &&
1910 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1911 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1912 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1913 <            try {
1914 <                if (tab == table) {
1915 <                    table = rebuild(tab);
1916 <                    sc = (n << 1) - (n >>> 1);
1902 >     * Adds to count, and if table is too small and not already
1903 >     * resizing, initiates transfer. If already resizing, helps
1904 >     * perform transfer if work is available.  Rechecks occupancy
1905 >     * after a transfer to see if another resize is already needed
1906 >     * because resizings are lagging additions.
1907 >     *
1908 >     * @param x the count to add
1909 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1910 >     */
1911 >    private final void addCount(long x, int check) {
1912 >        CounterCell[] as; long b, s;
1913 >        if ((as = counterCells) != null ||
1914 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1915 >            CounterHashCode hc; CounterCell a; long v; int m;
1916 >            boolean uncontended = true;
1917 >            if ((hc = threadCounterHashCode.get()) == null ||
1918 >                as == null || (m = as.length - 1) < 0 ||
1919 >                (a = as[m & hc.code]) == null ||
1920 >                !(uncontended =
1921 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1922 >                fullAddCount(x, hc, uncontended);
1923 >                return;
1924 >            }
1925 >            if (check <= 1)
1926 >                return;
1927 >            s = sumCount();
1928 >        }
1929 >        if (check >= 0) {
1930 >            Node<V>[] tab, nt; int sc;
1931 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1932 >                   tab.length < MAXIMUM_CAPACITY) {
1933 >                if (sc < 0) {
1934 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1935 >                        (nt = nextTable) == null)
1936 >                        break;
1937 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1938 >                        transfer(tab, nt);
1939                  }
1940 <            } finally {
1941 <                sizeCtl = sc;
1940 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1941 >                    transfer(tab, null);
1942 >                s = sumCount();
1943              }
1944          }
1945      }
# Line 2095 | Line 1949 | public class ConcurrentHashMapV8<K, V>
1949       *
1950       * @param size number of elements (doesn't need to be perfectly accurate)
1951       */
1952 <    private final void tryPresize(int size) {
1952 >    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
1953          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1954              tableSizeFor(size + (size >>> 1) + 1);
1955          int sc;
1956          while ((sc = sizeCtl) >= 0) {
1957 <            Node[] tab = table; int n;
1957 >            Node<V>[] tab = table; int n;
1958              if (tab == null || (n = tab.length) == 0) {
1959                  n = (sc > c) ? sc : c;
1960 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1960 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1961                      try {
1962                          if (table == tab) {
1963 <                            table = new Node[n];
1963 >                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1964 >                            table = (Node<V>[])tb;
1965                              sc = n - (n >>> 2);
1966                          }
1967                      } finally {
# Line 2116 | Line 1971 | public class ConcurrentHashMapV8<K, V>
1971              }
1972              else if (c <= sc || n >= MAXIMUM_CAPACITY)
1973                  break;
1974 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1975 <                try {
1976 <                    if (table == tab) {
2122 <                        table = rebuild(tab);
2123 <                        sc = (n << 1) - (n >>> 1);
2124 <                    }
2125 <                } finally {
2126 <                    sizeCtl = sc;
2127 <                }
2128 <            }
1974 >            else if (tab == table &&
1975 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1976 >                transfer(tab, null);
1977          }
1978      }
1979  
1980 <    /*
1980 >    /**
1981       * Moves and/or copies the nodes in each bin to new table. See
1982       * above for explanation.
2135     *
2136     * @return the new table
1983       */
1984 <    private static final Node[] rebuild(Node[] tab) {
1985 <        int n = tab.length;
1986 <        Node[] nextTab = new Node[n << 1];
1987 <        Node fwd = new Node(MOVED, nextTab, null, null);
1988 <        int[] buffer = null;       // holds bins to revisit; null until needed
1989 <        Node rev = null;           // reverse forwarder; null until needed
1990 <        int nbuffered = 0;         // the number of bins in buffer list
1991 <        int bufferIndex = 0;       // buffer index of current buffered bin
1992 <        int bin = n - 1;           // current non-buffered bin or -1 if none
1993 <
1994 <        for (int i = bin;;) {      // start upwards sweep
1995 <            int fh; Node f;
1996 <            if ((f = tabAt(tab, i)) == null) {
1997 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
1998 <                    if (!casTabAt(tab, i, f, fwd))
1999 <                        continue;
2000 <                }
2001 <                else {             // transiently use a locked forwarding node
2002 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2003 <                    if (!casTabAt(tab, i, f, g))
2004 <                        continue;
1984 >    @SuppressWarnings("unchecked") private final void transfer
1985 >        (Node<V>[] tab, Node<V>[] nextTab) {
1986 >        int n = tab.length, stride;
1987 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1988 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1989 >        if (nextTab == null) {            // initiating
1990 >            try {
1991 >                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
1992 >                nextTab = (Node<V>[])tb;
1993 >            } catch (Throwable ex) {      // try to cope with OOME
1994 >                sizeCtl = Integer.MAX_VALUE;
1995 >                return;
1996 >            }
1997 >            nextTable = nextTab;
1998 >            transferOrigin = n;
1999 >            transferIndex = n;
2000 >            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2001 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2002 >                int nextk = (k > stride) ? k - stride : 0;
2003 >                for (int m = nextk; m < k; ++m)
2004 >                    nextTab[m] = rev;
2005 >                for (int m = n + nextk; m < n + k; ++m)
2006 >                    nextTab[m] = rev;
2007 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2008 >            }
2009 >        }
2010 >        int nextn = nextTab.length;
2011 >        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2012 >        boolean advance = true;
2013 >        for (int i = 0, bound = 0;;) {
2014 >            int nextIndex, nextBound; Node<V> f; Object fk;
2015 >            while (advance) {
2016 >                if (--i >= bound)
2017 >                    advance = false;
2018 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2019 >                    i = -1;
2020 >                    advance = false;
2021 >                }
2022 >                else if (U.compareAndSwapInt
2023 >                         (this, TRANSFERINDEX, nextIndex,
2024 >                          nextBound = (nextIndex > stride ?
2025 >                                       nextIndex - stride : 0))) {
2026 >                    bound = nextBound;
2027 >                    i = nextIndex - 1;
2028 >                    advance = false;
2029 >                }
2030 >            }
2031 >            if (i < 0 || i >= n || i + n >= nextn) {
2032 >                for (int sc;;) {
2033 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2034 >                        if (sc == -1) {
2035 >                            nextTable = null;
2036 >                            table = nextTab;
2037 >                            sizeCtl = (n << 1) - (n >>> 1);
2038 >                        }
2039 >                        return;
2040 >                    }
2041 >                }
2042 >            }
2043 >            else if ((f = tabAt(tab, i)) == null) {
2044 >                if (casTabAt(tab, i, null, fwd)) {
2045                      setTabAt(nextTab, i, null);
2046                      setTabAt(nextTab, i + n, null);
2047 <                    setTabAt(tab, i, fwd);
2162 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2163 <                        g.hash = MOVED;
2164 <                        synchronized (g) { g.notifyAll(); }
2165 <                    }
2047 >                    advance = true;
2048                  }
2049              }
2050 <            else if ((fh = f.hash) == MOVED) {
2051 <                Object fk = f.key;
2052 <                if (fk instanceof TreeBin) {
2053 <                    TreeBin t = (TreeBin)fk;
2054 <                    boolean validated = false;
2055 <                    t.acquire(0);
2056 <                    try {
2057 <                        if (tabAt(tab, i) == f) {
2058 <                            validated = true;
2059 <                            splitTreeBin(nextTab, i, t);
2060 <                            setTabAt(tab, i, fwd);
2050 >            else if (f.hash >= 0) {
2051 >                synchronized (f) {
2052 >                    if (tabAt(tab, i) == f) {
2053 >                        int runBit = f.hash & n;
2054 >                        Node<V> lastRun = f, lo = null, hi = null;
2055 >                        for (Node<V> p = f.next; p != null; p = p.next) {
2056 >                            int b = p.hash & n;
2057 >                            if (b != runBit) {
2058 >                                runBit = b;
2059 >                                lastRun = p;
2060 >                            }
2061                          }
2062 <                    } finally {
2063 <                        t.release(0);
2062 >                        if (runBit == 0)
2063 >                            lo = lastRun;
2064 >                        else
2065 >                            hi = lastRun;
2066 >                        for (Node<V> p = f; p != lastRun; p = p.next) {
2067 >                            int ph = p.hash;
2068 >                            Object pk = p.key; V pv = p.val;
2069 >                            if ((ph & n) == 0)
2070 >                                lo = new Node<V>(ph, pk, pv, lo);
2071 >                            else
2072 >                                hi = new Node<V>(ph, pk, pv, hi);
2073 >                        }
2074 >                        setTabAt(nextTab, i, lo);
2075 >                        setTabAt(nextTab, i + n, hi);
2076 >                        setTabAt(tab, i, fwd);
2077 >                        advance = true;
2078                      }
2183                    if (!validated)
2184                        continue;
2079                  }
2080              }
2081 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2082 <                boolean validated = false;
2083 <                try {              // split to lo and hi lists; copying as needed
2081 >            else if ((fk = f.key) instanceof TreeBin) {
2082 >                TreeBin<V> t = (TreeBin<V>)fk;
2083 >                t.acquire(0);
2084 >                try {
2085                      if (tabAt(tab, i) == f) {
2086 <                        validated = true;
2087 <                        splitBin(nextTab, i, f);
2086 >                        TreeBin<V> lt = new TreeBin<V>();
2087 >                        TreeBin<V> ht = new TreeBin<V>();
2088 >                        int lc = 0, hc = 0;
2089 >                        for (Node<V> e = t.first; e != null; e = e.next) {
2090 >                            int h = e.hash;
2091 >                            Object k = e.key; V v = e.val;
2092 >                            if ((h & n) == 0) {
2093 >                                ++lc;
2094 >                                lt.putTreeNode(h, k, v);
2095 >                            }
2096 >                            else {
2097 >                                ++hc;
2098 >                                ht.putTreeNode(h, k, v);
2099 >                            }
2100 >                        }
2101 >                        Node<V> ln, hn; // throw away trees if too small
2102 >                        if (lc < TREE_THRESHOLD) {
2103 >                            ln = null;
2104 >                            for (Node<V> p = lt.first; p != null; p = p.next)
2105 >                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2106 >                        }
2107 >                        else
2108 >                            ln = new Node<V>(MOVED, lt, null, null);
2109 >                        setTabAt(nextTab, i, ln);
2110 >                        if (hc < TREE_THRESHOLD) {
2111 >                            hn = null;
2112 >                            for (Node<V> p = ht.first; p != null; p = p.next)
2113 >                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2114 >                        }
2115 >                        else
2116 >                            hn = new Node<V>(MOVED, ht, null, null);
2117 >                        setTabAt(nextTab, i + n, hn);
2118                          setTabAt(tab, i, fwd);
2119 +                        advance = true;
2120                      }
2121                  } finally {
2122 <                    if (!f.casHash(fh | LOCKED, fh)) {
2197 <                        f.hash = fh;
2198 <                        synchronized (f) { f.notifyAll(); };
2199 <                    }
2122 >                    t.release(0);
2123                  }
2201                if (!validated)
2202                    continue;
2203            }
2204            else {
2205                if (buffer == null) // initialize buffer for revisits
2206                    buffer = new int[TRANSFER_BUFFER_SIZE];
2207                if (bin < 0 && bufferIndex > 0) {
2208                    int j = buffer[--bufferIndex];
2209                    buffer[bufferIndex] = i;
2210                    i = j;         // swap with another bin
2211                    continue;
2212                }
2213                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2214                    f.tryAwaitLock(tab, i);
2215                    continue;      // no other options -- block
2216                }
2217                if (rev == null)   // initialize reverse-forwarder
2218                    rev = new Node(MOVED, tab, null, null);
2219                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2220                    continue;      // recheck before adding to list
2221                buffer[nbuffered++] = i;
2222                setTabAt(nextTab, i, rev);     // install place-holders
2223                setTabAt(nextTab, i + n, rev);
2224            }
2225
2226            if (bin > 0)
2227                i = --bin;
2228            else if (buffer != null && nbuffered > 0) {
2229                bin = -1;
2230                i = buffer[bufferIndex = --nbuffered];
2124              }
2125              else
2126 <                return nextTab;
2126 >                advance = true; // already processed
2127          }
2128      }
2129  
2130 <    /**
2131 <     * Splits a normal bin with list headed by e into lo and hi parts;
2132 <     * installs in given table.
2133 <     */
2134 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2135 <        int bit = nextTab.length >>> 1; // bit to split on
2136 <        int runBit = e.hash & bit;
2137 <        Node lastRun = e, lo = null, hi = null;
2138 <        for (Node p = e.next; p != null; p = p.next) {
2246 <            int b = p.hash & bit;
2247 <            if (b != runBit) {
2248 <                runBit = b;
2249 <                lastRun = p;
2130 >    /* ---------------- Counter support -------------- */
2131 >
2132 >    final long sumCount() {
2133 >        CounterCell[] as = counterCells; CounterCell a;
2134 >        long sum = baseCount;
2135 >        if (as != null) {
2136 >            for (int i = 0; i < as.length; ++i) {
2137 >                if ((a = as[i]) != null)
2138 >                    sum += a.value;
2139              }
2140          }
2141 <        if (runBit == 0)
2253 <            lo = lastRun;
2254 <        else
2255 <            hi = lastRun;
2256 <        for (Node p = e; p != lastRun; p = p.next) {
2257 <            int ph = p.hash & HASH_BITS;
2258 <            Object pk = p.key, pv = p.val;
2259 <            if ((ph & bit) == 0)
2260 <                lo = new Node(ph, pk, pv, lo);
2261 <            else
2262 <                hi = new Node(ph, pk, pv, hi);
2263 <        }
2264 <        setTabAt(nextTab, i, lo);
2265 <        setTabAt(nextTab, i + bit, hi);
2141 >        return sum;
2142      }
2143  
2144 <    /**
2145 <     * Splits a tree bin into lo and hi parts; installs in given table.
2146 <     */
2147 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2148 <        int bit = nextTab.length >>> 1;
2149 <        TreeBin lt = new TreeBin();
2150 <        TreeBin ht = new TreeBin();
2151 <        int lc = 0, hc = 0;
2152 <        for (Node e = t.first; e != null; e = e.next) {
2277 <            int h = e.hash & HASH_BITS;
2278 <            Object k = e.key, v = e.val;
2279 <            if ((h & bit) == 0) {
2280 <                ++lc;
2281 <                lt.putTreeNode(h, k, v);
2282 <            }
2283 <            else {
2284 <                ++hc;
2285 <                ht.putTreeNode(h, k, v);
2286 <            }
2287 <        }
2288 <        Node ln, hn; // throw away trees if too small
2289 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2290 <            ln = null;
2291 <            for (Node p = lt.first; p != null; p = p.next)
2292 <                ln = new Node(p.hash, p.key, p.val, ln);
2144 >    // See LongAdder version for explanation
2145 >    private final void fullAddCount(long x, CounterHashCode hc,
2146 >                                    boolean wasUncontended) {
2147 >        int h;
2148 >        if (hc == null) {
2149 >            hc = new CounterHashCode();
2150 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2151 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2152 >            threadCounterHashCode.set(hc);
2153          }
2154          else
2155 <            ln = new Node(MOVED, lt, null, null);
2156 <        setTabAt(nextTab, i, ln);
2157 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2158 <            hn = null;
2159 <            for (Node p = ht.first; p != null; p = p.next)
2160 <                hn = new Node(p.hash, p.key, p.val, hn);
2161 <        }
2162 <        else
2163 <            hn = new Node(MOVED, ht, null, null);
2164 <        setTabAt(nextTab, i + bit, hn);
2165 <    }
2166 <
2167 <    /**
2168 <     * Implementation for clear. Steps through each bin, removing all
2169 <     * nodes.
2170 <     */
2171 <    private final void internalClear() {
2172 <        long delta = 0L; // negative number of deletions
2313 <        int i = 0;
2314 <        Node[] tab = table;
2315 <        while (tab != null && i < tab.length) {
2316 <            int fh; Object fk;
2317 <            Node f = tabAt(tab, i);
2318 <            if (f == null)
2319 <                ++i;
2320 <            else if ((fh = f.hash) == MOVED) {
2321 <                if ((fk = f.key) instanceof TreeBin) {
2322 <                    TreeBin t = (TreeBin)fk;
2323 <                    t.acquire(0);
2324 <                    try {
2325 <                        if (tabAt(tab, i) == f) {
2326 <                            for (Node p = t.first; p != null; p = p.next) {
2327 <                                if (p.val != null) { // (currently always true)
2328 <                                    p.val = null;
2329 <                                    --delta;
2155 >            h = hc.code;
2156 >        boolean collide = false;                // True if last slot nonempty
2157 >        for (;;) {
2158 >            CounterCell[] as; CounterCell a; int n; long v;
2159 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2160 >                if ((a = as[(n - 1) & h]) == null) {
2161 >                    if (counterBusy == 0) {            // Try to attach new Cell
2162 >                        CounterCell r = new CounterCell(x); // Optimistic create
2163 >                        if (counterBusy == 0 &&
2164 >                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2165 >                            boolean created = false;
2166 >                            try {               // Recheck under lock
2167 >                                CounterCell[] rs; int m, j;
2168 >                                if ((rs = counterCells) != null &&
2169 >                                    (m = rs.length) > 0 &&
2170 >                                    rs[j = (m - 1) & h] == null) {
2171 >                                    rs[j] = r;
2172 >                                    created = true;
2173                                  }
2174 +                            } finally {
2175 +                                counterBusy = 0;
2176                              }
2177 <                            t.first = null;
2178 <                            t.root = null;
2179 <                            ++i;
2177 >                            if (created)
2178 >                                break;
2179 >                            continue;           // Slot is now non-empty
2180                          }
2336                    } finally {
2337                        t.release(0);
2181                      }
2182 +                    collide = false;
2183                  }
2184 <                else
2185 <                    tab = (Node[])fk;
2186 <            }
2187 <            else if ((fh & LOCKED) != 0) {
2188 <                counter.add(delta); // opportunistically update count
2189 <                delta = 0L;
2190 <                f.tryAwaitLock(tab, i);
2191 <            }
2192 <            else if (f.casHash(fh, fh | LOCKED)) {
2193 <                try {
2194 <                    if (tabAt(tab, i) == f) {
2195 <                        for (Node e = f; e != null; e = e.next) {
2196 <                            if (e.val != null) {  // (currently always true)
2197 <                                e.val = null;
2198 <                                --delta;
2199 <                            }
2184 >                else if (!wasUncontended)       // CAS already known to fail
2185 >                    wasUncontended = true;      // Continue after rehash
2186 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2187 >                    break;
2188 >                else if (counterCells != as || n >= NCPU)
2189 >                    collide = false;            // At max size or stale
2190 >                else if (!collide)
2191 >                    collide = true;
2192 >                else if (counterBusy == 0 &&
2193 >                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2194 >                    try {
2195 >                        if (counterCells == as) {// Expand table unless stale
2196 >                            CounterCell[] rs = new CounterCell[n << 1];
2197 >                            for (int i = 0; i < n; ++i)
2198 >                                rs[i] = as[i];
2199 >                            counterCells = rs;
2200                          }
2201 <                        setTabAt(tab, i, null);
2202 <                        ++i;
2201 >                    } finally {
2202 >                        counterBusy = 0;
2203                      }
2204 <                } finally {
2205 <                    if (!f.casHash(fh | LOCKED, fh)) {
2206 <                        f.hash = fh;
2207 <                        synchronized (f) { f.notifyAll(); };
2204 >                    collide = false;
2205 >                    continue;                   // Retry with expanded table
2206 >                }
2207 >                h ^= h << 13;                   // Rehash
2208 >                h ^= h >>> 17;
2209 >                h ^= h << 5;
2210 >            }
2211 >            else if (counterBusy == 0 && counterCells == as &&
2212 >                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2213 >                boolean init = false;
2214 >                try {                           // Initialize table
2215 >                    if (counterCells == as) {
2216 >                        CounterCell[] rs = new CounterCell[2];
2217 >                        rs[h & 1] = new CounterCell(x);
2218 >                        counterCells = rs;
2219 >                        init = true;
2220                      }
2221 +                } finally {
2222 +                    counterBusy = 0;
2223                  }
2224 +                if (init)
2225 +                    break;
2226              }
2227 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2228 +                break;                          // Fall back on using base
2229          }
2230 <        if (delta != 0)
2369 <            counter.add(delta);
2230 >        hc.code = h;                            // Record index for next time
2231      }
2232  
2233      /* ----------------Table Traversal -------------- */
# Line 2416 | Line 2277 | public class ConcurrentHashMapV8<K, V>
2277       * Serializable, but iterators need not be, we need to add warning
2278       * suppressions.
2279       */
2280 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends CountedCompleter<R> {
2280 >    @SuppressWarnings("serial") static class Traverser<K,V,R>
2281 >        extends CountedCompleter<R> {
2282          final ConcurrentHashMapV8<K, V> map;
2283 <        Node next;           // the next entry to use
2283 >        Node<V> next;        // the next entry to use
2284          Object nextKey;      // cached key field of next
2285 <        Object nextVal;      // cached val field of next
2286 <        Node[] tab;          // current table; updated if resized
2285 >        V nextVal;           // cached val field of next
2286 >        Node<V>[] tab;       // current table; updated if resized
2287          int index;           // index of bin to use next
2288          int baseIndex;       // current index of initial table
2289          int baseLimit;       // index bound for initial table
# Line 2438 | Line 2300 | public class ConcurrentHashMapV8<K, V>
2300              super(it);
2301              this.batch = batch;
2302              if ((this.map = map) != null && it != null) { // split parent
2303 <                Node[] t;
2303 >                Node<V>[] t;
2304                  if ((t = it.tab) == null &&
2305                      (t = it.tab = map.table) != null)
2306                      it.baseLimit = it.baseSize = t.length;
# Line 2454 | Line 2316 | public class ConcurrentHashMapV8<K, V>
2316           * Advances next; returns nextVal or null if terminated.
2317           * See above for explanation.
2318           */
2319 <        final Object advance() {
2320 <            Node e = next;
2321 <            Object ev = null;
2319 >        @SuppressWarnings("unchecked") final V advance() {
2320 >            Node<V> e = next;
2321 >            V ev = null;
2322              outer: do {
2323                  if (e != null)                  // advance past used/skipped node
2324                      e = e.next;
2325                  while (e == null) {             // get to next non-null bin
2326                      ConcurrentHashMapV8<K, V> m;
2327 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2327 >                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2328                      if ((t = tab) != null)
2329                          n = t.length;
2330                      else if ((m = map) != null && (t = tab = m.table) != null)
# Line 2472 | Line 2334 | public class ConcurrentHashMapV8<K, V>
2334                      if ((b = baseIndex) >= baseLimit ||
2335                          (i = index) < 0 || i >= n)
2336                          break outer;
2337 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2337 >                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2338                          if ((ek = e.key) instanceof TreeBin)
2339 <                            e = ((TreeBin)ek).first;
2339 >                            e = ((TreeBin<V>)ek).first;
2340                          else {
2341 <                            tab = (Node[])ek;
2341 >                            tab = (Node<V>[])ek;
2342                              continue;           // restarts due to null val
2343                          }
2344                      }                           // visit upper slots if present
# Line 2514 | Line 2376 | public class ConcurrentHashMapV8<K, V>
2376           * anyway.
2377           */
2378          final int preSplit() {
2379 <            ConcurrentHashMapV8<K, V> m; int b; Node[] t;  ForkJoinPool pool;
2379 >            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2380              if ((b = batch) < 0 && (m = map) != null) { // force initialization
2381                  if ((t = tab) == null && (t = tab = m.table) != null)
2382                      baseLimit = baseSize = t.length;
2383                  if (t != null) {
2384 <                    long n = m.counter.sum();
2384 >                    long n = m.sumCount();
2385                      int par = ((pool = getPool()) == null) ?
2386                          ForkJoinPool.getCommonPoolParallelism() :
2387                          pool.getParallelism();
# Line 2541 | Line 2403 | public class ConcurrentHashMapV8<K, V>
2403       * Creates a new, empty map with the default initial table size (16).
2404       */
2405      public ConcurrentHashMapV8() {
2544        this.counter = new LongAdder();
2406      }
2407  
2408      /**
# Line 2560 | Line 2421 | public class ConcurrentHashMapV8<K, V>
2421          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2422                     MAXIMUM_CAPACITY :
2423                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2563        this.counter = new LongAdder();
2424          this.sizeCtl = cap;
2425      }
2426  
# Line 2570 | Line 2430 | public class ConcurrentHashMapV8<K, V>
2430       * @param m the map
2431       */
2432      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2573        this.counter = new LongAdder();
2433          this.sizeCtl = DEFAULT_CAPACITY;
2434          internalPutAll(m);
2435      }
# Line 2621 | Line 2480 | public class ConcurrentHashMapV8<K, V>
2480          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2481          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2482              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2624        this.counter = new LongAdder();
2483          this.sizeCtl = cap;
2484      }
2485  
# Line 2647 | Line 2505 | public class ConcurrentHashMapV8<K, V>
2505       * @return the new set
2506       */
2507      public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2508 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(initialCapacity),
2509 <                                      Boolean.TRUE);
2508 >        return new KeySetView<K,Boolean>
2509 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2510      }
2511  
2512      /**
2513       * {@inheritDoc}
2514       */
2515      public boolean isEmpty() {
2516 <        return counter.sum() <= 0L; // ignore transient negative values
2516 >        return sumCount() <= 0L; // ignore transient negative values
2517      }
2518  
2519      /**
2520       * {@inheritDoc}
2521       */
2522      public int size() {
2523 <        long n = counter.sum();
2523 >        long n = sumCount();
2524          return ((n < 0L) ? 0 :
2525                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2526                  (int)n);
# Line 2678 | Line 2536 | public class ConcurrentHashMapV8<K, V>
2536       * @return the number of mappings
2537       */
2538      public long mappingCount() {
2539 <        long n = counter.sum();
2539 >        long n = sumCount();
2540          return (n < 0L) ? 0L : n; // ignore transient negative values
2541      }
2542  
# Line 2693 | Line 2551 | public class ConcurrentHashMapV8<K, V>
2551       *
2552       * @throws NullPointerException if the specified key is null
2553       */
2554 <    @SuppressWarnings("unchecked") public V get(Object key) {
2555 <        if (key == null)
2698 <            throw new NullPointerException();
2699 <        return (V)internalGet(key);
2554 >    public V get(Object key) {
2555 >        return internalGet(key);
2556      }
2557  
2558      /**
# Line 2709 | Line 2565 | public class ConcurrentHashMapV8<K, V>
2565       * @return the mapping for the key, if present; else the defaultValue
2566       * @throws NullPointerException if the specified key is null
2567       */
2568 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
2569 <        if (key == null)
2570 <            throw new NullPointerException();
2715 <        V v = (V) internalGet(key);
2716 <        return v == null ? defaultValue : v;
2568 >    public V getValueOrDefault(Object key, V defaultValue) {
2569 >        V v;
2570 >        return (v = internalGet(key)) == null ? defaultValue : v;
2571      }
2572  
2573      /**
# Line 2726 | Line 2580 | public class ConcurrentHashMapV8<K, V>
2580       * @throws NullPointerException if the specified key is null
2581       */
2582      public boolean containsKey(Object key) {
2729        if (key == null)
2730            throw new NullPointerException();
2583          return internalGet(key) != null;
2584      }
2585  
# Line 2744 | Line 2596 | public class ConcurrentHashMapV8<K, V>
2596      public boolean containsValue(Object value) {
2597          if (value == null)
2598              throw new NullPointerException();
2599 <        Object v;
2599 >        V v;
2600          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2601          while ((v = it.advance()) != null) {
2602              if (v == value || value.equals(v))
# Line 2768 | Line 2620 | public class ConcurrentHashMapV8<K, V>
2620       *         {@code false} otherwise
2621       * @throws NullPointerException if the specified value is null
2622       */
2623 <    public boolean contains(Object value) {
2623 >    @Deprecated public boolean contains(Object value) {
2624          return containsValue(value);
2625      }
2626  
# Line 2785 | Line 2637 | public class ConcurrentHashMapV8<K, V>
2637       *         {@code null} if there was no mapping for {@code key}
2638       * @throws NullPointerException if the specified key or value is null
2639       */
2640 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
2641 <        if (key == null || value == null)
2790 <            throw new NullPointerException();
2791 <        return (V)internalPut(key, value);
2640 >    public V put(K key, V value) {
2641 >        return internalPut(key, value, false);
2642      }
2643  
2644      /**
# Line 2798 | Line 2648 | public class ConcurrentHashMapV8<K, V>
2648       *         or {@code null} if there was no mapping for the key
2649       * @throws NullPointerException if the specified key or value is null
2650       */
2651 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
2652 <        if (key == null || value == null)
2803 <            throw new NullPointerException();
2804 <        return (V)internalPutIfAbsent(key, value);
2651 >    public V putIfAbsent(K key, V value) {
2652 >        return internalPut(key, value, true);
2653      }
2654  
2655      /**
# Line 2854 | Line 2702 | public class ConcurrentHashMapV8<K, V>
2702       * @throws RuntimeException or Error if the mappingFunction does so,
2703       *         in which case the mapping is left unestablished
2704       */
2705 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2705 >    public V computeIfAbsent
2706          (K key, Fun<? super K, ? extends V> mappingFunction) {
2707 <        if (key == null || mappingFunction == null)
2860 <            throw new NullPointerException();
2861 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2707 >        return internalComputeIfAbsent(key, mappingFunction);
2708      }
2709  
2710      /**
# Line 2895 | Line 2741 | public class ConcurrentHashMapV8<K, V>
2741       * @throws RuntimeException or Error if the remappingFunction does so,
2742       *         in which case the mapping is unchanged
2743       */
2744 <    @SuppressWarnings("unchecked") public V computeIfPresent
2744 >    public V computeIfPresent
2745          (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2746 <        if (key == null || remappingFunction == null)
2901 <            throw new NullPointerException();
2902 <        return (V)internalCompute(key, true, remappingFunction);
2746 >        return internalCompute(key, true, remappingFunction);
2747      }
2748  
2749      /**
# Line 2942 | Line 2786 | public class ConcurrentHashMapV8<K, V>
2786       * @throws RuntimeException or Error if the remappingFunction does so,
2787       *         in which case the mapping is unchanged
2788       */
2789 <    @SuppressWarnings("unchecked") public V compute
2789 >    public V compute
2790          (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2791 <        if (key == null || remappingFunction == null)
2948 <            throw new NullPointerException();
2949 <        return (V)internalCompute(key, false, remappingFunction);
2791 >        return internalCompute(key, false, remappingFunction);
2792      }
2793  
2794      /**
# Line 2974 | Line 2816 | public class ConcurrentHashMapV8<K, V>
2816       * so the computation should be short and simple, and must not
2817       * attempt to update any other mappings of this Map.
2818       */
2819 <    @SuppressWarnings("unchecked") public V merge
2820 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2821 <        if (key == null || value == null || remappingFunction == null)
2822 <            throw new NullPointerException();
2981 <        return (V)internalMerge(key, value, remappingFunction);
2819 >    public V merge
2820 >        (K key, V value,
2821 >         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2822 >        return internalMerge(key, value, remappingFunction);
2823      }
2824  
2825      /**
# Line 2990 | Line 2831 | public class ConcurrentHashMapV8<K, V>
2831       *         {@code null} if there was no mapping for {@code key}
2832       * @throws NullPointerException if the specified key is null
2833       */
2834 <    @SuppressWarnings("unchecked") public V remove(Object key) {
2835 <        if (key == null)
2995 <            throw new NullPointerException();
2996 <        return (V)internalReplace(key, null, null);
2834 >    public V remove(Object key) {
2835 >        return internalReplace(key, null, null);
2836      }
2837  
2838      /**
# Line 3002 | Line 2841 | public class ConcurrentHashMapV8<K, V>
2841       * @throws NullPointerException if the specified key is null
2842       */
2843      public boolean remove(Object key, Object value) {
2844 <        if (key == null)
3006 <            throw new NullPointerException();
3007 <        if (value == null)
3008 <            return false;
3009 <        return internalReplace(key, null, value) != null;
2844 >        return value != null && internalReplace(key, null, value) != null;
2845      }
2846  
2847      /**
# Line 3027 | Line 2862 | public class ConcurrentHashMapV8<K, V>
2862       *         or {@code null} if there was no mapping for the key
2863       * @throws NullPointerException if the specified key or value is null
2864       */
2865 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
2865 >    public V replace(K key, V value) {
2866          if (key == null || value == null)
2867              throw new NullPointerException();
2868 <        return (V)internalReplace(key, value, null);
2868 >        return internalReplace(key, value, null);
2869      }
2870  
2871      /**
# Line 3059 | Line 2894 | public class ConcurrentHashMapV8<K, V>
2894       * course only appropriate if it is acceptable to use the same
2895       * value for all additions from this view.
2896       *
2897 <     * @param mappedValue the mapped value to use for any
3063 <     * additions.
2897 >     * @param mappedValue the mapped value to use for any additions
2898       * @return the set view
2899       * @throws NullPointerException if the mappedValue is null
2900       */
# Line 3158 | Line 2992 | public class ConcurrentHashMapV8<K, V>
2992      public int hashCode() {
2993          int h = 0;
2994          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2995 <        Object v;
2995 >        V v;
2996          while ((v = it.advance()) != null) {
2997              h += it.nextKey.hashCode() ^ v.hashCode();
2998          }
# Line 3180 | Line 3014 | public class ConcurrentHashMapV8<K, V>
3014          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3015          StringBuilder sb = new StringBuilder();
3016          sb.append('{');
3017 <        Object v;
3017 >        V v;
3018          if ((v = it.advance()) != null) {
3019              for (;;) {
3020                  Object k = it.nextKey;
# Line 3211 | Line 3045 | public class ConcurrentHashMapV8<K, V>
3045                  return false;
3046              Map<?,?> m = (Map<?,?>) o;
3047              Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3048 <            Object val;
3048 >            V val;
3049              while ((val = it.advance()) != null) {
3050                  Object v = m.get(it.nextKey);
3051                  if (v == null || (v != val && !v.equals(val)))
# Line 3231 | Line 3065 | public class ConcurrentHashMapV8<K, V>
3065  
3066      /* ----------------Iterators -------------- */
3067  
3068 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3068 >    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3069 >        extends Traverser<K,V,Object>
3070          implements Spliterator<K>, Enumeration<K> {
3071          KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3072          KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
# Line 3253 | Line 3088 | public class ConcurrentHashMapV8<K, V>
3088          public final K nextElement() { return next(); }
3089      }
3090  
3091 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3091 >    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3092 >        extends Traverser<K,V,Object>
3093          implements Spliterator<V>, Enumeration<V> {
3094          ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3095          ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
# Line 3265 | Line 3101 | public class ConcurrentHashMapV8<K, V>
3101              return new ValueIterator<K,V>(map, this);
3102          }
3103  
3104 <        @SuppressWarnings("unchecked") public final V next() {
3105 <            Object v;
3104 >        public final V next() {
3105 >            V v;
3106              if ((v = nextVal) == null && (v = advance()) == null)
3107                  throw new NoSuchElementException();
3108              nextVal = null;
3109 <            return (V) v;
3109 >            return v;
3110          }
3111  
3112          public final V nextElement() { return next(); }
3113      }
3114  
3115 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3115 >    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3116 >        extends Traverser<K,V,Object>
3117          implements Spliterator<Map.Entry<K,V>> {
3118          EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3119          EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
# Line 3289 | Line 3126 | public class ConcurrentHashMapV8<K, V>
3126          }
3127  
3128          @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3129 <            Object v;
3129 >            V v;
3130              if ((v = nextVal) == null && (v = advance()) == null)
3131                  throw new NoSuchElementException();
3132              Object k = nextKey;
3133              nextVal = null;
3134 <            return new MapEntry<K,V>((K)k, (V)v, map);
3134 >            return new MapEntry<K,V>((K)k, v, map);
3135          }
3136      }
3137  
# Line 3370 | Line 3207 | public class ConcurrentHashMapV8<K, V>
3207       * for each key-value mapping, followed by a null pair.
3208       * The key-value mappings are emitted in no particular order.
3209       */
3210 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
3210 >    @SuppressWarnings("unchecked") private void writeObject
3211 >        (java.io.ObjectOutputStream s)
3212          throws java.io.IOException {
3213          if (segments == null) { // for serialization compatibility
3214              segments = (Segment<K,V>[])
# Line 3380 | Line 3218 | public class ConcurrentHashMapV8<K, V>
3218          }
3219          s.defaultWriteObject();
3220          Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3221 <        Object v;
3221 >        V v;
3222          while ((v = it.advance()) != null) {
3223              s.writeObject(it.nextKey);
3224              s.writeObject(v);
# Line 3394 | Line 3232 | public class ConcurrentHashMapV8<K, V>
3232       * Reconstitutes the instance from a stream (that is, deserializes it).
3233       * @param s the stream
3234       */
3235 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
3235 >    @SuppressWarnings("unchecked") private void readObject
3236 >        (java.io.ObjectInputStream s)
3237          throws java.io.IOException, ClassNotFoundException {
3238          s.defaultReadObject();
3239          this.segments = null; // unneeded
3401        // initialize transient final field
3402        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
3240  
3241          // Create all nodes, then place in table once size is known
3242          long size = 0L;
3243 <        Node p = null;
3243 >        Node<V> p = null;
3244          for (;;) {
3245              K k = (K) s.readObject();
3246              V v = (V) s.readObject();
3247              if (k != null && v != null) {
3248                  int h = spread(k.hashCode());
3249 <                p = new Node(h, k, v, p);
3249 >                p = new Node<V>(h, k, v, p);
3250                  ++size;
3251              }
3252              else
# Line 3427 | Line 3264 | public class ConcurrentHashMapV8<K, V>
3264              int sc = sizeCtl;
3265              boolean collide = false;
3266              if (n > sc &&
3267 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3267 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3268                  try {
3269                      if (table == null) {
3270                          init = true;
3271 <                        Node[] tab = new Node[n];
3271 >                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3272 >                        Node<V>[] tab = (Node<V>[])rt;
3273                          int mask = n - 1;
3274                          while (p != null) {
3275                              int j = p.hash & mask;
3276 <                            Node next = p.next;
3277 <                            Node q = p.next = tabAt(tab, j);
3276 >                            Node<V> next = p.next;
3277 >                            Node<V> q = p.next = tabAt(tab, j);
3278                              setTabAt(tab, j, p);
3279                              if (!collide && q != null && q.hash == p.hash)
3280                                  collide = true;
3281                              p = next;
3282                          }
3283                          table = tab;
3284 <                        counter.add(size);
3284 >                        addCount(size, -1);
3285                          sc = n - (n >>> 2);
3286                      }
3287                  } finally {
3288                      sizeCtl = sc;
3289                  }
3290                  if (collide) { // rescan and convert to TreeBins
3291 <                    Node[] tab = table;
3291 >                    Node<V>[] tab = table;
3292                      for (int i = 0; i < tab.length; ++i) {
3293                          int c = 0;
3294 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3294 >                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3295                              if (++c > TREE_THRESHOLD &&
3296                                  (e.key instanceof Comparable)) {
3297                                  replaceWithTreeBin(tab, i, e.key);
# Line 3465 | Line 3303 | public class ConcurrentHashMapV8<K, V>
3303              }
3304              if (!init) { // Can only happen if unsafely published.
3305                  while (p != null) {
3306 <                    internalPut(p.key, p.val);
3306 >                    internalPut((K)p.key, p.val, false);
3307                      p = p.next;
3308                  }
3309              }
3310          }
3311      }
3312  
3475
3313      // -------------------------------------------------------
3314  
3315      // Sams
# Line 3514 | Line 3351 | public class ConcurrentHashMapV8<K, V>
3351  
3352      // -------------------------------------------------------
3353  
3354 +    // Sequential bulk operations
3355 +
3356 +    /**
3357 +     * Performs the given action for each (key, value).
3358 +     *
3359 +     * @param action the action
3360 +     */
3361 +    @SuppressWarnings("unchecked") public void forEachSequentially
3362 +        (BiAction<K,V> action) {
3363 +        if (action == null) throw new NullPointerException();
3364 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3365 +        V v;
3366 +        while ((v = it.advance()) != null)
3367 +            action.apply((K)it.nextKey, v);
3368 +    }
3369 +
3370 +    /**
3371 +     * Performs the given action for each non-null transformation
3372 +     * of each (key, value).
3373 +     *
3374 +     * @param transformer a function returning the transformation
3375 +     * for an element, or null if there is no transformation (in
3376 +     * which case the action is not applied)
3377 +     * @param action the action
3378 +     */
3379 +    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3380 +        (BiFun<? super K, ? super V, ? extends U> transformer,
3381 +         Action<U> action) {
3382 +        if (transformer == null || action == null)
3383 +            throw new NullPointerException();
3384 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3385 +        V v; U u;
3386 +        while ((v = it.advance()) != null) {
3387 +            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3388 +                action.apply(u);
3389 +        }
3390 +    }
3391 +
3392 +    /**
3393 +     * Returns a non-null result from applying the given search
3394 +     * function on each (key, value), or null if none.
3395 +     *
3396 +     * @param searchFunction a function returning a non-null
3397 +     * result on success, else null
3398 +     * @return a non-null result from applying the given search
3399 +     * function on each (key, value), or null if none
3400 +     */
3401 +    @SuppressWarnings("unchecked") public <U> U searchSequentially
3402 +        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3403 +        if (searchFunction == null) throw new NullPointerException();
3404 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3405 +        V v; U u;
3406 +        while ((v = it.advance()) != null) {
3407 +            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3408 +                return u;
3409 +        }
3410 +        return null;
3411 +    }
3412 +
3413 +    /**
3414 +     * Returns the result of accumulating the given transformation
3415 +     * of all (key, value) pairs using the given reducer to
3416 +     * combine values, or null if none.
3417 +     *
3418 +     * @param transformer a function returning the transformation
3419 +     * for an element, or null if there is no transformation (in
3420 +     * which case it is not combined)
3421 +     * @param reducer a commutative associative combining function
3422 +     * @return the result of accumulating the given transformation
3423 +     * of all (key, value) pairs
3424 +     */
3425 +    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3426 +        (BiFun<? super K, ? super V, ? extends U> transformer,
3427 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3428 +        if (transformer == null || reducer == null)
3429 +            throw new NullPointerException();
3430 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3431 +        U r = null, u; V v;
3432 +        while ((v = it.advance()) != null) {
3433 +            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3434 +                r = (r == null) ? u : reducer.apply(r, u);
3435 +        }
3436 +        return r;
3437 +    }
3438 +
3439 +    /**
3440 +     * Returns the result of accumulating the given transformation
3441 +     * of all (key, value) pairs using the given reducer to
3442 +     * combine values, and the given basis as an identity value.
3443 +     *
3444 +     * @param transformer a function returning the transformation
3445 +     * for an element
3446 +     * @param basis the identity (initial default value) for the reduction
3447 +     * @param reducer a commutative associative combining function
3448 +     * @return the result of accumulating the given transformation
3449 +     * of all (key, value) pairs
3450 +     */
3451 +    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3452 +        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3453 +         double basis,
3454 +         DoubleByDoubleToDouble reducer) {
3455 +        if (transformer == null || reducer == null)
3456 +            throw new NullPointerException();
3457 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3458 +        double r = basis; V v;
3459 +        while ((v = it.advance()) != null)
3460 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3461 +        return r;
3462 +    }
3463 +
3464 +    /**
3465 +     * Returns the result of accumulating the given transformation
3466 +     * of all (key, value) pairs using the given reducer to
3467 +     * combine values, and the given basis as an identity value.
3468 +     *
3469 +     * @param transformer a function returning the transformation
3470 +     * for an element
3471 +     * @param basis the identity (initial default value) for the reduction
3472 +     * @param reducer a commutative associative combining function
3473 +     * @return the result of accumulating the given transformation
3474 +     * of all (key, value) pairs
3475 +     */
3476 +    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3477 +        (ObjectByObjectToLong<? super K, ? super V> transformer,
3478 +         long basis,
3479 +         LongByLongToLong reducer) {
3480 +        if (transformer == null || reducer == null)
3481 +            throw new NullPointerException();
3482 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3483 +        long r = basis; V v;
3484 +        while ((v = it.advance()) != null)
3485 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3486 +        return r;
3487 +    }
3488 +
3489 +    /**
3490 +     * Returns the result of accumulating the given transformation
3491 +     * of all (key, value) pairs using the given reducer to
3492 +     * combine values, and the given basis as an identity value.
3493 +     *
3494 +     * @param transformer a function returning the transformation
3495 +     * for an element
3496 +     * @param basis the identity (initial default value) for the reduction
3497 +     * @param reducer a commutative associative combining function
3498 +     * @return the result of accumulating the given transformation
3499 +     * of all (key, value) pairs
3500 +     */
3501 +    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3502 +        (ObjectByObjectToInt<? super K, ? super V> transformer,
3503 +         int basis,
3504 +         IntByIntToInt reducer) {
3505 +        if (transformer == null || reducer == null)
3506 +            throw new NullPointerException();
3507 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3508 +        int r = basis; V v;
3509 +        while ((v = it.advance()) != null)
3510 +            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3511 +        return r;
3512 +    }
3513 +
3514 +    /**
3515 +     * Performs the given action for each key.
3516 +     *
3517 +     * @param action the action
3518 +     */
3519 +    @SuppressWarnings("unchecked") public void forEachKeySequentially
3520 +        (Action<K> action) {
3521 +        if (action == null) throw new NullPointerException();
3522 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3523 +        while (it.advance() != null)
3524 +            action.apply((K)it.nextKey);
3525 +    }
3526 +
3527 +    /**
3528 +     * Performs the given action for each non-null transformation
3529 +     * of each key.
3530 +     *
3531 +     * @param transformer a function returning the transformation
3532 +     * for an element, or null if there is no transformation (in
3533 +     * which case the action is not applied)
3534 +     * @param action the action
3535 +     */
3536 +    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3537 +        (Fun<? super K, ? extends U> transformer,
3538 +         Action<U> action) {
3539 +        if (transformer == null || action == null)
3540 +            throw new NullPointerException();
3541 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3542 +        U u;
3543 +        while (it.advance() != null) {
3544 +            if ((u = transformer.apply((K)it.nextKey)) != null)
3545 +                action.apply(u);
3546 +        }
3547 +        ForkJoinTasks.forEachKey
3548 +            (this, transformer, action).invoke();
3549 +    }
3550 +
3551 +    /**
3552 +     * Returns a non-null result from applying the given search
3553 +     * function on each key, or null if none.
3554 +     *
3555 +     * @param searchFunction a function returning a non-null
3556 +     * result on success, else null
3557 +     * @return a non-null result from applying the given search
3558 +     * function on each key, or null if none
3559 +     */
3560 +    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3561 +        (Fun<? super K, ? extends U> searchFunction) {
3562 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3563 +        U u;
3564 +        while (it.advance() != null) {
3565 +            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3566 +                return u;
3567 +        }
3568 +        return null;
3569 +    }
3570 +
3571 +    /**
3572 +     * Returns the result of accumulating all keys using the given
3573 +     * reducer to combine values, or null if none.
3574 +     *
3575 +     * @param reducer a commutative associative combining function
3576 +     * @return the result of accumulating all keys using the given
3577 +     * reducer to combine values, or null if none
3578 +     */
3579 +    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3580 +        (BiFun<? super K, ? super K, ? extends K> reducer) {
3581 +        if (reducer == null) throw new NullPointerException();
3582 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3583 +        K r = null;
3584 +        while (it.advance() != null) {
3585 +            K u = (K)it.nextKey;
3586 +            r = (r == null) ? u : reducer.apply(r, u);
3587 +        }
3588 +        return r;
3589 +    }
3590 +
3591 +    /**
3592 +     * Returns the result of accumulating the given transformation
3593 +     * of all keys using the given reducer to combine values, or
3594 +     * null if none.
3595 +     *
3596 +     * @param transformer a function returning the transformation
3597 +     * for an element, or null if there is no transformation (in
3598 +     * which case it is not combined)
3599 +     * @param reducer a commutative associative combining function
3600 +     * @return the result of accumulating the given transformation
3601 +     * of all keys
3602 +     */
3603 +    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3604 +        (Fun<? super K, ? extends U> transformer,
3605 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3606 +        if (transformer == null || reducer == null)
3607 +            throw new NullPointerException();
3608 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3609 +        U r = null, u;
3610 +        while (it.advance() != null) {
3611 +            if ((u = transformer.apply((K)it.nextKey)) != null)
3612 +                r = (r == null) ? u : reducer.apply(r, u);
3613 +        }
3614 +        return r;
3615 +    }
3616 +
3617 +    /**
3618 +     * Returns the result of accumulating the given transformation
3619 +     * of all keys using the given reducer to combine values, and
3620 +     * the given basis as an identity value.
3621 +     *
3622 +     * @param transformer a function returning the transformation
3623 +     * for an element
3624 +     * @param basis the identity (initial default value) for the reduction
3625 +     * @param reducer a commutative associative combining function
3626 +     * @return  the result of accumulating the given transformation
3627 +     * of all keys
3628 +     */
3629 +    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3630 +        (ObjectToDouble<? super K> transformer,
3631 +         double basis,
3632 +         DoubleByDoubleToDouble reducer) {
3633 +        if (transformer == null || reducer == null)
3634 +            throw new NullPointerException();
3635 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3636 +        double r = basis;
3637 +        while (it.advance() != null)
3638 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3639 +        return r;
3640 +    }
3641 +
3642 +    /**
3643 +     * Returns the result of accumulating the given transformation
3644 +     * of all keys using the given reducer to combine values, and
3645 +     * the given basis as an identity value.
3646 +     *
3647 +     * @param transformer a function returning the transformation
3648 +     * for an element
3649 +     * @param basis the identity (initial default value) for the reduction
3650 +     * @param reducer a commutative associative combining function
3651 +     * @return the result of accumulating the given transformation
3652 +     * of all keys
3653 +     */
3654 +    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3655 +        (ObjectToLong<? super K> transformer,
3656 +         long basis,
3657 +         LongByLongToLong reducer) {
3658 +        if (transformer == null || reducer == null)
3659 +            throw new NullPointerException();
3660 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3661 +        long r = basis;
3662 +        while (it.advance() != null)
3663 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3664 +        return r;
3665 +    }
3666 +
3667 +    /**
3668 +     * Returns the result of accumulating the given transformation
3669 +     * of all keys using the given reducer to combine values, and
3670 +     * the given basis as an identity value.
3671 +     *
3672 +     * @param transformer a function returning the transformation
3673 +     * for an element
3674 +     * @param basis the identity (initial default value) for the reduction
3675 +     * @param reducer a commutative associative combining function
3676 +     * @return the result of accumulating the given transformation
3677 +     * of all keys
3678 +     */
3679 +    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3680 +        (ObjectToInt<? super K> transformer,
3681 +         int basis,
3682 +         IntByIntToInt reducer) {
3683 +        if (transformer == null || reducer == null)
3684 +            throw new NullPointerException();
3685 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3686 +        int r = basis;
3687 +        while (it.advance() != null)
3688 +            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3689 +        return r;
3690 +    }
3691 +
3692 +    /**
3693 +     * Performs the given action for each value.
3694 +     *
3695 +     * @param action the action
3696 +     */
3697 +    public void forEachValueSequentially(Action<V> action) {
3698 +        if (action == null) throw new NullPointerException();
3699 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3700 +        V v;
3701 +        while ((v = it.advance()) != null)
3702 +            action.apply(v);
3703 +    }
3704 +
3705 +    /**
3706 +     * Performs the given action for each non-null transformation
3707 +     * of each value.
3708 +     *
3709 +     * @param transformer a function returning the transformation
3710 +     * for an element, or null if there is no transformation (in
3711 +     * which case the action is not applied)
3712 +     */
3713 +    public <U> void forEachValueSequentially
3714 +        (Fun<? super V, ? extends U> transformer,
3715 +         Action<U> action) {
3716 +        if (transformer == null || action == null)
3717 +            throw new NullPointerException();
3718 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3719 +        V v; U u;
3720 +        while ((v = it.advance()) != null) {
3721 +            if ((u = transformer.apply(v)) != null)
3722 +                action.apply(u);
3723 +        }
3724 +    }
3725 +
3726 +    /**
3727 +     * Returns a non-null result from applying the given search
3728 +     * function on each value, or null if none.
3729 +     *
3730 +     * @param searchFunction a function returning a non-null
3731 +     * result on success, else null
3732 +     * @return a non-null result from applying the given search
3733 +     * function on each value, or null if none
3734 +     */
3735 +    public <U> U searchValuesSequentially
3736 +        (Fun<? super V, ? extends U> searchFunction) {
3737 +        if (searchFunction == null) throw new NullPointerException();
3738 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3739 +        V v; U u;
3740 +        while ((v = it.advance()) != null) {
3741 +            if ((u = searchFunction.apply(v)) != null)
3742 +                return u;
3743 +        }
3744 +        return null;
3745 +    }
3746 +
3747 +    /**
3748 +     * Returns the result of accumulating all values using the
3749 +     * given reducer to combine values, or null if none.
3750 +     *
3751 +     * @param reducer a commutative associative combining function
3752 +     * @return  the result of accumulating all values
3753 +     */
3754 +    public V reduceValuesSequentially
3755 +        (BiFun<? super V, ? super V, ? extends V> reducer) {
3756 +        if (reducer == null) throw new NullPointerException();
3757 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3758 +        V r = null; V v;
3759 +        while ((v = it.advance()) != null)
3760 +            r = (r == null) ? v : reducer.apply(r, v);
3761 +        return r;
3762 +    }
3763 +
3764 +    /**
3765 +     * Returns the result of accumulating the given transformation
3766 +     * of all values using the given reducer to combine values, or
3767 +     * null if none.
3768 +     *
3769 +     * @param transformer a function returning the transformation
3770 +     * for an element, or null if there is no transformation (in
3771 +     * which case it is not combined)
3772 +     * @param reducer a commutative associative combining function
3773 +     * @return the result of accumulating the given transformation
3774 +     * of all values
3775 +     */
3776 +    public <U> U reduceValuesSequentially
3777 +        (Fun<? super V, ? extends U> transformer,
3778 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3779 +        if (transformer == null || reducer == null)
3780 +            throw new NullPointerException();
3781 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3782 +        U r = null, u; V v;
3783 +        while ((v = it.advance()) != null) {
3784 +            if ((u = transformer.apply(v)) != null)
3785 +                r = (r == null) ? u : reducer.apply(r, u);
3786 +        }
3787 +        return r;
3788 +    }
3789 +
3790 +    /**
3791 +     * Returns the result of accumulating the given transformation
3792 +     * of all values using the given reducer to combine values,
3793 +     * and the given basis as an identity value.
3794 +     *
3795 +     * @param transformer a function returning the transformation
3796 +     * for an element
3797 +     * @param basis the identity (initial default value) for the reduction
3798 +     * @param reducer a commutative associative combining function
3799 +     * @return the result of accumulating the given transformation
3800 +     * of all values
3801 +     */
3802 +    public double reduceValuesToDoubleSequentially
3803 +        (ObjectToDouble<? super V> transformer,
3804 +         double basis,
3805 +         DoubleByDoubleToDouble reducer) {
3806 +        if (transformer == null || reducer == null)
3807 +            throw new NullPointerException();
3808 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3809 +        double r = basis; V v;
3810 +        while ((v = it.advance()) != null)
3811 +            r = reducer.apply(r, transformer.apply(v));
3812 +        return r;
3813 +    }
3814 +
3815 +    /**
3816 +     * Returns the result of accumulating the given transformation
3817 +     * of all values using the given reducer to combine values,
3818 +     * and the given basis as an identity value.
3819 +     *
3820 +     * @param transformer a function returning the transformation
3821 +     * for an element
3822 +     * @param basis the identity (initial default value) for the reduction
3823 +     * @param reducer a commutative associative combining function
3824 +     * @return the result of accumulating the given transformation
3825 +     * of all values
3826 +     */
3827 +    public long reduceValuesToLongSequentially
3828 +        (ObjectToLong<? super V> transformer,
3829 +         long basis,
3830 +         LongByLongToLong reducer) {
3831 +        if (transformer == null || reducer == null)
3832 +            throw new NullPointerException();
3833 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3834 +        long r = basis; V v;
3835 +        while ((v = it.advance()) != null)
3836 +            r = reducer.apply(r, transformer.apply(v));
3837 +        return r;
3838 +    }
3839 +
3840 +    /**
3841 +     * Returns the result of accumulating the given transformation
3842 +     * of all values using the given reducer to combine values,
3843 +     * and the given basis as an identity value.
3844 +     *
3845 +     * @param transformer a function returning the transformation
3846 +     * for an element
3847 +     * @param basis the identity (initial default value) for the reduction
3848 +     * @param reducer a commutative associative combining function
3849 +     * @return the result of accumulating the given transformation
3850 +     * of all values
3851 +     */
3852 +    public int reduceValuesToIntSequentially
3853 +        (ObjectToInt<? super V> transformer,
3854 +         int basis,
3855 +         IntByIntToInt reducer) {
3856 +        if (transformer == null || reducer == null)
3857 +            throw new NullPointerException();
3858 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3859 +        int r = basis; V v;
3860 +        while ((v = it.advance()) != null)
3861 +            r = reducer.apply(r, transformer.apply(v));
3862 +        return r;
3863 +    }
3864 +
3865 +    /**
3866 +     * Performs the given action for each entry.
3867 +     *
3868 +     * @param action the action
3869 +     */
3870 +    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3871 +        (Action<Map.Entry<K,V>> action) {
3872 +        if (action == null) throw new NullPointerException();
3873 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874 +        V v;
3875 +        while ((v = it.advance()) != null)
3876 +            action.apply(entryFor((K)it.nextKey, v));
3877 +    }
3878 +
3879 +    /**
3880 +     * Performs the given action for each non-null transformation
3881 +     * of each entry.
3882 +     *
3883 +     * @param transformer a function returning the transformation
3884 +     * for an element, or null if there is no transformation (in
3885 +     * which case the action is not applied)
3886 +     * @param action the action
3887 +     */
3888 +    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3889 +        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3890 +         Action<U> action) {
3891 +        if (transformer == null || action == null)
3892 +            throw new NullPointerException();
3893 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3894 +        V v; U u;
3895 +        while ((v = it.advance()) != null) {
3896 +            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3897 +                action.apply(u);
3898 +        }
3899 +    }
3900 +
3901 +    /**
3902 +     * Returns 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 if there is no transformation (in
3948 +     * which case it is not combined)
3949 +     * @param reducer a commutative associative combining function
3950 +     * @return the result of accumulating the given transformation
3951 +     * of all entries
3952 +     */
3953 +    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
3954 +        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3955 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3956 +        if (transformer == null || reducer == null)
3957 +            throw new NullPointerException();
3958 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3959 +        U r = null, u; V v;
3960 +        while ((v = it.advance()) != null) {
3961 +            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3962 +                r = (r == null) ? u : reducer.apply(r, u);
3963 +        }
3964 +        return r;
3965 +    }
3966 +
3967 +    /**
3968 +     * Returns the result of accumulating the given transformation
3969 +     * of all entries using the given reducer to combine values,
3970 +     * and the given basis as an identity value.
3971 +     *
3972 +     * @param transformer a function returning the transformation
3973 +     * for an element
3974 +     * @param basis the identity (initial default value) for the reduction
3975 +     * @param reducer a commutative associative combining function
3976 +     * @return the result of accumulating the given transformation
3977 +     * of all entries
3978 +     */
3979 +    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
3980 +        (ObjectToDouble<Map.Entry<K,V>> transformer,
3981 +         double basis,
3982 +         DoubleByDoubleToDouble reducer) {
3983 +        if (transformer == null || reducer == null)
3984 +            throw new NullPointerException();
3985 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3986 +        double r = basis; V v;
3987 +        while ((v = it.advance()) != null)
3988 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3989 +        return r;
3990 +    }
3991 +
3992 +    /**
3993 +     * Returns the result of accumulating the given transformation
3994 +     * of all entries using the given reducer to combine values,
3995 +     * and the given basis as an identity value.
3996 +     *
3997 +     * @param transformer a function returning the transformation
3998 +     * for an element
3999 +     * @param basis the identity (initial default value) for the reduction
4000 +     * @param reducer a commutative associative combining function
4001 +     * @return  the result of accumulating the given transformation
4002 +     * of all entries
4003 +     */
4004 +    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4005 +        (ObjectToLong<Map.Entry<K,V>> transformer,
4006 +         long basis,
4007 +         LongByLongToLong reducer) {
4008 +        if (transformer == null || reducer == null)
4009 +            throw new NullPointerException();
4010 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4011 +        long r = basis; V v;
4012 +        while ((v = it.advance()) != null)
4013 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4014 +        return r;
4015 +    }
4016 +
4017 +    /**
4018 +     * Returns the result of accumulating the given transformation
4019 +     * of all entries using the given reducer to combine values,
4020 +     * and the given basis as an identity value.
4021 +     *
4022 +     * @param transformer a function returning the transformation
4023 +     * for an element
4024 +     * @param basis the identity (initial default value) for the reduction
4025 +     * @param reducer a commutative associative combining function
4026 +     * @return the result of accumulating the given transformation
4027 +     * of all entries
4028 +     */
4029 +    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4030 +        (ObjectToInt<Map.Entry<K,V>> transformer,
4031 +         int basis,
4032 +         IntByIntToInt reducer) {
4033 +        if (transformer == null || reducer == null)
4034 +            throw new NullPointerException();
4035 +        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4036 +        int r = basis; V v;
4037 +        while ((v = it.advance()) != null)
4038 +            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4039 +        return r;
4040 +    }
4041 +
4042 +    // Parallel bulk operations
4043 +
4044      /**
4045       * Performs the given action for each (key, value).
4046       *
4047       * @param action the action
4048       */
4049 <    public void forEach(BiAction<K,V> action) {
4049 >    public void forEachInParallel(BiAction<K,V> action) {
4050          ForkJoinTasks.forEach
4051              (this, action).invoke();
4052      }
# Line 3529 | Line 4056 | public class ConcurrentHashMapV8<K, V>
4056       * of each (key, value).
4057       *
4058       * @param transformer a function returning the transformation
4059 <     * for an element, or null of there is no transformation (in
4060 <     * which case the action is not applied).
4059 >     * for an element, or null if there is no transformation (in
4060 >     * which case the action is not applied)
4061       * @param action the action
4062       */
4063 <    public <U> void 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 3551 | 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 3562 | Line 4091 | public class ConcurrentHashMapV8<K, V>
4091       * combine values, or null if none.
4092       *
4093       * @param transformer a function returning the transformation
4094 <     * for an element, or null of there is no transformation (in
4095 <     * which case it is not combined).
4094 >     * for an element, or null if there is no transformation (in
4095 >     * which case it is not combined)
4096       * @param reducer a commutative associative combining function
4097       * @return the result of accumulating the given transformation
4098       * of all (key, value) pairs
4099       */
4100 <    public <U> U 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 3586 | 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 3605 | 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 3624 | 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 3636 | 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 3646 | Line 4179 | public class ConcurrentHashMapV8<K, V>
4179       * of each key.
4180       *
4181       * @param transformer a function returning the transformation
4182 <     * for an element, or null of there is no transformation (in
4183 <     * which case the action is not applied).
4182 >     * for an element, or null if there is no transformation (in
4183 >     * which case the action is not applied)
4184       * @param action the action
4185       */
4186 <    public <U> void 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 3668 | 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 3681 | 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 3692 | Line 4228 | public class ConcurrentHashMapV8<K, V>
4228       * null if none.
4229       *
4230       * @param transformer a function returning the transformation
4231 <     * for an element, or null of there is no transformation (in
4232 <     * which case it is not combined).
4231 >     * for an element, or null if there is no transformation (in
4232 >     * which case it is not combined)
4233       * @param reducer a commutative associative combining function
4234       * @return the result of accumulating the given transformation
4235       * of all keys
4236       */
4237 <    public <U> U 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 3716 | 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 3735 | 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 3754 | 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 3766 | 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 3776 | Line 4316 | public class ConcurrentHashMapV8<K, V>
4316       * of each value.
4317       *
4318       * @param transformer a function returning the transformation
4319 <     * for an element, or null of there is no transformation (in
4320 <     * which case the action is not applied).
4319 >     * for an element, or null if there is no transformation (in
4320 >     * which case the action is not applied)
4321       */
4322 <    public <U> void 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 3796 | Line 4337 | public class ConcurrentHashMapV8<K, V>
4337       * result on success, else null
4338       * @return a non-null result from applying the given search
4339       * function on each value, or null if none
3799     *
4340       */
4341 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
4341 >    public <U> U searchValuesInParallel
4342 >        (Fun<? super V, ? extends U> searchFunction) {
4343          return ForkJoinTasks.searchValues
4344              (this, searchFunction).invoke();
4345      }
# Line 3810 | Line 4351 | public class ConcurrentHashMapV8<K, V>
4351       * @param reducer a commutative associative combining function
4352       * @return  the result of accumulating all values
4353       */
4354 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
4354 >    public V reduceValuesInParallel
4355 >        (BiFun<? super V, ? super V, ? extends V> reducer) {
4356          return ForkJoinTasks.reduceValues
4357              (this, reducer).invoke();
4358      }
# Line 3821 | Line 4363 | public class ConcurrentHashMapV8<K, V>
4363       * null if none.
4364       *
4365       * @param transformer a function returning the transformation
4366 <     * for an element, or null of there is no transformation (in
4367 <     * which case it is not combined).
4366 >     * for an element, or null if there is no transformation (in
4367 >     * which case it is not combined)
4368       * @param reducer a commutative associative combining function
4369       * @return the result of accumulating the given transformation
4370       * of all values
4371       */
4372 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
4373 <                              BiFun<? super U, ? super U, ? extends U> reducer) {
4372 >    public <U> U reduceValuesInParallel
4373 >        (Fun<? super V, ? extends U> transformer,
4374 >         BiFun<? super U, ? super U, ? extends U> reducer) {
4375          return ForkJoinTasks.reduceValues
4376              (this, transformer, reducer).invoke();
4377      }
# Line 3845 | Line 4388 | public class ConcurrentHashMapV8<K, V>
4388       * @return the result of accumulating the given transformation
4389       * of all values
4390       */
4391 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4392 <                                       double basis,
4393 <                                       DoubleByDoubleToDouble reducer) {
4391 >    public double reduceValuesToDoubleInParallel
4392 >        (ObjectToDouble<? super V> transformer,
4393 >         double basis,
4394 >         DoubleByDoubleToDouble reducer) {
4395          return ForkJoinTasks.reduceValuesToDouble
4396              (this, transformer, basis, reducer).invoke();
4397      }
# Line 3864 | Line 4408 | public class ConcurrentHashMapV8<K, V>
4408       * @return the result of accumulating the given transformation
4409       * of all values
4410       */
4411 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4412 <                                   long basis,
4413 <                                   LongByLongToLong reducer) {
4411 >    public long reduceValuesToLongInParallel
4412 >        (ObjectToLong<? super V> transformer,
4413 >         long basis,
4414 >         LongByLongToLong reducer) {
4415          return ForkJoinTasks.reduceValuesToLong
4416              (this, transformer, basis, reducer).invoke();
4417      }
# Line 3883 | Line 4428 | public class ConcurrentHashMapV8<K, V>
4428       * @return the result of accumulating the given transformation
4429       * of all values
4430       */
4431 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4432 <                                 int basis,
4433 <                                 IntByIntToInt reducer) {
4431 >    public int reduceValuesToIntInParallel
4432 >        (ObjectToInt<? super V> transformer,
4433 >         int basis,
4434 >         IntByIntToInt reducer) {
4435          return ForkJoinTasks.reduceValuesToInt
4436              (this, transformer, basis, reducer).invoke();
4437      }
# Line 3895 | Line 4441 | public class ConcurrentHashMapV8<K, V>
4441       *
4442       * @param action the action
4443       */
4444 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4444 >    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4445          ForkJoinTasks.forEachEntry
4446              (this, action).invoke();
4447      }
# Line 3905 | Line 4451 | public class ConcurrentHashMapV8<K, V>
4451       * of each entry.
4452       *
4453       * @param transformer a function returning the transformation
4454 <     * for an element, or null of there is no transformation (in
4455 <     * which case the action is not applied).
4454 >     * for an element, or null if there is no transformation (in
4455 >     * which case the action is not applied)
4456       * @param action the action
4457       */
4458 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4459 <                                 Action<U> action) {
4458 >    public <U> void forEachEntryInParallel
4459 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4460 >         Action<U> action) {
4461          ForkJoinTasks.forEachEntry
4462              (this, transformer, action).invoke();
4463      }
# Line 3927 | Line 4474 | public class ConcurrentHashMapV8<K, V>
4474       * @return a non-null result from applying the given search
4475       * function on each entry, or null if none
4476       */
4477 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4477 >    public <U> U searchEntriesInParallel
4478 >        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4479          return ForkJoinTasks.searchEntries
4480              (this, searchFunction).invoke();
4481      }
# Line 3939 | Line 4487 | public class ConcurrentHashMapV8<K, V>
4487       * @param reducer a commutative associative combining function
4488       * @return the result of accumulating all entries
4489       */
4490 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4490 >    public Map.Entry<K,V> reduceEntriesInParallel
4491 >        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4492          return ForkJoinTasks.reduceEntries
4493              (this, reducer).invoke();
4494      }
# Line 3950 | Line 4499 | public class ConcurrentHashMapV8<K, V>
4499       * or null if none.
4500       *
4501       * @param transformer a function returning the transformation
4502 <     * for an element, or null of there is no transformation (in
4503 <     * which case it is not combined).
4502 >     * for an element, or null if there is no transformation (in
4503 >     * which case it is not combined)
4504       * @param reducer a commutative associative combining function
4505       * @return the result of accumulating the given transformation
4506       * of all entries
4507       */
4508 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4509 <                               BiFun<? super U, ? super U, ? extends U> reducer) {
4508 >    public <U> U reduceEntriesInParallel
4509 >        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4510 >         BiFun<? super U, ? super U, ? extends U> reducer) {
4511          return ForkJoinTasks.reduceEntries
4512              (this, transformer, reducer).invoke();
4513      }
# Line 3974 | Line 4524 | public class ConcurrentHashMapV8<K, V>
4524       * @return the result of accumulating the given transformation
4525       * of all entries
4526       */
4527 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4528 <                                        double basis,
4529 <                                        DoubleByDoubleToDouble reducer) {
4527 >    public double reduceEntriesToDoubleInParallel
4528 >        (ObjectToDouble<Map.Entry<K,V>> transformer,
4529 >         double basis,
4530 >         DoubleByDoubleToDouble reducer) {
4531          return ForkJoinTasks.reduceEntriesToDouble
4532              (this, transformer, basis, reducer).invoke();
4533      }
# Line 3993 | Line 4544 | public class ConcurrentHashMapV8<K, V>
4544       * @return  the result of accumulating the given transformation
4545       * of all entries
4546       */
4547 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4548 <                                    long basis,
4549 <                                    LongByLongToLong reducer) {
4547 >    public long reduceEntriesToLongInParallel
4548 >        (ObjectToLong<Map.Entry<K,V>> transformer,
4549 >         long basis,
4550 >         LongByLongToLong reducer) {
4551          return ForkJoinTasks.reduceEntriesToLong
4552              (this, transformer, basis, reducer).invoke();
4553      }
# Line 4012 | Line 4564 | public class ConcurrentHashMapV8<K, V>
4564       * @return the result of accumulating the given transformation
4565       * of all entries
4566       */
4567 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4568 <                                  int basis,
4569 <                                  IntByIntToInt reducer) {
4567 >    public int reduceEntriesToIntInParallel
4568 >        (ObjectToInt<Map.Entry<K,V>> transformer,
4569 >         int basis,
4570 >         IntByIntToInt reducer) {
4571          return ForkJoinTasks.reduceEntriesToInt
4572              (this, transformer, basis, reducer).invoke();
4573      }
4574  
4575 +
4576      /* ----------------Views -------------- */
4577  
4578      /**
4579       * Base class for views.
4580       */
4581 <    static abstract class CHMView<K, V> {
4581 >    abstract static class CHMView<K, V> {
4582          final ConcurrentHashMapV8<K, V> map;
4583          CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4584  
# Line 4040 | Line 4594 | public class ConcurrentHashMapV8<K, V>
4594          public final void clear()               { map.clear(); }
4595  
4596          // implementations below rely on concrete classes supplying these
4597 <        abstract public Iterator<?> iterator();
4598 <        abstract public boolean contains(Object o);
4599 <        abstract public boolean remove(Object o);
4597 >        public abstract Iterator<?> iterator();
4598 >        public abstract boolean contains(Object o);
4599 >        public abstract boolean remove(Object o);
4600  
4601          private static final String oomeMsg = "Required array size too large";
4602  
# Line 4161 | Line 4715 | public class ConcurrentHashMapV8<K, V>
4715       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4716       * which additions may optionally be enabled by mapping to a
4717       * common value.  This class cannot be directly instantiated. See
4718 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4718 >     * {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()},
4719       * {@link #newKeySet(int)}.
4720       */
4721 <    public static class KeySetView<K,V> extends CHMView<K,V> implements Set<K>, java.io.Serializable {
4721 >    public static class KeySetView<K,V> extends CHMView<K,V>
4722 >        implements Set<K>, java.io.Serializable {
4723          private static final long serialVersionUID = 7249069246763182397L;
4724          private final V value;
4725          KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
# Line 4177 | Line 4732 | public class ConcurrentHashMapV8<K, V>
4732           * or {@code null} if additions are not supported.
4733           *
4734           * @return the default mapped value for additions, or {@code null}
4735 <         * if not supported.
4735 >         * if not supported
4736           */
4737          public V getMappedValue() { return value; }
4738  
# Line 4201 | Line 4756 | public class ConcurrentHashMapV8<K, V>
4756              V v;
4757              if ((v = value) == null)
4758                  throw new UnsupportedOperationException();
4759 <            if (e == null)
4205 <                throw new NullPointerException();
4206 <            return map.internalPutIfAbsent(e, v) == null;
4759 >            return map.internalPut(e, v, true) == null;
4760          }
4761          public boolean addAll(Collection<? extends K> c) {
4762              boolean added = false;
# Line 4211 | Line 4764 | public class ConcurrentHashMapV8<K, V>
4764              if ((v = value) == null)
4765                  throw new UnsupportedOperationException();
4766              for (K e : c) {
4767 <                if (e == null)
4215 <                    throw new NullPointerException();
4216 <                if (map.internalPutIfAbsent(e, v) == null)
4767 >                if (map.internalPut(e, v, true) == null)
4768                      added = true;
4769              }
4770              return added;
# Line 4224 | Line 4775 | public class ConcurrentHashMapV8<K, V>
4775                      ((c = (Set<?>)o) == this ||
4776                       (containsAll(c) && c.containsAll(this))));
4777          }
4227
4228        /**
4229         * Performs the given action for each key.
4230         *
4231         * @param action the action
4232         */
4233        public void forEach(Action<K> action) {
4234            ForkJoinTasks.forEachKey
4235                (map, action).invoke();
4236        }
4237
4238        /**
4239         * Performs the given action for each non-null transformation
4240         * of each key.
4241         *
4242         * @param transformer a function returning the transformation
4243         * for an element, or null of there is no transformation (in
4244         * which case the action is not applied).
4245         * @param action the action
4246         */
4247        public <U> void forEach(Fun<? super K, ? extends U> transformer,
4248                                Action<U> action) {
4249            ForkJoinTasks.forEachKey
4250                (map, transformer, action).invoke();
4251        }
4252
4253        /**
4254         * Returns a non-null result from applying the given search
4255         * function on each key, or null if none. Upon success,
4256         * further element processing is suppressed and the results of
4257         * any other parallel invocations of the search function are
4258         * ignored.
4259         *
4260         * @param searchFunction a function returning a non-null
4261         * result on success, else null
4262         * @return a non-null result from applying the given search
4263         * function on each key, or null if none
4264         */
4265        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4266            return ForkJoinTasks.searchKeys
4267                (map, searchFunction).invoke();
4268        }
4269
4270        /**
4271         * Returns the result of accumulating all keys using the given
4272         * reducer to combine values, or null if none.
4273         *
4274         * @param reducer a commutative associative combining function
4275         * @return the result of accumulating all keys using the given
4276         * reducer to combine values, or null if none
4277         */
4278        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4279            return ForkJoinTasks.reduceKeys
4280                (map, reducer).invoke();
4281        }
4282
4283        /**
4284         * Returns the result of accumulating the given transformation
4285         * of all keys using the given reducer to combine values, and
4286         * the given basis as an identity value.
4287         *
4288         * @param transformer a function returning the transformation
4289         * for an element
4290         * @param basis the identity (initial default value) for the reduction
4291         * @param reducer a commutative associative combining function
4292         * @return  the result of accumulating the given transformation
4293         * of all keys
4294         */
4295        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4296                                     double basis,
4297                                     DoubleByDoubleToDouble reducer) {
4298            return ForkJoinTasks.reduceKeysToDouble
4299                (map, transformer, basis, reducer).invoke();
4300        }
4301
4302
4303        /**
4304         * Returns the result of accumulating the given transformation
4305         * of all keys using the given reducer to combine values, and
4306         * the given basis as an identity value.
4307         *
4308         * @param transformer a function returning the transformation
4309         * for an element
4310         * @param basis the identity (initial default value) for the reduction
4311         * @param reducer a commutative associative combining function
4312         * @return the result of accumulating the given transformation
4313         * of all keys
4314         */
4315        public long reduceToLong(ObjectToLong<? super K> transformer,
4316                                 long basis,
4317                                 LongByLongToLong reducer) {
4318            return ForkJoinTasks.reduceKeysToLong
4319                (map, transformer, basis, reducer).invoke();
4320        }
4321
4322        /**
4323         * Returns the result of accumulating the given transformation
4324         * of all keys using the given reducer to combine values, and
4325         * the given basis as an identity value.
4326         *
4327         * @param transformer a function returning the transformation
4328         * for an element
4329         * @param basis the identity (initial default value) for the reduction
4330         * @param reducer a commutative associative combining function
4331         * @return the result of accumulating the given transformation
4332         * of all keys
4333         */
4334        public int reduceToInt(ObjectToInt<? super K> transformer,
4335                               int basis,
4336                               IntByIntToInt reducer) {
4337            return ForkJoinTasks.reduceKeysToInt
4338                (map, transformer, basis, reducer).invoke();
4339        }
4340
4778      }
4779  
4780      /**
4781       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4782       * values, in which additions are disabled. This class cannot be
4783 <     * directly instantiated. See {@link #values},
4783 >     * directly instantiated. See {@link #values()}.
4784       *
4785       * <p>The view's {@code iterator} is a "weakly consistent" iterator
4786       * that will never throw {@link ConcurrentModificationException},
# Line 4388 | Line 4825 | public class ConcurrentHashMapV8<K, V>
4825              throw new UnsupportedOperationException();
4826          }
4827  
4391        /**
4392         * Performs the given action for each value.
4393         *
4394         * @param action the action
4395         */
4396        public void forEach(Action<V> action) {
4397            ForkJoinTasks.forEachValue
4398                (map, action).invoke();
4399        }
4400
4401        /**
4402         * Performs the given action for each non-null transformation
4403         * of each value.
4404         *
4405         * @param transformer a function returning the transformation
4406         * for an element, or null of there is no transformation (in
4407         * which case the action is not applied).
4408         */
4409        public <U> void forEach(Fun<? super V, ? extends U> transformer,
4410                                     Action<U> action) {
4411            ForkJoinTasks.forEachValue
4412                (map, transformer, action).invoke();
4413        }
4414
4415        /**
4416         * Returns a non-null result from applying the given search
4417         * function on each value, or null if none.  Upon success,
4418         * further element processing is suppressed and the results of
4419         * any other parallel invocations of the search function are
4420         * ignored.
4421         *
4422         * @param searchFunction a function returning a non-null
4423         * result on success, else null
4424         * @return a non-null result from applying the given search
4425         * function on each value, or null if none
4426         *
4427         */
4428        public <U> U search(Fun<? super V, ? extends U> searchFunction) {
4429            return ForkJoinTasks.searchValues
4430                (map, searchFunction).invoke();
4431        }
4432
4433        /**
4434         * Returns the result of accumulating all values using the
4435         * given reducer to combine values, or null if none.
4436         *
4437         * @param reducer a commutative associative combining function
4438         * @return  the result of accumulating all values
4439         */
4440        public V reduce(BiFun<? super V, ? super V, ? extends V> reducer) {
4441            return ForkJoinTasks.reduceValues
4442                (map, reducer).invoke();
4443        }
4444
4445        /**
4446         * Returns the result of accumulating the given transformation
4447         * of all values using the given reducer to combine values, or
4448         * null if none.
4449         *
4450         * @param transformer a function returning the transformation
4451         * for an element, or null of there is no transformation (in
4452         * which case it is not combined).
4453         * @param reducer a commutative associative combining function
4454         * @return the result of accumulating the given transformation
4455         * of all values
4456         */
4457        public <U> U reduce(Fun<? super V, ? extends U> transformer,
4458                            BiFun<? super U, ? super U, ? extends U> reducer) {
4459            return ForkJoinTasks.reduceValues
4460                (map, transformer, reducer).invoke();
4461        }
4462
4463        /**
4464         * Returns the result of accumulating the given transformation
4465         * of all values using the given reducer to combine values,
4466         * and the given basis as an identity value.
4467         *
4468         * @param transformer a function returning the transformation
4469         * for an element
4470         * @param basis the identity (initial default value) for the reduction
4471         * @param reducer a commutative associative combining function
4472         * @return the result of accumulating the given transformation
4473         * of all values
4474         */
4475        public double reduceToDouble(ObjectToDouble<? super V> transformer,
4476                                     double basis,
4477                                     DoubleByDoubleToDouble reducer) {
4478            return ForkJoinTasks.reduceValuesToDouble
4479                (map, transformer, basis, reducer).invoke();
4480        }
4481
4482        /**
4483         * Returns the result of accumulating the given transformation
4484         * of all values using the given reducer to combine values,
4485         * and the given basis as an identity value.
4486         *
4487         * @param transformer a function returning the transformation
4488         * for an element
4489         * @param basis the identity (initial default value) for the reduction
4490         * @param reducer a commutative associative combining function
4491         * @return the result of accumulating the given transformation
4492         * of all values
4493         */
4494        public long reduceToLong(ObjectToLong<? super V> transformer,
4495                                 long basis,
4496                                 LongByLongToLong reducer) {
4497            return ForkJoinTasks.reduceValuesToLong
4498                (map, transformer, basis, reducer).invoke();
4499        }
4500
4501        /**
4502         * Returns the result of accumulating the given transformation
4503         * of all values using the given reducer to combine values,
4504         * and the given basis as an identity value.
4505         *
4506         * @param transformer a function returning the transformation
4507         * for an element
4508         * @param basis the identity (initial default value) for the reduction
4509         * @param reducer a commutative associative combining function
4510         * @return the result of accumulating the given transformation
4511         * of all values
4512         */
4513        public int reduceToInt(ObjectToInt<? super V> transformer,
4514                               int basis,
4515                               IntByIntToInt reducer) {
4516            return ForkJoinTasks.reduceValuesToInt
4517                (map, transformer, basis, reducer).invoke();
4518        }
4519
4828      }
4829  
4830      /**
4831       * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4832       * entries.  This class cannot be directly instantiated. See
4833 <     * {@link #entrySet}.
4833 >     * {@link #entrySet()}.
4834       */
4835      public static final class EntrySetView<K,V> extends CHMView<K,V>
4836          implements Set<Map.Entry<K,V>> {
# Line 4558 | Line 4866 | public class ConcurrentHashMapV8<K, V>
4866          }
4867  
4868          public final boolean add(Entry<K,V> e) {
4869 <            K key = e.getKey();
4562 <            V value = e.getValue();
4563 <            if (key == null || value == null)
4564 <                throw new NullPointerException();
4565 <            return map.internalPut(key, value) == null;
4869 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4870          }
4871          public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4872              boolean added = false;
# Line 4578 | Line 4882 | public class ConcurrentHashMapV8<K, V>
4882                      ((c = (Set<?>)o) == this ||
4883                       (containsAll(c) && c.containsAll(this))));
4884          }
4581
4582        /**
4583         * Performs the given action for each entry.
4584         *
4585         * @param action the action
4586         */
4587        public void forEach(Action<Map.Entry<K,V>> action) {
4588            ForkJoinTasks.forEachEntry
4589                (map, action).invoke();
4590        }
4591
4592        /**
4593         * Performs the given action for each non-null transformation
4594         * of each entry.
4595         *
4596         * @param transformer a function returning the transformation
4597         * for an element, or null of there is no transformation (in
4598         * which case the action is not applied).
4599         * @param action the action
4600         */
4601        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4602                                Action<U> action) {
4603            ForkJoinTasks.forEachEntry
4604                (map, transformer, action).invoke();
4605        }
4606
4607        /**
4608         * Returns a non-null result from applying the given search
4609         * function on each entry, or null if none.  Upon success,
4610         * further element processing is suppressed and the results of
4611         * any other parallel invocations of the search function are
4612         * ignored.
4613         *
4614         * @param searchFunction a function returning a non-null
4615         * result on success, else null
4616         * @return a non-null result from applying the given search
4617         * function on each entry, or null if none
4618         */
4619        public <U> U search(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4620            return ForkJoinTasks.searchEntries
4621                (map, searchFunction).invoke();
4622        }
4623
4624        /**
4625         * Returns the result of accumulating all entries using the
4626         * given reducer to combine values, or null if none.
4627         *
4628         * @param reducer a commutative associative combining function
4629         * @return the result of accumulating all entries
4630         */
4631        public Map.Entry<K,V> reduce(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4632            return ForkJoinTasks.reduceEntries
4633                (map, reducer).invoke();
4634        }
4635
4636        /**
4637         * Returns the result of accumulating the given transformation
4638         * of all entries using the given reducer to combine values,
4639         * or null if none.
4640         *
4641         * @param transformer a function returning the transformation
4642         * for an element, or null of there is no transformation (in
4643         * which case it is not combined).
4644         * @param reducer a commutative associative combining function
4645         * @return the result of accumulating the given transformation
4646         * of all entries
4647         */
4648        public <U> U reduce(Fun<Map.Entry<K,V>, ? extends U> transformer,
4649                            BiFun<? super U, ? super U, ? extends U> reducer) {
4650            return ForkJoinTasks.reduceEntries
4651                (map, transformer, reducer).invoke();
4652        }
4653
4654        /**
4655         * Returns the result of accumulating the given transformation
4656         * of all entries using the given reducer to combine values,
4657         * and the given basis as an identity value.
4658         *
4659         * @param transformer a function returning the transformation
4660         * for an element
4661         * @param basis the identity (initial default value) for the reduction
4662         * @param reducer a commutative associative combining function
4663         * @return the result of accumulating the given transformation
4664         * of all entries
4665         */
4666        public double reduceToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4667                                     double basis,
4668                                     DoubleByDoubleToDouble reducer) {
4669            return ForkJoinTasks.reduceEntriesToDouble
4670                (map, transformer, basis, reducer).invoke();
4671        }
4672
4673        /**
4674         * Returns the result of accumulating the given transformation
4675         * of all entries using the given reducer to combine values,
4676         * and the given basis as an identity value.
4677         *
4678         * @param transformer a function returning the transformation
4679         * for an element
4680         * @param basis the identity (initial default value) for the reduction
4681         * @param reducer a commutative associative combining function
4682         * @return  the result of accumulating the given transformation
4683         * of all entries
4684         */
4685        public long reduceToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4686                                 long basis,
4687                                 LongByLongToLong reducer) {
4688            return ForkJoinTasks.reduceEntriesToLong
4689                (map, transformer, basis, reducer).invoke();
4690        }
4691
4692        /**
4693         * Returns the result of accumulating the given transformation
4694         * of all entries using the given reducer to combine values,
4695         * and the given basis as an identity value.
4696         *
4697         * @param transformer a function returning the transformation
4698         * for an element
4699         * @param basis the identity (initial default value) for the reduction
4700         * @param reducer a commutative associative combining function
4701         * @return the result of accumulating the given transformation
4702         * of all entries
4703         */
4704        public int reduceToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4705                               int basis,
4706                               IntByIntToInt reducer) {
4707            return ForkJoinTasks.reduceEntriesToInt
4708                (map, transformer, basis, reducer).invoke();
4709        }
4710
4885      }
4886  
4887      // ---------------------------------------------------------------------
# Line 4789 | Line 4963 | public class ConcurrentHashMapV8<K, V>
4963           * @param map the map
4964           * @param transformer a function returning the transformation
4965           * for an element, or null if there is no transformation (in
4966 <         * which case it is not combined).
4966 >         * which case it is not combined)
4967           * @param reducer a commutative associative combining function
4968           * @return the task
4969           */
# Line 4956 | Line 5130 | public class ConcurrentHashMapV8<K, V>
5130           * @param map the map
5131           * @param transformer a function returning the transformation
5132           * for an element, or null if there is no transformation (in
5133 <         * which case it is not combined).
5133 >         * which case it is not combined)
5134           * @param reducer a commutative associative combining function
5135           * @return the task
5136           */
# Line 5122 | Line 5296 | public class ConcurrentHashMapV8<K, V>
5296           * @param map the map
5297           * @param transformer a function returning the transformation
5298           * for an element, or null if there is no transformation (in
5299 <         * which case it is not combined).
5299 >         * which case it is not combined)
5300           * @param reducer a commutative associative combining function
5301           * @return the task
5302           */
# Line 5288 | Line 5462 | public class ConcurrentHashMapV8<K, V>
5462           * @param map the map
5463           * @param transformer a function returning the transformation
5464           * for an element, or null if there is no transformation (in
5465 <         * which case it is not combined).
5465 >         * which case it is not combined)
5466           * @param reducer a commutative associative combining function
5467           * @return the task
5468           */
# Line 5380 | Line 5554 | public class ConcurrentHashMapV8<K, V>
5554      /*
5555       * Task classes. Coded in a regular but ugly format/style to
5556       * simplify checks that each variant differs in the right way from
5557 <     * others.
5557 >     * others. The null screenings exist because compilers cannot tell
5558 >     * that we've already null-checked task arguments, so we force
5559 >     * simplest hoisted bypass to help avoid convoluted traps.
5560       */
5561  
5562      @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
# Line 5394 | Line 5570 | public class ConcurrentHashMapV8<K, V>
5570          }
5571          @SuppressWarnings("unchecked") public final void compute() {
5572              final Action<K> action;
5573 <            if ((action = this.action) == null)
5574 <                throw new NullPointerException();
5575 <            for (int b; (b = preSplit()) > 0;)
5576 <                new ForEachKeyTask<K,V>(map, this, b, action).fork();
5577 <            while (advance() != null)
5578 <                action.apply((K)nextKey);
5579 <            propagateCompletion();
5573 >            if ((action = this.action) != null) {
5574 >                for (int b; (b = preSplit()) > 0;)
5575 >                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
5576 >                while (advance() != null)
5577 >                    action.apply((K)nextKey);
5578 >                propagateCompletion();
5579 >            }
5580          }
5581      }
5582  
# Line 5415 | Line 5591 | public class ConcurrentHashMapV8<K, V>
5591          }
5592          @SuppressWarnings("unchecked") public final void compute() {
5593              final Action<V> action;
5594 <            if ((action = this.action) == null)
5595 <                throw new NullPointerException();
5596 <            for (int b; (b = preSplit()) > 0;)
5597 <                new ForEachValueTask<K,V>(map, this, b, action).fork();
5598 <            Object v;
5599 <            while ((v = advance()) != null)
5600 <                action.apply((V)v);
5601 <            propagateCompletion();
5594 >            if ((action = this.action) != null) {
5595 >                for (int b; (b = preSplit()) > 0;)
5596 >                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5597 >                V v;
5598 >                while ((v = advance()) != null)
5599 >                    action.apply(v);
5600 >                propagateCompletion();
5601 >            }
5602          }
5603      }
5604  
# Line 5437 | Line 5613 | public class ConcurrentHashMapV8<K, V>
5613          }
5614          @SuppressWarnings("unchecked") public final void compute() {
5615              final Action<Entry<K,V>> action;
5616 <            if ((action = this.action) == null)
5617 <                throw new NullPointerException();
5618 <            for (int b; (b = preSplit()) > 0;)
5619 <                new ForEachEntryTask<K,V>(map, this, b, action).fork();
5620 <            Object v;
5621 <            while ((v = advance()) != null)
5622 <                action.apply(entryFor((K)nextKey, (V)v));
5623 <            propagateCompletion();
5616 >            if ((action = this.action) != null) {
5617 >                for (int b; (b = preSplit()) > 0;)
5618 >                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5619 >                V v;
5620 >                while ((v = advance()) != null)
5621 >                    action.apply(entryFor((K)nextKey, v));
5622 >                propagateCompletion();
5623 >            }
5624          }
5625      }
5626  
# Line 5459 | Line 5635 | public class ConcurrentHashMapV8<K, V>
5635          }
5636          @SuppressWarnings("unchecked") public final void compute() {
5637              final BiAction<K,V> action;
5638 <            if ((action = this.action) == null)
5639 <                throw new NullPointerException();
5640 <            for (int b; (b = preSplit()) > 0;)
5641 <                new ForEachMappingTask<K,V>(map, this, b, action).fork();
5642 <            Object v;
5643 <            while ((v = advance()) != null)
5644 <                action.apply((K)nextKey, (V)v);
5645 <            propagateCompletion();
5638 >            if ((action = this.action) != null) {
5639 >                for (int b; (b = preSplit()) > 0;)
5640 >                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5641 >                V v;
5642 >                while ((v = advance()) != null)
5643 >                    action.apply((K)nextKey, v);
5644 >                propagateCompletion();
5645 >            }
5646          }
5647      }
5648  
# Line 5483 | Line 5659 | public class ConcurrentHashMapV8<K, V>
5659          @SuppressWarnings("unchecked") public final void compute() {
5660              final Fun<? super K, ? extends U> transformer;
5661              final Action<U> action;
5662 <            if ((transformer = this.transformer) == null ||
5663 <                (action = this.action) == null)
5664 <                throw new NullPointerException();
5665 <            for (int b; (b = preSplit()) > 0;)
5666 <                new ForEachTransformedKeyTask<K,V,U>
5667 <                     (map, this, b, transformer, action).fork();
5668 <            U u;
5669 <            while (advance() != null) {
5670 <                if ((u = transformer.apply((K)nextKey)) != null)
5671 <                    action.apply(u);
5662 >            if ((transformer = this.transformer) != null &&
5663 >                (action = this.action) != null) {
5664 >                for (int b; (b = preSplit()) > 0;)
5665 >                    new ForEachTransformedKeyTask<K,V,U>
5666 >                        (map, this, b, transformer, action).fork();
5667 >                U u;
5668 >                while (advance() != null) {
5669 >                    if ((u = transformer.apply((K)nextKey)) != null)
5670 >                        action.apply(u);
5671 >                }
5672 >                propagateCompletion();
5673              }
5497            propagateCompletion();
5674          }
5675      }
5676  
# Line 5511 | Line 5687 | public class ConcurrentHashMapV8<K, V>
5687          @SuppressWarnings("unchecked") public final void compute() {
5688              final Fun<? super V, ? extends U> transformer;
5689              final Action<U> action;
5690 <            if ((transformer = this.transformer) == null ||
5691 <                (action = this.action) == null)
5692 <                throw new NullPointerException();
5693 <            for (int b; (b = preSplit()) > 0;)
5694 <                new ForEachTransformedValueTask<K,V,U>
5695 <                    (map, this, b, transformer, action).fork();
5696 <            Object v; U u;
5697 <            while ((v = advance()) != null) {
5698 <                if ((u = transformer.apply((V)v)) != null)
5699 <                    action.apply(u);
5690 >            if ((transformer = this.transformer) != null &&
5691 >                (action = this.action) != null) {
5692 >                for (int b; (b = preSplit()) > 0;)
5693 >                    new ForEachTransformedValueTask<K,V,U>
5694 >                        (map, this, b, transformer, action).fork();
5695 >                V v; U u;
5696 >                while ((v = advance()) != null) {
5697 >                    if ((u = transformer.apply(v)) != null)
5698 >                        action.apply(u);
5699 >                }
5700 >                propagateCompletion();
5701              }
5525            propagateCompletion();
5702          }
5703      }
5704  
# Line 5539 | Line 5715 | public class ConcurrentHashMapV8<K, V>
5715          @SuppressWarnings("unchecked") public final void compute() {
5716              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5717              final Action<U> action;
5718 <            if ((transformer = this.transformer) == null ||
5719 <                (action = this.action) == null)
5720 <                throw new NullPointerException();
5721 <            for (int b; (b = preSplit()) > 0;)
5722 <                new ForEachTransformedEntryTask<K,V,U>
5723 <                    (map, this, b, transformer, action).fork();
5724 <            Object v; U u;
5725 <            while ((v = advance()) != null) {
5726 <                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5727 <                    action.apply(u);
5718 >            if ((transformer = this.transformer) != null &&
5719 >                (action = this.action) != null) {
5720 >                for (int b; (b = preSplit()) > 0;)
5721 >                    new ForEachTransformedEntryTask<K,V,U>
5722 >                        (map, this, b, transformer, action).fork();
5723 >                V v; U u;
5724 >                while ((v = advance()) != null) {
5725 >                    if ((u = transformer.apply(entryFor((K)nextKey,
5726 >                                                        v))) != null)
5727 >                        action.apply(u);
5728 >                }
5729 >                propagateCompletion();
5730              }
5553            propagateCompletion();
5731          }
5732      }
5733  
# Line 5568 | Line 5745 | public class ConcurrentHashMapV8<K, V>
5745          @SuppressWarnings("unchecked") public final void compute() {
5746              final BiFun<? super K, ? super V, ? extends U> transformer;
5747              final Action<U> action;
5748 <            if ((transformer = this.transformer) == null ||
5749 <                (action = this.action) == null)
5750 <                throw new NullPointerException();
5751 <            for (int b; (b = preSplit()) > 0;)
5752 <                new ForEachTransformedMappingTask<K,V,U>
5753 <                    (map, this, b, transformer, action).fork();
5754 <            Object v; U u;
5755 <            while ((v = advance()) != null) {
5756 <                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5757 <                    action.apply(u);
5748 >            if ((transformer = this.transformer) != null &&
5749 >                (action = this.action) != null) {
5750 >                for (int b; (b = preSplit()) > 0;)
5751 >                    new ForEachTransformedMappingTask<K,V,U>
5752 >                        (map, this, b, transformer, action).fork();
5753 >                V v; U u;
5754 >                while ((v = advance()) != null) {
5755 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
5756 >                        action.apply(u);
5757 >                }
5758 >                propagateCompletion();
5759              }
5582            propagateCompletion();
5760          }
5761      }
5762  
# Line 5598 | Line 5775 | public class ConcurrentHashMapV8<K, V>
5775          @SuppressWarnings("unchecked") public final void compute() {
5776              final Fun<? super K, ? extends U> searchFunction;
5777              final AtomicReference<U> result;
5778 <            if ((searchFunction = this.searchFunction) == null ||
5779 <                (result = this.result) == null)
5780 <                throw new NullPointerException();
5781 <            for (int b;;) {
5782 <                if (result.get() != null)
5783 <                    return;
5784 <                if ((b = preSplit()) <= 0)
5785 <                    break;
5786 <                new SearchKeysTask<K,V,U>
5610 <                    (map, this, b, searchFunction, result).fork();
5611 <            }
5612 <            while (result.get() == null) {
5613 <                U u;
5614 <                if (advance() == null) {
5615 <                    propagateCompletion();
5616 <                    break;
5778 >            if ((searchFunction = this.searchFunction) != null &&
5779 >                (result = this.result) != null) {
5780 >                for (int b;;) {
5781 >                    if (result.get() != null)
5782 >                        return;
5783 >                    if ((b = preSplit()) <= 0)
5784 >                        break;
5785 >                    new SearchKeysTask<K,V,U>
5786 >                        (map, this, b, searchFunction, result).fork();
5787                  }
5788 <                if ((u = searchFunction.apply((K)nextKey)) != null) {
5789 <                    if (result.compareAndSet(null, u))
5790 <                        quietlyCompleteRoot();
5791 <                    break;
5788 >                while (result.get() == null) {
5789 >                    U u;
5790 >                    if (advance() == null) {
5791 >                        propagateCompletion();
5792 >                        break;
5793 >                    }
5794 >                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5795 >                        if (result.compareAndSet(null, u))
5796 >                            quietlyCompleteRoot();
5797 >                        break;
5798 >                    }
5799                  }
5800              }
5801          }
# Line 5639 | Line 5816 | public class ConcurrentHashMapV8<K, V>
5816          @SuppressWarnings("unchecked") public final void compute() {
5817              final Fun<? super V, ? extends U> searchFunction;
5818              final AtomicReference<U> result;
5819 <            if ((searchFunction = this.searchFunction) == null ||
5820 <                (result = this.result) == null)
5821 <                throw new NullPointerException();
5822 <            for (int b;;) {
5823 <                if (result.get() != null)
5824 <                    return;
5825 <                if ((b = preSplit()) <= 0)
5826 <                    break;
5827 <                new SearchValuesTask<K,V,U>
5651 <                    (map, this, b, searchFunction, result).fork();
5652 <            }
5653 <            while (result.get() == null) {
5654 <                Object v; U u;
5655 <                if ((v = advance()) == null) {
5656 <                    propagateCompletion();
5657 <                    break;
5819 >            if ((searchFunction = this.searchFunction) != null &&
5820 >                (result = this.result) != null) {
5821 >                for (int b;;) {
5822 >                    if (result.get() != null)
5823 >                        return;
5824 >                    if ((b = preSplit()) <= 0)
5825 >                        break;
5826 >                    new SearchValuesTask<K,V,U>
5827 >                        (map, this, b, searchFunction, result).fork();
5828                  }
5829 <                if ((u = searchFunction.apply((V)v)) != null) {
5830 <                    if (result.compareAndSet(null, u))
5831 <                        quietlyCompleteRoot();
5832 <                    break;
5829 >                while (result.get() == null) {
5830 >                    V v; U u;
5831 >                    if ((v = advance()) == null) {
5832 >                        propagateCompletion();
5833 >                        break;
5834 >                    }
5835 >                    if ((u = searchFunction.apply(v)) != null) {
5836 >                        if (result.compareAndSet(null, u))
5837 >                            quietlyCompleteRoot();
5838 >                        break;
5839 >                    }
5840                  }
5841              }
5842          }
# Line 5680 | Line 5857 | public class ConcurrentHashMapV8<K, V>
5857          @SuppressWarnings("unchecked") public final void compute() {
5858              final Fun<Entry<K,V>, ? extends U> searchFunction;
5859              final AtomicReference<U> result;
5860 <            if ((searchFunction = this.searchFunction) == null ||
5861 <                (result = this.result) == null)
5862 <                throw new NullPointerException();
5863 <            for (int b;;) {
5864 <                if (result.get() != null)
5865 <                    return;
5866 <                if ((b = preSplit()) <= 0)
5867 <                    break;
5868 <                new SearchEntriesTask<K,V,U>
5692 <                    (map, this, b, searchFunction, result).fork();
5693 <            }
5694 <            while (result.get() == null) {
5695 <                Object v; U u;
5696 <                if ((v = advance()) == null) {
5697 <                    propagateCompletion();
5698 <                    break;
5860 >            if ((searchFunction = this.searchFunction) != null &&
5861 >                (result = this.result) != null) {
5862 >                for (int b;;) {
5863 >                    if (result.get() != null)
5864 >                        return;
5865 >                    if ((b = preSplit()) <= 0)
5866 >                        break;
5867 >                    new SearchEntriesTask<K,V,U>
5868 >                        (map, this, b, searchFunction, result).fork();
5869                  }
5870 <                if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5871 <                    if (result.compareAndSet(null, u))
5872 <                        quietlyCompleteRoot();
5873 <                    return;
5870 >                while (result.get() == null) {
5871 >                    V v; U u;
5872 >                    if ((v = advance()) == null) {
5873 >                        propagateCompletion();
5874 >                        break;
5875 >                    }
5876 >                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5877 >                                                           v))) != null) {
5878 >                        if (result.compareAndSet(null, u))
5879 >                            quietlyCompleteRoot();
5880 >                        return;
5881 >                    }
5882                  }
5883              }
5884          }
# Line 5721 | Line 5899 | public class ConcurrentHashMapV8<K, V>
5899          @SuppressWarnings("unchecked") public final void compute() {
5900              final BiFun<? super K, ? super V, ? extends U> searchFunction;
5901              final AtomicReference<U> result;
5902 <            if ((searchFunction = this.searchFunction) == null ||
5903 <                (result = this.result) == null)
5904 <                throw new NullPointerException();
5905 <            for (int b;;) {
5906 <                if (result.get() != null)
5907 <                    return;
5908 <                if ((b = preSplit()) <= 0)
5909 <                    break;
5910 <                new SearchMappingsTask<K,V,U>
5733 <                    (map, this, b, searchFunction, result).fork();
5734 <            }
5735 <            while (result.get() == null) {
5736 <                Object v; U u;
5737 <                if ((v = advance()) == null) {
5738 <                    propagateCompletion();
5739 <                    break;
5902 >            if ((searchFunction = this.searchFunction) != null &&
5903 >                (result = this.result) != null) {
5904 >                for (int b;;) {
5905 >                    if (result.get() != null)
5906 >                        return;
5907 >                    if ((b = preSplit()) <= 0)
5908 >                        break;
5909 >                    new SearchMappingsTask<K,V,U>
5910 >                        (map, this, b, searchFunction, result).fork();
5911                  }
5912 <                if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5913 <                    if (result.compareAndSet(null, u))
5914 <                        quietlyCompleteRoot();
5915 <                    break;
5912 >                while (result.get() == null) {
5913 >                    V v; U u;
5914 >                    if ((v = advance()) == null) {
5915 >                        propagateCompletion();
5916 >                        break;
5917 >                    }
5918 >                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5919 >                        if (result.compareAndSet(null, u))
5920 >                            quietlyCompleteRoot();
5921 >                        break;
5922 >                    }
5923                  }
5924              }
5925          }
# Line 5761 | Line 5939 | public class ConcurrentHashMapV8<K, V>
5939          }
5940          public final K getRawResult() { return result; }
5941          @SuppressWarnings("unchecked") public final void compute() {
5942 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5943 <                this.reducer;
5944 <            if (reducer == null)
5945 <                throw new NullPointerException();
5946 <            for (int b; (b = preSplit()) > 0;)
5947 <                (rights = new ReduceKeysTask<K,V>
5948 <                 (map, this, b, rights, reducer)).fork();
5949 <            K r = null;
5950 <            while (advance() != null) {
5951 <                K u = (K)nextKey;
5952 <                r = (r == null) ? u : reducer.apply(r, u);
5953 <            }
5954 <            result = r;
5955 <            CountedCompleter<?> c;
5956 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
5957 <                ReduceKeysTask<K,V>
5958 <                    t = (ReduceKeysTask<K,V>)c,
5959 <                    s = t.rights;
5960 <                while (s != null) {
5961 <                    K tr, sr;
5962 <                    if ((sr = s.result) != null)
5963 <                        t.result = (((tr = t.result) == null) ? sr :
5964 <                                    reducer.apply(tr, sr));
5787 <                    s = t.rights = s.nextRight;
5942 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5943 >            if ((reducer = this.reducer) != null) {
5944 >                for (int b; (b = preSplit()) > 0;)
5945 >                    (rights = new ReduceKeysTask<K,V>
5946 >                     (map, this, b, rights, reducer)).fork();
5947 >                K r = null;
5948 >                while (advance() != null) {
5949 >                    K u = (K)nextKey;
5950 >                    r = (r == null) ? u : reducer.apply(r, u);
5951 >                }
5952 >                result = r;
5953 >                CountedCompleter<?> c;
5954 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5955 >                    ReduceKeysTask<K,V>
5956 >                        t = (ReduceKeysTask<K,V>)c,
5957 >                        s = t.rights;
5958 >                    while (s != null) {
5959 >                        K tr, sr;
5960 >                        if ((sr = s.result) != null)
5961 >                            t.result = (((tr = t.result) == null) ? sr :
5962 >                                        reducer.apply(tr, sr));
5963 >                        s = t.rights = s.nextRight;
5964 >                    }
5965                  }
5966              }
5967          }
# Line 5804 | Line 5981 | public class ConcurrentHashMapV8<K, V>
5981          }
5982          public final V getRawResult() { return result; }
5983          @SuppressWarnings("unchecked") public final void compute() {
5984 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5985 <                this.reducer;
5986 <            if (reducer == null)
5987 <                throw new NullPointerException();
5988 <            for (int b; (b = preSplit()) > 0;)
5989 <                (rights = new ReduceValuesTask<K,V>
5990 <                 (map, this, b, rights, reducer)).fork();
5991 <            V r = null;
5992 <            Object v;
5993 <            while ((v = advance()) != null) {
5994 <                V u = (V)v;
5995 <                r = (r == null) ? u : reducer.apply(r, u);
5996 <            }
5997 <            result = r;
5998 <            CountedCompleter<?> c;
5999 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6000 <                ReduceValuesTask<K,V>
6001 <                    t = (ReduceValuesTask<K,V>)c,
6002 <                    s = t.rights;
6003 <                while (s != null) {
6004 <                    V tr, sr;
6005 <                    if ((sr = s.result) != null)
6006 <                        t.result = (((tr = t.result) == null) ? sr :
6007 <                                    reducer.apply(tr, sr));
5831 <                    s = t.rights = s.nextRight;
5984 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5985 >            if ((reducer = this.reducer) != null) {
5986 >                for (int b; (b = preSplit()) > 0;)
5987 >                    (rights = new ReduceValuesTask<K,V>
5988 >                     (map, this, b, rights, reducer)).fork();
5989 >                V r = null;
5990 >                V v;
5991 >                while ((v = advance()) != null) {
5992 >                    V u = v;
5993 >                    r = (r == null) ? u : reducer.apply(r, u);
5994 >                }
5995 >                result = r;
5996 >                CountedCompleter<?> c;
5997 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5998 >                    ReduceValuesTask<K,V>
5999 >                        t = (ReduceValuesTask<K,V>)c,
6000 >                        s = t.rights;
6001 >                    while (s != null) {
6002 >                        V tr, sr;
6003 >                        if ((sr = s.result) != null)
6004 >                            t.result = (((tr = t.result) == null) ? sr :
6005 >                                        reducer.apply(tr, sr));
6006 >                        s = t.rights = s.nextRight;
6007 >                    }
6008                  }
6009              }
6010          }
# Line 5848 | Line 6024 | public class ConcurrentHashMapV8<K, V>
6024          }
6025          public final Map.Entry<K,V> getRawResult() { return result; }
6026          @SuppressWarnings("unchecked") public final void compute() {
6027 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
6028 <                this.reducer;
6029 <            if (reducer == null)
6030 <                throw new NullPointerException();
6031 <            for (int b; (b = preSplit()) > 0;)
6032 <                (rights = new ReduceEntriesTask<K,V>
6033 <                 (map, this, b, rights, reducer)).fork();
6034 <            Map.Entry<K,V> r = null;
6035 <            Object v;
6036 <            while ((v = advance()) != null) {
6037 <                Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
6038 <                r = (r == null) ? u : reducer.apply(r, u);
6039 <            }
6040 <            result = r;
6041 <            CountedCompleter<?> c;
6042 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6043 <                ReduceEntriesTask<K,V>
6044 <                    t = (ReduceEntriesTask<K,V>)c,
6045 <                    s = t.rights;
6046 <                while (s != null) {
6047 <                    Map.Entry<K,V> tr, sr;
6048 <                    if ((sr = s.result) != null)
6049 <                        t.result = (((tr = t.result) == null) ? sr :
6050 <                                    reducer.apply(tr, sr));
5875 <                    s = t.rights = s.nextRight;
6027 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6028 >            if ((reducer = this.reducer) != null) {
6029 >                for (int b; (b = preSplit()) > 0;)
6030 >                    (rights = new ReduceEntriesTask<K,V>
6031 >                     (map, this, b, rights, reducer)).fork();
6032 >                Map.Entry<K,V> r = null;
6033 >                V v;
6034 >                while ((v = advance()) != null) {
6035 >                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6036 >                    r = (r == null) ? u : reducer.apply(r, u);
6037 >                }
6038 >                result = r;
6039 >                CountedCompleter<?> c;
6040 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6041 >                    ReduceEntriesTask<K,V>
6042 >                        t = (ReduceEntriesTask<K,V>)c,
6043 >                        s = t.rights;
6044 >                    while (s != null) {
6045 >                        Map.Entry<K,V> tr, sr;
6046 >                        if ((sr = s.result) != null)
6047 >                            t.result = (((tr = t.result) == null) ? sr :
6048 >                                        reducer.apply(tr, sr));
6049 >                        s = t.rights = s.nextRight;
6050 >                    }
6051                  }
6052              }
6053          }
# Line 5895 | Line 6070 | public class ConcurrentHashMapV8<K, V>
6070          }
6071          public final U getRawResult() { return result; }
6072          @SuppressWarnings("unchecked") public final void compute() {
6073 <            final Fun<? super K, ? extends U> transformer =
6074 <                this.transformer;
6075 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6076 <                this.reducer;
6077 <            if (transformer == null || reducer == null)
6078 <                throw new NullPointerException();
6079 <            for (int b; (b = preSplit()) > 0;)
6080 <                (rights = new MapReduceKeysTask<K,V,U>
6081 <                 (map, this, b, rights, transformer, reducer)).fork();
6082 <            U r = null, u;
6083 <            while (advance() != null) {
6084 <                if ((u = transformer.apply((K)nextKey)) != null)
6085 <                    r = (r == null) ? u : reducer.apply(r, u);
6086 <            }
6087 <            result = r;
6088 <            CountedCompleter<?> c;
6089 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6090 <                MapReduceKeysTask<K,V,U>
6091 <                    t = (MapReduceKeysTask<K,V,U>)c,
6092 <                    s = t.rights;
6093 <                while (s != null) {
6094 <                    U tr, sr;
6095 <                    if ((sr = s.result) != null)
6096 <                        t.result = (((tr = t.result) == null) ? sr :
6097 <                                    reducer.apply(tr, sr));
5923 <                    s = t.rights = s.nextRight;
6073 >            final Fun<? super K, ? extends U> transformer;
6074 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6075 >            if ((transformer = this.transformer) != null &&
6076 >                (reducer = this.reducer) != null) {
6077 >                for (int b; (b = preSplit()) > 0;)
6078 >                    (rights = new MapReduceKeysTask<K,V,U>
6079 >                     (map, this, b, rights, transformer, reducer)).fork();
6080 >                U r = null, u;
6081 >                while (advance() != null) {
6082 >                    if ((u = transformer.apply((K)nextKey)) != null)
6083 >                        r = (r == null) ? u : reducer.apply(r, u);
6084 >                }
6085 >                result = r;
6086 >                CountedCompleter<?> c;
6087 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6088 >                    MapReduceKeysTask<K,V,U>
6089 >                        t = (MapReduceKeysTask<K,V,U>)c,
6090 >                        s = t.rights;
6091 >                    while (s != null) {
6092 >                        U tr, sr;
6093 >                        if ((sr = s.result) != null)
6094 >                            t.result = (((tr = t.result) == null) ? sr :
6095 >                                        reducer.apply(tr, sr));
6096 >                        s = t.rights = s.nextRight;
6097 >                    }
6098                  }
6099              }
6100          }
# Line 5943 | Line 6117 | public class ConcurrentHashMapV8<K, V>
6117          }
6118          public final U getRawResult() { return result; }
6119          @SuppressWarnings("unchecked") public final void compute() {
6120 <            final Fun<? super V, ? extends U> transformer =
6121 <                this.transformer;
6122 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6123 <                this.reducer;
6124 <            if (transformer == null || reducer == null)
6125 <                throw new NullPointerException();
6126 <            for (int b; (b = preSplit()) > 0;)
6127 <                (rights = new MapReduceValuesTask<K,V,U>
6128 <                 (map, this, b, rights, transformer, reducer)).fork();
6129 <            U r = null, u;
6130 <            Object v;
6131 <            while ((v = advance()) != null) {
6132 <                if ((u = transformer.apply((V)v)) != null)
6133 <                    r = (r == null) ? u : reducer.apply(r, u);
6134 <            }
6135 <            result = r;
6136 <            CountedCompleter<?> c;
6137 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6138 <                MapReduceValuesTask<K,V,U>
6139 <                    t = (MapReduceValuesTask<K,V,U>)c,
6140 <                    s = t.rights;
6141 <                while (s != null) {
6142 <                    U tr, sr;
6143 <                    if ((sr = s.result) != null)
6144 <                        t.result = (((tr = t.result) == null) ? sr :
6145 <                                    reducer.apply(tr, sr));
5972 <                    s = t.rights = s.nextRight;
6120 >            final Fun<? super V, ? extends U> transformer;
6121 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6122 >            if ((transformer = this.transformer) != null &&
6123 >                (reducer = this.reducer) != null) {
6124 >                for (int b; (b = preSplit()) > 0;)
6125 >                    (rights = new MapReduceValuesTask<K,V,U>
6126 >                     (map, this, b, rights, transformer, reducer)).fork();
6127 >                U r = null, u;
6128 >                V v;
6129 >                while ((v = advance()) != null) {
6130 >                    if ((u = transformer.apply(v)) != null)
6131 >                        r = (r == null) ? u : reducer.apply(r, u);
6132 >                }
6133 >                result = r;
6134 >                CountedCompleter<?> c;
6135 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6136 >                    MapReduceValuesTask<K,V,U>
6137 >                        t = (MapReduceValuesTask<K,V,U>)c,
6138 >                        s = t.rights;
6139 >                    while (s != null) {
6140 >                        U tr, sr;
6141 >                        if ((sr = s.result) != null)
6142 >                            t.result = (((tr = t.result) == null) ? sr :
6143 >                                        reducer.apply(tr, sr));
6144 >                        s = t.rights = s.nextRight;
6145 >                    }
6146                  }
6147              }
6148          }
# Line 5992 | Line 6165 | public class ConcurrentHashMapV8<K, V>
6165          }
6166          public final U getRawResult() { return result; }
6167          @SuppressWarnings("unchecked") public final void compute() {
6168 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
6169 <                this.transformer;
6170 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6171 <                this.reducer;
6172 <            if (transformer == null || reducer == null)
6173 <                throw new NullPointerException();
6174 <            for (int b; (b = preSplit()) > 0;)
6175 <                (rights = new MapReduceEntriesTask<K,V,U>
6176 <                 (map, this, b, rights, transformer, reducer)).fork();
6177 <            U r = null, u;
6178 <            Object v;
6179 <            while ((v = advance()) != null) {
6180 <                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
6181 <                    r = (r == null) ? u : reducer.apply(r, u);
6182 <            }
6183 <            result = r;
6184 <            CountedCompleter<?> c;
6185 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6186 <                MapReduceEntriesTask<K,V,U>
6187 <                    t = (MapReduceEntriesTask<K,V,U>)c,
6188 <                    s = t.rights;
6189 <                while (s != null) {
6190 <                    U tr, sr;
6191 <                    if ((sr = s.result) != null)
6192 <                        t.result = (((tr = t.result) == null) ? sr :
6193 <                                    reducer.apply(tr, sr));
6194 <                    s = t.rights = s.nextRight;
6168 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
6169 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6170 >            if ((transformer = this.transformer) != null &&
6171 >                (reducer = this.reducer) != null) {
6172 >                for (int b; (b = preSplit()) > 0;)
6173 >                    (rights = new MapReduceEntriesTask<K,V,U>
6174 >                     (map, this, b, rights, transformer, reducer)).fork();
6175 >                U r = null, u;
6176 >                V v;
6177 >                while ((v = advance()) != null) {
6178 >                    if ((u = transformer.apply(entryFor((K)nextKey,
6179 >                                                        v))) != null)
6180 >                        r = (r == null) ? u : reducer.apply(r, u);
6181 >                }
6182 >                result = r;
6183 >                CountedCompleter<?> c;
6184 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6185 >                    MapReduceEntriesTask<K,V,U>
6186 >                        t = (MapReduceEntriesTask<K,V,U>)c,
6187 >                        s = t.rights;
6188 >                    while (s != null) {
6189 >                        U tr, sr;
6190 >                        if ((sr = s.result) != null)
6191 >                            t.result = (((tr = t.result) == null) ? sr :
6192 >                                        reducer.apply(tr, sr));
6193 >                        s = t.rights = s.nextRight;
6194 >                    }
6195                  }
6196              }
6197          }
# Line 6041 | Line 6214 | public class ConcurrentHashMapV8<K, V>
6214          }
6215          public final U getRawResult() { return result; }
6216          @SuppressWarnings("unchecked") public final void compute() {
6217 <            final BiFun<? super K, ? super V, ? extends U> transformer =
6218 <                this.transformer;
6219 <            final BiFun<? super U, ? super U, ? extends U> reducer =
6220 <                this.reducer;
6221 <            if (transformer == null || reducer == null)
6222 <                throw new NullPointerException();
6223 <            for (int b; (b = preSplit()) > 0;)
6224 <                (rights = new MapReduceMappingsTask<K,V,U>
6225 <                 (map, this, b, rights, transformer, reducer)).fork();
6226 <            U r = null, u;
6227 <            Object v;
6228 <            while ((v = advance()) != null) {
6229 <                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
6230 <                    r = (r == null) ? u : reducer.apply(r, u);
6231 <            }
6232 <            result = r;
6233 <            CountedCompleter<?> c;
6234 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6235 <                MapReduceMappingsTask<K,V,U>
6236 <                    t = (MapReduceMappingsTask<K,V,U>)c,
6237 <                    s = t.rights;
6238 <                while (s != null) {
6239 <                    U tr, sr;
6240 <                    if ((sr = s.result) != null)
6241 <                        t.result = (((tr = t.result) == null) ? sr :
6242 <                                    reducer.apply(tr, sr));
6070 <                    s = t.rights = s.nextRight;
6217 >            final BiFun<? super K, ? super V, ? extends U> transformer;
6218 >            final BiFun<? super U, ? super U, ? extends U> reducer;
6219 >            if ((transformer = this.transformer) != null &&
6220 >                (reducer = this.reducer) != null) {
6221 >                for (int b; (b = preSplit()) > 0;)
6222 >                    (rights = new MapReduceMappingsTask<K,V,U>
6223 >                     (map, this, b, rights, transformer, reducer)).fork();
6224 >                U r = null, u;
6225 >                V v;
6226 >                while ((v = advance()) != null) {
6227 >                    if ((u = transformer.apply((K)nextKey, v)) != null)
6228 >                        r = (r == null) ? u : reducer.apply(r, u);
6229 >                }
6230 >                result = r;
6231 >                CountedCompleter<?> c;
6232 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6233 >                    MapReduceMappingsTask<K,V,U>
6234 >                        t = (MapReduceMappingsTask<K,V,U>)c,
6235 >                        s = t.rights;
6236 >                    while (s != null) {
6237 >                        U tr, sr;
6238 >                        if ((sr = s.result) != null)
6239 >                            t.result = (((tr = t.result) == null) ? sr :
6240 >                                        reducer.apply(tr, sr));
6241 >                        s = t.rights = s.nextRight;
6242 >                    }
6243                  }
6244              }
6245          }
# Line 6092 | Line 6264 | public class ConcurrentHashMapV8<K, V>
6264          }
6265          public final Double getRawResult() { return result; }
6266          @SuppressWarnings("unchecked") public final void compute() {
6267 <            final ObjectToDouble<? super K> transformer =
6268 <                this.transformer;
6269 <            final DoubleByDoubleToDouble reducer = this.reducer;
6270 <            if (transformer == null || reducer == null)
6271 <                throw new NullPointerException();
6272 <            double r = this.basis;
6273 <            for (int b; (b = preSplit()) > 0;)
6274 <                (rights = new MapReduceKeysToDoubleTask<K,V>
6275 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6276 <            while (advance() != null)
6277 <                r = reducer.apply(r, transformer.apply((K)nextKey));
6278 <            result = r;
6279 <            CountedCompleter<?> c;
6280 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6281 <                MapReduceKeysToDoubleTask<K,V>
6282 <                    t = (MapReduceKeysToDoubleTask<K,V>)c,
6283 <                    s = t.rights;
6284 <                while (s != null) {
6285 <                    t.result = reducer.apply(t.result, s.result);
6286 <                    s = t.rights = s.nextRight;
6267 >            final ObjectToDouble<? super K> transformer;
6268 >            final DoubleByDoubleToDouble reducer;
6269 >            if ((transformer = this.transformer) != null &&
6270 >                (reducer = this.reducer) != null) {
6271 >                double r = this.basis;
6272 >                for (int b; (b = preSplit()) > 0;)
6273 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
6274 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6275 >                while (advance() != null)
6276 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6277 >                result = r;
6278 >                CountedCompleter<?> c;
6279 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6280 >                    MapReduceKeysToDoubleTask<K,V>
6281 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
6282 >                        s = t.rights;
6283 >                    while (s != null) {
6284 >                        t.result = reducer.apply(t.result, s.result);
6285 >                        s = t.rights = s.nextRight;
6286 >                    }
6287                  }
6288              }
6289          }
# Line 6136 | Line 6308 | public class ConcurrentHashMapV8<K, V>
6308          }
6309          public final Double getRawResult() { return result; }
6310          @SuppressWarnings("unchecked") public final void compute() {
6311 <            final ObjectToDouble<? super V> transformer =
6312 <                this.transformer;
6313 <            final DoubleByDoubleToDouble reducer = this.reducer;
6314 <            if (transformer == null || reducer == null)
6315 <                throw new NullPointerException();
6316 <            double r = this.basis;
6317 <            for (int b; (b = preSplit()) > 0;)
6318 <                (rights = new MapReduceValuesToDoubleTask<K,V>
6319 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6320 <            Object v;
6321 <            while ((v = advance()) != null)
6322 <                r = reducer.apply(r, transformer.apply((V)v));
6323 <            result = r;
6324 <            CountedCompleter<?> c;
6325 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6326 <                MapReduceValuesToDoubleTask<K,V>
6327 <                    t = (MapReduceValuesToDoubleTask<K,V>)c,
6328 <                    s = t.rights;
6329 <                while (s != null) {
6330 <                    t.result = reducer.apply(t.result, s.result);
6331 <                    s = t.rights = s.nextRight;
6311 >            final ObjectToDouble<? super V> transformer;
6312 >            final DoubleByDoubleToDouble reducer;
6313 >            if ((transformer = this.transformer) != null &&
6314 >                (reducer = this.reducer) != null) {
6315 >                double r = this.basis;
6316 >                for (int b; (b = preSplit()) > 0;)
6317 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
6318 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6319 >                V v;
6320 >                while ((v = advance()) != null)
6321 >                    r = reducer.apply(r, transformer.apply(v));
6322 >                result = r;
6323 >                CountedCompleter<?> c;
6324 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6325 >                    MapReduceValuesToDoubleTask<K,V>
6326 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
6327 >                        s = t.rights;
6328 >                    while (s != null) {
6329 >                        t.result = reducer.apply(t.result, s.result);
6330 >                        s = t.rights = s.nextRight;
6331 >                    }
6332                  }
6333              }
6334          }
# Line 6181 | Line 6353 | public class ConcurrentHashMapV8<K, V>
6353          }
6354          public final Double getRawResult() { return result; }
6355          @SuppressWarnings("unchecked") public final void compute() {
6356 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
6357 <                this.transformer;
6358 <            final DoubleByDoubleToDouble reducer = this.reducer;
6359 <            if (transformer == null || reducer == null)
6360 <                throw new NullPointerException();
6361 <            double r = this.basis;
6362 <            for (int b; (b = preSplit()) > 0;)
6363 <                (rights = new MapReduceEntriesToDoubleTask<K,V>
6364 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6365 <            Object v;
6366 <            while ((v = advance()) != null)
6367 <                r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6368 <            result = r;
6369 <            CountedCompleter<?> c;
6370 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6371 <                MapReduceEntriesToDoubleTask<K,V>
6372 <                    t = (MapReduceEntriesToDoubleTask<K,V>)c,
6373 <                    s = t.rights;
6374 <                while (s != null) {
6375 <                    t.result = reducer.apply(t.result, s.result);
6376 <                    s = t.rights = s.nextRight;
6356 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
6357 >            final DoubleByDoubleToDouble reducer;
6358 >            if ((transformer = this.transformer) != null &&
6359 >                (reducer = this.reducer) != null) {
6360 >                double r = this.basis;
6361 >                for (int b; (b = preSplit()) > 0;)
6362 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
6363 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6364 >                V v;
6365 >                while ((v = advance()) != null)
6366 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6367 >                                                                    v)));
6368 >                result = r;
6369 >                CountedCompleter<?> c;
6370 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6371 >                    MapReduceEntriesToDoubleTask<K,V>
6372 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
6373 >                        s = t.rights;
6374 >                    while (s != null) {
6375 >                        t.result = reducer.apply(t.result, s.result);
6376 >                        s = t.rights = s.nextRight;
6377 >                    }
6378                  }
6379              }
6380          }
# Line 6226 | Line 6399 | public class ConcurrentHashMapV8<K, V>
6399          }
6400          public final Double getRawResult() { return result; }
6401          @SuppressWarnings("unchecked") public final void compute() {
6402 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
6403 <                this.transformer;
6404 <            final DoubleByDoubleToDouble reducer = this.reducer;
6405 <            if (transformer == null || reducer == null)
6406 <                throw new NullPointerException();
6407 <            double r = this.basis;
6408 <            for (int b; (b = preSplit()) > 0;)
6409 <                (rights = new MapReduceMappingsToDoubleTask<K,V>
6410 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6411 <            Object v;
6412 <            while ((v = advance()) != null)
6413 <                r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6414 <            result = r;
6415 <            CountedCompleter<?> c;
6416 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6417 <                MapReduceMappingsToDoubleTask<K,V>
6418 <                    t = (MapReduceMappingsToDoubleTask<K,V>)c,
6419 <                    s = t.rights;
6420 <                while (s != null) {
6421 <                    t.result = reducer.apply(t.result, s.result);
6422 <                    s = t.rights = s.nextRight;
6402 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
6403 >            final DoubleByDoubleToDouble reducer;
6404 >            if ((transformer = this.transformer) != null &&
6405 >                (reducer = this.reducer) != null) {
6406 >                double r = this.basis;
6407 >                for (int b; (b = preSplit()) > 0;)
6408 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
6409 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6410 >                V v;
6411 >                while ((v = advance()) != null)
6412 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6413 >                result = r;
6414 >                CountedCompleter<?> c;
6415 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6416 >                    MapReduceMappingsToDoubleTask<K,V>
6417 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
6418 >                        s = t.rights;
6419 >                    while (s != null) {
6420 >                        t.result = reducer.apply(t.result, s.result);
6421 >                        s = t.rights = s.nextRight;
6422 >                    }
6423                  }
6424              }
6425          }
# Line 6271 | Line 6444 | public class ConcurrentHashMapV8<K, V>
6444          }
6445          public final Long getRawResult() { return result; }
6446          @SuppressWarnings("unchecked") public final void compute() {
6447 <            final ObjectToLong<? super K> transformer =
6448 <                this.transformer;
6449 <            final LongByLongToLong reducer = this.reducer;
6450 <            if (transformer == null || reducer == null)
6451 <                throw new NullPointerException();
6452 <            long r = this.basis;
6453 <            for (int b; (b = preSplit()) > 0;)
6454 <                (rights = new MapReduceKeysToLongTask<K,V>
6455 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6456 <            while (advance() != null)
6457 <                r = reducer.apply(r, transformer.apply((K)nextKey));
6458 <            result = r;
6459 <            CountedCompleter<?> c;
6460 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6461 <                MapReduceKeysToLongTask<K,V>
6462 <                    t = (MapReduceKeysToLongTask<K,V>)c,
6463 <                    s = t.rights;
6464 <                while (s != null) {
6465 <                    t.result = reducer.apply(t.result, s.result);
6466 <                    s = t.rights = s.nextRight;
6447 >            final ObjectToLong<? super K> transformer;
6448 >            final LongByLongToLong reducer;
6449 >            if ((transformer = this.transformer) != null &&
6450 >                (reducer = this.reducer) != null) {
6451 >                long r = this.basis;
6452 >                for (int b; (b = preSplit()) > 0;)
6453 >                    (rights = new MapReduceKeysToLongTask<K,V>
6454 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6455 >                while (advance() != null)
6456 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6457 >                result = r;
6458 >                CountedCompleter<?> c;
6459 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6460 >                    MapReduceKeysToLongTask<K,V>
6461 >                        t = (MapReduceKeysToLongTask<K,V>)c,
6462 >                        s = t.rights;
6463 >                    while (s != null) {
6464 >                        t.result = reducer.apply(t.result, s.result);
6465 >                        s = t.rights = s.nextRight;
6466 >                    }
6467                  }
6468              }
6469          }
# Line 6315 | Line 6488 | public class ConcurrentHashMapV8<K, V>
6488          }
6489          public final Long getRawResult() { return result; }
6490          @SuppressWarnings("unchecked") public final void compute() {
6491 <            final ObjectToLong<? super V> transformer =
6492 <                this.transformer;
6493 <            final LongByLongToLong reducer = this.reducer;
6494 <            if (transformer == null || reducer == null)
6495 <                throw new NullPointerException();
6496 <            long r = this.basis;
6497 <            for (int b; (b = preSplit()) > 0;)
6498 <                (rights = new MapReduceValuesToLongTask<K,V>
6499 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6500 <            Object v;
6501 <            while ((v = advance()) != null)
6502 <                r = reducer.apply(r, transformer.apply((V)v));
6503 <            result = r;
6504 <            CountedCompleter<?> c;
6505 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6506 <                MapReduceValuesToLongTask<K,V>
6507 <                    t = (MapReduceValuesToLongTask<K,V>)c,
6508 <                    s = t.rights;
6509 <                while (s != null) {
6510 <                    t.result = reducer.apply(t.result, s.result);
6511 <                    s = t.rights = s.nextRight;
6491 >            final ObjectToLong<? super V> transformer;
6492 >            final LongByLongToLong reducer;
6493 >            if ((transformer = this.transformer) != null &&
6494 >                (reducer = this.reducer) != null) {
6495 >                long r = this.basis;
6496 >                for (int b; (b = preSplit()) > 0;)
6497 >                    (rights = new MapReduceValuesToLongTask<K,V>
6498 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6499 >                V v;
6500 >                while ((v = advance()) != null)
6501 >                    r = reducer.apply(r, transformer.apply(v));
6502 >                result = r;
6503 >                CountedCompleter<?> c;
6504 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6505 >                    MapReduceValuesToLongTask<K,V>
6506 >                        t = (MapReduceValuesToLongTask<K,V>)c,
6507 >                        s = t.rights;
6508 >                    while (s != null) {
6509 >                        t.result = reducer.apply(t.result, s.result);
6510 >                        s = t.rights = s.nextRight;
6511 >                    }
6512                  }
6513              }
6514          }
# Line 6360 | Line 6533 | public class ConcurrentHashMapV8<K, V>
6533          }
6534          public final Long getRawResult() { return result; }
6535          @SuppressWarnings("unchecked") public final void compute() {
6536 <            final ObjectToLong<Map.Entry<K,V>> transformer =
6537 <                this.transformer;
6538 <            final LongByLongToLong reducer = this.reducer;
6539 <            if (transformer == null || reducer == null)
6540 <                throw new NullPointerException();
6541 <            long r = this.basis;
6542 <            for (int b; (b = preSplit()) > 0;)
6543 <                (rights = new MapReduceEntriesToLongTask<K,V>
6544 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6545 <            Object v;
6546 <            while ((v = advance()) != null)
6547 <                r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6548 <            result = r;
6549 <            CountedCompleter<?> c;
6550 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6551 <                MapReduceEntriesToLongTask<K,V>
6552 <                    t = (MapReduceEntriesToLongTask<K,V>)c,
6553 <                    s = t.rights;
6554 <                while (s != null) {
6555 <                    t.result = reducer.apply(t.result, s.result);
6556 <                    s = t.rights = s.nextRight;
6536 >            final ObjectToLong<Map.Entry<K,V>> transformer;
6537 >            final LongByLongToLong reducer;
6538 >            if ((transformer = this.transformer) != null &&
6539 >                (reducer = this.reducer) != null) {
6540 >                long r = this.basis;
6541 >                for (int b; (b = preSplit()) > 0;)
6542 >                    (rights = new MapReduceEntriesToLongTask<K,V>
6543 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6544 >                V v;
6545 >                while ((v = advance()) != null)
6546 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6547 >                                                                    v)));
6548 >                result = r;
6549 >                CountedCompleter<?> c;
6550 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6551 >                    MapReduceEntriesToLongTask<K,V>
6552 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6553 >                        s = t.rights;
6554 >                    while (s != null) {
6555 >                        t.result = reducer.apply(t.result, s.result);
6556 >                        s = t.rights = s.nextRight;
6557 >                    }
6558                  }
6559              }
6560          }
# Line 6405 | Line 6579 | public class ConcurrentHashMapV8<K, V>
6579          }
6580          public final Long getRawResult() { return result; }
6581          @SuppressWarnings("unchecked") public final void compute() {
6582 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
6583 <                this.transformer;
6584 <            final LongByLongToLong reducer = this.reducer;
6585 <            if (transformer == null || reducer == null)
6586 <                throw new NullPointerException();
6587 <            long r = this.basis;
6588 <            for (int b; (b = preSplit()) > 0;)
6589 <                (rights = new MapReduceMappingsToLongTask<K,V>
6590 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6591 <            Object v;
6592 <            while ((v = advance()) != null)
6593 <                r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6594 <            result = r;
6595 <            CountedCompleter<?> c;
6596 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6597 <                MapReduceMappingsToLongTask<K,V>
6598 <                    t = (MapReduceMappingsToLongTask<K,V>)c,
6599 <                    s = t.rights;
6600 <                while (s != null) {
6601 <                    t.result = reducer.apply(t.result, s.result);
6602 <                    s = t.rights = s.nextRight;
6582 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
6583 >            final LongByLongToLong reducer;
6584 >            if ((transformer = this.transformer) != null &&
6585 >                (reducer = this.reducer) != null) {
6586 >                long r = this.basis;
6587 >                for (int b; (b = preSplit()) > 0;)
6588 >                    (rights = new MapReduceMappingsToLongTask<K,V>
6589 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6590 >                V v;
6591 >                while ((v = advance()) != null)
6592 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6593 >                result = r;
6594 >                CountedCompleter<?> c;
6595 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6596 >                    MapReduceMappingsToLongTask<K,V>
6597 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6598 >                        s = t.rights;
6599 >                    while (s != null) {
6600 >                        t.result = reducer.apply(t.result, s.result);
6601 >                        s = t.rights = s.nextRight;
6602 >                    }
6603                  }
6604              }
6605          }
# Line 6450 | Line 6624 | public class ConcurrentHashMapV8<K, V>
6624          }
6625          public final Integer getRawResult() { return result; }
6626          @SuppressWarnings("unchecked") public final void compute() {
6627 <            final ObjectToInt<? super K> transformer =
6628 <                this.transformer;
6629 <            final IntByIntToInt reducer = this.reducer;
6630 <            if (transformer == null || reducer == null)
6631 <                throw new NullPointerException();
6632 <            int r = this.basis;
6633 <            for (int b; (b = preSplit()) > 0;)
6634 <                (rights = new MapReduceKeysToIntTask<K,V>
6635 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6636 <            while (advance() != null)
6637 <                r = reducer.apply(r, transformer.apply((K)nextKey));
6638 <            result = r;
6639 <            CountedCompleter<?> c;
6640 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6641 <                MapReduceKeysToIntTask<K,V>
6642 <                    t = (MapReduceKeysToIntTask<K,V>)c,
6643 <                    s = t.rights;
6644 <                while (s != null) {
6645 <                    t.result = reducer.apply(t.result, s.result);
6646 <                    s = t.rights = s.nextRight;
6627 >            final ObjectToInt<? super K> transformer;
6628 >            final IntByIntToInt reducer;
6629 >            if ((transformer = this.transformer) != null &&
6630 >                (reducer = this.reducer) != null) {
6631 >                int r = this.basis;
6632 >                for (int b; (b = preSplit()) > 0;)
6633 >                    (rights = new MapReduceKeysToIntTask<K,V>
6634 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6635 >                while (advance() != null)
6636 >                    r = reducer.apply(r, transformer.apply((K)nextKey));
6637 >                result = r;
6638 >                CountedCompleter<?> c;
6639 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6640 >                    MapReduceKeysToIntTask<K,V>
6641 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6642 >                        s = t.rights;
6643 >                    while (s != null) {
6644 >                        t.result = reducer.apply(t.result, s.result);
6645 >                        s = t.rights = s.nextRight;
6646 >                    }
6647                  }
6648              }
6649          }
# Line 6494 | Line 6668 | public class ConcurrentHashMapV8<K, V>
6668          }
6669          public final Integer getRawResult() { return result; }
6670          @SuppressWarnings("unchecked") public final void compute() {
6671 <            final ObjectToInt<? super V> transformer =
6672 <                this.transformer;
6673 <            final IntByIntToInt reducer = this.reducer;
6674 <            if (transformer == null || reducer == null)
6675 <                throw new NullPointerException();
6676 <            int r = this.basis;
6677 <            for (int b; (b = preSplit()) > 0;)
6678 <                (rights = new MapReduceValuesToIntTask<K,V>
6679 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6680 <            Object v;
6681 <            while ((v = advance()) != null)
6682 <                r = reducer.apply(r, transformer.apply((V)v));
6683 <            result = r;
6684 <            CountedCompleter<?> c;
6685 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6686 <                MapReduceValuesToIntTask<K,V>
6687 <                    t = (MapReduceValuesToIntTask<K,V>)c,
6688 <                    s = t.rights;
6689 <                while (s != null) {
6690 <                    t.result = reducer.apply(t.result, s.result);
6691 <                    s = t.rights = s.nextRight;
6671 >            final ObjectToInt<? super V> transformer;
6672 >            final IntByIntToInt reducer;
6673 >            if ((transformer = this.transformer) != null &&
6674 >                (reducer = this.reducer) != null) {
6675 >                int r = this.basis;
6676 >                for (int b; (b = preSplit()) > 0;)
6677 >                    (rights = new MapReduceValuesToIntTask<K,V>
6678 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6679 >                V v;
6680 >                while ((v = advance()) != null)
6681 >                    r = reducer.apply(r, transformer.apply(v));
6682 >                result = r;
6683 >                CountedCompleter<?> c;
6684 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6685 >                    MapReduceValuesToIntTask<K,V>
6686 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6687 >                        s = t.rights;
6688 >                    while (s != null) {
6689 >                        t.result = reducer.apply(t.result, s.result);
6690 >                        s = t.rights = s.nextRight;
6691 >                    }
6692                  }
6693              }
6694          }
# Line 6539 | Line 6713 | public class ConcurrentHashMapV8<K, V>
6713          }
6714          public final Integer getRawResult() { return result; }
6715          @SuppressWarnings("unchecked") public final void compute() {
6716 <            final ObjectToInt<Map.Entry<K,V>> transformer =
6717 <                this.transformer;
6718 <            final IntByIntToInt reducer = this.reducer;
6719 <            if (transformer == null || reducer == null)
6720 <                throw new NullPointerException();
6721 <            int r = this.basis;
6722 <            for (int b; (b = preSplit()) > 0;)
6723 <                (rights = new MapReduceEntriesToIntTask<K,V>
6724 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6725 <            Object v;
6726 <            while ((v = advance()) != null)
6727 <                r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
6728 <            result = r;
6729 <            CountedCompleter<?> c;
6730 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6731 <                MapReduceEntriesToIntTask<K,V>
6732 <                    t = (MapReduceEntriesToIntTask<K,V>)c,
6733 <                    s = t.rights;
6734 <                while (s != null) {
6735 <                    t.result = reducer.apply(t.result, s.result);
6736 <                    s = t.rights = s.nextRight;
6716 >            final ObjectToInt<Map.Entry<K,V>> transformer;
6717 >            final IntByIntToInt reducer;
6718 >            if ((transformer = this.transformer) != null &&
6719 >                (reducer = this.reducer) != null) {
6720 >                int r = this.basis;
6721 >                for (int b; (b = preSplit()) > 0;)
6722 >                    (rights = new MapReduceEntriesToIntTask<K,V>
6723 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6724 >                V v;
6725 >                while ((v = advance()) != null)
6726 >                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6727 >                                                                    v)));
6728 >                result = r;
6729 >                CountedCompleter<?> c;
6730 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6731 >                    MapReduceEntriesToIntTask<K,V>
6732 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6733 >                        s = t.rights;
6734 >                    while (s != null) {
6735 >                        t.result = reducer.apply(t.result, s.result);
6736 >                        s = t.rights = s.nextRight;
6737 >                    }
6738                  }
6739              }
6740          }
# Line 6584 | Line 6759 | public class ConcurrentHashMapV8<K, V>
6759          }
6760          public final Integer getRawResult() { return result; }
6761          @SuppressWarnings("unchecked") public final void compute() {
6762 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6763 <                this.transformer;
6764 <            final IntByIntToInt reducer = this.reducer;
6765 <            if (transformer == null || reducer == null)
6766 <                throw new NullPointerException();
6767 <            int r = this.basis;
6768 <            for (int b; (b = preSplit()) > 0;)
6769 <                (rights = new MapReduceMappingsToIntTask<K,V>
6770 <                 (map, this, b, rights, transformer, r, reducer)).fork();
6771 <            Object v;
6772 <            while ((v = advance()) != null)
6773 <                r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6774 <            result = r;
6775 <            CountedCompleter<?> c;
6776 <            for (c = firstComplete(); c != null; c = c.nextComplete()) {
6777 <                MapReduceMappingsToIntTask<K,V>
6778 <                    t = (MapReduceMappingsToIntTask<K,V>)c,
6779 <                    s = t.rights;
6780 <                while (s != null) {
6781 <                    t.result = reducer.apply(t.result, s.result);
6782 <                    s = t.rights = s.nextRight;
6762 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
6763 >            final IntByIntToInt reducer;
6764 >            if ((transformer = this.transformer) != null &&
6765 >                (reducer = this.reducer) != null) {
6766 >                int r = this.basis;
6767 >                for (int b; (b = preSplit()) > 0;)
6768 >                    (rights = new MapReduceMappingsToIntTask<K,V>
6769 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6770 >                V v;
6771 >                while ((v = advance()) != null)
6772 >                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
6773 >                result = r;
6774 >                CountedCompleter<?> c;
6775 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6776 >                    MapReduceMappingsToIntTask<K,V>
6777 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6778 >                        s = t.rights;
6779 >                    while (s != null) {
6780 >                        t.result = reducer.apply(t.result, s.result);
6781 >                        s = t.rights = s.nextRight;
6782 >                    }
6783                  }
6784              }
6785          }
6786      }
6787  
6788      // Unsafe mechanics
6789 <    private static final sun.misc.Unsafe UNSAFE;
6790 <    private static final long counterOffset;
6791 <    private static final long sizeCtlOffset;
6789 >    private static final sun.misc.Unsafe U;
6790 >    private static final long SIZECTL;
6791 >    private static final long TRANSFERINDEX;
6792 >    private static final long TRANSFERORIGIN;
6793 >    private static final long BASECOUNT;
6794 >    private static final long COUNTERBUSY;
6795 >    private static final long CELLVALUE;
6796      private static final long ABASE;
6797      private static final int ASHIFT;
6798  
6799      static {
6621        int ss;
6800          try {
6801 <            UNSAFE = getUnsafe();
6801 >            U = getUnsafe();
6802              Class<?> k = ConcurrentHashMapV8.class;
6803 <            counterOffset = UNSAFE.objectFieldOffset
6626 <                (k.getDeclaredField("counter"));
6627 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6803 >            SIZECTL = U.objectFieldOffset
6804                  (k.getDeclaredField("sizeCtl"));
6805 +            TRANSFERINDEX = U.objectFieldOffset
6806 +                (k.getDeclaredField("transferIndex"));
6807 +            TRANSFERORIGIN = U.objectFieldOffset
6808 +                (k.getDeclaredField("transferOrigin"));
6809 +            BASECOUNT = U.objectFieldOffset
6810 +                (k.getDeclaredField("baseCount"));
6811 +            COUNTERBUSY = U.objectFieldOffset
6812 +                (k.getDeclaredField("counterBusy"));
6813 +            Class<?> ck = CounterCell.class;
6814 +            CELLVALUE = U.objectFieldOffset
6815 +                (ck.getDeclaredField("value"));
6816              Class<?> sc = Node[].class;
6817 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6818 <            ss = UNSAFE.arrayIndexScale(sc);
6817 >            ABASE = U.arrayBaseOffset(sc);
6818 >            int scale = U.arrayIndexScale(sc);
6819 >            if ((scale & (scale - 1)) != 0)
6820 >                throw new Error("data type scale not a power of two");
6821 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6822          } catch (Exception e) {
6823              throw new Error(e);
6824          }
6635        if ((ss & (ss-1)) != 0)
6636            throw new Error("data type scale not a power of two");
6637        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6825      }
6826  
6827      /**
# Line 6647 | Line 6834 | public class ConcurrentHashMapV8<K, V>
6834      private static sun.misc.Unsafe getUnsafe() {
6835          try {
6836              return sun.misc.Unsafe.getUnsafe();
6837 <        } catch (SecurityException se) {
6838 <            try {
6839 <                return java.security.AccessController.doPrivileged
6840 <                    (new java.security
6841 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6842 <                        public sun.misc.Unsafe run() throws Exception {
6843 <                            java.lang.reflect.Field f = sun.misc
6844 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6845 <                            f.setAccessible(true);
6846 <                            return (sun.misc.Unsafe) f.get(null);
6847 <                        }});
6848 <            } catch (java.security.PrivilegedActionException e) {
6849 <                throw new RuntimeException("Could not initialize intrinsics",
6850 <                                           e.getCause());
6851 <            }
6837 >        } catch (SecurityException tryReflectionInstead) {}
6838 >        try {
6839 >            return java.security.AccessController.doPrivileged
6840 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6841 >                public sun.misc.Unsafe run() throws Exception {
6842 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6843 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6844 >                        f.setAccessible(true);
6845 >                        Object x = f.get(null);
6846 >                        if (k.isInstance(x))
6847 >                            return k.cast(x);
6848 >                    }
6849 >                    throw new NoSuchFieldError("the Unsafe");
6850 >                }});
6851 >        } catch (java.security.PrivilegedActionException e) {
6852 >            throw new RuntimeException("Could not initialize intrinsics",
6853 >                                       e.getCause());
6854          }
6855      }
6856   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines