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

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.205 by dl, Thu Apr 11 20:13:38 2013 UTC vs.
Revision 1.228 by jsr166, Tue Jun 18 18:39:14 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package java.util.concurrent;
8 import java.util.concurrent.ForkJoinPool;
9 import java.util.concurrent.CountedCompleter;
10 import java.util.Spliterator;
11 import java.util.stream.Stream;
12 import java.util.stream.Streams;
13 import java.util.function.*;
14 import java.util.function.Consumer;
15 import java.util.function.Function;
16 import java.util.function.BiFunction;
8  
9 < import java.util.Comparator;
9 > import java.io.ObjectStreamField;
10 > import java.io.Serializable;
11 > import java.lang.reflect.ParameterizedType;
12 > import java.lang.reflect.Type;
13   import java.util.Arrays;
20 import java.util.Map;
21 import java.util.Set;
14   import java.util.Collection;
15 < import java.util.AbstractMap;
16 < import java.util.AbstractSet;
17 < import java.util.AbstractCollection;
26 < import java.util.Hashtable;
15 > import java.util.Comparator;
16 > import java.util.ConcurrentModificationException;
17 > import java.util.Enumeration;
18   import java.util.HashMap;
19 + import java.util.Hashtable;
20   import java.util.Iterator;
21 < import java.util.Enumeration;
30 < import java.util.ConcurrentModificationException;
21 > import java.util.Map;
22   import java.util.NoSuchElementException;
23 + import java.util.Set;
24 + import java.util.Spliterator;
25   import java.util.concurrent.ConcurrentMap;
26 < import java.util.concurrent.locks.AbstractQueuedSynchronizer;
34 < import java.util.concurrent.atomic.AtomicInteger;
26 > import java.util.concurrent.ForkJoinPool;
27   import java.util.concurrent.atomic.AtomicReference;
28 < import java.io.Serializable;
29 < import java.lang.reflect.Type;
30 < import java.lang.reflect.ParameterizedType;
28 > import java.util.concurrent.locks.LockSupport;
29 > import java.util.concurrent.locks.ReentrantLock;
30 > import java.util.function.BiConsumer;
31 > import java.util.function.BiFunction;
32 > import java.util.function.BinaryOperator;
33 > import java.util.function.Consumer;
34 > import java.util.function.DoubleBinaryOperator;
35 > import java.util.function.Function;
36 > import java.util.function.IntBinaryOperator;
37 > import java.util.function.LongBinaryOperator;
38 > import java.util.function.ToDoubleBiFunction;
39 > import java.util.function.ToDoubleFunction;
40 > import java.util.function.ToIntBiFunction;
41 > import java.util.function.ToIntFunction;
42 > import java.util.function.ToLongBiFunction;
43 > import java.util.function.ToLongFunction;
44 > import java.util.stream.Stream;
45  
46   /**
47   * A hash table supporting full concurrency of retrievals and
# Line 89 | Line 95 | import java.lang.reflect.ParameterizedTy
95   * expected {@code concurrencyLevel} as an additional hint for
96   * internal sizing.  Note that using many keys with exactly the same
97   * {@code hashCode()} is a sure way to slow down performance of any
98 < * hash table.
98 > * hash table. To ameliorate impact, when keys are {@link Comparable},
99 > * this class may use comparison order among keys to help break ties.
100   *
101   * <p>A {@link Set} projection of a ConcurrentHashMap may be created
102   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 111 | Line 118 | import java.lang.reflect.ParameterizedTy
118   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
119   * does <em>not</em> allow {@code null} to be used as a key or value.
120   *
121 < * <p>ConcurrentHashMaps support sequential and parallel operations
122 < * bulk operations. (Parallel forms use the {@link
123 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
124 < * contexts are available in class {@link ForkJoinTasks}. These
125 < * operations are designed to be safely, and often sensibly, applied
126 < * even with maps that are being concurrently updated by other
127 < * threads; for example, when computing a snapshot summary of the
128 < * values in a shared registry.  There are three kinds of operation,
129 < * each with four forms, accepting functions with Keys, Values,
130 < * Entries, and (Key, Value) arguments and/or return values. Because
131 < * the elements of a ConcurrentHashMap are not ordered in any
132 < * particular way, and may be processed in different orders in
133 < * different parallel executions, the correctness of supplied
134 < * functions should not depend on any ordering, or on any other
135 < * objects or values that may transiently change while computation is
129 < * in progress; and except for forEach actions, should ideally be
130 < * side-effect-free.
121 > * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
122 > * operations that, unlike most {@link Stream} methods, are designed
123 > * to be safely, and often sensibly, applied even with maps that are
124 > * being concurrently updated by other threads; for example, when
125 > * computing a snapshot summary of the values in a shared registry.
126 > * There are three kinds of operation, each with four forms, accepting
127 > * functions with Keys, Values, Entries, and (Key, Value) arguments
128 > * and/or return values. Because the elements of a ConcurrentHashMap
129 > * are not ordered in any particular way, and may be processed in
130 > * different orders in different parallel executions, the correctness
131 > * of supplied functions should not depend on any ordering, or on any
132 > * other objects or values that may transiently change while
133 > * computation is in progress; and except for forEach actions, should
134 > * ideally be side-effect-free. Bulk operations on {@link Map.Entry}
135 > * objects do not support method {@code setValue}.
136   *
137   * <ul>
138   * <li> forEach: Perform a given action on each element.
# Line 158 | Line 163 | import java.lang.reflect.ParameterizedTy
163   * </li>
164   * </ul>
165   *
166 + * <p>These bulk operations accept a {@code parallelismThreshold}
167 + * argument. Methods proceed sequentially if the current map size is
168 + * estimated to be less than the given threshold. Using a value of
169 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
170 + * of {@code 1} results in maximal parallelism by partitioning into
171 + * enough subtasks to fully utilize the {@link
172 + * ForkJoinPool#commonPool()} that is used for all parallel
173 + * computations. Normally, you would initially choose one of these
174 + * extreme values, and then measure performance of using in-between
175 + * values that trade off overhead versus throughput.
176 + *
177   * <p>The concurrency properties of bulk operations follow
178   * from those of ConcurrentHashMap: Any non-null result returned
179   * from {@code get(key)} and related access methods bears a
# Line 219 | Line 235 | import java.lang.reflect.ParameterizedTy
235   * @param <K> the type of keys maintained by this map
236   * @param <V> the type of mapped values
237   */
238 < public class ConcurrentHashMap<K,V>
223 <    implements ConcurrentMap<K,V>, Serializable {
238 > public class ConcurrentHashMap<K,V> implements ConcurrentMap<K,V>, Serializable {
239      private static final long serialVersionUID = 7249069246763182397L;
240  
241      /*
# Line 233 | Line 248 | public class ConcurrentHashMap<K,V>
248       * the same or better than java.util.HashMap, and to support high
249       * initial insertion rates on an empty table by many threads.
250       *
251 <     * Each key-value mapping is held in a Node.  Because Node key
252 <     * fields can contain special values, they are defined using plain
253 <     * Object types (not type "K"). This leads to a lot of explicit
254 <     * casting (and many explicit warning suppressions to tell
255 <     * compilers not to complain about it). It also allows some of the
256 <     * public methods to be factored into a smaller number of internal
257 <     * methods (although sadly not so for the five variants of
258 <     * put-related operations). The validation-based approach
259 <     * explained below leads to a lot of code sprawl because
260 <     * retry-control precludes factoring into smaller methods.
251 >     * This map usually acts as a binned (bucketed) hash table.  Each
252 >     * key-value mapping is held in a Node.  Most nodes are instances
253 >     * of the basic Node class with hash, key, value, and next
254 >     * fields. However, various subclasses exist: TreeNodes are
255 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
256 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
257 >     * of bins during resizing. ReservationNodes are used as
258 >     * placeholders while establishing values in computeIfAbsent and
259 >     * related methods.  The types TreeBin, ForwardingNode, and
260 >     * ReservationNode do not hold normal user keys, values, or
261 >     * hashes, and are readily distinguishable during search etc
262 >     * because they have negative hash fields and null key and value
263 >     * fields. (These special nodes are either uncommon or transient,
264 >     * so the impact of carrying around some unused fields is
265 >     * insignficant.)
266       *
267       * The table is lazily initialized to a power-of-two size upon the
268       * first insertion.  Each bin in the table normally contains a
# Line 250 | Line 270 | public class ConcurrentHashMap<K,V>
270       * Table accesses require volatile/atomic reads, writes, and
271       * CASes.  Because there is no other way to arrange this without
272       * adding further indirections, we use intrinsics
273 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
254 <     * are always accurately traversable under volatile reads, so long
255 <     * as lookups check hash code and non-nullness of value before
256 <     * checking key equality.
273 >     * (sun.misc.Unsafe) operations.
274       *
275       * We use the top (sign) bit of Node hash fields for control
276       * purposes -- it is available anyway because of addressing
277 <     * constraints.  Nodes with negative hash fields are forwarding
278 <     * nodes to either TreeBins or resized tables.  The lower 31 bits
262 <     * of each normal Node's hash field contain a transformation of
263 <     * the key's hash code.
277 >     * constraints.  Nodes with negative hash fields are specially
278 >     * handled or ignored in map methods.
279       *
280       * Insertion (via put or its variants) of the first node in an
281       * empty bin is performed by just CASing it to the bin.  This is
# Line 277 | Line 292 | public class ConcurrentHashMap<K,V>
292       * validate that it is still the first node after locking it, and
293       * retry if not. Because new nodes are always appended to lists,
294       * once a node is first in a bin, it remains first until deleted
295 <     * or the bin becomes invalidated (upon resizing).  However,
281 <     * operations that only conditionally update may inspect nodes
282 <     * until the point of update. This is a converse of sorts to the
283 <     * lazy locking technique described by Herlihy & Shavit.
295 >     * or the bin becomes invalidated (upon resizing).
296       *
297       * The main disadvantage of per-bin locks is that other update
298       * operations on other nodes in a bin list protected by the same
# Line 313 | Line 325 | public class ConcurrentHashMap<K,V>
325       * sometimes deviate significantly from uniform randomness.  This
326       * includes the case when N > (1<<30), so some keys MUST collide.
327       * Similarly for dumb or hostile usages in which multiple keys are
328 <     * designed to have identical hash codes. Also, although we guard
329 <     * against the worst effects of this (see method spread), sets of
330 <     * hashes may differ only in bits that do not impact their bin
331 <     * index for a given power-of-two mask.  So we use a secondary
332 <     * strategy that applies when the number of nodes in a bin exceeds
333 <     * a threshold, and at least one of the keys implements
322 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
323 <     * (a specialized form of red-black trees), bounding search time
324 <     * to O(log N).  Each search step in a TreeBin is around twice as
328 >     * designed to have identical hash codes or ones that differs only
329 >     * in masked-out high bits. So we use a secondary strategy that
330 >     * applies when the number of nodes in a bin exceeds a
331 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
332 >     * specialized form of red-black trees), bounding search time to
333 >     * O(log N).  Each search step in a TreeBin is at least twice as
334       * slow as in a regular list, but given that N cannot exceed
335       * (1<<64) (before running out of addresses) this bounds search
336       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 387 | Line 396 | public class ConcurrentHashMap<K,V>
396       * LongAdder. We need to incorporate a specialization rather than
397       * just use a LongAdder in order to access implicit
398       * contention-sensing that leads to creation of multiple
399 <     * Cells.  The counter mechanics avoid contention on
399 >     * CounterCells.  The counter mechanics avoid contention on
400       * updates but can encounter cache thrashing if read too
401       * frequently during concurrent access. To avoid reading so often,
402       * resizing under contention is attempted only upon adding to a
403       * bin already holding two or more nodes. Under uniform hash
404       * distributions, the probability of this occurring at threshold
405       * is around 13%, meaning that only about 1 in 8 puts check
406 <     * threshold (and after resizing, many fewer do so). The bulk
407 <     * putAll operation further reduces contention by only committing
408 <     * count updates upon these size checks.
406 >     * threshold (and after resizing, many fewer do so).
407 >     *
408 >     * TreeBins use a special form of comparison for search and
409 >     * related operations (which is the main reason we cannot use
410 >     * existing collections such as TreeMaps). TreeBins contain
411 >     * Comparable elements, but may contain others, as well as
412 >     * elements that are Comparable but not necessarily Comparable
413 >     * for the same T, so we cannot invoke compareTo among them. To
414 >     * handle this, the tree is ordered primarily by hash value, then
415 >     * by Comparable.compareTo order if applicable.  On lookup at a
416 >     * node, if elements are not comparable or compare as 0 then both
417 >     * left and right children may need to be searched in the case of
418 >     * tied hash values. (This corresponds to the full list search
419 >     * that would be necessary if all elements were non-Comparable and
420 >     * had tied hashes.)  The red-black balancing code is updated from
421 >     * pre-jdk-collections
422 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
423 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
424 >     * Algorithms" (CLR).
425 >     *
426 >     * TreeBins also require an additional locking mechanism.  While
427 >     * list traversal is always possible by readers even during
428 >     * updates, tree traversal is not, mainly beause of tree-rotations
429 >     * that may change the root node and/or its linkages.  TreeBins
430 >     * include a simple read-write lock mechanism parasitic on the
431 >     * main bin-synchronization strategy: Structural adjustments
432 >     * associated with an insertion or removal are already bin-locked
433 >     * (and so cannot conflict with other writers) but must wait for
434 >     * ongoing readers to finish. Since there can be only one such
435 >     * waiter, we use a simple scheme using a single "waiter" field to
436 >     * block writers.  However, readers need never block.  If the root
437 >     * lock is held, they proceed along the slow traversal path (via
438 >     * next-pointers) until the lock becomes available or the list is
439 >     * exhausted, whichever comes first. These cases are not fast, but
440 >     * maximize aggregate expected throughput.
441       *
442       * Maintaining API and serialization compatibility with previous
443       * versions of this class introduces several oddities. Mainly: We
# Line 406 | Line 447 | public class ConcurrentHashMap<K,V>
447       * time that we can guarantee to honor it.) We also declare an
448       * unused "Segment" class that is instantiated in minimal form
449       * only when serializing.
450 +     *
451 +     * This file is organized to make things a little easier to follow
452 +     * while reading than they might otherwise: First the main static
453 +     * declarations and utilities, then fields, then main public
454 +     * methods (with a few factorings of multiple public methods into
455 +     * internal ones), then sizing methods, trees, traversers, and
456 +     * bulk operations.
457       */
458  
459      /* ---------------- Constants -------------- */
# Line 448 | Line 496 | public class ConcurrentHashMap<K,V>
496  
497      /**
498       * The bin count threshold for using a tree rather than list for a
499 <     * bin.  The value reflects the approximate break-even point for
500 <     * using tree-based operations.
499 >     * bin.  Bins are converted to trees when adding an element to a
500 >     * bin with at least this many nodes. The value must be greater
501 >     * than 2, and should be at least 8 to mesh with assumptions in
502 >     * tree removal about conversion back to plain bins upon
503 >     * shrinkage.
504 >     */
505 >    static final int TREEIFY_THRESHOLD = 8;
506 >
507 >    /**
508 >     * The bin count threshold for untreeifying a (split) bin during a
509 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
510 >     * most 6 to mesh with shrinkage detection under removal.
511 >     */
512 >    static final int UNTREEIFY_THRESHOLD = 6;
513 >
514 >    /**
515 >     * The smallest table capacity for which bins may be treeified.
516 >     * (Otherwise the table is resized if too many nodes in a bin.)
517 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
518 >     * conflicts between resizing and treeification thresholds.
519       */
520 <    private static final int TREE_THRESHOLD = 16;
520 >    static final int MIN_TREEIFY_CAPACITY = 64;
521  
522      /**
523       * Minimum number of rebinnings per transfer step. Ranges are
# Line 465 | Line 531 | public class ConcurrentHashMap<K,V>
531      /*
532       * Encodings for Node hash fields. See above for explanation.
533       */
534 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
534 >    static final int MOVED     = 0x8fffffff; // (-1) hash for forwarding nodes
535 >    static final int TREEBIN   = 0x80000000; // hash for heads of treea
536 >    static final int RESERVED  = 0x80000001; // hash for transient reservations
537      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
538  
539      /** Number of CPUS, to place bounds on some sizings */
540      static final int NCPU = Runtime.getRuntime().availableProcessors();
541  
542 <    /* ---------------- Counters -------------- */
542 >    /** For serialization compatibility. */
543 >    private static final ObjectStreamField[] serialPersistentFields = {
544 >        new ObjectStreamField("segments", Segment[].class),
545 >        new ObjectStreamField("segmentMask", Integer.TYPE),
546 >        new ObjectStreamField("segmentShift", Integer.TYPE)
547 >    };
548  
549 <    // Adapted from LongAdder and Striped64.
477 <    // See their internal docs for explanation.
549 >    /* ---------------- Nodes -------------- */
550  
551 <    // A padded cell for distributing counts
552 <    static final class Cell {
553 <        volatile long p0, p1, p2, p3, p4, p5, p6;
554 <        volatile long value;
555 <        volatile long q0, q1, q2, q3, q4, q5, q6;
556 <        Cell(long x) { value = x; }
551 >    /**
552 >     * Key-value entry.  This class is never exported out as a
553 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
554 >     * MapEntry below), but can be used for read-only traversals used
555 >     * in bulk tasks.  Subclasses of Node with a negativehash field
556 >     * are special, and contain null keys and values (but are never
557 >     * exported).  Otherwise, keys and vals are never null.
558 >     */
559 >    static class Node<K,V> implements Map.Entry<K,V> {
560 >        final int hash;
561 >        final K key;
562 >        volatile V val;
563 >        Node<K,V> next;
564 >
565 >        Node(int hash, K key, V val, Node<K,V> next) {
566 >            this.hash = hash;
567 >            this.key = key;
568 >            this.val = val;
569 >            this.next = next;
570 >        }
571 >
572 >        public final K getKey()       { return key; }
573 >        public final V getValue()     { return val; }
574 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
575 >        public final String toString(){ return key + "=" + val; }
576 >        public final V setValue(V value) {
577 >            throw new UnsupportedOperationException();
578 >        }
579 >
580 >        public final boolean equals(Object o) {
581 >            Object k, v, u; Map.Entry<?,?> e;
582 >            return ((o instanceof Map.Entry) &&
583 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
584 >                    (v = e.getValue()) != null &&
585 >                    (k == key || k.equals(key)) &&
586 >                    (v == (u = val) || v.equals(u)));
587 >        }
588 >
589 >        /**
590 >         * Virtualized support for map.get(); overridden in subclasses.
591 >         */
592 >        Node<K,V> find(int h, Object k) {
593 >            Node<K,V> e = this;
594 >            if (k != null) {
595 >                do {
596 >                    K ek;
597 >                    if (e.hash == h &&
598 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
599 >                        return e;
600 >                } while ((e = e.next) != null);
601 >            }
602 >            return null;
603 >        }
604 >    }
605 >
606 >    /* ---------------- Static utilities -------------- */
607 >
608 >    /**
609 >     * Spreads (XORs) higher bits of hash to lower and also forces top
610 >     * bit to 0. Because the table uses power-of-two masking, sets of
611 >     * hashes that vary only in bits above the current mask will
612 >     * always collide. (Among known examples are sets of Float keys
613 >     * holding consecutive whole numbers in small tables.)  So we
614 >     * apply a transform that spreads the impact of higher bits
615 >     * downward. There is a tradeoff between speed, utility, and
616 >     * quality of bit-spreading. Because many common sets of hashes
617 >     * are already reasonably distributed (so don't benefit from
618 >     * spreading), and because we use trees to handle large sets of
619 >     * collisions in bins, we just XOR some shifted bits in the
620 >     * cheapest possible way to reduce systematic lossage, as well as
621 >     * to incorporate impact of the highest bits that would otherwise
622 >     * never be used in index calculations because of table bounds.
623 >     */
624 >    static final int spread(int h) {
625 >        return (h ^ (h >>> 16)) & HASH_BITS;
626 >    }
627 >
628 >    /**
629 >     * Returns a power of two table size for the given desired capacity.
630 >     * See Hackers Delight, sec 3.2
631 >     */
632 >    private static final int tableSizeFor(int c) {
633 >        int n = c - 1;
634 >        n |= n >>> 1;
635 >        n |= n >>> 2;
636 >        n |= n >>> 4;
637 >        n |= n >>> 8;
638 >        n |= n >>> 16;
639 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
640 >    }
641 >
642 >    /**
643 >     * Returns x's Class if it is of the form "class C implements
644 >     * Comparable<C>", else null.
645 >     */
646 >    static Class<?> comparableClassFor(Object x) {
647 >        if (x instanceof Comparable) {
648 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
649 >            if ((c = x.getClass()) == String.class) // bypass checks
650 >                return c;
651 >            if ((ts = c.getGenericInterfaces()) != null) {
652 >                for (int i = 0; i < ts.length; ++i) {
653 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
654 >                        ((p = (ParameterizedType)t).getRawType() ==
655 >                         Comparable.class) &&
656 >                        (as = p.getActualTypeArguments()) != null &&
657 >                        as.length == 1 && as[0] == c) // type arg is c
658 >                        return c;
659 >                }
660 >            }
661 >        }
662 >        return null;
663 >    }
664 >
665 >    /**
666 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
667 >     * class), else 0.
668 >     */
669 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
670 >    static int compareComparables(Class<?> kc, Object k, Object x) {
671 >        return (x == null || x.getClass() != kc ? 0 :
672 >                ((Comparable)k).compareTo(x));
673 >    }
674 >
675 >    /* ---------------- Table element access -------------- */
676 >
677 >    /*
678 >     * Volatile access methods are used for table elements as well as
679 >     * elements of in-progress next table while resizing.  All uses of
680 >     * the tab arguments must be null checked by callers.  All callers
681 >     * also paranoically precheck that tab's length is not zero (or an
682 >     * equivalent check), thus ensuring that any index argument taking
683 >     * the form of a hash value anded with (length - 1) is a valid
684 >     * index.  Note that, to be correct wrt arbitrary concurrency
685 >     * errors by users, these checks must operate on local variables,
686 >     * which accounts for some odd-looking inline assignments below.
687 >     * Note that calls to setTabAt always occur within locked regions,
688 >     * and so do not need full volatile semantics, but still require
689 >     * ordering to maintain concurrent readability.
690 >     */
691 >
692 >    @SuppressWarnings("unchecked")
693 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
694 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
695 >    }
696 >
697 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
698 >                                        Node<K,V> c, Node<K,V> v) {
699 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
700 >    }
701 >
702 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
703 >        U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
704      }
705  
706      /* ---------------- Fields -------------- */
# Line 490 | Line 709 | public class ConcurrentHashMap<K,V>
709       * The array of bins. Lazily initialized upon first insertion.
710       * Size is always a power of two. Accessed directly by iterators.
711       */
712 <    transient volatile Node<V>[] table;
712 >    transient volatile Node<K,V>[] table;
713  
714      /**
715       * The next table to use; non-null only while resizing.
716       */
717 <    private transient volatile Node<V>[] nextTable;
717 >    private transient volatile Node<K,V>[] nextTable;
718  
719      /**
720       * Base counter value, used mainly when there is no contention,
# Line 525 | Line 744 | public class ConcurrentHashMap<K,V>
744      private transient volatile int transferOrigin;
745  
746      /**
747 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
747 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
748       */
749      private transient volatile int cellsBusy;
750  
751      /**
752       * Table of counter cells. When non-null, size is a power of 2.
753       */
754 <    private transient volatile Cell[] counterCells;
754 >    private transient volatile CounterCell[] counterCells;
755  
756      // views
757      private transient KeySetView<K,V> keySet;
758      private transient ValuesView<K,V> values;
759      private transient EntrySetView<K,V> entrySet;
760  
542    /** For serialization compatibility. Null unless serialized; see below */
543    private Segment<K,V>[] segments;
761  
762 <    /* ---------------- Table element access -------------- */
762 >    /* ---------------- Public operations -------------- */
763  
764 <    /*
765 <     * Volatile access methods are used for table elements as well as
766 <     * elements of in-progress next table while resizing.  Uses are
767 <     * null checked by callers, and implicitly bounds-checked, relying
551 <     * on the invariants that tab arrays have non-zero size, and all
552 <     * indices are masked with (tab.length - 1) which is never
553 <     * negative and always less than length. Note that, to be correct
554 <     * wrt arbitrary concurrency errors by users, bounds checks must
555 <     * operate on local variables, which accounts for some odd-looking
556 <     * inline assignments below.
557 <     */
558 <
559 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
560 <        (Node<V>[] tab, int i) { // used by Traverser
561 <        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
764 >    /**
765 >     * Creates a new, empty map with the default initial table size (16).
766 >     */
767 >    public ConcurrentHashMap() {
768      }
769  
770 <    private static final <V> boolean casTabAt
771 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
772 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
770 >    /**
771 >     * Creates a new, empty map with an initial table size
772 >     * accommodating the specified number of elements without the need
773 >     * to dynamically resize.
774 >     *
775 >     * @param initialCapacity The implementation performs internal
776 >     * sizing to accommodate this many elements.
777 >     * @throws IllegalArgumentException if the initial capacity of
778 >     * elements is negative
779 >     */
780 >    public ConcurrentHashMap(int initialCapacity) {
781 >        if (initialCapacity < 0)
782 >            throw new IllegalArgumentException();
783 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
784 >                   MAXIMUM_CAPACITY :
785 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
786 >        this.sizeCtl = cap;
787      }
788  
789 <    private static final <V> void setTabAt
790 <        (Node<V>[] tab, int i, Node<V> v) {
791 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
789 >    /**
790 >     * Creates a new map with the same mappings as the given map.
791 >     *
792 >     * @param m the map
793 >     */
794 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
795 >        this.sizeCtl = DEFAULT_CAPACITY;
796 >        putAll(m);
797      }
798  
574    /* ---------------- Nodes -------------- */
575
799      /**
800 <     * Key-value entry. Note that this is never exported out as a
801 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
802 <     * field of MOVED are special, and do not contain user keys or
803 <     * values.  Otherwise, keys are never null, and null val fields
804 <     * indicate that a node is in the process of being deleted or
805 <     * created. For purposes of read-only access, a key may be read
806 <     * before a val, but can only be used after checking val to be
807 <     * non-null.
800 >     * Creates a new, empty map with an initial table size based on
801 >     * the given number of elements ({@code initialCapacity}) and
802 >     * initial table density ({@code loadFactor}).
803 >     *
804 >     * @param initialCapacity the initial capacity. The implementation
805 >     * performs internal sizing to accommodate this many elements,
806 >     * given the specified load factor.
807 >     * @param loadFactor the load factor (table density) for
808 >     * establishing the initial table size
809 >     * @throws IllegalArgumentException if the initial capacity of
810 >     * elements is negative or the load factor is nonpositive
811 >     *
812 >     * @since 1.6
813       */
814 <    static class Node<V> {
815 <        final int hash;
816 <        final Object key;
589 <        volatile V val;
590 <        volatile Node<V> next;
814 >    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
815 >        this(initialCapacity, loadFactor, 1);
816 >    }
817  
818 <        Node(int hash, Object key, V val, Node<V> next) {
819 <            this.hash = hash;
820 <            this.key = key;
821 <            this.val = val;
822 <            this.next = next;
823 <        }
818 >    /**
819 >     * Creates a new, empty map with an initial table size based on
820 >     * the given number of elements ({@code initialCapacity}), table
821 >     * density ({@code loadFactor}), and number of concurrently
822 >     * updating threads ({@code concurrencyLevel}).
823 >     *
824 >     * @param initialCapacity the initial capacity. The implementation
825 >     * performs internal sizing to accommodate this many elements,
826 >     * given the specified load factor.
827 >     * @param loadFactor the load factor (table density) for
828 >     * establishing the initial table size
829 >     * @param concurrencyLevel the estimated number of concurrently
830 >     * updating threads. The implementation may use this value as
831 >     * a sizing hint.
832 >     * @throws IllegalArgumentException if the initial capacity is
833 >     * negative or the load factor or concurrencyLevel are
834 >     * nonpositive
835 >     */
836 >    public ConcurrentHashMap(int initialCapacity,
837 >                             float loadFactor, int concurrencyLevel) {
838 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
839 >            throw new IllegalArgumentException();
840 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
841 >            initialCapacity = concurrencyLevel;   // as estimated threads
842 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
843 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
844 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
845 >        this.sizeCtl = cap;
846      }
847  
848 <    /* ---------------- TreeBins -------------- */
848 >    // Original (since JDK1.2) Map methods
849  
850      /**
851 <     * Nodes for use in TreeBins
851 >     * {@inheritDoc}
852       */
853 <    static final class TreeNode<V> extends Node<V> {
854 <        TreeNode<V> parent;  // red-black tree links
855 <        TreeNode<V> left;
856 <        TreeNode<V> right;
857 <        TreeNode<V> prev;    // needed to unlink next upon deletion
610 <        boolean red;
611 <
612 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
613 <            super(hash, key, val, next);
614 <            this.parent = parent;
615 <        }
853 >    public int size() {
854 >        long n = sumCount();
855 >        return ((n < 0L) ? 0 :
856 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
857 >                (int)n);
858      }
859  
860 +    /**
861 +     * {@inheritDoc}
862 +     */
863 +    public boolean isEmpty() {
864 +        return sumCount() <= 0L; // ignore transient negative values
865 +    }
866  
867      /**
868 <     * Returns a Class for the given object of the form "class C
869 <     * implements Comparable<C>", if one exists, else null.  See below
870 <     * for explanation.
868 >     * Returns the value to which the specified key is mapped,
869 >     * or {@code null} if this map contains no mapping for the key.
870 >     *
871 >     * <p>More formally, if this map contains a mapping from a key
872 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
873 >     * then this method returns {@code v}; otherwise it returns
874 >     * {@code null}.  (There can be at most one such mapping.)
875 >     *
876 >     * @throws NullPointerException if the specified key is null
877       */
878 <    static Class<?> comparableClassFor(Object x) {
879 <        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
880 <        if ((c = x.getClass()) == String.class) // bypass checks
881 <            return c;
882 <        if ((cmpc = Comparable.class).isAssignableFrom(c)) {
883 <            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
884 <                c = s; // find topmost comparable class
885 <            if ((ts  = c.getGenericInterfaces()) != null) {
886 <                for (int i = 0; i < ts.length; ++i) {
887 <                    if (((t = ts[i]) instanceof ParameterizedType) &&
888 <                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
889 <                        (as = p.getActualTypeArguments()) != null &&
890 <                        as.length == 1 && as[0] == c) // type arg is c
891 <                        return c;
892 <                }
878 >    public V get(Object key) {
879 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
880 >        int h = spread(key.hashCode());
881 >        if ((tab = table) != null && (n = tab.length) > 0 &&
882 >            (e = tabAt(tab, (n - 1) & h)) != null) {
883 >            if ((eh = e.hash) == h) {
884 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
885 >                    return e.val;
886 >            }
887 >            else if (eh < 0)
888 >                return (p = e.find(h, key)) != null ? p.val : null;
889 >            while ((e = e.next) != null) {
890 >                if (e.hash == h &&
891 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
892 >                    return e.val;
893              }
894          }
895          return null;
896      }
897  
898      /**
899 <     * A specialized form of red-black tree for use in bins
646 <     * whose size exceeds a threshold.
647 <     *
648 <     * TreeBins use a special form of comparison for search and
649 <     * related operations (which is the main reason we cannot use
650 <     * existing collections such as TreeMaps). TreeBins contain
651 <     * Comparable elements, but may contain others, as well as
652 <     * elements that are Comparable but not necessarily Comparable<T>
653 <     * for the same T, so we cannot invoke compareTo among them. To
654 <     * handle this, the tree is ordered primarily by hash value, then
655 <     * by Comparable.compareTo order if applicable.  On lookup at a
656 <     * node, if elements are not comparable or compare as 0 then both
657 <     * left and right children may need to be searched in the case of
658 <     * tied hash values. (This corresponds to the full list search
659 <     * that would be necessary if all elements were non-Comparable and
660 <     * had tied hashes.)  The red-black balancing code is updated from
661 <     * pre-jdk-collections
662 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
663 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
664 <     * Algorithms" (CLR).
899 >     * Tests if the specified object is a key in this table.
900       *
901 <     * TreeBins also maintain a separate locking discipline than
902 <     * regular bins. Because they are forwarded via special MOVED
903 <     * nodes at bin heads (which can never change once established),
904 <     * we cannot use those nodes as locks. Instead, TreeBin
905 <     * extends AbstractQueuedSynchronizer to support a simple form of
671 <     * read-write lock. For update operations and table validation,
672 <     * the exclusive form of lock behaves in the same way as bin-head
673 <     * locks. However, lookups use shared read-lock mechanics to allow
674 <     * multiple readers in the absence of writers.  Additionally,
675 <     * these lookups do not ever block: While the lock is not
676 <     * available, they proceed along the slow traversal path (via
677 <     * next-pointers) until the lock becomes available or the list is
678 <     * exhausted, whichever comes first. (These cases are not fast,
679 <     * but maximize aggregate expected throughput.)  The AQS mechanics
680 <     * for doing this are straightforward.  The lock state is held as
681 <     * AQS getState().  Read counts are negative; the write count (1)
682 <     * is positive.  There are no signalling preferences among readers
683 <     * and writers. Since we don't need to export full Lock API, we
684 <     * just override the minimal AQS methods and use them directly.
901 >     * @param  key possible key
902 >     * @return {@code true} if and only if the specified object
903 >     *         is a key in this table, as determined by the
904 >     *         {@code equals} method; {@code false} otherwise
905 >     * @throws NullPointerException if the specified key is null
906       */
907 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
908 <        private static final long serialVersionUID = 2249069246763182397L;
909 <        transient TreeNode<V> root;  // root of tree
689 <        transient TreeNode<V> first; // head of next-pointer list
690 <
691 <        /* AQS overrides */
692 <        public final boolean isHeldExclusively() { return getState() > 0; }
693 <        public final boolean tryAcquire(int ignore) {
694 <            if (compareAndSetState(0, 1)) {
695 <                setExclusiveOwnerThread(Thread.currentThread());
696 <                return true;
697 <            }
698 <            return false;
699 <        }
700 <        public final boolean tryRelease(int ignore) {
701 <            setExclusiveOwnerThread(null);
702 <            setState(0);
703 <            return true;
704 <        }
705 <        public final int tryAcquireShared(int ignore) {
706 <            for (int c;;) {
707 <                if ((c = getState()) > 0)
708 <                    return -1;
709 <                if (compareAndSetState(c, c -1))
710 <                    return 1;
711 <            }
712 <        }
713 <        public final boolean tryReleaseShared(int ignore) {
714 <            int c;
715 <            do {} while (!compareAndSetState(c = getState(), c + 1));
716 <            return c == -1;
717 <        }
718 <
719 <        /** From CLR */
720 <        private void rotateLeft(TreeNode<V> p) {
721 <            if (p != null) {
722 <                TreeNode<V> r = p.right, pp, rl;
723 <                if ((rl = p.right = r.left) != null)
724 <                    rl.parent = p;
725 <                if ((pp = r.parent = p.parent) == null)
726 <                    root = r;
727 <                else if (pp.left == p)
728 <                    pp.left = r;
729 <                else
730 <                    pp.right = r;
731 <                r.left = p;
732 <                p.parent = r;
733 <            }
734 <        }
907 >    public boolean containsKey(Object key) {
908 >        return get(key) != null;
909 >    }
910  
911 <        /** From CLR */
912 <        private void rotateRight(TreeNode<V> p) {
913 <            if (p != null) {
914 <                TreeNode<V> l = p.left, pp, lr;
915 <                if ((lr = p.left = l.right) != null)
916 <                    lr.parent = p;
917 <                if ((pp = l.parent = p.parent) == null)
918 <                    root = l;
919 <                else if (pp.right == p)
920 <                    pp.right = l;
921 <                else
922 <                    pp.left = l;
923 <                l.right = p;
924 <                p.parent = l;
911 >    /**
912 >     * Returns {@code true} if this map maps one or more keys to the
913 >     * specified value. Note: This method may require a full traversal
914 >     * of the map, and is much slower than method {@code containsKey}.
915 >     *
916 >     * @param value value whose presence in this map is to be tested
917 >     * @return {@code true} if this map maps one or more keys to the
918 >     *         specified value
919 >     * @throws NullPointerException if the specified value is null
920 >     */
921 >    public boolean containsValue(Object value) {
922 >        if (value == null)
923 >            throw new NullPointerException();
924 >        Node<K,V>[] t;
925 >        if ((t = table) != null) {
926 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
927 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
928 >                V v;
929 >                if ((v = p.val) == value || (v != null && value.equals(v)))
930 >                    return true;
931              }
932          }
933 +        return false;
934 +    }
935  
936 <        /**
937 <         * Returns the TreeNode (or null if not found) for the given
938 <         * key.  A front-end for recursive version.
939 <         */
940 <        final TreeNode<V> getTreeNode(int h, Object k) {
941 <            return getTreeNode(h, k, root, comparableClassFor(k));
942 <        }
936 >    /**
937 >     * Maps the specified key to the specified value in this table.
938 >     * Neither the key nor the value can be null.
939 >     *
940 >     * <p>The value can be retrieved by calling the {@code get} method
941 >     * with a key that is equal to the original key.
942 >     *
943 >     * @param key key with which the specified value is to be associated
944 >     * @param value value to be associated with the specified key
945 >     * @return the previous value associated with {@code key}, or
946 >     *         {@code null} if there was no mapping for {@code key}
947 >     * @throws NullPointerException if the specified key or value is null
948 >     */
949 >    public V put(K key, V value) {
950 >        return putVal(key, value, false);
951 >    }
952  
953 <        /**
954 <         * Returns the TreeNode (or null if not found) for the given key
955 <         * starting at given root.
956 <         */
957 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
958 <            (int h, Object k, TreeNode<V> p, Class<?> cc) {
959 <            while (p != null) {
960 <                int dir, ph;  Object pk;
961 <                if ((ph = p.hash) != h)
962 <                    dir = (h < ph) ? -1 : 1;
963 <                else if ((pk = p.key) == k || k.equals(pk))
964 <                    return p;
965 <                else if (cc == null || comparableClassFor(pk) != cc ||
774 <                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
775 <                    TreeNode<V> r, pl, pr; // check both sides
776 <                    if ((pr = p.right) != null && h >= pr.hash &&
777 <                        (r = getTreeNode(h, k, pr, cc)) != null)
778 <                        return r;
779 <                    else if ((pl = p.left) != null && h <= pl.hash)
780 <                        dir = -1;
781 <                    else // nothing there
782 <                        break;
783 <                }
784 <                p = (dir > 0) ? p.right : p.left;
953 >    /** Implementation for put and putIfAbsent */
954 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
955 >        if (key == null || value == null) throw new NullPointerException();
956 >        int hash = spread(key.hashCode());
957 >        int binCount = 0;
958 >        for (Node<K,V>[] tab = table;;) {
959 >            Node<K,V> f; int n, i, fh;
960 >            if (tab == null || (n = tab.length) == 0)
961 >                tab = initTable();
962 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
963 >                if (casTabAt(tab, i, null,
964 >                             new Node<K,V>(hash, key, value, null)))
965 >                    break;                   // no lock when adding to empty bin
966              }
967 <            return null;
968 <        }
969 <
970 <        /**
971 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
972 <         * read-lock to call getTreeNode, but during failure to get
973 <         * lock, searches along next links.
974 <         */
975 <        final V getValue(int h, Object k) {
976 <            Node<V> r = null;
977 <            int c = getState(); // Must read lock state first
978 <            for (Node<V> e = first; e != null; e = e.next) {
979 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
980 <                    try {
981 <                        r = getTreeNode(h, k, root, comparableClassFor(k));
982 <                    } finally {
983 <                        releaseShared(0);
967 >            else if ((fh = f.hash) == MOVED)
968 >                tab = helpTransfer(tab, f);
969 >            else {
970 >                V oldVal = null;
971 >                synchronized (f) {
972 >                    if (tabAt(tab, i) == f) {
973 >                        if (fh >= 0) {
974 >                            binCount = 1;
975 >                            for (Node<K,V> e = f;; ++binCount) {
976 >                                K ek;
977 >                                if (e.hash == hash &&
978 >                                    ((ek = e.key) == key ||
979 >                                     (ek != null && key.equals(ek)))) {
980 >                                    oldVal = e.val;
981 >                                    if (!onlyIfAbsent)
982 >                                        e.val = value;
983 >                                    break;
984 >                                }
985 >                                Node<K,V> pred = e;
986 >                                if ((e = e.next) == null) {
987 >                                    pred.next = new Node<K,V>(hash, key,
988 >                                                              value, null);
989 >                                    break;
990 >                                }
991 >                            }
992 >                        }
993 >                        else if (f instanceof TreeBin) {
994 >                            Node<K,V> p;
995 >                            binCount = 2;
996 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
997 >                                                           value)) != null) {
998 >                                oldVal = p.val;
999 >                                if (!onlyIfAbsent)
1000 >                                    p.val = value;
1001 >                            }
1002 >                        }
1003                      }
804                    break;
1004                  }
1005 <                else if (e.hash == h && k.equals(e.key)) {
1006 <                    r = e;
1005 >                if (binCount != 0) {
1006 >                    if (binCount >= TREEIFY_THRESHOLD)
1007 >                        treeifyBin(tab, i);
1008 >                    if (oldVal != null)
1009 >                        return oldVal;
1010                      break;
1011                  }
810                else
811                    c = getState();
1012              }
813            return r == null ? null : r.val;
1013          }
1014 +        addCount(1L, binCount);
1015 +        return null;
1016 +    }
1017  
1018 <        /**
1019 <         * Finds or adds a node.
1020 <         * @return null if added
1021 <         */
1022 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
1023 <            (int h, Object k, V v) {
1024 <            Class<?> cc = comparableClassFor(k);
1025 <            TreeNode<V> pp = root, p = null;
1026 <            int dir = 0;
1027 <            while (pp != null) { // find existing node or leaf to insert at
1028 <                int ph;  Object pk;
1029 <                p = pp;
828 <                if ((ph = p.hash) != h)
829 <                    dir = (h < ph) ? -1 : 1;
830 <                else if ((pk = p.key) == k || k.equals(pk))
831 <                    return p;
832 <                else if (cc == null || comparableClassFor(pk) != cc ||
833 <                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
834 <                    TreeNode<V> r, pr;
835 <                    if ((pr = p.right) != null && h >= pr.hash &&
836 <                        (r = getTreeNode(h, k, pr, cc)) != null)
837 <                        return r;
838 <                    else // continue left
839 <                        dir = -1;
840 <                }
841 <                pp = (dir > 0) ? p.right : p.left;
842 <            }
1018 >    /**
1019 >     * Copies all of the mappings from the specified map to this one.
1020 >     * These mappings replace any mappings that this map had for any of the
1021 >     * keys currently in the specified map.
1022 >     *
1023 >     * @param m mappings to be stored in this map
1024 >     */
1025 >    public void putAll(Map<? extends K, ? extends V> m) {
1026 >        tryPresize(m.size());
1027 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1028 >            putVal(e.getKey(), e.getValue(), false);
1029 >    }
1030  
1031 <            TreeNode<V> f = first;
1032 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
1033 <            if (p == null)
1034 <                root = x;
1035 <            else { // attach and rebalance; adapted from CLR
1036 <                TreeNode<V> xp, xpp;
1037 <                if (f != null)
1038 <                    f.prev = x;
1039 <                if (dir <= 0)
1040 <                    p.left = x;
1041 <                else
1042 <                    p.right = x;
1043 <                x.red = true;
1044 <                while (x != null && (xp = x.parent) != null && xp.red &&
1045 <                       (xpp = xp.parent) != null) {
1046 <                    TreeNode<V> xppl = xpp.left;
1047 <                    if (xp == xppl) {
1048 <                        TreeNode<V> y = xpp.right;
1049 <                        if (y != null && y.red) {
1050 <                            y.red = false;
1051 <                            xp.red = false;
1052 <                            xpp.red = true;
1053 <                            x = xpp;
1054 <                        }
1055 <                        else {
1056 <                            if (x == xp.right) {
1057 <                                rotateLeft(x = xp);
1058 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1059 <                            }
1060 <                            if (xp != null) {
1061 <                                xp.red = false;
1062 <                                if (xpp != null) {
1063 <                                    xpp.red = true;
1064 <                                    rotateRight(xpp);
1031 >    /**
1032 >     * Removes the key (and its corresponding value) from this map.
1033 >     * This method does nothing if the key is not in the map.
1034 >     *
1035 >     * @param  key the key that needs to be removed
1036 >     * @return the previous value associated with {@code key}, or
1037 >     *         {@code null} if there was no mapping for {@code key}
1038 >     * @throws NullPointerException if the specified key is null
1039 >     */
1040 >    public V remove(Object key) {
1041 >        return replaceNode(key, null, null);
1042 >    }
1043 >
1044 >    /**
1045 >     * Implementation for the four public remove/replace methods:
1046 >     * Replaces node value with v, conditional upon match of cv if
1047 >     * non-null.  If resulting value is null, delete.
1048 >     */
1049 >    final V replaceNode(Object key, V value, Object cv) {
1050 >        int hash = spread(key.hashCode());
1051 >        for (Node<K,V>[] tab = table;;) {
1052 >            Node<K,V> f; int n, i, fh;
1053 >            if (tab == null || (n = tab.length) == 0 ||
1054 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1055 >                break;
1056 >            else if ((fh = f.hash) == MOVED)
1057 >                tab = helpTransfer(tab, f);
1058 >            else {
1059 >                V oldVal = null;
1060 >                boolean validated = false;
1061 >                synchronized (f) {
1062 >                    if (tabAt(tab, i) == f) {
1063 >                        if (fh >= 0) {
1064 >                            validated = true;
1065 >                            for (Node<K,V> e = f, pred = null;;) {
1066 >                                K ek;
1067 >                                if (e.hash == hash &&
1068 >                                    ((ek = e.key) == key ||
1069 >                                     (ek != null && key.equals(ek)))) {
1070 >                                    V ev = e.val;
1071 >                                    if (cv == null || cv == ev ||
1072 >                                        (ev != null && cv.equals(ev))) {
1073 >                                        oldVal = ev;
1074 >                                        if (value != null)
1075 >                                            e.val = value;
1076 >                                        else if (pred != null)
1077 >                                            pred.next = e.next;
1078 >                                        else
1079 >                                            setTabAt(tab, i, e.next);
1080 >                                    }
1081 >                                    break;
1082                                  }
1083 +                                pred = e;
1084 +                                if ((e = e.next) == null)
1085 +                                    break;
1086                              }
1087                          }
1088 <                    }
1089 <                    else {
1090 <                        TreeNode<V> y = xppl;
1091 <                        if (y != null && y.red) {
1092 <                            y.red = false;
1093 <                            xp.red = false;
1094 <                            xpp.red = true;
1095 <                            x = xpp;
1096 <                        }
1097 <                        else {
1098 <                            if (x == xp.left) {
1099 <                                rotateRight(x = xp);
1100 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1101 <                            }
895 <                            if (xp != null) {
896 <                                xp.red = false;
897 <                                if (xpp != null) {
898 <                                    xpp.red = true;
899 <                                    rotateLeft(xpp);
1088 >                        else if (f instanceof TreeBin) {
1089 >                            validated = true;
1090 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1091 >                            TreeNode<K,V> r, p;
1092 >                            if ((r = t.root) != null &&
1093 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1094 >                                V pv = p.val;
1095 >                                if (cv == null || cv == pv ||
1096 >                                    (pv != null && cv.equals(pv))) {
1097 >                                    oldVal = pv;
1098 >                                    if (value != null)
1099 >                                        p.val = value;
1100 >                                    else if (t.removeTreeNode(p))
1101 >                                        setTabAt(tab, i, untreeify(t.first));
1102                                  }
1103                              }
1104                          }
1105                      }
1106                  }
1107 <                TreeNode<V> r = root;
1108 <                if (r != null && r.red)
1109 <                    r.red = false;
1110 <            }
1111 <            return null;
910 <        }
911 <
912 <        /**
913 <         * Removes the given node, that must be present before this
914 <         * call.  This is messier than typical red-black deletion code
915 <         * because we cannot swap the contents of an interior node
916 <         * with a leaf successor that is pinned by "next" pointers
917 <         * that are accessible independently of lock. So instead we
918 <         * swap the tree linkages.
919 <         */
920 <        final void deleteTreeNode(TreeNode<V> p) {
921 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
922 <            TreeNode<V> pred = p.prev;
923 <            if (pred == null)
924 <                first = next;
925 <            else
926 <                pred.next = next;
927 <            if (next != null)
928 <                next.prev = pred;
929 <            TreeNode<V> replacement;
930 <            TreeNode<V> pl = p.left;
931 <            TreeNode<V> pr = p.right;
932 <            if (pl != null && pr != null) {
933 <                TreeNode<V> s = pr, sl;
934 <                while ((sl = s.left) != null) // find successor
935 <                    s = sl;
936 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
937 <                TreeNode<V> sr = s.right;
938 <                TreeNode<V> pp = p.parent;
939 <                if (s == pr) { // p was s's direct parent
940 <                    p.parent = s;
941 <                    s.right = p;
942 <                }
943 <                else {
944 <                    TreeNode<V> sp = s.parent;
945 <                    if ((p.parent = sp) != null) {
946 <                        if (s == sp.left)
947 <                            sp.left = p;
948 <                        else
949 <                            sp.right = p;
1107 >                if (validated) {
1108 >                    if (oldVal != null) {
1109 >                        if (value == null)
1110 >                            addCount(-1L, -1);
1111 >                        return oldVal;
1112                      }
1113 <                    if ((s.right = pr) != null)
952 <                        pr.parent = s;
1113 >                    break;
1114                  }
954                p.left = null;
955                if ((p.right = sr) != null)
956                    sr.parent = p;
957                if ((s.left = pl) != null)
958                    pl.parent = s;
959                if ((s.parent = pp) == null)
960                    root = s;
961                else if (p == pp.left)
962                    pp.left = s;
963                else
964                    pp.right = s;
965                replacement = sr;
1115              }
1116 <            else
1117 <                replacement = (pl != null) ? pl : pr;
1118 <            TreeNode<V> pp = p.parent;
1119 <            if (replacement == null) {
1120 <                if (pp == null) {
1121 <                    root = null;
1122 <                    return;
1123 <                }
1124 <                replacement = p;
1116 >        }
1117 >        return null;
1118 >    }
1119 >
1120 >    /**
1121 >     * Removes all of the mappings from this map.
1122 >     */
1123 >    public void clear() {
1124 >        long delta = 0L; // negative number of deletions
1125 >        int i = 0;
1126 >        Node<K,V>[] tab = table;
1127 >        while (tab != null && i < tab.length) {
1128 >            int fh;
1129 >            Node<K,V> f = tabAt(tab, i);
1130 >            if (f == null)
1131 >                ++i;
1132 >            else if ((fh = f.hash) == MOVED) {
1133 >                tab = helpTransfer(tab, f);
1134 >                i = 0; // restart
1135              }
1136              else {
1137 <                replacement.parent = pp;
1138 <                if (pp == null)
1139 <                    root = replacement;
1140 <                else if (p == pp.left)
1141 <                    pp.left = replacement;
1142 <                else
1143 <                    pp.right = replacement;
1144 <                p.left = p.right = p.parent = null;
986 <            }
987 <            if (!p.red) { // rebalance, from CLR
988 <                TreeNode<V> x = replacement;
989 <                while (x != null) {
990 <                    TreeNode<V> xp, xpl;
991 <                    if (x.red || (xp = x.parent) == null) {
992 <                        x.red = false;
993 <                        break;
994 <                    }
995 <                    if (x == (xpl = xp.left)) {
996 <                        TreeNode<V> sib = xp.right;
997 <                        if (sib != null && sib.red) {
998 <                            sib.red = false;
999 <                            xp.red = true;
1000 <                            rotateLeft(xp);
1001 <                            sib = (xp = x.parent) == null ? null : xp.right;
1002 <                        }
1003 <                        if (sib == null)
1004 <                            x = xp;
1005 <                        else {
1006 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1007 <                            if ((sr == null || !sr.red) &&
1008 <                                (sl == null || !sl.red)) {
1009 <                                sib.red = true;
1010 <                                x = xp;
1011 <                            }
1012 <                            else {
1013 <                                if (sr == null || !sr.red) {
1014 <                                    if (sl != null)
1015 <                                        sl.red = false;
1016 <                                    sib.red = true;
1017 <                                    rotateRight(sib);
1018 <                                    sib = (xp = x.parent) == null ?
1019 <                                        null : xp.right;
1020 <                                }
1021 <                                if (sib != null) {
1022 <                                    sib.red = (xp == null) ? false : xp.red;
1023 <                                    if ((sr = sib.right) != null)
1024 <                                        sr.red = false;
1025 <                                }
1026 <                                if (xp != null) {
1027 <                                    xp.red = false;
1028 <                                    rotateLeft(xp);
1029 <                                }
1030 <                                x = root;
1031 <                            }
1032 <                        }
1033 <                    }
1034 <                    else { // symmetric
1035 <                        TreeNode<V> sib = xpl;
1036 <                        if (sib != null && sib.red) {
1037 <                            sib.red = false;
1038 <                            xp.red = true;
1039 <                            rotateRight(xp);
1040 <                            sib = (xp = x.parent) == null ? null : xp.left;
1041 <                        }
1042 <                        if (sib == null)
1043 <                            x = xp;
1044 <                        else {
1045 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1046 <                            if ((sl == null || !sl.red) &&
1047 <                                (sr == null || !sr.red)) {
1048 <                                sib.red = true;
1049 <                                x = xp;
1050 <                            }
1051 <                            else {
1052 <                                if (sl == null || !sl.red) {
1053 <                                    if (sr != null)
1054 <                                        sr.red = false;
1055 <                                    sib.red = true;
1056 <                                    rotateLeft(sib);
1057 <                                    sib = (xp = x.parent) == null ?
1058 <                                        null : xp.left;
1059 <                                }
1060 <                                if (sib != null) {
1061 <                                    sib.red = (xp == null) ? false : xp.red;
1062 <                                    if ((sl = sib.left) != null)
1063 <                                        sl.red = false;
1064 <                                }
1065 <                                if (xp != null) {
1066 <                                    xp.red = false;
1067 <                                    rotateRight(xp);
1068 <                                }
1069 <                                x = root;
1070 <                            }
1137 >                synchronized (f) {
1138 >                    if (tabAt(tab, i) == f) {
1139 >                        Node<K,V> p = (fh >= 0 ? f :
1140 >                                       (f instanceof TreeBin) ?
1141 >                                       ((TreeBin<K,V>)f).first : null);
1142 >                        while (p != null) {
1143 >                            --delta;
1144 >                            p = p.next;
1145                          }
1146 +                        setTabAt(tab, i++, null);
1147                      }
1148                  }
1149              }
1075            if (p == replacement && (pp = p.parent) != null) {
1076                if (p == pp.left) // detach pointers
1077                    pp.left = null;
1078                else if (p == pp.right)
1079                    pp.right = null;
1080                p.parent = null;
1081            }
1150          }
1151 +        if (delta != 0L)
1152 +            addCount(delta, -1);
1153      }
1154  
1155 <    /* ---------------- Collision reduction methods -------------- */
1155 >    /**
1156 >     * Returns a {@link Set} view of the keys contained in this map.
1157 >     * The set is backed by the map, so changes to the map are
1158 >     * reflected in the set, and vice-versa. The set supports element
1159 >     * removal, which removes the corresponding mapping from this map,
1160 >     * via the {@code Iterator.remove}, {@code Set.remove},
1161 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1162 >     * operations.  It does not support the {@code add} or
1163 >     * {@code addAll} operations.
1164 >     *
1165 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1166 >     * that will never throw {@link ConcurrentModificationException},
1167 >     * and guarantees to traverse elements as they existed upon
1168 >     * construction of the iterator, and may (but is not guaranteed to)
1169 >     * reflect any modifications subsequent to construction.
1170 >     *
1171 >     * @return the set view
1172 >     */
1173 >    public KeySetView<K,V> keySet() {
1174 >        KeySetView<K,V> ks;
1175 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1176 >    }
1177  
1178      /**
1179 <     * Spreads higher bits to lower, and also forces top bit to 0.
1180 <     * Because the table uses power-of-two masking, sets of hashes
1181 <     * that vary only in bits above the current mask will always
1182 <     * collide. (Among known examples are sets of Float keys holding
1183 <     * consecutive whole numbers in small tables.)  To counter this,
1184 <     * we apply a transform that spreads the impact of higher bits
1185 <     * downward. There is a tradeoff between speed, utility, and
1186 <     * quality of bit-spreading. Because many common sets of hashes
1187 <     * are already reasonably distributed across bits (so don't benefit
1188 <     * from spreading), and because we use trees to handle large sets
1189 <     * of collisions in bins, we don't need excessively high quality.
1179 >     * Returns a {@link Collection} view of the values contained in this map.
1180 >     * The collection is backed by the map, so changes to the map are
1181 >     * reflected in the collection, and vice-versa.  The collection
1182 >     * supports element removal, which removes the corresponding
1183 >     * mapping from this map, via the {@code Iterator.remove},
1184 >     * {@code Collection.remove}, {@code removeAll},
1185 >     * {@code retainAll}, and {@code clear} operations.  It does not
1186 >     * support the {@code add} or {@code addAll} operations.
1187 >     *
1188 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1189 >     * that will never throw {@link ConcurrentModificationException},
1190 >     * and guarantees to traverse elements as they existed upon
1191 >     * construction of the iterator, and may (but is not guaranteed to)
1192 >     * reflect any modifications subsequent to construction.
1193 >     *
1194 >     * @return the collection view
1195       */
1196 <    private static final int spread(int h) {
1197 <        h ^= (h >>> 18) ^ (h >>> 12);
1198 <        return (h ^ (h >>> 10)) & HASH_BITS;
1196 >    public Collection<V> values() {
1197 >        ValuesView<K,V> vs;
1198 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1199      }
1200  
1201      /**
1202 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1203 <     * only when locked.
1202 >     * Returns a {@link Set} view of the mappings contained in this map.
1203 >     * The set is backed by the map, so changes to the map are
1204 >     * reflected in the set, and vice-versa.  The set supports element
1205 >     * removal, which removes the corresponding mapping from the map,
1206 >     * via the {@code Iterator.remove}, {@code Set.remove},
1207 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1208 >     * operations.
1209 >     *
1210 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1211 >     * that will never throw {@link ConcurrentModificationException},
1212 >     * and guarantees to traverse elements as they existed upon
1213 >     * construction of the iterator, and may (but is not guaranteed to)
1214 >     * reflect any modifications subsequent to construction.
1215 >     *
1216 >     * @return the set view
1217 >     */
1218 >    public Set<Map.Entry<K,V>> entrySet() {
1219 >        EntrySetView<K,V> es;
1220 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1221 >    }
1222 >
1223 >    /**
1224 >     * Returns the hash code value for this {@link Map}, i.e.,
1225 >     * the sum of, for each key-value pair in the map,
1226 >     * {@code key.hashCode() ^ value.hashCode()}.
1227 >     *
1228 >     * @return the hash code value for this map
1229       */
1230 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1231 <        if (comparableClassFor(key) != null) {
1232 <            TreeBin<V> t = new TreeBin<V>();
1233 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1234 <                t.putTreeNode(e.hash, e.key, e.val);
1235 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1230 >    public int hashCode() {
1231 >        int h = 0;
1232 >        Node<K,V>[] t;
1233 >        if ((t = table) != null) {
1234 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1235 >            for (Node<K,V> p; (p = it.advance()) != null; )
1236 >                h += p.key.hashCode() ^ p.val.hashCode();
1237          }
1238 +        return h;
1239      }
1240  
1241 <    /* ---------------- Internal access and update methods -------------- */
1241 >    /**
1242 >     * Returns a string representation of this map.  The string
1243 >     * representation consists of a list of key-value mappings (in no
1244 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1245 >     * mappings are separated by the characters {@code ", "} (comma
1246 >     * and space).  Each key-value mapping is rendered as the key
1247 >     * followed by an equals sign ("{@code =}") followed by the
1248 >     * associated value.
1249 >     *
1250 >     * @return a string representation of this map
1251 >     */
1252 >    public String toString() {
1253 >        Node<K,V>[] t;
1254 >        int f = (t = table) == null ? 0 : t.length;
1255 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1256 >        StringBuilder sb = new StringBuilder();
1257 >        sb.append('{');
1258 >        Node<K,V> p;
1259 >        if ((p = it.advance()) != null) {
1260 >            for (;;) {
1261 >                K k = p.key;
1262 >                V v = p.val;
1263 >                sb.append(k == this ? "(this Map)" : k);
1264 >                sb.append('=');
1265 >                sb.append(v == this ? "(this Map)" : v);
1266 >                if ((p = it.advance()) == null)
1267 >                    break;
1268 >                sb.append(',').append(' ');
1269 >            }
1270 >        }
1271 >        return sb.append('}').toString();
1272 >    }
1273  
1274 <    /** Implementation for get and containsKey */
1275 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1276 <        int h = spread(k.hashCode());
1277 <        retry: for (Node<V>[] tab = table; tab != null;) {
1278 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1279 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1280 <                if ((eh = e.hash) < 0) {
1281 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1282 <                        return ((TreeBin<V>)ek).getValue(h, k);
1283 <                    else {                      // restart with new table
1284 <                        tab = (Node<V>[])ek;
1285 <                        continue retry;
1286 <                    }
1287 <                }
1288 <                else if (eh == h && (ev = e.val) != null &&
1289 <                         ((ek = e.key) == k || k.equals(ek)))
1290 <                    return ev;
1274 >    /**
1275 >     * Compares the specified object with this map for equality.
1276 >     * Returns {@code true} if the given object is a map with the same
1277 >     * mappings as this map.  This operation may return misleading
1278 >     * results if either map is concurrently modified during execution
1279 >     * of this method.
1280 >     *
1281 >     * @param o object to be compared for equality with this map
1282 >     * @return {@code true} if the specified object is equal to this map
1283 >     */
1284 >    public boolean equals(Object o) {
1285 >        if (o != this) {
1286 >            if (!(o instanceof Map))
1287 >                return false;
1288 >            Map<?,?> m = (Map<?,?>) o;
1289 >            Node<K,V>[] t;
1290 >            int f = (t = table) == null ? 0 : t.length;
1291 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1292 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1293 >                V val = p.val;
1294 >                Object v = m.get(p.key);
1295 >                if (v == null || (v != val && !v.equals(val)))
1296 >                    return false;
1297 >            }
1298 >            for (Map.Entry<?,?> e : m.entrySet()) {
1299 >                Object mk, mv, v;
1300 >                if ((mk = e.getKey()) == null ||
1301 >                    (mv = e.getValue()) == null ||
1302 >                    (v = get(mk)) == null ||
1303 >                    (mv != v && !mv.equals(v)))
1304 >                    return false;
1305              }
1138            break;
1306          }
1307 <        return null;
1307 >        return true;
1308      }
1309  
1310      /**
1311 <     * Implementation for the four public remove/replace methods:
1312 <     * Replaces node value with v, conditional upon match of cv if
1146 <     * non-null.  If resulting value is null, delete.
1311 >     * Stripped-down version of helper class used in previous version,
1312 >     * declared for the sake of serialization compatibility
1313       */
1314 <    @SuppressWarnings("unchecked") private final V internalReplace
1315 <        (Object k, V v, Object cv) {
1316 <        int h = spread(k.hashCode());
1317 <        V oldVal = null;
1318 <        for (Node<V>[] tab = table;;) {
1319 <            Node<V> f; int i, fh; Object fk;
1320 <            if (tab == null ||
1321 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1322 <                break;
1323 <            else if ((fh = f.hash) < 0) {
1324 <                if ((fk = f.key) instanceof TreeBin) {
1325 <                    TreeBin<V> t = (TreeBin<V>)fk;
1326 <                    boolean validated = false;
1327 <                    boolean deleted = false;
1328 <                    t.acquire(0);
1329 <                    try {
1330 <                        if (tabAt(tab, i) == f) {
1331 <                            validated = true;
1332 <                            TreeNode<V> p = t.getTreeNode(h, k);
1333 <                            if (p != null) {
1334 <                                V pv = p.val;
1335 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1336 <                                    oldVal = pv;
1337 <                                    if ((p.val = v) == null) {
1338 <                                        deleted = true;
1339 <                                        t.deleteTreeNode(p);
1340 <                                    }
1341 <                                }
1342 <                            }
1343 <                        }
1344 <                    } finally {
1345 <                        t.release(0);
1346 <                    }
1347 <                    if (validated) {
1348 <                        if (deleted)
1349 <                            addCount(-1L, -1);
1350 <                        break;
1351 <                    }
1352 <                }
1353 <                else
1354 <                    tab = (Node<V>[])fk;
1314 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1315 >        private static final long serialVersionUID = 2249069246763182397L;
1316 >        final float loadFactor;
1317 >        Segment(float lf) { this.loadFactor = lf; }
1318 >    }
1319 >
1320 >    /**
1321 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
1322 >     * stream (i.e., serializes it).
1323 >     * @param s the stream
1324 >     * @serialData
1325 >     * the key (Object) and value (Object)
1326 >     * for each key-value mapping, followed by a null pair.
1327 >     * The key-value mappings are emitted in no particular order.
1328 >     */
1329 >    private void writeObject(java.io.ObjectOutputStream s)
1330 >        throws java.io.IOException {
1331 >        // For serialization compatibility
1332 >        // Emulate segment calculation from previous version of this class
1333 >        int sshift = 0;
1334 >        int ssize = 1;
1335 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1336 >            ++sshift;
1337 >            ssize <<= 1;
1338 >        }
1339 >        int segmentShift = 32 - sshift;
1340 >        int segmentMask = ssize - 1;
1341 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1342 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1343 >        for (int i = 0; i < segments.length; ++i)
1344 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1345 >        s.putFields().put("segments", segments);
1346 >        s.putFields().put("segmentShift", segmentShift);
1347 >        s.putFields().put("segmentMask", segmentMask);
1348 >        s.writeFields();
1349 >
1350 >        Node<K,V>[] t;
1351 >        if ((t = table) != null) {
1352 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1353 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1354 >                s.writeObject(p.key);
1355 >                s.writeObject(p.val);
1356              }
1357 <            else if (fh != h && f.next == null) // precheck
1358 <                break;                          // rules out possible existence
1357 >        }
1358 >        s.writeObject(null);
1359 >        s.writeObject(null);
1360 >        segments = null; // throw away
1361 >    }
1362 >
1363 >    /**
1364 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1365 >     * @param s the stream
1366 >     */
1367 >    private void readObject(java.io.ObjectInputStream s)
1368 >        throws java.io.IOException, ClassNotFoundException {
1369 >        /*
1370 >         * To improve performance in typical cases, we create nodes
1371 >         * while reading, then place in table once size is known.
1372 >         * However, we must also validate uniqueness and deal with
1373 >         * overpopulated bins while doing so, which requires
1374 >         * specialized versions of putVal mechanics.
1375 >         */
1376 >        sizeCtl = -1; // force exclusion for table construction
1377 >        s.defaultReadObject();
1378 >        long size = 0L;
1379 >        Node<K,V> p = null;
1380 >        for (;;) {
1381 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1382 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1383 >            if (k != null && v != null) {
1384 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1385 >                ++size;
1386 >            }
1387 >            else
1388 >                break;
1389 >        }
1390 >        if (size == 0L)
1391 >            sizeCtl = 0;
1392 >        else {
1393 >            int n;
1394 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1395 >                n = MAXIMUM_CAPACITY;
1396              else {
1397 <                boolean validated = false;
1398 <                boolean deleted = false;
1399 <                synchronized (f) {
1400 <                    if (tabAt(tab, i) == f) {
1401 <                        validated = true;
1402 <                        for (Node<V> e = f, pred = null;;) {
1403 <                            Object ek; V ev;
1404 <                            if (e.hash == h &&
1405 <                                ((ev = e.val) != null) &&
1406 <                                ((ek = e.key) == k || k.equals(ek))) {
1407 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1408 <                                    oldVal = ev;
1409 <                                    if ((e.val = v) == null) {
1410 <                                        deleted = true;
1411 <                                        Node<V> en = e.next;
1412 <                                        if (pred != null)
1413 <                                            pred.next = en;
1414 <                                        else
1415 <                                            setTabAt(tab, i, en);
1416 <                                    }
1417 <                                }
1397 >                int sz = (int)size;
1398 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1399 >            }
1400 >            @SuppressWarnings({"rawtypes","unchecked"})
1401 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1402 >            int mask = n - 1;
1403 >            long added = 0L;
1404 >            while (p != null) {
1405 >                boolean insertAtFront;
1406 >                Node<K,V> next = p.next, first;
1407 >                int h = p.hash, j = h & mask;
1408 >                if ((first = tabAt(tab, j)) == null)
1409 >                    insertAtFront = true;
1410 >                else {
1411 >                    K k = p.key;
1412 >                    if (first.hash < 0) {
1413 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1414 >                        if (t.putTreeVal(h, k, p.val) == null)
1415 >                            ++added;
1416 >                        insertAtFront = false;
1417 >                    }
1418 >                    else {
1419 >                        int binCount = 0;
1420 >                        insertAtFront = true;
1421 >                        Node<K,V> q; K qk;
1422 >                        for (q = first; q != null; q = q.next) {
1423 >                            if (q.hash == h &&
1424 >                                ((qk = q.key) == k ||
1425 >                                 (qk != null && k.equals(qk)))) {
1426 >                                insertAtFront = false;
1427                                  break;
1428                              }
1429 <                            pred = e;
1430 <                            if ((e = e.next) == null)
1431 <                                break;
1429 >                            ++binCount;
1430 >                        }
1431 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1432 >                            insertAtFront = false;
1433 >                            ++added;
1434 >                            p.next = first;
1435 >                            TreeNode<K,V> hd = null, tl = null;
1436 >                            for (q = p; q != null; q = q.next) {
1437 >                                TreeNode<K,V> t = new TreeNode<K,V>
1438 >                                    (q.hash, q.key, q.val, null, null);
1439 >                                if ((t.prev = tl) == null)
1440 >                                    hd = t;
1441 >                                else
1442 >                                    tl.next = t;
1443 >                                tl = t;
1444 >                            }
1445 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1446                          }
1447                      }
1448                  }
1449 <                if (validated) {
1450 <                    if (deleted)
1451 <                        addCount(-1L, -1);
1452 <                    break;
1449 >                if (insertAtFront) {
1450 >                    ++added;
1451 >                    p.next = first;
1452 >                    setTabAt(tab, j, p);
1453                  }
1454 +                p = next;
1455              }
1456 +            table = tab;
1457 +            sizeCtl = n - (n >>> 2);
1458 +            baseCount = added;
1459          }
1229        return oldVal;
1460      }
1461  
1462 <    /*
1463 <     * Internal versions of insertion methods
1464 <     * All have the same basic structure as the first (internalPut):
1465 <     *  1. If table uninitialized, create
1466 <     *  2. If bin empty, try to CAS new node
1467 <     *  3. If bin stale, use new table
1468 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1469 <     *  5. Lock and validate; if valid, scan and add or update
1240 <     *
1241 <     * The putAll method differs mainly in attempting to pre-allocate
1242 <     * enough table space, and also more lazily performs count updates
1243 <     * and checks.
1244 <     *
1245 <     * Most of the function-accepting methods can't be factored nicely
1246 <     * because they require different functional forms, so instead
1247 <     * sprawl out similar mechanics.
1462 >    // ConcurrentMap methods
1463 >
1464 >    /**
1465 >     * {@inheritDoc}
1466 >     *
1467 >     * @return the previous value associated with the specified key,
1468 >     *         or {@code null} if there was no mapping for the key
1469 >     * @throws NullPointerException if the specified key or value is null
1470       */
1471 +    public V putIfAbsent(K key, V value) {
1472 +        return putVal(key, value, true);
1473 +    }
1474  
1475 <    /** Implementation for put and putIfAbsent */
1476 <    @SuppressWarnings("unchecked") private final V internalPut
1477 <        (K k, V v, boolean onlyIfAbsent) {
1478 <        if (k == null || v == null) throw new NullPointerException();
1479 <        int h = spread(k.hashCode());
1480 <        int len = 0;
1481 <        for (Node<V>[] tab = table;;) {
1482 <            int i, fh; Node<V> f; Object fk; V fv;
1483 <            if (tab == null)
1484 <                tab = initTable();
1485 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1486 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1487 <                    break;                   // no lock when adding to empty bin
1475 >    /**
1476 >     * {@inheritDoc}
1477 >     *
1478 >     * @throws NullPointerException if the specified key is null
1479 >     */
1480 >    public boolean remove(Object key, Object value) {
1481 >        if (key == null)
1482 >            throw new NullPointerException();
1483 >        return value != null && replaceNode(key, null, value) != null;
1484 >    }
1485 >
1486 >    /**
1487 >     * {@inheritDoc}
1488 >     *
1489 >     * @throws NullPointerException if any of the arguments are null
1490 >     */
1491 >    public boolean replace(K key, V oldValue, V newValue) {
1492 >        if (key == null || oldValue == null || newValue == null)
1493 >            throw new NullPointerException();
1494 >        return replaceNode(key, newValue, oldValue) != null;
1495 >    }
1496 >
1497 >    /**
1498 >     * {@inheritDoc}
1499 >     *
1500 >     * @return the previous value associated with the specified key,
1501 >     *         or {@code null} if there was no mapping for the key
1502 >     * @throws NullPointerException if the specified key or value is null
1503 >     */
1504 >    public V replace(K key, V value) {
1505 >        if (key == null || value == null)
1506 >            throw new NullPointerException();
1507 >        return replaceNode(key, value, null);
1508 >    }
1509 >
1510 >    // Overrides of JDK8+ Map extension method defaults
1511 >
1512 >    /**
1513 >     * Returns the value to which the specified key is mapped, or the
1514 >     * given default value if this map contains no mapping for the
1515 >     * key.
1516 >     *
1517 >     * @param key the key whose associated value is to be returned
1518 >     * @param defaultValue the value to return if this map contains
1519 >     * no mapping for the given key
1520 >     * @return the mapping for the key, if present; else the default value
1521 >     * @throws NullPointerException if the specified key is null
1522 >     */
1523 >    public V getOrDefault(Object key, V defaultValue) {
1524 >        V v;
1525 >        return (v = get(key)) == null ? defaultValue : v;
1526 >    }
1527 >
1528 >    public void forEach(BiConsumer<? super K, ? super V> action) {
1529 >        if (action == null) throw new NullPointerException();
1530 >        Node<K,V>[] t;
1531 >        if ((t = table) != null) {
1532 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1533 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1534 >                action.accept(p.key, p.val);
1535              }
1536 <            else if ((fh = f.hash) < 0) {
1537 <                if ((fk = f.key) instanceof TreeBin) {
1538 <                    TreeBin<V> t = (TreeBin<V>)fk;
1539 <                    V oldVal = null;
1540 <                    t.acquire(0);
1541 <                    try {
1542 <                        if (tabAt(tab, i) == f) {
1543 <                            len = 2;
1544 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1545 <                            if (p != null) {
1546 <                                oldVal = p.val;
1547 <                                if (!onlyIfAbsent)
1548 <                                    p.val = v;
1549 <                            }
1550 <                        }
1551 <                    } finally {
1280 <                        t.release(0);
1281 <                    }
1282 <                    if (len != 0) {
1283 <                        if (oldVal != null)
1284 <                            return oldVal;
1536 >        }
1537 >    }
1538 >
1539 >    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1540 >        if (function == null) throw new NullPointerException();
1541 >        Node<K,V>[] t;
1542 >        if ((t = table) != null) {
1543 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1544 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1545 >                V oldValue = p.val;
1546 >                for (K key = p.key;;) {
1547 >                    V newValue = function.apply(key, oldValue);
1548 >                    if (newValue == null)
1549 >                        throw new NullPointerException();
1550 >                    if (replaceNode(key, newValue, oldValue) != null ||
1551 >                        (oldValue = get(key)) == null)
1552                          break;
1286                    }
1287                }
1288                else
1289                    tab = (Node<V>[])fk;
1290            }
1291            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1292                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1293                return fv;
1294            else {
1295                V oldVal = null;
1296                synchronized (f) {
1297                    if (tabAt(tab, i) == f) {
1298                        len = 1;
1299                        for (Node<V> e = f;; ++len) {
1300                            Object ek; V ev;
1301                            if (e.hash == h &&
1302                                (ev = e.val) != null &&
1303                                ((ek = e.key) == k || k.equals(ek))) {
1304                                oldVal = ev;
1305                                if (!onlyIfAbsent)
1306                                    e.val = v;
1307                                break;
1308                            }
1309                            Node<V> last = e;
1310                            if ((e = e.next) == null) {
1311                                last.next = new Node<V>(h, k, v, null);
1312                                if (len >= TREE_THRESHOLD)
1313                                    replaceWithTreeBin(tab, i, k);
1314                                break;
1315                            }
1316                        }
1317                    }
1318                }
1319                if (len != 0) {
1320                    if (oldVal != null)
1321                        return oldVal;
1322                    break;
1553                  }
1554              }
1555          }
1326        addCount(1L, len);
1327        return null;
1556      }
1557  
1558 <    /** Implementation for computeIfAbsent */
1559 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1560 <        (K k, Function<? super K, ? extends V> mf) {
1561 <        if (k == null || mf == null)
1558 >    /**
1559 >     * If the specified key is not already associated with a value,
1560 >     * attempts to compute its value using the given mapping function
1561 >     * and enters it into this map unless {@code null}.  The entire
1562 >     * method invocation is performed atomically, so the function is
1563 >     * applied at most once per key.  Some attempted update operations
1564 >     * on this map by other threads may be blocked while computation
1565 >     * is in progress, so the computation should be short and simple,
1566 >     * and must not attempt to update any other mappings of this map.
1567 >     *
1568 >     * @param key key with which the specified value is to be associated
1569 >     * @param mappingFunction the function to compute a value
1570 >     * @return the current (existing or computed) value associated with
1571 >     *         the specified key, or null if the computed value is null
1572 >     * @throws NullPointerException if the specified key or mappingFunction
1573 >     *         is null
1574 >     * @throws IllegalStateException if the computation detectably
1575 >     *         attempts a recursive update to this map that would
1576 >     *         otherwise never complete
1577 >     * @throws RuntimeException or Error if the mappingFunction does so,
1578 >     *         in which case the mapping is left unestablished
1579 >     */
1580 >    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1581 >        if (key == null || mappingFunction == null)
1582              throw new NullPointerException();
1583 <        int h = spread(k.hashCode());
1583 >        int h = spread(key.hashCode());
1584          V val = null;
1585 <        int len = 0;
1586 <        for (Node<V>[] tab = table;;) {
1587 <            Node<V> f; int i; Object fk;
1588 <            if (tab == null)
1585 >        int binCount = 0;
1586 >        for (Node<K,V>[] tab = table;;) {
1587 >            Node<K,V> f; int n, i, fh;
1588 >            if (tab == null || (n = tab.length) == 0)
1589                  tab = initTable();
1590 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1591 <                Node<V> node = new Node<V>(h, k, null, null);
1592 <                synchronized (node) {
1593 <                    if (casTabAt(tab, i, null, node)) {
1594 <                        len = 1;
1590 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1591 >                Node<K,V> r = new ReservationNode<K,V>();
1592 >                synchronized (r) {
1593 >                    if (casTabAt(tab, i, null, r)) {
1594 >                        binCount = 1;
1595 >                        Node<K,V> node = null;
1596                          try {
1597 <                            if ((val = mf.apply(k)) != null)
1598 <                                node.val = val;
1597 >                            if ((val = mappingFunction.apply(key)) != null)
1598 >                                node = new Node<K,V>(h, key, val, null);
1599                          } finally {
1600 <                            if (val == null)
1352 <                                setTabAt(tab, i, null);
1600 >                            setTabAt(tab, i, node);
1601                          }
1602                      }
1603                  }
1604 <                if (len != 0)
1604 >                if (binCount != 0)
1605                      break;
1606              }
1607 <            else if (f.hash < 0) {
1608 <                if ((fk = f.key) instanceof TreeBin) {
1609 <                    TreeBin<V> t = (TreeBin<V>)fk;
1610 <                    boolean added = false;
1611 <                    t.acquire(0);
1612 <                    try {
1613 <                        if (tabAt(tab, i) == f) {
1614 <                            len = 1;
1615 <                            TreeNode<V> p = t.getTreeNode(h, k);
1616 <                            if (p != null)
1607 >            else if ((fh = f.hash) == MOVED)
1608 >                tab = helpTransfer(tab, f);
1609 >            else {
1610 >                boolean added = false;
1611 >                synchronized (f) {
1612 >                    if (tabAt(tab, i) == f) {
1613 >                        if (fh >= 0) {
1614 >                            binCount = 1;
1615 >                            for (Node<K,V> e = f;; ++binCount) {
1616 >                                K ek; V ev;
1617 >                                if (e.hash == h &&
1618 >                                    ((ek = e.key) == key ||
1619 >                                     (ek != null && key.equals(ek)))) {
1620 >                                    val = e.val;
1621 >                                    break;
1622 >                                }
1623 >                                Node<K,V> pred = e;
1624 >                                if ((e = e.next) == null) {
1625 >                                    if ((val = mappingFunction.apply(key)) != null) {
1626 >                                        added = true;
1627 >                                        pred.next = new Node<K,V>(h, key, val, null);
1628 >                                    }
1629 >                                    break;
1630 >                                }
1631 >                            }
1632 >                        }
1633 >                        else if (f instanceof TreeBin) {
1634 >                            binCount = 2;
1635 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1636 >                            TreeNode<K,V> r, p;
1637 >                            if ((r = t.root) != null &&
1638 >                                (p = r.findTreeNode(h, key, null)) != null)
1639                                  val = p.val;
1640 <                            else if ((val = mf.apply(k)) != null) {
1640 >                            else if ((val = mappingFunction.apply(key)) != null) {
1641                                  added = true;
1642 <                                len = 2;
1373 <                                t.putTreeNode(h, k, val);
1642 >                                t.putTreeVal(h, key, val);
1643                              }
1644                          }
1376                    } finally {
1377                        t.release(0);
1378                    }
1379                    if (len != 0) {
1380                        if (!added)
1381                            return val;
1382                        break;
1645                      }
1646                  }
1647 <                else
1648 <                    tab = (Node<V>[])fk;
1647 >                if (binCount != 0) {
1648 >                    if (binCount >= TREEIFY_THRESHOLD)
1649 >                        treeifyBin(tab, i);
1650 >                    if (!added)
1651 >                        return val;
1652 >                    break;
1653 >                }
1654              }
1655 +        }
1656 +        if (val != null)
1657 +            addCount(1L, binCount);
1658 +        return val;
1659 +    }
1660 +
1661 +    /**
1662 +     * If the value for the specified key is present, attempts to
1663 +     * compute a new mapping given the key and its current mapped
1664 +     * value.  The entire method invocation is performed atomically.
1665 +     * Some attempted update operations on this map by other threads
1666 +     * may be blocked while computation is in progress, so the
1667 +     * computation should be short and simple, and must not attempt to
1668 +     * update any other mappings of this map.
1669 +     *
1670 +     * @param key key with which a value may be associated
1671 +     * @param remappingFunction the function to compute a value
1672 +     * @return the new value associated with the specified key, or null if none
1673 +     * @throws NullPointerException if the specified key or remappingFunction
1674 +     *         is null
1675 +     * @throws IllegalStateException if the computation detectably
1676 +     *         attempts a recursive update to this map that would
1677 +     *         otherwise never complete
1678 +     * @throws RuntimeException or Error if the remappingFunction does so,
1679 +     *         in which case the mapping is unchanged
1680 +     */
1681 +    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1682 +        if (key == null || remappingFunction == null)
1683 +            throw new NullPointerException();
1684 +        int h = spread(key.hashCode());
1685 +        V val = null;
1686 +        int delta = 0;
1687 +        int binCount = 0;
1688 +        for (Node<K,V>[] tab = table;;) {
1689 +            Node<K,V> f; int n, i, fh;
1690 +            if (tab == null || (n = tab.length) == 0)
1691 +                tab = initTable();
1692 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1693 +                break;
1694 +            else if ((fh = f.hash) == MOVED)
1695 +                tab = helpTransfer(tab, f);
1696              else {
1389                for (Node<V> e = f; e != null; e = e.next) { // prescan
1390                    Object ek; V ev;
1391                    if (e.hash == h && (ev = e.val) != null &&
1392                        ((ek = e.key) == k || k.equals(ek)))
1393                        return ev;
1394                }
1395                boolean added = false;
1697                  synchronized (f) {
1698                      if (tabAt(tab, i) == f) {
1699 <                        len = 1;
1700 <                        for (Node<V> e = f;; ++len) {
1701 <                            Object ek; V ev;
1702 <                            if (e.hash == h &&
1703 <                                (ev = e.val) != null &&
1704 <                                ((ek = e.key) == k || k.equals(ek))) {
1705 <                                val = ev;
1706 <                                break;
1699 >                        if (fh >= 0) {
1700 >                            binCount = 1;
1701 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1702 >                                K ek;
1703 >                                if (e.hash == h &&
1704 >                                    ((ek = e.key) == key ||
1705 >                                     (ek != null && key.equals(ek)))) {
1706 >                                    val = remappingFunction.apply(key, e.val);
1707 >                                    if (val != null)
1708 >                                        e.val = val;
1709 >                                    else {
1710 >                                        delta = -1;
1711 >                                        Node<K,V> en = e.next;
1712 >                                        if (pred != null)
1713 >                                            pred.next = en;
1714 >                                        else
1715 >                                            setTabAt(tab, i, en);
1716 >                                    }
1717 >                                    break;
1718 >                                }
1719 >                                pred = e;
1720 >                                if ((e = e.next) == null)
1721 >                                    break;
1722                              }
1723 <                            Node<V> last = e;
1724 <                            if ((e = e.next) == null) {
1725 <                                if ((val = mf.apply(k)) != null) {
1726 <                                    added = true;
1727 <                                    last.next = new Node<V>(h, k, val, null);
1728 <                                    if (len >= TREE_THRESHOLD)
1729 <                                        replaceWithTreeBin(tab, i, k);
1723 >                        }
1724 >                        else if (f instanceof TreeBin) {
1725 >                            binCount = 2;
1726 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1727 >                            TreeNode<K,V> r, p;
1728 >                            if ((r = t.root) != null &&
1729 >                                (p = r.findTreeNode(h, key, null)) != null) {
1730 >                                val = remappingFunction.apply(key, p.val);
1731 >                                if (val != null)
1732 >                                    p.val = val;
1733 >                                else {
1734 >                                    delta = -1;
1735 >                                    if (t.removeTreeNode(p))
1736 >                                        setTabAt(tab, i, untreeify(t.first));
1737                                  }
1415                                break;
1738                              }
1739                          }
1740                      }
1741                  }
1742 <                if (len != 0) {
1421 <                    if (!added)
1422 <                        return val;
1742 >                if (binCount != 0)
1743                      break;
1424                }
1744              }
1745          }
1746 <        if (val != null)
1747 <            addCount(1L, len);
1746 >        if (delta != 0)
1747 >            addCount((long)delta, binCount);
1748          return val;
1749      }
1750  
1751 <    /** Implementation for compute */
1752 <    @SuppressWarnings("unchecked") private final V internalCompute
1753 <        (K k, boolean onlyIfPresent,
1754 <         BiFunction<? super K, ? super V, ? extends V> mf) {
1755 <        if (k == null || mf == null)
1751 >    /**
1752 >     * Attempts to compute a mapping for the specified key and its
1753 >     * current mapped value (or {@code null} if there is no current
1754 >     * mapping). The entire method invocation is performed atomically.
1755 >     * Some attempted update operations on this map by other threads
1756 >     * may be blocked while computation is in progress, so the
1757 >     * computation should be short and simple, and must not attempt to
1758 >     * update any other mappings of this Map.
1759 >     *
1760 >     * @param key key with which the specified value is to be associated
1761 >     * @param remappingFunction the function to compute a value
1762 >     * @return the new value associated with the specified key, or null if none
1763 >     * @throws NullPointerException if the specified key or remappingFunction
1764 >     *         is null
1765 >     * @throws IllegalStateException if the computation detectably
1766 >     *         attempts a recursive update to this map that would
1767 >     *         otherwise never complete
1768 >     * @throws RuntimeException or Error if the remappingFunction does so,
1769 >     *         in which case the mapping is unchanged
1770 >     */
1771 >    public V compute(K key,
1772 >                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1773 >        if (key == null || remappingFunction == null)
1774              throw new NullPointerException();
1775 <        int h = spread(k.hashCode());
1775 >        int h = spread(key.hashCode());
1776          V val = null;
1777          int delta = 0;
1778 <        int len = 0;
1779 <        for (Node<V>[] tab = table;;) {
1780 <            Node<V> f; int i, fh; Object fk;
1781 <            if (tab == null)
1778 >        int binCount = 0;
1779 >        for (Node<K,V>[] tab = table;;) {
1780 >            Node<K,V> f; int n, i, fh;
1781 >            if (tab == null || (n = tab.length) == 0)
1782                  tab = initTable();
1783 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1784 <                if (onlyIfPresent)
1785 <                    break;
1786 <                Node<V> node = new Node<V>(h, k, null, null);
1787 <                synchronized (node) {
1788 <                    if (casTabAt(tab, i, null, node)) {
1783 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1784 >                Node<K,V> r = new ReservationNode<K,V>();
1785 >                synchronized (r) {
1786 >                    if (casTabAt(tab, i, null, r)) {
1787 >                        binCount = 1;
1788 >                        Node<K,V> node = null;
1789                          try {
1790 <                            len = 1;
1454 <                            if ((val = mf.apply(k, null)) != null) {
1455 <                                node.val = val;
1790 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1791                                  delta = 1;
1792 +                                node = new Node<K,V>(h, key, val, null);
1793                              }
1794                          } finally {
1795 <                            if (delta == 0)
1460 <                                setTabAt(tab, i, null);
1795 >                            setTabAt(tab, i, node);
1796                          }
1797                      }
1798                  }
1799 <                if (len != 0)
1799 >                if (binCount != 0)
1800                      break;
1801              }
1802 <            else if ((fh = f.hash) < 0) {
1803 <                if ((fk = f.key) instanceof TreeBin) {
1804 <                    TreeBin<V> t = (TreeBin<V>)fk;
1805 <                    t.acquire(0);
1806 <                    try {
1807 <                        if (tabAt(tab, i) == f) {
1808 <                            len = 1;
1809 <                            TreeNode<V> p = t.getTreeNode(h, k);
1810 <                            if (p == null && onlyIfPresent)
1811 <                                break;
1802 >            else if ((fh = f.hash) == MOVED)
1803 >                tab = helpTransfer(tab, f);
1804 >            else {
1805 >                synchronized (f) {
1806 >                    if (tabAt(tab, i) == f) {
1807 >                        if (fh >= 0) {
1808 >                            binCount = 1;
1809 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1810 >                                K ek;
1811 >                                if (e.hash == h &&
1812 >                                    ((ek = e.key) == key ||
1813 >                                     (ek != null && key.equals(ek)))) {
1814 >                                    val = remappingFunction.apply(key, e.val);
1815 >                                    if (val != null)
1816 >                                        e.val = val;
1817 >                                    else {
1818 >                                        delta = -1;
1819 >                                        Node<K,V> en = e.next;
1820 >                                        if (pred != null)
1821 >                                            pred.next = en;
1822 >                                        else
1823 >                                            setTabAt(tab, i, en);
1824 >                                    }
1825 >                                    break;
1826 >                                }
1827 >                                pred = e;
1828 >                                if ((e = e.next) == null) {
1829 >                                    val = remappingFunction.apply(key, null);
1830 >                                    if (val != null) {
1831 >                                        delta = 1;
1832 >                                        pred.next =
1833 >                                            new Node<K,V>(h, key, val, null);
1834 >                                    }
1835 >                                    break;
1836 >                                }
1837 >                            }
1838 >                        }
1839 >                        else if (f instanceof TreeBin) {
1840 >                            binCount = 1;
1841 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1842 >                            TreeNode<K,V> r, p;
1843 >                            if ((r = t.root) != null)
1844 >                                p = r.findTreeNode(h, key, null);
1845 >                            else
1846 >                                p = null;
1847                              V pv = (p == null) ? null : p.val;
1848 <                            if ((val = mf.apply(k, pv)) != null) {
1848 >                            val = remappingFunction.apply(key, pv);
1849 >                            if (val != null) {
1850                                  if (p != null)
1851                                      p.val = val;
1852                                  else {
1482                                    len = 2;
1853                                      delta = 1;
1854 <                                    t.putTreeNode(h, k, val);
1854 >                                    t.putTreeVal(h, key, val);
1855                                  }
1856                              }
1857                              else if (p != null) {
1858                                  delta = -1;
1859 <                                t.deleteTreeNode(p);
1859 >                                if (t.removeTreeNode(p))
1860 >                                    setTabAt(tab, i, untreeify(t.first));
1861                              }
1862                          }
1492                    } finally {
1493                        t.release(0);
1863                      }
1495                    if (len != 0)
1496                        break;
1864                  }
1865 <                else
1866 <                    tab = (Node<V>[])fk;
1867 <            }
1501 <            else {
1502 <                synchronized (f) {
1503 <                    if (tabAt(tab, i) == f) {
1504 <                        len = 1;
1505 <                        for (Node<V> e = f, pred = null;; ++len) {
1506 <                            Object ek; V ev;
1507 <                            if (e.hash == h &&
1508 <                                (ev = e.val) != null &&
1509 <                                ((ek = e.key) == k || k.equals(ek))) {
1510 <                                val = mf.apply(k, ev);
1511 <                                if (val != null)
1512 <                                    e.val = val;
1513 <                                else {
1514 <                                    delta = -1;
1515 <                                    Node<V> en = e.next;
1516 <                                    if (pred != null)
1517 <                                        pred.next = en;
1518 <                                    else
1519 <                                        setTabAt(tab, i, en);
1520 <                                }
1521 <                                break;
1522 <                            }
1523 <                            pred = e;
1524 <                            if ((e = e.next) == null) {
1525 <                                if (!onlyIfPresent &&
1526 <                                    (val = mf.apply(k, null)) != null) {
1527 <                                    pred.next = new Node<V>(h, k, val, null);
1528 <                                    delta = 1;
1529 <                                    if (len >= TREE_THRESHOLD)
1530 <                                        replaceWithTreeBin(tab, i, k);
1531 <                                }
1532 <                                break;
1533 <                            }
1534 <                        }
1535 <                    }
1536 <                }
1537 <                if (len != 0)
1865 >                if (binCount != 0) {
1866 >                    if (binCount >= TREEIFY_THRESHOLD)
1867 >                        treeifyBin(tab, i);
1868                      break;
1869 +                }
1870              }
1871          }
1872          if (delta != 0)
1873 <            addCount((long)delta, len);
1873 >            addCount((long)delta, binCount);
1874          return val;
1875      }
1876  
1877 <    /** Implementation for merge */
1878 <    @SuppressWarnings("unchecked") private final V internalMerge
1879 <        (K k, V v, BiFunction<? super V, ? super V, ? extends V> mf) {
1880 <        if (k == null || v == null || mf == null)
1877 >    /**
1878 >     * If the specified key is not already associated with a
1879 >     * (non-null) value, associates it with the given value.
1880 >     * Otherwise, replaces the value with the results of the given
1881 >     * remapping function, or removes if {@code null}. The entire
1882 >     * method invocation is performed atomically.  Some attempted
1883 >     * update operations on this map by other threads may be blocked
1884 >     * while computation is in progress, so the computation should be
1885 >     * short and simple, and must not attempt to update any other
1886 >     * mappings of this Map.
1887 >     *
1888 >     * @param key key with which the specified value is to be associated
1889 >     * @param value the value to use if absent
1890 >     * @param remappingFunction the function to recompute a value if present
1891 >     * @return the new value associated with the specified key, or null if none
1892 >     * @throws NullPointerException if the specified key or the
1893 >     *         remappingFunction is null
1894 >     * @throws RuntimeException or Error if the remappingFunction does so,
1895 >     *         in which case the mapping is unchanged
1896 >     */
1897 >    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1898 >        if (key == null || value == null || remappingFunction == null)
1899              throw new NullPointerException();
1900 <        int h = spread(k.hashCode());
1900 >        int h = spread(key.hashCode());
1901          V val = null;
1902          int delta = 0;
1903 <        int len = 0;
1904 <        for (Node<V>[] tab = table;;) {
1905 <            int i; Node<V> f; Object fk; V fv;
1906 <            if (tab == null)
1903 >        int binCount = 0;
1904 >        for (Node<K,V>[] tab = table;;) {
1905 >            Node<K,V> f; int n, i, fh;
1906 >            if (tab == null || (n = tab.length) == 0)
1907                  tab = initTable();
1908 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1909 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1908 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1909 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1910                      delta = 1;
1911 <                    val = v;
1911 >                    val = value;
1912                      break;
1913                  }
1914              }
1915 <            else if (f.hash < 0) {
1916 <                if ((fk = f.key) instanceof TreeBin) {
1917 <                    TreeBin<V> t = (TreeBin<V>)fk;
1918 <                    t.acquire(0);
1919 <                    try {
1920 <                        if (tabAt(tab, i) == f) {
1921 <                            len = 1;
1922 <                            TreeNode<V> p = t.getTreeNode(h, k);
1923 <                            val = (p == null) ? v : mf.apply(p.val, v);
1915 >            else if ((fh = f.hash) == MOVED)
1916 >                tab = helpTransfer(tab, f);
1917 >            else {
1918 >                synchronized (f) {
1919 >                    if (tabAt(tab, i) == f) {
1920 >                        if (fh >= 0) {
1921 >                            binCount = 1;
1922 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1923 >                                K ek;
1924 >                                if (e.hash == h &&
1925 >                                    ((ek = e.key) == key ||
1926 >                                     (ek != null && key.equals(ek)))) {
1927 >                                    val = remappingFunction.apply(e.val, value);
1928 >                                    if (val != null)
1929 >                                        e.val = val;
1930 >                                    else {
1931 >                                        delta = -1;
1932 >                                        Node<K,V> en = e.next;
1933 >                                        if (pred != null)
1934 >                                            pred.next = en;
1935 >                                        else
1936 >                                            setTabAt(tab, i, en);
1937 >                                    }
1938 >                                    break;
1939 >                                }
1940 >                                pred = e;
1941 >                                if ((e = e.next) == null) {
1942 >                                    delta = 1;
1943 >                                    val = value;
1944 >                                    pred.next =
1945 >                                        new Node<K,V>(h, key, val, null);
1946 >                                    break;
1947 >                                }
1948 >                            }
1949 >                        }
1950 >                        else if (f instanceof TreeBin) {
1951 >                            binCount = 2;
1952 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1953 >                            TreeNode<K,V> r = t.root;
1954 >                            TreeNode<K,V> p = (r == null) ? null :
1955 >                                r.findTreeNode(h, key, null);
1956 >                            val = (p == null) ? value :
1957 >                                remappingFunction.apply(p.val, value);
1958                              if (val != null) {
1959                                  if (p != null)
1960                                      p.val = val;
1961                                  else {
1579                                    len = 2;
1962                                      delta = 1;
1963 <                                    t.putTreeNode(h, k, val);
1963 >                                    t.putTreeVal(h, key, val);
1964                                  }
1965                              }
1966                              else if (p != null) {
1967                                  delta = -1;
1968 <                                t.deleteTreeNode(p);
1969 <                            }
1588 <                        }
1589 <                    } finally {
1590 <                        t.release(0);
1591 <                    }
1592 <                    if (len != 0)
1593 <                        break;
1594 <                }
1595 <                else
1596 <                    tab = (Node<V>[])fk;
1597 <            }
1598 <            else {
1599 <                synchronized (f) {
1600 <                    if (tabAt(tab, i) == f) {
1601 <                        len = 1;
1602 <                        for (Node<V> e = f, pred = null;; ++len) {
1603 <                            Object ek; V ev;
1604 <                            if (e.hash == h &&
1605 <                                (ev = e.val) != null &&
1606 <                                ((ek = e.key) == k || k.equals(ek))) {
1607 <                                val = mf.apply(ev, v);
1608 <                                if (val != null)
1609 <                                    e.val = val;
1610 <                                else {
1611 <                                    delta = -1;
1612 <                                    Node<V> en = e.next;
1613 <                                    if (pred != null)
1614 <                                        pred.next = en;
1615 <                                    else
1616 <                                        setTabAt(tab, i, en);
1617 <                                }
1618 <                                break;
1619 <                            }
1620 <                            pred = e;
1621 <                            if ((e = e.next) == null) {
1622 <                                val = v;
1623 <                                pred.next = new Node<V>(h, k, val, null);
1624 <                                delta = 1;
1625 <                                if (len >= TREE_THRESHOLD)
1626 <                                    replaceWithTreeBin(tab, i, k);
1627 <                                break;
1968 >                                if (t.removeTreeNode(p))
1969 >                                    setTabAt(tab, i, untreeify(t.first));
1970                              }
1971                          }
1972                      }
1973                  }
1974 <                if (len != 0)
1974 >                if (binCount != 0) {
1975 >                    if (binCount >= TREEIFY_THRESHOLD)
1976 >                        treeifyBin(tab, i);
1977                      break;
1978 +                }
1979              }
1980          }
1981          if (delta != 0)
1982 <            addCount((long)delta, len);
1982 >            addCount((long)delta, binCount);
1983          return val;
1984      }
1985  
1986 <    /** Implementation for putAll */
1987 <    @SuppressWarnings("unchecked") private final void internalPutAll
1988 <        (Map<? extends K, ? extends V> m) {
1989 <        tryPresize(m.size());
1990 <        long delta = 0L;     // number of uncommitted additions
1991 <        boolean npe = false; // to throw exception on exit for nulls
1992 <        try {                // to clean up counts on other exceptions
1993 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
1994 <                Object k; V v;
1995 <                if (entry == null || (k = entry.getKey()) == null ||
1996 <                    (v = entry.getValue()) == null) {
1997 <                    npe = true;
1998 <                    break;
1999 <                }
2000 <                int h = spread(k.hashCode());
2001 <                for (Node<V>[] tab = table;;) {
2002 <                    int i; Node<V> f; int fh; Object fk;
2003 <                    if (tab == null)
2004 <                        tab = initTable();
2005 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2006 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2007 <                            ++delta;
2008 <                            break;
2009 <                        }
2010 <                    }
2011 <                    else if ((fh = f.hash) < 0) {
2012 <                        if ((fk = f.key) instanceof TreeBin) {
2013 <                            TreeBin<V> t = (TreeBin<V>)fk;
2014 <                            boolean validated = false;
2015 <                            t.acquire(0);
2016 <                            try {
2017 <                                if (tabAt(tab, i) == f) {
2018 <                                    validated = true;
2019 <                                    TreeNode<V> p = t.getTreeNode(h, k);
2020 <                                    if (p != null)
2021 <                                        p.val = v;
2022 <                                    else {
2023 <                                        t.putTreeNode(h, k, v);
2024 <                                        ++delta;
2025 <                                    }
2026 <                                }
2027 <                            } finally {
2028 <                                t.release(0);
2029 <                            }
2030 <                            if (validated)
2031 <                                break;
2032 <                        }
2033 <                        else
2034 <                            tab = (Node<V>[])fk;
2035 <                    }
2036 <                    else {
2037 <                        int len = 0;
2038 <                        synchronized (f) {
2039 <                            if (tabAt(tab, i) == f) {
2040 <                                len = 1;
2041 <                                for (Node<V> e = f;; ++len) {
2042 <                                    Object ek; V ev;
2043 <                                    if (e.hash == h &&
2044 <                                        (ev = e.val) != null &&
2045 <                                        ((ek = e.key) == k || k.equals(ek))) {
2046 <                                        e.val = v;
2047 <                                        break;
2048 <                                    }
2049 <                                    Node<V> last = e;
2050 <                                    if ((e = e.next) == null) {
2051 <                                        ++delta;
2052 <                                        last.next = new Node<V>(h, k, v, null);
2053 <                                        if (len >= TREE_THRESHOLD)
2054 <                                            replaceWithTreeBin(tab, i, k);
2055 <                                        break;
2056 <                                    }
2057 <                                }
2058 <                            }
2059 <                        }
2060 <                        if (len != 0) {
2061 <                            if (len > 1) {
2062 <                                addCount(delta, len);
2063 <                                delta = 0L;
2064 <                            }
2065 <                            break;
2066 <                        }
2067 <                    }
2068 <                }
2069 <            }
2070 <        } finally {
2071 <            if (delta != 0L)
2072 <                addCount(delta, 2);
2073 <        }
2074 <        if (npe)
1986 >    // Hashtable legacy methods
1987 >
1988 >    /**
1989 >     * Legacy method testing if some key maps into the specified value
1990 >     * in this table.  This method is identical in functionality to
1991 >     * {@link #containsValue(Object)}, and exists solely to ensure
1992 >     * full compatibility with class {@link java.util.Hashtable},
1993 >     * which supported this method prior to introduction of the
1994 >     * Java Collections framework.
1995 >     *
1996 >     * @param  value a value to search for
1997 >     * @return {@code true} if and only if some key maps to the
1998 >     *         {@code value} argument in this table as
1999 >     *         determined by the {@code equals} method;
2000 >     *         {@code false} otherwise
2001 >     * @throws NullPointerException if the specified value is null
2002 >     */
2003 >    @Deprecated public boolean contains(Object value) {
2004 >        return containsValue(value);
2005 >    }
2006 >
2007 >    /**
2008 >     * Returns an enumeration of the keys in this table.
2009 >     *
2010 >     * @return an enumeration of the keys in this table
2011 >     * @see #keySet()
2012 >     */
2013 >    public Enumeration<K> keys() {
2014 >        Node<K,V>[] t;
2015 >        int f = (t = table) == null ? 0 : t.length;
2016 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2017 >    }
2018 >
2019 >    /**
2020 >     * Returns an enumeration of the values in this table.
2021 >     *
2022 >     * @return an enumeration of the values in this table
2023 >     * @see #values()
2024 >     */
2025 >    public Enumeration<V> elements() {
2026 >        Node<K,V>[] t;
2027 >        int f = (t = table) == null ? 0 : t.length;
2028 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2029 >    }
2030 >
2031 >    // ConcurrentHashMap-only methods
2032 >
2033 >    /**
2034 >     * Returns the number of mappings. This method should be used
2035 >     * instead of {@link #size} because a ConcurrentHashMap may
2036 >     * contain more mappings than can be represented as an int. The
2037 >     * value returned is an estimate; the actual count may differ if
2038 >     * there are concurrent insertions or removals.
2039 >     *
2040 >     * @return the number of mappings
2041 >     * @since 1.8
2042 >     */
2043 >    public long mappingCount() {
2044 >        long n = sumCount();
2045 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2046 >    }
2047 >
2048 >    /**
2049 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2050 >     * from the given type to {@code Boolean.TRUE}.
2051 >     *
2052 >     * @return the new set
2053 >     * @since 1.8
2054 >     */
2055 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2056 >        return new KeySetView<K,Boolean>
2057 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2058 >    }
2059 >
2060 >    /**
2061 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2062 >     * from the given type to {@code Boolean.TRUE}.
2063 >     *
2064 >     * @param initialCapacity The implementation performs internal
2065 >     * sizing to accommodate this many elements.
2066 >     * @throws IllegalArgumentException if the initial capacity of
2067 >     * elements is negative
2068 >     * @return the new set
2069 >     * @since 1.8
2070 >     */
2071 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2072 >        return new KeySetView<K,Boolean>
2073 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2074 >    }
2075 >
2076 >    /**
2077 >     * Returns a {@link Set} view of the keys in this map, using the
2078 >     * given common mapped value for any additions (i.e., {@link
2079 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2080 >     * This is of course only appropriate if it is acceptable to use
2081 >     * the same value for all additions from this view.
2082 >     *
2083 >     * @param mappedValue the mapped value to use for any additions
2084 >     * @return the set view
2085 >     * @throws NullPointerException if the mappedValue is null
2086 >     */
2087 >    public KeySetView<K,V> keySet(V mappedValue) {
2088 >        if (mappedValue == null)
2089              throw new NullPointerException();
2090 +        return new KeySetView<K,V>(this, mappedValue);
2091      }
2092  
2093 +    /* ---------------- Special Nodes -------------- */
2094 +
2095      /**
2096 <     * Implementation for clear. Steps through each bin, removing all
1735 <     * nodes.
2096 >     * A node inserted at head of bins during transfer operations.
2097       */
2098 <    @SuppressWarnings("unchecked") private final void internalClear() {
2099 <        long delta = 0L; // negative number of deletions
2100 <        int i = 0;
2101 <        Node<V>[] tab = table;
2102 <        while (tab != null && i < tab.length) {
2103 <            Node<V> f = tabAt(tab, i);
2104 <            if (f == null)
2105 <                ++i;
2106 <            else if (f.hash < 0) {
2107 <                Object fk;
2108 <                if ((fk = f.key) instanceof TreeBin) {
2109 <                    TreeBin<V> t = (TreeBin<V>)fk;
2110 <                    t.acquire(0);
2111 <                    try {
2112 <                        if (tabAt(tab, i) == f) {
2113 <                            for (Node<V> p = t.first; p != null; p = p.next) {
2114 <                                if (p.val != null) { // (currently always true)
2115 <                                    p.val = null;
2116 <                                    --delta;
2117 <                                }
1757 <                            }
1758 <                            t.first = null;
1759 <                            t.root = null;
1760 <                            ++i;
1761 <                        }
1762 <                    } finally {
1763 <                        t.release(0);
1764 <                    }
1765 <                }
1766 <                else
1767 <                    tab = (Node<V>[])fk;
1768 <            }
1769 <            else {
1770 <                synchronized (f) {
1771 <                    if (tabAt(tab, i) == f) {
1772 <                        for (Node<V> e = f; e != null; e = e.next) {
1773 <                            if (e.val != null) {  // (currently always true)
1774 <                                e.val = null;
1775 <                                --delta;
1776 <                            }
1777 <                        }
1778 <                        setTabAt(tab, i, null);
1779 <                        ++i;
1780 <                    }
1781 <                }
2098 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2099 >        final Node<K,V>[] nextTable;
2100 >        ForwardingNode(Node<K,V>[] tab) {
2101 >            super(MOVED, null, null, null);
2102 >            this.nextTable = tab;
2103 >        }
2104 >
2105 >        Node<K,V> find(int h, Object k) {
2106 >            Node<K,V> e; int n;
2107 >            Node<K,V>[] tab = nextTable;
2108 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2109 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2110 >                do {
2111 >                    int eh; K ek;
2112 >                    if ((eh = e.hash) == h &&
2113 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2114 >                        return e;
2115 >                    if (eh < 0)
2116 >                        return e.find(h, k);
2117 >                } while ((e = e.next) != null);
2118              }
2119 +            return null;
2120          }
1784        if (delta != 0L)
1785            addCount(delta, -1);
2121      }
2122  
1788    /* ---------------- Table Initialization and Resizing -------------- */
1789
2123      /**
2124 <     * Returns a power of two table size for the given desired capacity.
1792 <     * See Hackers Delight, sec 3.2
2124 >     * A place-holder node used in computeIfAbsent and compute
2125       */
2126 <    private static final int tableSizeFor(int c) {
2127 <        int n = c - 1;
2128 <        n |= n >>> 1;
2129 <        n |= n >>> 2;
2130 <        n |= n >>> 4;
2131 <        n |= n >>> 8;
2132 <        n |= n >>> 16;
2133 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2126 >    static final class ReservationNode<K,V> extends Node<K,V> {
2127 >        ReservationNode() {
2128 >            super(RESERVED, null, null, null);
2129 >        }
2130 >
2131 >        Node<K,V> find(int h, Object k) {
2132 >            return null;
2133 >        }
2134      }
2135  
2136 +    /* ---------------- Table Initialization and Resizing -------------- */
2137 +
2138      /**
2139       * Initializes table, using the size recorded in sizeCtl.
2140       */
2141 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2142 <        Node<V>[] tab; int sc;
2143 <        while ((tab = table) == null) {
2141 >    private final Node<K,V>[] initTable() {
2142 >        Node<K,V>[] tab; int sc;
2143 >        while ((tab = table) == null || tab.length == 0) {
2144              if ((sc = sizeCtl) < 0)
2145                  Thread.yield(); // lost initialization race; just spin
2146              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2147                  try {
2148 <                    if ((tab = table) == null) {
2148 >                    if ((tab = table) == null || tab.length == 0) {
2149                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2150 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2151 <                        table = tab = (Node<V>[])tb;
2150 >                        @SuppressWarnings({"rawtypes","unchecked"})
2151 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2152 >                        table = tab = nt;
2153                          sc = n - (n >>> 2);
2154                      }
2155                  } finally {
# Line 1837 | Line 2172 | public class ConcurrentHashMap<K,V>
2172       * @param check if <0, don't check resize, if <= 1 only check if uncontended
2173       */
2174      private final void addCount(long x, int check) {
2175 <        Cell[] as; long b, s;
2175 >        CounterCell[] as; long b, s;
2176          if ((as = counterCells) != null ||
2177              !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2178 <            Cell a; long v; int m;
2178 >            CounterCell a; long v; int m;
2179              boolean uncontended = true;
2180              if (as == null || (m = as.length - 1) < 0 ||
2181                  (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
# Line 1854 | Line 2189 | public class ConcurrentHashMap<K,V>
2189              s = sumCount();
2190          }
2191          if (check >= 0) {
2192 <            Node<V>[] tab, nt; int sc;
2192 >            Node<K,V>[] tab, nt; int sc;
2193              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2194                     tab.length < MAXIMUM_CAPACITY) {
2195                  if (sc < 0) {
# Line 1872 | Line 2207 | public class ConcurrentHashMap<K,V>
2207      }
2208  
2209      /**
2210 +     * Helps transfer if a resize is in progress.
2211 +     */
2212 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2213 +        Node<K,V>[] nextTab; int sc;
2214 +        if ((f instanceof ForwardingNode) &&
2215 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2216 +            if (nextTab == nextTable && tab == table &&
2217 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2218 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2219 +                transfer(tab, nextTab);
2220 +            return nextTab;
2221 +        }
2222 +        return table;
2223 +    }
2224 +
2225 +    /**
2226       * Tries to presize table to accommodate the given number of elements.
2227       *
2228       * @param size number of elements (doesn't need to be perfectly accurate)
2229       */
2230 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2230 >    private final void tryPresize(int size) {
2231          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2232              tableSizeFor(size + (size >>> 1) + 1);
2233          int sc;
2234          while ((sc = sizeCtl) >= 0) {
2235 <            Node<V>[] tab = table; int n;
2235 >            Node<K,V>[] tab = table; int n;
2236              if (tab == null || (n = tab.length) == 0) {
2237                  n = (sc > c) ? sc : c;
2238                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2239                      try {
2240                          if (table == tab) {
2241 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2242 <                            table = (Node<V>[])tb;
2241 >                            @SuppressWarnings({"rawtypes","unchecked"})
2242 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2243 >                            table = nt;
2244                              sc = n - (n >>> 2);
2245                          }
2246                      } finally {
# Line 1908 | Line 2260 | public class ConcurrentHashMap<K,V>
2260       * Moves and/or copies the nodes in each bin to new table. See
2261       * above for explanation.
2262       */
2263 <    @SuppressWarnings("unchecked") private final void transfer
1912 <        (Node<V>[] tab, Node<V>[] nextTab) {
2263 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2264          int n = tab.length, stride;
2265          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2266              stride = MIN_TRANSFER_STRIDE; // subdivide range
2267          if (nextTab == null) {            // initiating
2268              try {
2269 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2270 <                nextTab = (Node<V>[])tb;
2269 >                @SuppressWarnings({"rawtypes","unchecked"})
2270 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2271 >                nextTab = nt;
2272              } catch (Throwable ex) {      // try to cope with OOME
2273                  sizeCtl = Integer.MAX_VALUE;
2274                  return;
# Line 1924 | Line 2276 | public class ConcurrentHashMap<K,V>
2276              nextTable = nextTab;
2277              transferOrigin = n;
2278              transferIndex = n;
2279 <            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2279 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2280              for (int k = n; k > 0;) {    // progressively reveal ready slots
2281                  int nextk = (k > stride) ? k - stride : 0;
2282                  for (int m = nextk; m < k; ++m)
# Line 1935 | Line 2287 | public class ConcurrentHashMap<K,V>
2287              }
2288          }
2289          int nextn = nextTab.length;
2290 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2290 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2291          boolean advance = true;
2292          for (int i = 0, bound = 0;;) {
2293 <            int nextIndex, nextBound; Node<V> f; Object fk;
2293 >            int nextIndex, nextBound, fh; Node<K,V> f;
2294              while (advance) {
2295                  if (--i >= bound)
2296                      advance = false;
# Line 1974 | Line 2326 | public class ConcurrentHashMap<K,V>
2326                      advance = true;
2327                  }
2328              }
2329 <            else if (f.hash >= 0) {
2329 >            else if ((fh = f.hash) == MOVED)
2330 >                advance = true; // already processed
2331 >            else {
2332                  synchronized (f) {
2333                      if (tabAt(tab, i) == f) {
2334 <                        int runBit = f.hash & n;
2335 <                        Node<V> lastRun = f, lo = null, hi = null;
2336 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2337 <                            int b = p.hash & n;
2338 <                            if (b != runBit) {
2339 <                                runBit = b;
2340 <                                lastRun = p;
2334 >                        Node<K,V> ln, hn;
2335 >                        if (fh >= 0) {
2336 >                            int runBit = fh & n;
2337 >                            Node<K,V> lastRun = f;
2338 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2339 >                                int b = p.hash & n;
2340 >                                if (b != runBit) {
2341 >                                    runBit = b;
2342 >                                    lastRun = p;
2343 >                                }
2344                              }
2345 <                        }
2346 <                        if (runBit == 0)
2347 <                            lo = lastRun;
1991 <                        else
1992 <                            hi = lastRun;
1993 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
1994 <                            int ph = p.hash;
1995 <                            Object pk = p.key; V pv = p.val;
1996 <                            if ((ph & n) == 0)
1997 <                                lo = new Node<V>(ph, pk, pv, lo);
1998 <                            else
1999 <                                hi = new Node<V>(ph, pk, pv, hi);
2000 <                        }
2001 <                        setTabAt(nextTab, i, lo);
2002 <                        setTabAt(nextTab, i + n, hi);
2003 <                        setTabAt(tab, i, fwd);
2004 <                        advance = true;
2005 <                    }
2006 <                }
2007 <            }
2008 <            else if ((fk = f.key) instanceof TreeBin) {
2009 <                TreeBin<V> t = (TreeBin<V>)fk;
2010 <                t.acquire(0);
2011 <                try {
2012 <                    if (tabAt(tab, i) == f) {
2013 <                        TreeBin<V> lt = new TreeBin<V>();
2014 <                        TreeBin<V> ht = new TreeBin<V>();
2015 <                        int lc = 0, hc = 0;
2016 <                        for (Node<V> e = t.first; e != null; e = e.next) {
2017 <                            int h = e.hash;
2018 <                            Object k = e.key; V v = e.val;
2019 <                            if ((h & n) == 0) {
2020 <                                ++lc;
2021 <                                lt.putTreeNode(h, k, v);
2345 >                            if (runBit == 0) {
2346 >                                ln = lastRun;
2347 >                                hn = null;
2348                              }
2349                              else {
2350 <                                ++hc;
2351 <                                ht.putTreeNode(h, k, v);
2350 >                                hn = lastRun;
2351 >                                ln = null;
2352 >                            }
2353 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2354 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2355 >                                if ((ph & n) == 0)
2356 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2357 >                                else
2358 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2359                              }
2360                          }
2361 <                        Node<V> ln, hn; // throw away trees if too small
2362 <                        if (lc < TREE_THRESHOLD) {
2363 <                            ln = null;
2364 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2365 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2361 >                        else if (f instanceof TreeBin) {
2362 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2363 >                            TreeNode<K,V> lo = null, loTail = null;
2364 >                            TreeNode<K,V> hi = null, hiTail = null;
2365 >                            int lc = 0, hc = 0;
2366 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2367 >                                int h = e.hash;
2368 >                                TreeNode<K,V> p = new TreeNode<K,V>
2369 >                                    (h, e.key, e.val, null, null);
2370 >                                if ((h & n) == 0) {
2371 >                                    if ((p.prev = loTail) == null)
2372 >                                        lo = p;
2373 >                                    else
2374 >                                        loTail.next = p;
2375 >                                    loTail = p;
2376 >                                    ++lc;
2377 >                                }
2378 >                                else {
2379 >                                    if ((p.prev = hiTail) == null)
2380 >                                        hi = p;
2381 >                                    else
2382 >                                        hiTail.next = p;
2383 >                                    hiTail = p;
2384 >                                    ++hc;
2385 >                                }
2386 >                            }
2387 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2388 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2389 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2390 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2391                          }
2392                          else
2393 <                            ln = new Node<V>(MOVED, lt, null, null);
2393 >                            ln = hn = null;
2394                          setTabAt(nextTab, i, ln);
2037                        if (hc < TREE_THRESHOLD) {
2038                            hn = null;
2039                            for (Node<V> p = ht.first; p != null; p = p.next)
2040                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2041                        }
2042                        else
2043                            hn = new Node<V>(MOVED, ht, null, null);
2395                          setTabAt(nextTab, i + n, hn);
2396                          setTabAt(tab, i, fwd);
2397                          advance = true;
2398                      }
2048                } finally {
2049                    t.release(0);
2399                  }
2400              }
2052            else
2053                advance = true; // already processed
2401          }
2402      }
2403  
2404      /* ---------------- Counter support -------------- */
2405  
2406 +    /**
2407 +     * A padded cell for distributing counts.  Adapted from LongAdder
2408 +     * and Striped64.  See their internal docs for explanation.
2409 +     */
2410 +    @sun.misc.Contended static final class CounterCell {
2411 +        volatile long value;
2412 +        CounterCell(long x) { value = x; }
2413 +    }
2414 +
2415      final long sumCount() {
2416 <        Cell[] as = counterCells; Cell a;
2416 >        CounterCell[] as = counterCells; CounterCell a;
2417          long sum = baseCount;
2418          if (as != null) {
2419              for (int i = 0; i < as.length; ++i) {
# Line 2078 | Line 2434 | public class ConcurrentHashMap<K,V>
2434          }
2435          boolean collide = false;                // True if last slot nonempty
2436          for (;;) {
2437 <            Cell[] as; Cell a; int n; long v;
2437 >            CounterCell[] as; CounterCell a; int n; long v;
2438              if ((as = counterCells) != null && (n = as.length) > 0) {
2439                  if ((a = as[(n - 1) & h]) == null) {
2440                      if (cellsBusy == 0) {            // Try to attach new Cell
2441 <                        Cell r = new Cell(x); // Optimistic create
2441 >                        CounterCell r = new CounterCell(x); // Optimistic create
2442                          if (cellsBusy == 0 &&
2443                              U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2444                              boolean created = false;
2445                              try {               // Recheck under lock
2446 <                                Cell[] rs; int m, j;
2446 >                                CounterCell[] rs; int m, j;
2447                                  if ((rs = counterCells) != null &&
2448                                      (m = rs.length) > 0 &&
2449                                      rs[j = (m - 1) & h] == null) {
# Line 2116 | Line 2472 | public class ConcurrentHashMap<K,V>
2472                           U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2473                      try {
2474                          if (counterCells == as) {// Expand table unless stale
2475 <                            Cell[] rs = new Cell[n << 1];
2475 >                            CounterCell[] rs = new CounterCell[n << 1];
2476                              for (int i = 0; i < n; ++i)
2477                                  rs[i] = as[i];
2478                              counterCells = rs;
# Line 2134 | Line 2490 | public class ConcurrentHashMap<K,V>
2490                  boolean init = false;
2491                  try {                           // Initialize table
2492                      if (counterCells == as) {
2493 <                        Cell[] rs = new Cell[2];
2494 <                        rs[h & 1] = new Cell(x);
2493 >                        CounterCell[] rs = new CounterCell[2];
2494 >                        rs[h & 1] = new CounterCell(x);
2495                          counterCells = rs;
2496                          init = true;
2497                      }
# Line 2150 | Line 2506 | public class ConcurrentHashMap<K,V>
2506          }
2507      }
2508  
2509 <    /* ----------------Table Traversal -------------- */
2509 >    /* ---------------- Conversion from/to TreeBins -------------- */
2510  
2511      /**
2512 <     * Encapsulates traversal for methods such as containsValue; also
2513 <     * serves as a base class for other iterators and bulk tasks.
2158 <     *
2159 <     * At each step, the iterator snapshots the key ("nextKey") and
2160 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2161 <     * snapshot, has a non-null user value). Because val fields can
2162 <     * change (including to null, indicating deletion), field nextVal
2163 <     * might not be accurate at point of use, but still maintains the
2164 <     * weak consistency property of holding a value that was once
2165 <     * valid. To support iterator.remove, the nextKey field is not
2166 <     * updated (nulled out) when the iterator cannot advance.
2167 <     *
2168 <     * Exported iterators must track whether the iterator has advanced
2169 <     * (in hasNext vs next) (by setting/checking/nulling field
2170 <     * nextVal), and then extract key, value, or key-value pairs as
2171 <     * return values of next().
2172 <     *
2173 <     * Method advance visits once each still-valid node that was
2174 <     * reachable upon iterator construction. It might miss some that
2175 <     * were added to a bin after the bin was visited, which is OK wrt
2176 <     * consistency guarantees. Maintaining this property in the face
2177 <     * of possible ongoing resizes requires a fair amount of
2178 <     * bookkeeping state that is difficult to optimize away amidst
2179 <     * volatile accesses.  Even so, traversal maintains reasonable
2180 <     * throughput.
2181 <     *
2182 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2183 <     * However, if the table has been resized, then all future steps
2184 <     * must traverse both the bin at the current index as well as at
2185 <     * (index + baseSize); and so on for further resizings. To
2186 <     * paranoically cope with potential sharing by users of iterators
2187 <     * across threads, iteration terminates if a bounds checks fails
2188 <     * for a table read.
2189 <     *
2190 <     * Methods advanceKey and advanceValue are specializations of the
2191 <     * common cases of advance, relaying to the full version
2192 <     * otherwise. The forEachKey and forEachValue methods further
2193 <     * specialize, bypassing all incremental field updates in most cases.
2194 <     *
2195 <     * This class supports both Spliterator-based traversal and
2196 <     * CountedCompleter-based bulk tasks. The same "batch" field is
2197 <     * used, but in slightly different ways, in the two cases.  For
2198 <     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2199 <     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2200 <     * size that halves down to zero for leaf tasks, that is only
2201 <     * computed upon execution of the task. (Tasks can be submitted to
2202 <     * any pool, of any size, so we don't know scale factors until
2203 <     * running.)
2204 <     *
2205 <     * This class extends CountedCompleter to streamline parallel
2206 <     * iteration in bulk operations. This adds only a few fields of
2207 <     * space overhead, which is small enough in cases where it is not
2208 <     * needed to not worry about it.  Because CountedCompleter is
2209 <     * Serializable, but iterators need not be, we need to add warning
2210 <     * suppressions.
2512 >     * Replaces all linked nodes in bin at given index unless table is
2513 >     * too small, in which case resizes instead.
2514       */
2515 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2516 <        extends CountedCompleter<R> {
2517 <        final ConcurrentHashMap<K,V> map;
2518 <        Node<V> next;        // the next entry to use
2519 <        K nextKey;           // cached key field of next
2520 <        V nextVal;           // cached val field of next
2521 <        Node<V>[] tab;       // current table; updated if resized
2522 <        int index;           // index of bin to use next
2523 <        int baseIndex;       // current index of initial table
2524 <        int baseLimit;       // index bound for initial table
2525 <        final int baseSize;  // initial table size
2526 <        int batch;           // split control
2515 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2516 >        Node<K,V> b; int n, sc;
2517 >        if (tab != null) {
2518 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2519 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2520 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2521 >                    transfer(tab, null);
2522 >            }
2523 >            else if ((b = tabAt(tab, index)) != null) {
2524 >                synchronized (b) {
2525 >                    if (tabAt(tab, index) == b) {
2526 >                        TreeNode<K,V> hd = null, tl = null;
2527 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2528 >                            TreeNode<K,V> p =
2529 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2530 >                                                  null, null);
2531 >                            if ((p.prev = tl) == null)
2532 >                                hd = p;
2533 >                            else
2534 >                                tl.next = p;
2535 >                            tl = p;
2536 >                        }
2537 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2538 >                    }
2539 >                }
2540 >            }
2541 >        }
2542 >    }
2543  
2544 <        /** Creates iterator for all entries in the table. */
2545 <        Traverser(ConcurrentHashMap<K,V> map) {
2546 <            this.map = map;
2547 <            Node<V>[] t = this.tab = map.table;
2548 <            baseLimit = baseSize = (t == null) ? 0 : t.length;
2544 >    /**
2545 >     * Returns a list on non-TreeNodes replacing those in given list
2546 >     */
2547 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2548 >        Node<K,V> hd = null, tl = null;
2549 >        for (Node<K,V> q = b; q != null; q = q.next) {
2550 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2551 >            if (tl == null)
2552 >                hd = p;
2553 >            else
2554 >                tl.next = p;
2555 >            tl = p;
2556          }
2557 +        return hd;
2558 +    }
2559  
2560 <        /** Task constructor */
2561 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2562 <            super(it);
2563 <            this.map = map;
2564 <            this.batch = batch; // -1 if unknown
2565 <            if (it == null) {
2566 <                Node<V>[] t = this.tab = map.table;
2567 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2568 <            }
2569 <            else { // split parent
2570 <                this.tab = it.tab;
2571 <                this.baseSize = it.baseSize;
2572 <                int hi = this.baseLimit = it.baseLimit;
2573 <                it.baseLimit = this.index = this.baseIndex =
2574 <                    (hi + it.baseIndex) >>> 1;
2575 <            }
2560 >    /* ---------------- TreeNodes -------------- */
2561 >
2562 >    /**
2563 >     * Nodes for use in TreeBins
2564 >     */
2565 >    static final class TreeNode<K,V> extends Node<K,V> {
2566 >        TreeNode<K,V> parent;  // red-black tree links
2567 >        TreeNode<K,V> left;
2568 >        TreeNode<K,V> right;
2569 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2570 >        boolean red;
2571 >
2572 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2573 >                 TreeNode<K,V> parent) {
2574 >            super(hash, key, val, next);
2575 >            this.parent = parent;
2576          }
2577  
2578 <        /** Spliterator constructor */
2579 <        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2252 <            super(it);
2253 <            this.map = map;
2254 <            if (it == null) {
2255 <                Node<V>[] t = this.tab = map.table;
2256 <                baseLimit = baseSize = (t == null) ? 0 : t.length;
2257 <                long n = map.sumCount();
2258 <                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2259 <                         (int)n);
2260 <            }
2261 <            else {
2262 <                this.tab = it.tab;
2263 <                this.baseSize = it.baseSize;
2264 <                int hi = this.baseLimit = it.baseLimit;
2265 <                it.baseLimit = this.index = this.baseIndex =
2266 <                    (hi + it.baseIndex) >>> 1;
2267 <                this.batch = it.batch >>>= 1;
2268 <            }
2578 >        Node<K,V> find(int h, Object k) {
2579 >            return findTreeNode(h, k, null);
2580          }
2581  
2582          /**
2583 <         * Advances if possible, returning next valid value, or null if none.
2583 >         * Returns the TreeNode (or null if not found) for the given key
2584 >         * starting at given root.
2585           */
2586 <        @SuppressWarnings("unchecked") final V advance() {
2587 <            for (Node<V> e = next;;) {
2588 <                if (e != null)                  // advance past used/skipped node
2589 <                    e = next = e.next;
2590 <                while (e == null) {             // get to next non-null bin
2591 <                    Node<V>[] t; int i, n;      // must use locals in checks
2592 <                    if (baseIndex >= baseLimit || (t = tab) == null ||
2593 <                        (n = t.length) <= (i = index) || i < 0)
2594 <                        return nextVal = null;
2595 <                    if ((e = next = tabAt(t, index)) != null && e.hash < 0) {
2596 <                        Object ek;
2597 <                        if ((ek = e.key) instanceof TreeBin)
2598 <                            e = ((TreeBin<V>)ek).first;
2599 <                        else {
2600 <                            tab = (Node<V>[])ek;
2601 <                            continue;           // restarts due to null val
2586 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2587 >            if (k != null) {
2588 >                TreeNode<K,V> p = this;
2589 >                do  {
2590 >                    int ph, dir; K pk; TreeNode<K,V> q;
2591 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2592 >                    if ((ph = p.hash) > h)
2593 >                        p = pl;
2594 >                    else if (ph < h)
2595 >                        p = pr;
2596 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2597 >                        return p;
2598 >                    else if (pl == null && pr == null)
2599 >                        break;
2600 >                    else if ((kc != null ||
2601 >                              (kc = comparableClassFor(k)) != null) &&
2602 >                             (dir = compareComparables(kc, k, pk)) != 0)
2603 >                        p = (dir < 0) ? pl : pr;
2604 >                    else if (pl == null)
2605 >                        p = pr;
2606 >                    else if (pr == null ||
2607 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2608 >                        p = pl;
2609 >                    else
2610 >                        return q;
2611 >                } while (p != null);
2612 >            }
2613 >            return null;
2614 >        }
2615 >    }
2616 >
2617 >    /* ---------------- TreeBins -------------- */
2618 >
2619 >    /**
2620 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2621 >     * keys or values, but instead point to list of TreeNodes and
2622 >     * their root. They also maintain a parasitic read-write lock
2623 >     * forcing writers (who hold bin lock) to wait for readers (who do
2624 >     * not) to complete before tree restructuring operations.
2625 >     */
2626 >    static final class TreeBin<K,V> extends Node<K,V> {
2627 >        TreeNode<K,V> root;
2628 >        volatile TreeNode<K,V> first;
2629 >        volatile Thread waiter;
2630 >        volatile int lockState;
2631 >        // values for lockState
2632 >        static final int WRITER = 1; // set while holding write lock
2633 >        static final int WAITER = 2; // set when waiting for write lock
2634 >        static final int READER = 4; // increment value for setting read lock
2635 >
2636 >        /**
2637 >         * Creates bin with initial set of nodes headed by b.
2638 >         */
2639 >        TreeBin(TreeNode<K,V> b) {
2640 >            super(TREEBIN, null, null, null);
2641 >            this.first = b;
2642 >            TreeNode<K,V> r = null;
2643 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2644 >                next = (TreeNode<K,V>)x.next;
2645 >                x.left = x.right = null;
2646 >                if (r == null) {
2647 >                    x.parent = null;
2648 >                    x.red = false;
2649 >                    r = x;
2650 >                }
2651 >                else {
2652 >                    Object key = x.key;
2653 >                    int hash = x.hash;
2654 >                    Class<?> kc = null;
2655 >                    for (TreeNode<K,V> p = r;;) {
2656 >                        int dir, ph;
2657 >                        if ((ph = p.hash) > hash)
2658 >                            dir = -1;
2659 >                        else if (ph < hash)
2660 >                            dir = 1;
2661 >                        else if ((kc != null ||
2662 >                                  (kc = comparableClassFor(key)) != null))
2663 >                            dir = compareComparables(kc, key, p.key);
2664 >                        else
2665 >                            dir = 0;
2666 >                        TreeNode<K,V> xp = p;
2667 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2668 >                            x.parent = xp;
2669 >                            if (dir <= 0)
2670 >                                xp.left = x;
2671 >                            else
2672 >                                xp.right = x;
2673 >                            r = balanceInsertion(r, x);
2674 >                            break;
2675                          }
2676                      }
2292                    if ((index += baseSize) >= n)
2293                        index = ++baseIndex;    // visit upper slots if present
2677                  }
2295                nextKey = (K)e.key;
2296                if ((nextVal = e.val) != null) // skip deleted or special nodes
2297                    return nextVal;
2678              }
2679 +            this.root = r;
2680          }
2681  
2682          /**
2683 <         * Common case version for value traversal
2683 >         * Acquires write lock for tree restructuring
2684           */
2685 <        @SuppressWarnings("unchecked") final V advanceValue() {
2686 <            outer: for (Node<V> e = next;;) {
2687 <                if (e == null || (e = e.next) == null) {
2688 <                    Node<V>[] t; int i, len, n; Object ek;
2689 <                    if ((t = tab) == null ||
2690 <                        baseSize != (len = t.length) ||
2691 <                        len < (n = baseLimit) ||
2692 <                        baseIndex != (i = index))
2693 <                        break;
2694 <                    do {
2695 <                        if (i < 0 || i >= n) {
2696 <                            index = baseIndex = n;
2697 <                            next = null;
2698 <                            return nextVal = null;
2699 <                        }
2700 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2701 <                            if ((ek = e.key) instanceof TreeBin)
2702 <                                e = ((TreeBin<V>)ek).first;
2703 <                            else {
2704 <                                index = baseIndex = i;
2705 <                                next = null;
2706 <                                tab = (Node<V>[])ek;
2707 <                                break outer;
2708 <                            }
2328 <                        }
2329 <                        ++i;
2330 <                    } while (e == null);
2331 <                    index = baseIndex = i;
2685 >        private final void lockRoot() {
2686 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2687 >                contendedLock(); // offload to separate method
2688 >        }
2689 >
2690 >        /**
2691 >         * Releases write lock for tree restructuring
2692 >         */
2693 >        private final void unlockRoot() {
2694 >            lockState = 0;
2695 >        }
2696 >
2697 >        /**
2698 >         * Possibly blocks awaiting root lock
2699 >         */
2700 >        private final void contendedLock() {
2701 >            boolean waiting = false;
2702 >            for (int s;;) {
2703 >                if (((s = lockState) & WRITER) == 0) {
2704 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2705 >                        if (waiting)
2706 >                            waiter = null;
2707 >                        return;
2708 >                    }
2709                  }
2710 <                V v;
2711 <                K k = (K)e.key;
2712 <                if ((v = e.val) != null) {
2713 <                    nextVal = v;
2714 <                    nextKey = k;
2338 <                    next = e;
2339 <                    return v;
2710 >                else if ((s | WAITER) == 0) {
2711 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2712 >                        waiting = true;
2713 >                        waiter = Thread.currentThread();
2714 >                    }
2715                  }
2716 +                else if (waiting)
2717 +                    LockSupport.park(this);
2718              }
2342            return advance();
2719          }
2720  
2721          /**
2722 <         * Common case version for key traversal
2722 >         * Returns matching node or null if none. Tries to search
2723 >         * using tree compareisons from root, but continues linear
2724 >         * search when lock not available.
2725           */
2726 <        @SuppressWarnings("unchecked") final K advanceKey() {
2727 <            outer: for (Node<V> e = next;;) {
2728 <                if (e == null || (e = e.next) == null) {
2729 <                    Node<V>[] t; int i, len, n; Object ek;
2730 <                    if ((t = tab) == null ||
2731 <                        baseSize != (len = t.length) ||
2732 <                        len < (n = baseLimit) ||
2733 <                        baseIndex != (i = index))
2734 <                        break;
2735 <                    do {
2736 <                        if (i < 0 || i >= n) {
2737 <                            index = baseIndex = n;
2738 <                            next = null;
2739 <                            nextVal = null;
2740 <                            return null;
2741 <                        }
2742 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2743 <                            if ((ek = e.key) instanceof TreeBin)
2744 <                                e = ((TreeBin<V>)ek).first;
2745 <                            else {
2368 <                                index = baseIndex = i;
2369 <                                next = null;
2370 <                                tab = (Node<V>[])ek;
2371 <                                break outer;
2372 <                            }
2726 >        final Node<K,V> find(int h, Object k) {
2727 >            if (k != null) {
2728 >                for (Node<K,V> e = first; e != null; e = e.next) {
2729 >                    int s; K ek;
2730 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2731 >                        if (e.hash == h &&
2732 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2733 >                            return e;
2734 >                    }
2735 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2736 >                                                 s + READER)) {
2737 >                        TreeNode<K,V> r, p;
2738 >                        try {
2739 >                            p = ((r = root) == null ? null :
2740 >                                 r.findTreeNode(h, k, null));
2741 >                        } finally {
2742 >                            Thread w;
2743 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2744 >                                (READER|WAITER) && (w = waiter) != null)
2745 >                                LockSupport.unpark(w);
2746                          }
2747 <                        ++i;
2748 <                    } while (e == null);
2376 <                    index = baseIndex = i;
2377 <                }
2378 <                V v;
2379 <                K k = (K)e.key;
2380 <                if ((v = e.val) != null) {
2381 <                    nextVal = v;
2382 <                    nextKey = k;
2383 <                    next = e;
2384 <                    return k;
2747 >                        return p;
2748 >                    }
2749                  }
2750              }
2751 <            return (advance() == null) ? null : nextKey;
2751 >            return null;
2752          }
2753  
2754 <        @SuppressWarnings("unchecked") final void forEachValue(Consumer<? super V> action) {
2755 <            if (action == null) throw new NullPointerException();
2756 <            Node<V>[] t; int i, len, n;
2757 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2758 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2759 <                index = baseIndex = n;
2760 <                nextVal = null;
2761 <                Node<V> e = next;
2762 <                next = null;
2763 <                if (e != null)
2764 <                    e = e.next;
2765 <                outer: for (;; e = e.next) {
2766 <                    V v; Object ek;
2767 <                    for (; e == null; ++i) {
2768 <                        if (i < 0 || i >= n)
2769 <                            return;
2770 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2771 <                            if ((ek = e.key) instanceof TreeBin)
2772 <                                e = ((TreeBin<V>)ek).first;
2773 <                            else {
2774 <                                index = baseIndex = i;
2775 <                                tab = (Node<V>[])ek;
2776 <                                break outer;
2777 <                            }
2754 >        /**
2755 >         * Finds or adds a node.
2756 >         * @return null if added
2757 >         */
2758 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2759 >            Class<?> kc = null;
2760 >            for (TreeNode<K,V> p = root;;) {
2761 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2762 >                if (p == null) {
2763 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2764 >                    break;
2765 >                }
2766 >                else if ((ph = p.hash) > h)
2767 >                    dir = -1;
2768 >                else if (ph < h)
2769 >                    dir = 1;
2770 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2771 >                    return p;
2772 >                else if ((kc == null &&
2773 >                          (kc = comparableClassFor(k)) == null) ||
2774 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2775 >                    if (p.left == null)
2776 >                        dir = 1;
2777 >                    else if ((pr = p.right) == null ||
2778 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2779 >                        dir = -1;
2780 >                    else
2781 >                        return q;
2782 >                }
2783 >                TreeNode<K,V> xp = p;
2784 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2785 >                    TreeNode<K,V> x, f = first;
2786 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2787 >                    if (f != null)
2788 >                        f.prev = x;
2789 >                    if (dir < 0)
2790 >                        xp.left = x;
2791 >                    else
2792 >                        xp.right = x;
2793 >                    if (!xp.red)
2794 >                        x.red = true;
2795 >                    else {
2796 >                        lockRoot();
2797 >                        try {
2798 >                            root = balanceInsertion(root, x);
2799 >                        } finally {
2800 >                            unlockRoot();
2801                          }
2802                      }
2803 <                    if ((v = e.val) != null)
2417 <                        action.accept(v);
2803 >                    break;
2804                  }
2805              }
2806 <            V v;
2807 <            while ((v = advance()) != null)
2422 <                action.accept(v);
2806 >            assert checkInvariants(root);
2807 >            return null;
2808          }
2809  
2810 <        @SuppressWarnings("unchecked") final void forEachKey(Consumer<? super K> action) {
2811 <            if (action == null) throw new NullPointerException();
2812 <            Node<V>[] t; int i, len, n;
2813 <            if ((t = tab) != null && baseSize == (len = t.length) &&
2814 <                len >= (n = baseLimit) && baseIndex == (i = index)) {
2815 <                index = baseIndex = n;
2816 <                nextVal = null;
2817 <                Node<V> e = next;
2818 <                next = null;
2819 <                if (e != null)
2820 <                    e = e.next;
2821 <                outer: for (;; e = e.next) {
2822 <                    for (; e == null; ++i) {
2823 <                        if (i < 0 || i >= n)
2824 <                            return;
2825 <                        if ((e = tabAt(t, i)) != null && e.hash < 0) {
2826 <                            Object ek;
2827 <                            if ((ek = e.key) instanceof TreeBin)
2828 <                                e = ((TreeBin<V>)ek).first;
2829 <                            else {
2830 <                                index = baseIndex = i;
2831 <                                tab = (Node<V>[])ek;
2832 <                                break outer;
2833 <                            }
2810 >        /**
2811 >         * Removes the given node, that must be present before this
2812 >         * call.  This is messier than typical red-black deletion code
2813 >         * because we cannot swap the contents of an interior node
2814 >         * with a leaf successor that is pinned by "next" pointers
2815 >         * that are accessible independently of lock. So instead we
2816 >         * swap the tree linkages.
2817 >         *
2818 >         * @return true if now too small so should be untreeified.
2819 >         */
2820 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2821 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2822 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2823 >            TreeNode<K,V> r, rl;
2824 >            if (pred == null)
2825 >                first = next;
2826 >            else
2827 >                pred.next = next;
2828 >            if (next != null)
2829 >                next.prev = pred;
2830 >            if (first == null) {
2831 >                root = null;
2832 >                return true;
2833 >            }
2834 >            if ((r = root) == null || r.right == null || // too small
2835 >                (rl = r.left) == null || rl.left == null)
2836 >                return true;
2837 >            lockRoot();
2838 >            try {
2839 >                TreeNode<K,V> replacement;
2840 >                TreeNode<K,V> pl = p.left;
2841 >                TreeNode<K,V> pr = p.right;
2842 >                if (pl != null && pr != null) {
2843 >                    TreeNode<K,V> s = pr, sl;
2844 >                    while ((sl = s.left) != null) // find successor
2845 >                        s = sl;
2846 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2847 >                    TreeNode<K,V> sr = s.right;
2848 >                    TreeNode<K,V> pp = p.parent;
2849 >                    if (s == pr) { // p was s's direct parent
2850 >                        p.parent = s;
2851 >                        s.right = p;
2852 >                    }
2853 >                    else {
2854 >                        TreeNode<K,V> sp = s.parent;
2855 >                        if ((p.parent = sp) != null) {
2856 >                            if (s == sp.left)
2857 >                                sp.left = p;
2858 >                            else
2859 >                                sp.right = p;
2860                          }
2861 +                        if ((s.right = pr) != null)
2862 +                            pr.parent = s;
2863                      }
2864 <                    Object k = e.key;
2865 <                    if (e.val != null)
2866 <                        action.accept((K)k);
2864 >                    p.left = null;
2865 >                    if ((p.right = sr) != null)
2866 >                        sr.parent = p;
2867 >                    if ((s.left = pl) != null)
2868 >                        pl.parent = s;
2869 >                    if ((s.parent = pp) == null)
2870 >                        r = s;
2871 >                    else if (p == pp.left)
2872 >                        pp.left = s;
2873 >                    else
2874 >                        pp.right = s;
2875 >                    if (sr != null)
2876 >                        replacement = sr;
2877 >                    else
2878 >                        replacement = p;
2879                  }
2880 +                else if (pl != null)
2881 +                    replacement = pl;
2882 +                else if (pr != null)
2883 +                    replacement = pr;
2884 +                else
2885 +                    replacement = p;
2886 +                if (replacement != p) {
2887 +                    TreeNode<K,V> pp = replacement.parent = p.parent;
2888 +                    if (pp == null)
2889 +                        r = replacement;
2890 +                    else if (p == pp.left)
2891 +                        pp.left = replacement;
2892 +                    else
2893 +                        pp.right = replacement;
2894 +                    p.left = p.right = p.parent = null;
2895 +                }
2896 +
2897 +                root = (p.red) ? r : balanceDeletion(r, replacement);
2898 +
2899 +                if (p == replacement) {  // detach pointers
2900 +                    TreeNode<K,V> pp;
2901 +                    if ((pp = p.parent) != null) {
2902 +                        if (p == pp.left)
2903 +                            pp.left = null;
2904 +                        else if (p == pp.right)
2905 +                            pp.right = null;
2906 +                        p.parent = null;
2907 +                    }
2908 +                }
2909 +            } finally {
2910 +                unlockRoot();
2911              }
2912 <            while (advance() != null)
2913 <                action.accept(nextKey);
2912 >            assert checkInvariants(root);
2913 >            return false;
2914          }
2915  
2916 <        public final void remove() {
2917 <            K k = nextKey;
2462 <            if (k == null && (advanceValue() == null || (k = nextKey) == null))
2463 <                throw new IllegalStateException();
2464 <            map.internalReplace(k, null, null);
2465 <        }
2916 >        /* ------------------------------------------------------------ */
2917 >        // Red-black tree methods, all adapted from CLR
2918  
2919 <        public final boolean hasNext() {
2920 <            return nextVal != null || advanceValue() != null;
2919 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2920 >                                              TreeNode<K,V> p) {
2921 >            TreeNode<K,V> r, pp, rl;
2922 >            if (p != null && (r = p.right) != null) {
2923 >                if ((rl = p.right = r.left) != null)
2924 >                    rl.parent = p;
2925 >                if ((pp = r.parent = p.parent) == null)
2926 >                    (root = r).red = false;
2927 >                else if (pp.left == p)
2928 >                    pp.left = r;
2929 >                else
2930 >                    pp.right = r;
2931 >                r.left = p;
2932 >                p.parent = r;
2933 >            }
2934 >            return root;
2935          }
2936  
2937 <        public final boolean hasMoreElements() { return hasNext(); }
2937 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2938 >                                               TreeNode<K,V> p) {
2939 >            TreeNode<K,V> l, pp, lr;
2940 >            if (p != null && (l = p.left) != null) {
2941 >                if ((lr = p.left = l.right) != null)
2942 >                    lr.parent = p;
2943 >                if ((pp = l.parent = p.parent) == null)
2944 >                    (root = l).red = false;
2945 >                else if (pp.right == p)
2946 >                    pp.right = l;
2947 >                else
2948 >                    pp.left = l;
2949 >                l.right = p;
2950 >                p.parent = l;
2951 >            }
2952 >            return root;
2953 >        }
2954  
2955 <        public void compute() { } // default no-op CountedCompleter body
2955 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2956 >                                                    TreeNode<K,V> x) {
2957 >            x.red = true;
2958 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2959 >                if ((xp = x.parent) == null) {
2960 >                    x.red = false;
2961 >                    return x;
2962 >                }
2963 >                else if (!xp.red || (xpp = xp.parent) == null)
2964 >                    return root;
2965 >                if (xp == (xppl = xpp.left)) {
2966 >                    if ((xppr = xpp.right) != null && xppr.red) {
2967 >                        xppr.red = false;
2968 >                        xp.red = false;
2969 >                        xpp.red = true;
2970 >                        x = xpp;
2971 >                    }
2972 >                    else {
2973 >                        if (x == xp.right) {
2974 >                            root = rotateLeft(root, x = xp);
2975 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2976 >                        }
2977 >                        if (xp != null) {
2978 >                            xp.red = false;
2979 >                            if (xpp != null) {
2980 >                                xpp.red = true;
2981 >                                root = rotateRight(root, xpp);
2982 >                            }
2983 >                        }
2984 >                    }
2985 >                }
2986 >                else {
2987 >                    if (xppl != null && xppl.red) {
2988 >                        xppl.red = false;
2989 >                        xp.red = false;
2990 >                        xpp.red = true;
2991 >                        x = xpp;
2992 >                    }
2993 >                    else {
2994 >                        if (x == xp.left) {
2995 >                            root = rotateRight(root, x = xp);
2996 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2997 >                        }
2998 >                        if (xp != null) {
2999 >                            xp.red = false;
3000 >                            if (xpp != null) {
3001 >                                xpp.red = true;
3002 >                                root = rotateLeft(root, xpp);
3003 >                            }
3004 >                        }
3005 >                    }
3006 >                }
3007 >            }
3008 >        }
3009  
3010 <        public long estimateSize() { return batch; }
3010 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3011 >                                                   TreeNode<K,V> x) {
3012 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3013 >                if (x == null || x == root)
3014 >                    return root;
3015 >                else if ((xp = x.parent) == null) {
3016 >                    x.red = false;
3017 >                    return x;
3018 >                }
3019 >                else if (x.red) {
3020 >                    x.red = false;
3021 >                    return root;
3022 >                }
3023 >                else if ((xpl = xp.left) == x) {
3024 >                    if ((xpr = xp.right) != null && xpr.red) {
3025 >                        xpr.red = false;
3026 >                        xp.red = true;
3027 >                        root = rotateLeft(root, xp);
3028 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3029 >                    }
3030 >                    if (xpr == null)
3031 >                        x = xp;
3032 >                    else {
3033 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3034 >                        if ((sr == null || !sr.red) &&
3035 >                            (sl == null || !sl.red)) {
3036 >                            xpr.red = true;
3037 >                            x = xp;
3038 >                        }
3039 >                        else {
3040 >                            if (sr == null || !sr.red) {
3041 >                                if (sl != null)
3042 >                                    sl.red = false;
3043 >                                xpr.red = true;
3044 >                                root = rotateRight(root, xpr);
3045 >                                xpr = (xp = x.parent) == null ?
3046 >                                    null : xp.right;
3047 >                            }
3048 >                            if (xpr != null) {
3049 >                                xpr.red = (xp == null) ? false : xp.red;
3050 >                                if ((sr = xpr.right) != null)
3051 >                                    sr.red = false;
3052 >                            }
3053 >                            if (xp != null) {
3054 >                                xp.red = false;
3055 >                                root = rotateLeft(root, xp);
3056 >                            }
3057 >                            x = root;
3058 >                        }
3059 >                    }
3060 >                }
3061 >                else { // symmetric
3062 >                    if (xpl != null && xpl.red) {
3063 >                        xpl.red = false;
3064 >                        xp.red = true;
3065 >                        root = rotateRight(root, xp);
3066 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3067 >                    }
3068 >                    if (xpl == null)
3069 >                        x = xp;
3070 >                    else {
3071 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3072 >                        if ((sl == null || !sl.red) &&
3073 >                            (sr == null || !sr.red)) {
3074 >                            xpl.red = true;
3075 >                            x = xp;
3076 >                        }
3077 >                        else {
3078 >                            if (sl == null || !sl.red) {
3079 >                                if (sr != null)
3080 >                                    sr.red = false;
3081 >                                xpl.red = true;
3082 >                                root = rotateLeft(root, xpl);
3083 >                                xpl = (xp = x.parent) == null ?
3084 >                                    null : xp.left;
3085 >                            }
3086 >                            if (xpl != null) {
3087 >                                xpl.red = (xp == null) ? false : xp.red;
3088 >                                if ((sl = xpl.left) != null)
3089 >                                    sl.red = false;
3090 >                            }
3091 >                            if (xp != null) {
3092 >                                xp.red = false;
3093 >                                root = rotateRight(root, xp);
3094 >                            }
3095 >                            x = root;
3096 >                        }
3097 >                    }
3098 >                }
3099 >            }
3100 >        }
3101  
3102          /**
3103 <         * Returns a batch value > 0 if this task should (and must) be
2479 <         * split, if so, adding to pending count, and in any case
2480 <         * updating batch value. The initial batch value is approx
2481 <         * exp2 of the number of times (minus one) to split task by
2482 <         * two before executing leaf action. This value is faster to
2483 <         * compute and more convenient to use as a guide to splitting
2484 <         * than is the depth, since it is used while dividing by two
2485 <         * anyway.
3103 >         * Recursive invariant check
3104           */
3105 <        final int preSplit() {
3106 <            int b;  ForkJoinPool pool;
3107 <            if ((b = batch) < 0) { // force initialization
3108 <                int sp = (((pool = getPool()) == null) ?
3109 <                          ForkJoinPool.getCommonPoolParallelism() :
3110 <                          pool.getParallelism()) << 3; // slack of 8
3111 <                long n = map.sumCount();
3112 <                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
3113 <            }
3114 <            b = (b <= 1 || baseIndex >= baseLimit) ? 0 : (b >>> 1);
3115 <            if ((batch = b) > 0)
3116 <                addToPendingCount(1);
3117 <            return b;
3105 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3106 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3107 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3108 >            if (tb != null && tb.next != t)
3109 >                return false;
3110 >            if (tn != null && tn.prev != t)
3111 >                return false;
3112 >            if (tp != null && t != tp.left && t != tp.right)
3113 >                return false;
3114 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3115 >                return false;
3116 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3117 >                return false;
3118 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3119 >                return false;
3120 >            if (tl != null && !checkInvariants(tl))
3121 >                return false;
3122 >            if (tr != null && !checkInvariants(tr))
3123 >                return false;
3124 >            return true;
3125          }
2501    }
2502
2503    /* ---------------- Public operations -------------- */
2504
2505    /**
2506     * Creates a new, empty map with the default initial table size (16).
2507     */
2508    public ConcurrentHashMap() {
2509    }
2510
2511    /**
2512     * Creates a new, empty map with an initial table size
2513     * accommodating the specified number of elements without the need
2514     * to dynamically resize.
2515     *
2516     * @param initialCapacity The implementation performs internal
2517     * sizing to accommodate this many elements.
2518     * @throws IllegalArgumentException if the initial capacity of
2519     * elements is negative
2520     */
2521    public ConcurrentHashMap(int initialCapacity) {
2522        if (initialCapacity < 0)
2523            throw new IllegalArgumentException();
2524        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2525                   MAXIMUM_CAPACITY :
2526                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2527        this.sizeCtl = cap;
2528    }
2529
2530    /**
2531     * Creates a new map with the same mappings as the given map.
2532     *
2533     * @param m the map
2534     */
2535    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2536        this.sizeCtl = DEFAULT_CAPACITY;
2537        internalPutAll(m);
2538    }
3126  
3127 <    /**
3128 <     * Creates a new, empty map with an initial table size based on
3129 <     * the given number of elements ({@code initialCapacity}) and
3130 <     * initial table density ({@code loadFactor}).
3131 <     *
3132 <     * @param initialCapacity the initial capacity. The implementation
3133 <     * performs internal sizing to accommodate this many elements,
3134 <     * given the specified load factor.
3135 <     * @param loadFactor the load factor (table density) for
3136 <     * establishing the initial table size
3137 <     * @throws IllegalArgumentException if the initial capacity of
2551 <     * elements is negative or the load factor is nonpositive
2552 <     *
2553 <     * @since 1.6
2554 <     */
2555 <    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2556 <        this(initialCapacity, loadFactor, 1);
2557 <    }
2558 <
2559 <    /**
2560 <     * Creates a new, empty map with an initial table size based on
2561 <     * the given number of elements ({@code initialCapacity}), table
2562 <     * density ({@code loadFactor}), and number of concurrently
2563 <     * updating threads ({@code concurrencyLevel}).
2564 <     *
2565 <     * @param initialCapacity the initial capacity. The implementation
2566 <     * performs internal sizing to accommodate this many elements,
2567 <     * given the specified load factor.
2568 <     * @param loadFactor the load factor (table density) for
2569 <     * establishing the initial table size
2570 <     * @param concurrencyLevel the estimated number of concurrently
2571 <     * updating threads. The implementation may use this value as
2572 <     * a sizing hint.
2573 <     * @throws IllegalArgumentException if the initial capacity is
2574 <     * negative or the load factor or concurrencyLevel are
2575 <     * nonpositive
2576 <     */
2577 <    public ConcurrentHashMap(int initialCapacity,
2578 <                               float loadFactor, int concurrencyLevel) {
2579 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2580 <            throw new IllegalArgumentException();
2581 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2582 <            initialCapacity = concurrencyLevel;   // as estimated threads
2583 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2584 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2585 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2586 <        this.sizeCtl = cap;
2587 <    }
2588 <
2589 <    /**
2590 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2591 <     * from the given type to {@code Boolean.TRUE}.
2592 <     *
2593 <     * @return the new set
2594 <     */
2595 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2596 <        return new KeySetView<K,Boolean>
2597 <            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2598 <    }
2599 <
2600 <    /**
2601 <     * Creates a new {@link Set} backed by a ConcurrentHashMap
2602 <     * from the given type to {@code Boolean.TRUE}.
2603 <     *
2604 <     * @param initialCapacity The implementation performs internal
2605 <     * sizing to accommodate this many elements.
2606 <     * @throws IllegalArgumentException if the initial capacity of
2607 <     * elements is negative
2608 <     * @return the new set
2609 <     */
2610 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2611 <        return new KeySetView<K,Boolean>
2612 <            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2613 <    }
2614 <
2615 <    /**
2616 <     * {@inheritDoc}
2617 <     */
2618 <    public boolean isEmpty() {
2619 <        return sumCount() <= 0L; // ignore transient negative values
2620 <    }
2621 <
2622 <    /**
2623 <     * {@inheritDoc}
2624 <     */
2625 <    public int size() {
2626 <        long n = sumCount();
2627 <        return ((n < 0L) ? 0 :
2628 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2629 <                (int)n);
2630 <    }
2631 <
2632 <    /**
2633 <     * Returns the number of mappings. This method should be used
2634 <     * instead of {@link #size} because a ConcurrentHashMap may
2635 <     * contain more mappings than can be represented as an int. The
2636 <     * value returned is an estimate; the actual count may differ if
2637 <     * there are concurrent insertions or removals.
2638 <     *
2639 <     * @return the number of mappings
2640 <     */
2641 <    public long mappingCount() {
2642 <        long n = sumCount();
2643 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2644 <    }
2645 <
2646 <    /**
2647 <     * Returns the value to which the specified key is mapped,
2648 <     * or {@code null} if this map contains no mapping for the key.
2649 <     *
2650 <     * <p>More formally, if this map contains a mapping from a key
2651 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2652 <     * then this method returns {@code v}; otherwise it returns
2653 <     * {@code null}.  (There can be at most one such mapping.)
2654 <     *
2655 <     * @throws NullPointerException if the specified key is null
2656 <     */
2657 <    public V get(Object key) {
2658 <        return internalGet(key);
2659 <    }
2660 <
2661 <    /**
2662 <     * Returns the value to which the specified key is mapped,
2663 <     * or the given defaultValue if this map contains no mapping for the key.
2664 <     *
2665 <     * @param key the key
2666 <     * @param defaultValue the value to return if this map contains
2667 <     * no mapping for the given key
2668 <     * @return the mapping for the key, if present; else the defaultValue
2669 <     * @throws NullPointerException if the specified key is null
2670 <     */
2671 <    public V getOrDefault(Object key, V defaultValue) {
2672 <        V v;
2673 <        return (v = internalGet(key)) == null ? defaultValue : v;
2674 <    }
2675 <
2676 <    /**
2677 <     * Tests if the specified object is a key in this table.
2678 <     *
2679 <     * @param  key possible key
2680 <     * @return {@code true} if and only if the specified object
2681 <     *         is a key in this table, as determined by the
2682 <     *         {@code equals} method; {@code false} otherwise
2683 <     * @throws NullPointerException if the specified key is null
2684 <     */
2685 <    public boolean containsKey(Object key) {
2686 <        return internalGet(key) != null;
2687 <    }
2688 <
2689 <    /**
2690 <     * Returns {@code true} if this map maps one or more keys to the
2691 <     * specified value. Note: This method may require a full traversal
2692 <     * of the map, and is much slower than method {@code containsKey}.
2693 <     *
2694 <     * @param value value whose presence in this map is to be tested
2695 <     * @return {@code true} if this map maps one or more keys to the
2696 <     *         specified value
2697 <     * @throws NullPointerException if the specified value is null
2698 <     */
2699 <    public boolean containsValue(Object value) {
2700 <        if (value == null)
2701 <            throw new NullPointerException();
2702 <        V v;
2703 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2704 <        while ((v = it.advanceValue()) != null) {
2705 <            if (v == value || value.equals(v))
2706 <                return true;
3127 >        private static final sun.misc.Unsafe U;
3128 >        private static final long LOCKSTATE;
3129 >        static {
3130 >            try {
3131 >                U = sun.misc.Unsafe.getUnsafe();
3132 >                Class<?> k = TreeBin.class;
3133 >                LOCKSTATE = U.objectFieldOffset
3134 >                    (k.getDeclaredField("lockState"));
3135 >            } catch (Exception e) {
3136 >                throw new Error(e);
3137 >            }
3138          }
2708        return false;
2709    }
2710
2711    /**
2712     * Legacy method testing if some key maps into the specified value
2713     * in this table.  This method is identical in functionality to
2714     * {@link #containsValue(Object)}, and exists solely to ensure
2715     * full compatibility with class {@link java.util.Hashtable},
2716     * which supported this method prior to introduction of the
2717     * Java Collections framework.
2718     *
2719     * @param  value a value to search for
2720     * @return {@code true} if and only if some key maps to the
2721     *         {@code value} argument in this table as
2722     *         determined by the {@code equals} method;
2723     *         {@code false} otherwise
2724     * @throws NullPointerException if the specified value is null
2725     */
2726    @Deprecated public boolean contains(Object value) {
2727        return containsValue(value);
2728    }
2729
2730    /**
2731     * Maps the specified key to the specified value in this table.
2732     * Neither the key nor the value can be null.
2733     *
2734     * <p>The value can be retrieved by calling the {@code get} method
2735     * with a key that is equal to the original key.
2736     *
2737     * @param key key with which the specified value is to be associated
2738     * @param value value to be associated with the specified key
2739     * @return the previous value associated with {@code key}, or
2740     *         {@code null} if there was no mapping for {@code key}
2741     * @throws NullPointerException if the specified key or value is null
2742     */
2743    public V put(K key, V value) {
2744        return internalPut(key, value, false);
2745    }
2746
2747    /**
2748     * {@inheritDoc}
2749     *
2750     * @return the previous value associated with the specified key,
2751     *         or {@code null} if there was no mapping for the key
2752     * @throws NullPointerException if the specified key or value is null
2753     */
2754    public V putIfAbsent(K key, V value) {
2755        return internalPut(key, value, true);
2756    }
2757
2758    /**
2759     * Copies all of the mappings from the specified map to this one.
2760     * These mappings replace any mappings that this map had for any of the
2761     * keys currently in the specified map.
2762     *
2763     * @param m mappings to be stored in this map
2764     */
2765    public void putAll(Map<? extends K, ? extends V> m) {
2766        internalPutAll(m);
2767    }
2768
2769    /**
2770     * If the specified key is not already associated with a value (or
2771     * is mapped to {@code null}), attempts to compute its value using
2772     * the given mapping function and enters it into this map unless
2773     * {@code null}. The entire method invocation is performed
2774     * atomically, so the function is applied at most once per key.
2775     * Some attempted update operations on this map by other threads
2776     * may be blocked while computation is in progress, so the
2777     * computation should be short and simple, and must not attempt to
2778     * update any other mappings of this Map.
2779     *
2780     * @param key key with which the specified value is to be associated
2781     * @param mappingFunction the function to compute a value
2782     * @return the current (existing or computed) value associated with
2783     *         the specified key, or null if the computed value is null
2784     * @throws NullPointerException if the specified key or mappingFunction
2785     *         is null
2786     * @throws IllegalStateException if the computation detectably
2787     *         attempts a recursive update to this map that would
2788     *         otherwise never complete
2789     * @throws RuntimeException or Error if the mappingFunction does so,
2790     *         in which case the mapping is left unestablished
2791     */
2792    public V computeIfAbsent
2793        (K key, Function<? super K, ? extends V> mappingFunction) {
2794        return internalComputeIfAbsent(key, mappingFunction);
2795    }
2796
2797    /**
2798     * If the value for the specified key is present and non-null,
2799     * attempts to compute a new mapping given the key and its current
2800     * mapped value.  The entire method invocation is performed
2801     * atomically.  Some attempted update operations on this map by
2802     * other threads may be blocked while computation is in progress,
2803     * so the computation should be short and simple, and must not
2804     * attempt to update any other mappings of this Map.
2805     *
2806     * @param key key with which a value may be associated
2807     * @param remappingFunction the function to compute a value
2808     * @return the new value associated with the specified key, or null if none
2809     * @throws NullPointerException if the specified key or remappingFunction
2810     *         is null
2811     * @throws IllegalStateException if the computation detectably
2812     *         attempts a recursive update to this map that would
2813     *         otherwise never complete
2814     * @throws RuntimeException or Error if the remappingFunction does so,
2815     *         in which case the mapping is unchanged
2816     */
2817    public V computeIfPresent
2818        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2819        return internalCompute(key, true, remappingFunction);
2820    }
2821
2822    /**
2823     * Attempts to compute a mapping for the specified key and its
2824     * current mapped value (or {@code null} if there is no current
2825     * mapping). The entire method invocation is performed atomically.
2826     * Some attempted update operations on this map by other threads
2827     * may be blocked while computation is in progress, so the
2828     * computation should be short and simple, and must not attempt to
2829     * update any other mappings of this Map.
2830     *
2831     * @param key key with which the specified value is to be associated
2832     * @param remappingFunction the function to compute a value
2833     * @return the new value associated with the specified key, or null if none
2834     * @throws NullPointerException if the specified key or remappingFunction
2835     *         is null
2836     * @throws IllegalStateException if the computation detectably
2837     *         attempts a recursive update to this map that would
2838     *         otherwise never complete
2839     * @throws RuntimeException or Error if the remappingFunction does so,
2840     *         in which case the mapping is unchanged
2841     */
2842    public V compute
2843        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2844        return internalCompute(key, false, remappingFunction);
3139      }
3140  
3141 <    /**
2848 <     * If the specified key is not already associated with a
2849 <     * (non-null) value, associates it with the given value.
2850 <     * Otherwise, replaces the value with the results of the given
2851 <     * remapping function, or removes if {@code null}. The entire
2852 <     * method invocation is performed atomically.  Some attempted
2853 <     * update operations on this map by other threads may be blocked
2854 <     * while computation is in progress, so the computation should be
2855 <     * short and simple, and must not attempt to update any other
2856 <     * mappings of this Map.
2857 <     *
2858 <     * @param key key with which the specified value is to be associated
2859 <     * @param value the value to use if absent
2860 <     * @param remappingFunction the function to recompute a value if present
2861 <     * @return the new value associated with the specified key, or null if none
2862 <     * @throws NullPointerException if the specified key or the
2863 <     *         remappingFunction is null
2864 <     * @throws RuntimeException or Error if the remappingFunction does so,
2865 <     *         in which case the mapping is unchanged
2866 <     */
2867 <    public V merge
2868 <        (K key, V value,
2869 <         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2870 <        return internalMerge(key, value, remappingFunction);
2871 <    }
2872 <
2873 <    /**
2874 <     * Removes the key (and its corresponding value) from this map.
2875 <     * This method does nothing if the key is not in the map.
2876 <     *
2877 <     * @param  key the key that needs to be removed
2878 <     * @return the previous value associated with {@code key}, or
2879 <     *         {@code null} if there was no mapping for {@code key}
2880 <     * @throws NullPointerException if the specified key is null
2881 <     */
2882 <    public V remove(Object key) {
2883 <        return internalReplace(key, null, null);
2884 <    }
2885 <
2886 <    /**
2887 <     * {@inheritDoc}
2888 <     *
2889 <     * @throws NullPointerException if the specified key is null
2890 <     */
2891 <    public boolean remove(Object key, Object value) {
2892 <        if (key == null)
2893 <            throw new NullPointerException();
2894 <        return value != null && internalReplace(key, null, value) != null;
2895 <    }
2896 <
2897 <    /**
2898 <     * {@inheritDoc}
2899 <     *
2900 <     * @throws NullPointerException if any of the arguments are null
2901 <     */
2902 <    public boolean replace(K key, V oldValue, V newValue) {
2903 <        if (key == null || oldValue == null || newValue == null)
2904 <            throw new NullPointerException();
2905 <        return internalReplace(key, newValue, oldValue) != null;
2906 <    }
2907 <
2908 <    /**
2909 <     * {@inheritDoc}
2910 <     *
2911 <     * @return the previous value associated with the specified key,
2912 <     *         or {@code null} if there was no mapping for the key
2913 <     * @throws NullPointerException if the specified key or value is null
2914 <     */
2915 <    public V replace(K key, V value) {
2916 <        if (key == null || value == null)
2917 <            throw new NullPointerException();
2918 <        return internalReplace(key, value, null);
2919 <    }
2920 <
2921 <    /**
2922 <     * Removes all of the mappings from this map.
2923 <     */
2924 <    public void clear() {
2925 <        internalClear();
2926 <    }
2927 <
2928 <    /**
2929 <     * Returns a {@link Set} view of the keys contained in this map.
2930 <     * The set is backed by the map, so changes to the map are
2931 <     * reflected in the set, and vice-versa.
2932 <     *
2933 <     * @return the set view
2934 <     */
2935 <    public KeySetView<K,V> keySet() {
2936 <        KeySetView<K,V> ks = keySet;
2937 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2938 <    }
2939 <
2940 <    /**
2941 <     * Returns a {@link Set} view of the keys in this map, using the
2942 <     * given common mapped value for any additions (i.e., {@link
2943 <     * Collection#add} and {@link Collection#addAll(Collection)}).
2944 <     * This is of course only appropriate if it is acceptable to use
2945 <     * the same value for all additions from this view.
2946 <     *
2947 <     * @param mappedValue the mapped value to use for any additions
2948 <     * @return the set view
2949 <     * @throws NullPointerException if the mappedValue is null
2950 <     */
2951 <    public KeySetView<K,V> keySet(V mappedValue) {
2952 <        if (mappedValue == null)
2953 <            throw new NullPointerException();
2954 <        return new KeySetView<K,V>(this, mappedValue);
2955 <    }
2956 <
2957 <    /**
2958 <     * Returns a {@link Collection} view of the values contained in this map.
2959 <     * The collection is backed by the map, so changes to the map are
2960 <     * reflected in the collection, and vice-versa.
2961 <     *
2962 <     * @return the collection view
2963 <     */
2964 <    public ValuesView<K,V> values() {
2965 <        ValuesView<K,V> vs = values;
2966 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2967 <    }
2968 <
2969 <    /**
2970 <     * Returns a {@link Set} view of the mappings contained in this map.
2971 <     * The set is backed by the map, so changes to the map are
2972 <     * reflected in the set, and vice-versa.  The set supports element
2973 <     * removal, which removes the corresponding mapping from the map,
2974 <     * via the {@code Iterator.remove}, {@code Set.remove},
2975 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2976 <     * operations.  It does not support the {@code add} or
2977 <     * {@code addAll} operations.
2978 <     *
2979 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2980 <     * that will never throw {@link ConcurrentModificationException},
2981 <     * and guarantees to traverse elements as they existed upon
2982 <     * construction of the iterator, and may (but is not guaranteed to)
2983 <     * reflect any modifications subsequent to construction.
2984 <     *
2985 <     * @return the set view
2986 <     */
2987 <    public Set<Map.Entry<K,V>> entrySet() {
2988 <        EntrySetView<K,V> es = entrySet;
2989 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2990 <    }
2991 <
2992 <    /**
2993 <     * Returns an enumeration of the keys in this table.
2994 <     *
2995 <     * @return an enumeration of the keys in this table
2996 <     * @see #keySet()
2997 <     */
2998 <    public Enumeration<K> keys() {
2999 <        return new KeyIterator<K,V>(this);
3000 <    }
3141 >    /* ----------------Table Traversal -------------- */
3142  
3143      /**
3144 <     * Returns an enumeration of the values in this table.
3144 >     * Encapsulates traversal for methods such as containsValue; also
3145 >     * serves as a base class for other iterators and spliterators.
3146       *
3147 <     * @return an enumeration of the values in this table
3148 <     * @see #values()
3149 <     */
3150 <    public Enumeration<V> elements() {
3151 <        return new ValueIterator<K,V>(this);
3152 <    }
3153 <
3154 <    /**
3013 <     * Returns the hash code value for this {@link Map}, i.e.,
3014 <     * the sum of, for each key-value pair in the map,
3015 <     * {@code key.hashCode() ^ value.hashCode()}.
3147 >     * Method advance visits once each still-valid node that was
3148 >     * reachable upon iterator construction. It might miss some that
3149 >     * were added to a bin after the bin was visited, which is OK wrt
3150 >     * consistency guarantees. Maintaining this property in the face
3151 >     * of possible ongoing resizes requires a fair amount of
3152 >     * bookkeeping state that is difficult to optimize away amidst
3153 >     * volatile accesses.  Even so, traversal maintains reasonable
3154 >     * throughput.
3155       *
3156 <     * @return the hash code value for this map
3156 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3157 >     * However, if the table has been resized, then all future steps
3158 >     * must traverse both the bin at the current index as well as at
3159 >     * (index + baseSize); and so on for further resizings. To
3160 >     * paranoically cope with potential sharing by users of iterators
3161 >     * across threads, iteration terminates if a bounds checks fails
3162 >     * for a table read.
3163       */
3164 <    public int hashCode() {
3165 <        int h = 0;
3166 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3167 <        V v;
3168 <        while ((v = it.advanceValue()) != null) {
3169 <            h += it.nextKey.hashCode() ^ v.hashCode();
3164 >    static class Traverser<K,V> {
3165 >        Node<K,V>[] tab;        // current table; updated if resized
3166 >        Node<K,V> next;         // the next entry to use
3167 >        int index;              // index of bin to use next
3168 >        int baseIndex;          // current index of initial table
3169 >        int baseLimit;          // index bound for initial table
3170 >        final int baseSize;     // initial table size
3171 >
3172 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3173 >            this.tab = tab;
3174 >            this.baseSize = size;
3175 >            this.baseIndex = this.index = index;
3176 >            this.baseLimit = limit;
3177 >            this.next = null;
3178          }
3026        return h;
3027    }
3179  
3180 <    /**
3181 <     * Returns a string representation of this map.  The string
3182 <     * representation consists of a list of key-value mappings (in no
3183 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3184 <     * mappings are separated by the characters {@code ", "} (comma
3185 <     * and space).  Each key-value mapping is rendered as the key
3186 <     * followed by an equals sign ("{@code =}") followed by the
3036 <     * associated value.
3037 <     *
3038 <     * @return a string representation of this map
3039 <     */
3040 <    public String toString() {
3041 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3042 <        StringBuilder sb = new StringBuilder();
3043 <        sb.append('{');
3044 <        V v;
3045 <        if ((v = it.advanceValue()) != null) {
3180 >        /**
3181 >         * Advances if possible, returning next valid node, or null if none.
3182 >         */
3183 >        final Node<K,V> advance() {
3184 >            Node<K,V> e;
3185 >            if ((e = next) != null)
3186 >                e = e.next;
3187              for (;;) {
3188 <                K k = it.nextKey;
3189 <                sb.append(k == this ? "(this Map)" : k);
3190 <                sb.append('=');
3191 <                sb.append(v == this ? "(this Map)" : v);
3192 <                if ((v = it.advanceValue()) == null)
3193 <                    break;
3194 <                sb.append(',').append(' ');
3188 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3189 >                if (e != null)
3190 >                    return next = e;
3191 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3192 >                    (n = t.length) <= (i = index) || i < 0)
3193 >                    return next = null;
3194 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3195 >                    if (e instanceof ForwardingNode) {
3196 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3197 >                        e = null;
3198 >                        continue;
3199 >                    }
3200 >                    else if (e instanceof TreeBin)
3201 >                        e = ((TreeBin<K,V>)e).first;
3202 >                    else
3203 >                        e = null;
3204 >                }
3205 >                if ((index += baseSize) >= n)
3206 >                    index = ++baseIndex;    // visit upper slots if present
3207              }
3208          }
3056        return sb.append('}').toString();
3209      }
3210  
3211      /**
3212 <     * Compares the specified object with this map for equality.
3213 <     * Returns {@code true} if the given object is a map with the same
3062 <     * mappings as this map.  This operation may return misleading
3063 <     * results if either map is concurrently modified during execution
3064 <     * of this method.
3065 <     *
3066 <     * @param o object to be compared for equality with this map
3067 <     * @return {@code true} if the specified object is equal to this map
3212 >     * Base of key, value, and entry Iterators. Adds fields to
3213 >     * Traverser to support iterator.remove
3214       */
3215 <    public boolean equals(Object o) {
3216 <        if (o != this) {
3217 <            if (!(o instanceof Map))
3218 <                return false;
3219 <            Map<?,?> m = (Map<?,?>) o;
3220 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3221 <            V val;
3222 <            while ((val = it.advanceValue()) != null) {
3077 <                Object v = m.get(it.nextKey);
3078 <                if (v == null || (v != val && !v.equals(val)))
3079 <                    return false;
3080 <            }
3081 <            for (Map.Entry<?,?> e : m.entrySet()) {
3082 <                Object mk, mv, v;
3083 <                if ((mk = e.getKey()) == null ||
3084 <                    (mv = e.getValue()) == null ||
3085 <                    (v = internalGet(mk)) == null ||
3086 <                    (mv != v && !mv.equals(v)))
3087 <                    return false;
3088 <            }
3215 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3216 >        final ConcurrentHashMap<K,V> map;
3217 >        Node<K,V> lastReturned;
3218 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3219 >                    ConcurrentHashMap<K,V> map) {
3220 >            super(tab, size, index, limit);
3221 >            this.map = map;
3222 >            advance();
3223          }
3090        return true;
3091    }
3224  
3225 <    /* ----------------Iterators -------------- */
3225 >        public final boolean hasNext() { return next != null; }
3226 >        public final boolean hasMoreElements() { return next != null; }
3227  
3228 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3229 <        extends Traverser<K,V,Object>
3230 <        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
3231 <        KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
3232 <        KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3233 <            super(map, it);
3228 >        public final void remove() {
3229 >            Node<K,V> p;
3230 >            if ((p = lastReturned) == null)
3231 >                throw new IllegalStateException();
3232 >            lastReturned = null;
3233 >            map.replaceNode(p.key, null, null);
3234          }
3235 <        public Spliterator<K> trySplit() {
3236 <            return (baseLimit - baseIndex <= 1) ? null :
3237 <                new KeyIterator<K,V>(map, this);
3235 >    }
3236 >
3237 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3238 >        implements Iterator<K>, Enumeration<K> {
3239 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3240 >                    ConcurrentHashMap<K,V> map) {
3241 >            super(tab, index, size, limit, map);
3242          }
3243 +
3244          public final K next() {
3245 <            K k;
3246 <            if ((k = (nextVal == null) ? advanceKey() : nextKey) == null)
3245 >            Node<K,V> p;
3246 >            if ((p = next) == null)
3247                  throw new NoSuchElementException();
3248 <            nextVal = null;
3248 >            K k = p.key;
3249 >            lastReturned = p;
3250 >            advance();
3251              return k;
3252          }
3253  
3254          public final K nextElement() { return next(); }
3115
3116        public Iterator<K> iterator() { return this; }
3117
3118        public void forEachRemaining(Consumer<? super K> action) {
3119            forEachKey(action);
3120        }
3121
3122        public boolean tryAdvance(Consumer<? super K> block) {
3123            if (block == null) throw new NullPointerException();
3124            K k;
3125            if ((k = advanceKey()) == null)
3126                return false;
3127            block.accept(k);
3128            return true;
3129        }
3130
3131        public int characteristics() {
3132            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3133                Spliterator.NONNULL;
3134        }
3135
3255      }
3256  
3257 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3258 <        extends Traverser<K,V,Object>
3259 <        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
3260 <        ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
3261 <        ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3143 <            super(map, it);
3144 <        }
3145 <        public Spliterator<V> trySplit() {
3146 <            return (baseLimit - baseIndex <= 1) ? null :
3147 <                new ValueIterator<K,V>(map, this);
3257 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3258 >        implements Iterator<V>, Enumeration<V> {
3259 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3260 >                      ConcurrentHashMap<K,V> map) {
3261 >            super(tab, index, size, limit, map);
3262          }
3263  
3264          public final V next() {
3265 <            V v;
3266 <            if ((v = nextVal) == null && (v = advanceValue()) == null)
3265 >            Node<K,V> p;
3266 >            if ((p = next) == null)
3267                  throw new NoSuchElementException();
3268 <            nextVal = null;
3268 >            V v = p.val;
3269 >            lastReturned = p;
3270 >            advance();
3271              return v;
3272          }
3273  
3274          public final V nextElement() { return next(); }
3159
3160        public Iterator<V> iterator() { return this; }
3161
3162        public void forEachRemaining(Consumer<? super V> action) {
3163            forEachValue(action);
3164        }
3165
3166        public boolean tryAdvance(Consumer<? super V> block) {
3167            V v;
3168            if (block == null) throw new NullPointerException();
3169            if ((v = advanceValue()) == null)
3170                return false;
3171            block.accept(v);
3172            return true;
3173        }
3174
3175        public int characteristics() {
3176            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3177        }
3275      }
3276  
3277 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3278 <        extends Traverser<K,V,Object>
3279 <        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3280 <        EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3281 <        EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3185 <            super(map, it);
3186 <        }
3187 <        public Spliterator<Map.Entry<K,V>> trySplit() {
3188 <            return (baseLimit - baseIndex <= 1) ? null :
3189 <                new EntryIterator<K,V>(map, this);
3277 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3278 >        implements Iterator<Map.Entry<K,V>> {
3279 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3280 >                      ConcurrentHashMap<K,V> map) {
3281 >            super(tab, index, size, limit, map);
3282          }
3283  
3284          public final Map.Entry<K,V> next() {
3285 <            V v;
3286 <            if ((v = nextVal) == null && (v = advanceValue()) == null)
3285 >            Node<K,V> p;
3286 >            if ((p = next) == null)
3287                  throw new NoSuchElementException();
3288 <            K k = nextKey;
3289 <            nextVal = null;
3288 >            K k = p.key;
3289 >            V v = p.val;
3290 >            lastReturned = p;
3291 >            advance();
3292              return new MapEntry<K,V>(k, v, map);
3293          }
3200
3201        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3202
3203        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3204            if (action == null) throw new NullPointerException();
3205            V v;
3206            while ((v = advanceValue()) != null)
3207                action.accept(entryFor(nextKey, v));
3208        }
3209
3210        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3211            V v;
3212            if (block == null) throw new NullPointerException();
3213            if ((v = advanceValue()) == null)
3214                return false;
3215            block.accept(entryFor(nextKey, v));
3216            return true;
3217        }
3218
3219        public int characteristics() {
3220            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3221                Spliterator.NONNULL;
3222        }
3294      }
3295  
3296      /**
3297 <     * Exported Entry for iterators
3297 >     * Exported Entry for EntryIterator
3298       */
3299      static final class MapEntry<K,V> implements Map.Entry<K,V> {
3300          final K key; // non-null
# Line 3234 | Line 3305 | public class ConcurrentHashMap<K,V>
3305              this.val = val;
3306              this.map = map;
3307          }
3308 <        public final K getKey()       { return key; }
3309 <        public final V getValue()     { return val; }
3310 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3311 <        public final String toString(){ return key + "=" + val; }
3308 >        public K getKey()        { return key; }
3309 >        public V getValue()      { return val; }
3310 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3311 >        public String toString() { return key + "=" + val; }
3312  
3313 <        public final boolean equals(Object o) {
3313 >        public boolean equals(Object o) {
3314              Object k, v; Map.Entry<?,?> e;
3315              return ((o instanceof Map.Entry) &&
3316                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3253 | Line 3324 | public class ConcurrentHashMap<K,V>
3324           * value to return is somewhat arbitrary here. Since we do not
3325           * necessarily track asynchronous changes, the most recent
3326           * "previous" value could be different from what we return (or
3327 <         * could even have been removed in which case the put will
3327 >         * could even have been removed, in which case the put will
3328           * re-establish). We do not and cannot guarantee more.
3329           */
3330 <        public final V setValue(V value) {
3330 >        public V setValue(V value) {
3331              if (value == null) throw new NullPointerException();
3332              V v = val;
3333              val = value;
# Line 3265 | Line 3336 | public class ConcurrentHashMap<K,V>
3336          }
3337      }
3338  
3339 <    /**
3340 <     * Returns exportable snapshot entry for the given key and value
3341 <     * when write-through can't or shouldn't be used.
3342 <     */
3343 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3344 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3345 <    }
3339 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3340 >        implements Spliterator<K> {
3341 >        long est;               // size estimate
3342 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3343 >                       long est) {
3344 >            super(tab, size, index, limit);
3345 >            this.est = est;
3346 >        }
3347  
3348 <    /* ---------------- Serialization Support -------------- */
3348 >        public Spliterator<K> trySplit() {
3349 >            int i, f, h;
3350 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3351 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3352 >                                        f, est >>>= 1);
3353 >        }
3354  
3355 <    /**
3356 <     * Stripped-down version of helper class used in previous version,
3357 <     * declared for the sake of serialization compatibility
3358 <     */
3359 <    static class Segment<K,V> implements Serializable {
3360 <        private static final long serialVersionUID = 2249069246763182397L;
3361 <        final float loadFactor;
3362 <        Segment(float lf) { this.loadFactor = lf; }
3355 >        public void forEachRemaining(Consumer<? super K> action) {
3356 >            if (action == null) throw new NullPointerException();
3357 >            for (Node<K,V> p; (p = advance()) != null;)
3358 >                action.accept(p.key);
3359 >        }
3360 >
3361 >        public boolean tryAdvance(Consumer<? super K> action) {
3362 >            if (action == null) throw new NullPointerException();
3363 >            Node<K,V> p;
3364 >            if ((p = advance()) == null)
3365 >                return false;
3366 >            action.accept(p.key);
3367 >            return true;
3368 >        }
3369 >
3370 >        public long estimateSize() { return est; }
3371 >
3372 >        public int characteristics() {
3373 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3374 >                Spliterator.NONNULL;
3375 >        }
3376      }
3377  
3378 <    /**
3379 <     * Saves the state of the {@code ConcurrentHashMap} instance to a
3380 <     * stream (i.e., serializes it).
3381 <     * @param s the stream
3382 <     * @serialData
3383 <     * the key (Object) and value (Object)
3384 <     * for each key-value mapping, followed by a null pair.
3295 <     * The key-value mappings are emitted in no particular order.
3296 <     */
3297 <    @SuppressWarnings("unchecked") private void writeObject
3298 <        (java.io.ObjectOutputStream s)
3299 <        throws java.io.IOException {
3300 <        if (segments == null) { // for serialization compatibility
3301 <            segments = (Segment<K,V>[])
3302 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3303 <            for (int i = 0; i < segments.length; ++i)
3304 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3378 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3379 >        implements Spliterator<V> {
3380 >        long est;               // size estimate
3381 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3382 >                         long est) {
3383 >            super(tab, size, index, limit);
3384 >            this.est = est;
3385          }
3386 <        s.defaultWriteObject();
3387 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3388 <        V v;
3389 <        while ((v = it.advanceValue()) != null) {
3390 <            s.writeObject(it.nextKey);
3391 <            s.writeObject(v);
3386 >
3387 >        public Spliterator<V> trySplit() {
3388 >            int i, f, h;
3389 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3390 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3391 >                                          f, est >>>= 1);
3392 >        }
3393 >
3394 >        public void forEachRemaining(Consumer<? super V> action) {
3395 >            if (action == null) throw new NullPointerException();
3396 >            for (Node<K,V> p; (p = advance()) != null;)
3397 >                action.accept(p.val);
3398 >        }
3399 >
3400 >        public boolean tryAdvance(Consumer<? super V> action) {
3401 >            if (action == null) throw new NullPointerException();
3402 >            Node<K,V> p;
3403 >            if ((p = advance()) == null)
3404 >                return false;
3405 >            action.accept(p.val);
3406 >            return true;
3407 >        }
3408 >
3409 >        public long estimateSize() { return est; }
3410 >
3411 >        public int characteristics() {
3412 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3413          }
3313        s.writeObject(null);
3314        s.writeObject(null);
3315        segments = null; // throw away
3414      }
3415  
3416 <    /**
3417 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3418 <     * @param s the stream
3419 <     */
3420 <    @SuppressWarnings("unchecked") private void readObject
3421 <        (java.io.ObjectInputStream s)
3422 <        throws java.io.IOException, ClassNotFoundException {
3423 <        s.defaultReadObject();
3424 <        this.segments = null; // unneeded
3416 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3417 >        implements Spliterator<Map.Entry<K,V>> {
3418 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3419 >        long est;               // size estimate
3420 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3421 >                         long est, ConcurrentHashMap<K,V> map) {
3422 >            super(tab, size, index, limit);
3423 >            this.map = map;
3424 >            this.est = est;
3425 >        }
3426  
3427 <        // Create all nodes, then place in table once size is known
3428 <        long size = 0L;
3429 <        Node<V> p = null;
3430 <        for (;;) {
3431 <            K k = (K) s.readObject();
3333 <            V v = (V) s.readObject();
3334 <            if (k != null && v != null) {
3335 <                int h = spread(k.hashCode());
3336 <                p = new Node<V>(h, k, v, p);
3337 <                ++size;
3338 <            }
3339 <            else
3340 <                break;
3427 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3428 >            int i, f, h;
3429 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3430 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3431 >                                          f, est >>>= 1, map);
3432          }
3433 <        if (p != null) {
3434 <            boolean init = false;
3435 <            int n;
3436 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3437 <                n = MAXIMUM_CAPACITY;
3438 <            else {
3439 <                int sz = (int)size;
3440 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3441 <            }
3442 <            int sc = sizeCtl;
3443 <            boolean collide = false;
3444 <            if (n > sc &&
3445 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3446 <                try {
3447 <                    if (table == null) {
3448 <                        init = true;
3449 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3450 <                        Node<V>[] tab = (Node<V>[])rt;
3451 <                        int mask = n - 1;
3452 <                        while (p != null) {
3453 <                            int j = p.hash & mask;
3363 <                            Node<V> next = p.next;
3364 <                            Node<V> q = p.next = tabAt(tab, j);
3365 <                            setTabAt(tab, j, p);
3366 <                            if (!collide && q != null && q.hash == p.hash)
3367 <                                collide = true;
3368 <                            p = next;
3369 <                        }
3370 <                        table = tab;
3371 <                        addCount(size, -1);
3372 <                        sc = n - (n >>> 2);
3373 <                    }
3374 <                } finally {
3375 <                    sizeCtl = sc;
3376 <                }
3377 <                if (collide) { // rescan and convert to TreeBins
3378 <                    Node<V>[] tab = table;
3379 <                    for (int i = 0; i < tab.length; ++i) {
3380 <                        int c = 0;
3381 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3382 <                            if (++c > TREE_THRESHOLD &&
3383 <                                (e.key instanceof Comparable)) {
3384 <                                replaceWithTreeBin(tab, i, e.key);
3385 <                                break;
3386 <                            }
3387 <                        }
3388 <                    }
3389 <                }
3390 <            }
3391 <            if (!init) { // Can only happen if unsafely published.
3392 <                while (p != null) {
3393 <                    internalPut((K)p.key, p.val, false);
3394 <                    p = p.next;
3395 <                }
3396 <            }
3433 >
3434 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3435 >            if (action == null) throw new NullPointerException();
3436 >            for (Node<K,V> p; (p = advance()) != null; )
3437 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3438 >        }
3439 >
3440 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3441 >            if (action == null) throw new NullPointerException();
3442 >            Node<K,V> p;
3443 >            if ((p = advance()) == null)
3444 >                return false;
3445 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3446 >            return true;
3447 >        }
3448 >
3449 >        public long estimateSize() { return est; }
3450 >
3451 >        public int characteristics() {
3452 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3453 >                Spliterator.NONNULL;
3454          }
3455      }
3456  
3457 <    // -------------------------------------------------------
3457 >    // Parallel bulk operations
3458  
3459 <    // Sequential bulk operations
3459 >    /**
3460 >     * Computes initial batch value for bulk tasks. The returned value
3461 >     * is approximately exp2 of the number of times (minus one) to
3462 >     * split task by two before executing leaf action. This value is
3463 >     * faster to compute and more convenient to use as a guide to
3464 >     * splitting than is the depth, since it is used while dividing by
3465 >     * two anyway.
3466 >     */
3467 >    final int batchFor(long b) {
3468 >        long n;
3469 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3470 >            return 0;
3471 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3472 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3473 >    }
3474  
3475      /**
3476       * Performs the given action for each (key, value).
3477       *
3478 +     * @param parallelismThreshold the (estimated) number of elements
3479 +     * needed for this operation to be executed in parallel
3480       * @param action the action
3481 +     * @since 1.8
3482       */
3483 <    public void forEachSequentially
3484 <        (BiConsumer<? super K, ? super V> action) {
3483 >    public void forEach(long parallelismThreshold,
3484 >                        BiConsumer<? super K,? super V> action) {
3485          if (action == null) throw new NullPointerException();
3486 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3487 <        V v;
3488 <        while ((v = it.advanceValue()) != null)
3415 <            action.accept(it.nextKey, v);
3486 >        new ForEachMappingTask<K,V>
3487 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3488 >             action).invoke();
3489      }
3490  
3491      /**
3492       * Performs the given action for each non-null transformation
3493       * of each (key, value).
3494       *
3495 +     * @param parallelismThreshold the (estimated) number of elements
3496 +     * needed for this operation to be executed in parallel
3497       * @param transformer a function returning the transformation
3498       * for an element, or null if there is no transformation (in
3499       * which case the action is not applied)
3500       * @param action the action
3501 +     * @since 1.8
3502       */
3503 <    public <U> void forEachSequentially
3504 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3505 <         Consumer<? super U> action) {
3503 >    public <U> void forEach(long parallelismThreshold,
3504 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3505 >                            Consumer<? super U> action) {
3506          if (transformer == null || action == null)
3507              throw new NullPointerException();
3508 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3509 <        V v; U u;
3510 <        while ((v = it.advanceValue()) != null) {
3435 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3436 <                action.accept(u);
3437 <        }
3508 >        new ForEachTransformedMappingTask<K,V,U>
3509 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3510 >             transformer, action).invoke();
3511      }
3512  
3513      /**
3514       * Returns a non-null result from applying the given search
3515 <     * function on each (key, value), or null if none.
3515 >     * function on each (key, value), or null if none.  Upon
3516 >     * success, further element processing is suppressed and the
3517 >     * results of any other parallel invocations of the search
3518 >     * function are ignored.
3519       *
3520 +     * @param parallelismThreshold the (estimated) number of elements
3521 +     * needed for this operation to be executed in parallel
3522       * @param searchFunction a function returning a non-null
3523       * result on success, else null
3524       * @return a non-null result from applying the given search
3525       * function on each (key, value), or null if none
3526 +     * @since 1.8
3527       */
3528 <    public <U> U searchSequentially
3529 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3528 >    public <U> U search(long parallelismThreshold,
3529 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3530          if (searchFunction == null) throw new NullPointerException();
3531 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3532 <        V v; U u;
3533 <        while ((v = it.advanceValue()) != null) {
3455 <            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3456 <                return u;
3457 <        }
3458 <        return null;
3531 >        return new SearchMappingsTask<K,V,U>
3532 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3533 >             searchFunction, new AtomicReference<U>()).invoke();
3534      }
3535  
3536      /**
# Line 3463 | Line 3538 | public class ConcurrentHashMap<K,V>
3538       * of all (key, value) pairs using the given reducer to
3539       * combine values, or null if none.
3540       *
3541 +     * @param parallelismThreshold the (estimated) number of elements
3542 +     * needed for this operation to be executed in parallel
3543       * @param transformer a function returning the transformation
3544       * for an element, or null if there is no transformation (in
3545       * which case it is not combined)
3546       * @param reducer a commutative associative combining function
3547       * @return the result of accumulating the given transformation
3548       * of all (key, value) pairs
3549 +     * @since 1.8
3550       */
3551 <    public <U> U reduceSequentially
3552 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
3553 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3551 >    public <U> U reduce(long parallelismThreshold,
3552 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3553 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3554          if (transformer == null || reducer == null)
3555              throw new NullPointerException();
3556 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3557 <        U r = null, u; V v;
3558 <        while ((v = it.advanceValue()) != null) {
3481 <            if ((u = transformer.apply(it.nextKey, v)) != null)
3482 <                r = (r == null) ? u : reducer.apply(r, u);
3483 <        }
3484 <        return r;
3556 >        return new MapReduceMappingsTask<K,V,U>
3557 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3558 >             null, transformer, reducer).invoke();
3559      }
3560  
3561      /**
# Line 3489 | Line 3563 | public class ConcurrentHashMap<K,V>
3563       * of all (key, value) pairs using the given reducer to
3564       * combine values, and the given basis as an identity value.
3565       *
3566 +     * @param parallelismThreshold the (estimated) number of elements
3567 +     * needed for this operation to be executed in parallel
3568       * @param transformer a function returning the transformation
3569       * for an element
3570       * @param basis the identity (initial default value) for the reduction
3571       * @param reducer a commutative associative combining function
3572       * @return the result of accumulating the given transformation
3573       * of all (key, value) pairs
3574 +     * @since 1.8
3575       */
3576 <    public double reduceToDoubleSequentially
3577 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
3578 <         double basis,
3579 <         DoubleBinaryOperator reducer) {
3576 >    public double reduceToDoubleIn(long parallelismThreshold,
3577 >                                   ToDoubleBiFunction<? super K, ? super V> transformer,
3578 >                                   double basis,
3579 >                                   DoubleBinaryOperator reducer) {
3580          if (transformer == null || reducer == null)
3581              throw new NullPointerException();
3582 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3583 <        double r = basis; V v;
3584 <        while ((v = it.advanceValue()) != null)
3508 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3509 <        return r;
3582 >        return new MapReduceMappingsToDoubleTask<K,V>
3583 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3584 >             null, transformer, basis, reducer).invoke();
3585      }
3586  
3587      /**
# Line 3514 | Line 3589 | public class ConcurrentHashMap<K,V>
3589       * of all (key, value) pairs using the given reducer to
3590       * combine values, and the given basis as an identity value.
3591       *
3592 +     * @param parallelismThreshold the (estimated) number of elements
3593 +     * needed for this operation to be executed in parallel
3594       * @param transformer a function returning the transformation
3595       * for an element
3596       * @param basis the identity (initial default value) for the reduction
3597       * @param reducer a commutative associative combining function
3598       * @return the result of accumulating the given transformation
3599       * of all (key, value) pairs
3600 +     * @since 1.8
3601       */
3602 <    public long reduceToLongSequentially
3603 <        (ToLongBiFunction<? super K, ? super V> transformer,
3604 <         long basis,
3605 <         LongBinaryOperator reducer) {
3602 >    public long reduceToLong(long parallelismThreshold,
3603 >                             ToLongBiFunction<? super K, ? super V> transformer,
3604 >                             long basis,
3605 >                             LongBinaryOperator reducer) {
3606          if (transformer == null || reducer == null)
3607              throw new NullPointerException();
3608 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3609 <        long r = basis; V v;
3610 <        while ((v = it.advanceValue()) != null)
3533 <            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3534 <        return r;
3608 >        return new MapReduceMappingsToLongTask<K,V>
3609 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3610 >             null, transformer, basis, reducer).invoke();
3611      }
3612  
3613      /**
# Line 3539 | Line 3615 | public class ConcurrentHashMap<K,V>
3615       * of all (key, value) pairs using the given reducer to
3616       * combine values, and the given basis as an identity value.
3617       *
3618 +     * @param parallelismThreshold the (estimated) number of elements
3619 +     * needed for this operation to be executed in parallel
3620       * @param transformer a function returning the transformation
3621       * for an element
3622       * @param basis the identity (initial default value) for the reduction
3623       * @param reducer a commutative associative combining function
3624       * @return the result of accumulating the given transformation
3625       * of all (key, value) pairs
3626 +     * @since 1.8
3627       */
3628 <    public int reduceToIntSequentially
3629 <        (ToIntBiFunction<? super K, ? super V> transformer,
3630 <         int basis,
3631 <         IntBinaryOperator reducer) {
3628 >    public int reduceToInt(long parallelismThreshold,
3629 >                           ToIntBiFunction<? super K, ? super V> transformer,
3630 >                           int basis,
3631 >                           IntBinaryOperator reducer) {
3632          if (transformer == null || reducer == null)
3633              throw new NullPointerException();
3634 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3635 <        int r = basis; V v;
3636 <        while ((v = it.advanceValue()) != null)
3558 <            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3559 <        return r;
3634 >        return new MapReduceMappingsToIntTask<K,V>
3635 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3636 >             null, transformer, basis, reducer).invoke();
3637      }
3638  
3639      /**
3640       * Performs the given action for each key.
3641       *
3642 +     * @param parallelismThreshold the (estimated) number of elements
3643 +     * needed for this operation to be executed in parallel
3644       * @param action the action
3645 +     * @since 1.8
3646       */
3647 <    public void forEachKeySequentially
3648 <        (Consumer<? super K> action) {
3649 <        new Traverser<K,V,Object>(this).forEachKey(action);
3647 >    public void forEachKey(long parallelismThreshold,
3648 >                           Consumer<? super K> action) {
3649 >        if (action == null) throw new NullPointerException();
3650 >        new ForEachKeyTask<K,V>
3651 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3652 >             action).invoke();
3653      }
3654  
3655      /**
3656       * Performs the given action for each non-null transformation
3657       * of each key.
3658       *
3659 +     * @param parallelismThreshold the (estimated) number of elements
3660 +     * needed for this operation to be executed in parallel
3661       * @param transformer a function returning the transformation
3662       * for an element, or null if there is no transformation (in
3663       * which case the action is not applied)
3664       * @param action the action
3665 +     * @since 1.8
3666       */
3667 <    public <U> void forEachKeySequentially
3668 <        (Function<? super K, ? extends U> transformer,
3669 <         Consumer<? super U> action) {
3667 >    public <U> void forEachKey(long parallelismThreshold,
3668 >                               Function<? super K, ? extends U> transformer,
3669 >                               Consumer<? super U> action) {
3670          if (transformer == null || action == null)
3671              throw new NullPointerException();
3672 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3673 <        K k; U u;
3674 <        while ((k = it.advanceKey()) != null) {
3589 <            if ((u = transformer.apply(k)) != null)
3590 <                action.accept(u);
3591 <        }
3672 >        new ForEachTransformedKeyTask<K,V,U>
3673 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3674 >             transformer, action).invoke();
3675      }
3676  
3677      /**
3678       * Returns a non-null result from applying the given search
3679 <     * function on each key, or null if none.
3679 >     * function on each key, or null if none. Upon success,
3680 >     * further element processing is suppressed and the results of
3681 >     * any other parallel invocations of the search function are
3682 >     * ignored.
3683       *
3684 +     * @param parallelismThreshold the (estimated) number of elements
3685 +     * needed for this operation to be executed in parallel
3686       * @param searchFunction a function returning a non-null
3687       * result on success, else null
3688       * @return a non-null result from applying the given search
3689       * function on each key, or null if none
3690 +     * @since 1.8
3691       */
3692 <    public <U> U searchKeysSequentially
3693 <        (Function<? super K, ? extends U> searchFunction) {
3694 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3695 <        K k; U u;
3696 <        while ((k = it.advanceKey()) != null) {
3697 <            if ((u = searchFunction.apply(k)) != null)
3609 <                return u;
3610 <        }
3611 <        return null;
3692 >    public <U> U searchKeys(long parallelismThreshold,
3693 >                            Function<? super K, ? extends U> searchFunction) {
3694 >        if (searchFunction == null) throw new NullPointerException();
3695 >        return new SearchKeysTask<K,V,U>
3696 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3697 >             searchFunction, new AtomicReference<U>()).invoke();
3698      }
3699  
3700      /**
3701       * Returns the result of accumulating all keys using the given
3702       * reducer to combine values, or null if none.
3703       *
3704 +     * @param parallelismThreshold the (estimated) number of elements
3705 +     * needed for this operation to be executed in parallel
3706       * @param reducer a commutative associative combining function
3707       * @return the result of accumulating all keys using the given
3708       * reducer to combine values, or null if none
3709 +     * @since 1.8
3710       */
3711 <    public K reduceKeysSequentially
3712 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3711 >    public K reduceKeys(long parallelismThreshold,
3712 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3713          if (reducer == null) throw new NullPointerException();
3714 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3715 <        K u, r = null;
3716 <        while ((u = it.advanceKey()) != null) {
3628 <            r = (r == null) ? u : reducer.apply(r, u);
3629 <        }
3630 <        return r;
3714 >        return new ReduceKeysTask<K,V>
3715 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3716 >             null, reducer).invoke();
3717      }
3718  
3719      /**
# Line 3635 | Line 3721 | public class ConcurrentHashMap<K,V>
3721       * of all keys using the given reducer to combine values, or
3722       * null if none.
3723       *
3724 +     * @param parallelismThreshold the (estimated) number of elements
3725 +     * needed for this operation to be executed in parallel
3726       * @param transformer a function returning the transformation
3727       * for an element, or null if there is no transformation (in
3728       * which case it is not combined)
3729       * @param reducer a commutative associative combining function
3730       * @return the result of accumulating the given transformation
3731       * of all keys
3732 +     * @since 1.8
3733       */
3734 <    public <U> U reduceKeysSequentially
3735 <        (Function<? super K, ? extends U> transformer,
3734 >    public <U> U reduceKeys(long parallelismThreshold,
3735 >                            Function<? super K, ? extends U> transformer,
3736           BiFunction<? super U, ? super U, ? extends U> reducer) {
3737          if (transformer == null || reducer == null)
3738              throw new NullPointerException();
3739 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3740 <        K k; U r = null, u;
3741 <        while ((k = it.advanceKey()) != null) {
3653 <            if ((u = transformer.apply(k)) != null)
3654 <                r = (r == null) ? u : reducer.apply(r, u);
3655 <        }
3656 <        return r;
3739 >        return new MapReduceKeysTask<K,V,U>
3740 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3741 >             null, transformer, reducer).invoke();
3742      }
3743  
3744      /**
# Line 3661 | Line 3746 | public class ConcurrentHashMap<K,V>
3746       * of all keys using the given reducer to combine values, and
3747       * the given basis as an identity value.
3748       *
3749 +     * @param parallelismThreshold the (estimated) number of elements
3750 +     * needed for this operation to be executed in parallel
3751       * @param transformer a function returning the transformation
3752       * for an element
3753       * @param basis the identity (initial default value) for the reduction
3754       * @param reducer a commutative associative combining function
3755       * @return the result of accumulating the given transformation
3756       * of all keys
3757 +     * @since 1.8
3758       */
3759 <    public double reduceKeysToDoubleSequentially
3760 <        (ToDoubleFunction<? super K> transformer,
3761 <         double basis,
3762 <         DoubleBinaryOperator reducer) {
3759 >    public double reduceKeysToDouble(long parallelismThreshold,
3760 >                                     ToDoubleFunction<? super K> transformer,
3761 >                                     double basis,
3762 >                                     DoubleBinaryOperator reducer) {
3763          if (transformer == null || reducer == null)
3764              throw new NullPointerException();
3765 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3766 <        double r = basis;
3767 <        K k;
3680 <        while ((k = it.advanceKey()) != null)
3681 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
3682 <        return r;
3765 >        return new MapReduceKeysToDoubleTask<K,V>
3766 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3767 >             null, transformer, basis, reducer).invoke();
3768      }
3769  
3770      /**
# Line 3687 | Line 3772 | public class ConcurrentHashMap<K,V>
3772       * of all keys using the given reducer to combine values, and
3773       * the given basis as an identity value.
3774       *
3775 +     * @param parallelismThreshold the (estimated) number of elements
3776 +     * needed for this operation to be executed in parallel
3777       * @param transformer a function returning the transformation
3778       * for an element
3779       * @param basis the identity (initial default value) for the reduction
3780       * @param reducer a commutative associative combining function
3781       * @return the result of accumulating the given transformation
3782       * of all keys
3783 +     * @since 1.8
3784       */
3785 <    public long reduceKeysToLongSequentially
3786 <        (ToLongFunction<? super K> transformer,
3787 <         long basis,
3788 <         LongBinaryOperator reducer) {
3785 >    public long reduceKeysToLong(long parallelismThreshold,
3786 >                                 ToLongFunction<? super K> transformer,
3787 >                                 long basis,
3788 >                                 LongBinaryOperator reducer) {
3789          if (transformer == null || reducer == null)
3790              throw new NullPointerException();
3791 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3792 <        long r = basis;
3793 <        K k;
3706 <        while ((k = it.advanceKey()) != null)
3707 <            r = reducer.applyAsLong(r, transformer.applyAsLong(k));
3708 <        return r;
3791 >        return new MapReduceKeysToLongTask<K,V>
3792 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3793 >             null, transformer, basis, reducer).invoke();
3794      }
3795  
3796      /**
# Line 3713 | Line 3798 | public class ConcurrentHashMap<K,V>
3798       * of all keys using the given reducer to combine values, and
3799       * the given basis as an identity value.
3800       *
3801 +     * @param parallelismThreshold the (estimated) number of elements
3802 +     * needed for this operation to be executed in parallel
3803       * @param transformer a function returning the transformation
3804       * for an element
3805       * @param basis the identity (initial default value) for the reduction
3806       * @param reducer a commutative associative combining function
3807       * @return the result of accumulating the given transformation
3808       * of all keys
3809 +     * @since 1.8
3810       */
3811 <    public int reduceKeysToIntSequentially
3812 <        (ToIntFunction<? super K> transformer,
3813 <         int basis,
3814 <         IntBinaryOperator reducer) {
3811 >    public int reduceKeysToInt(long parallelismThreshold,
3812 >                               ToIntFunction<? super K> transformer,
3813 >                               int basis,
3814 >                               IntBinaryOperator reducer) {
3815          if (transformer == null || reducer == null)
3816              throw new NullPointerException();
3817 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3818 <        int r = basis;
3819 <        K k;
3732 <        while ((k = it.advanceKey()) != null)
3733 <            r = reducer.applyAsInt(r, transformer.applyAsInt(k));
3734 <        return r;
3817 >        return new MapReduceKeysToIntTask<K,V>
3818 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3819 >             null, transformer, basis, reducer).invoke();
3820      }
3821  
3822      /**
3823       * Performs the given action for each value.
3824       *
3825 +     * @param parallelismThreshold the (estimated) number of elements
3826 +     * needed for this operation to be executed in parallel
3827       * @param action the action
3828 +     * @since 1.8
3829       */
3830 <    public void forEachValueSequentially(Consumer<? super V> action) {
3831 <        new Traverser<K,V,Object>(this).forEachValue(action);
3830 >    public void forEachValue(long parallelismThreshold,
3831 >                             Consumer<? super V> action) {
3832 >        if (action == null)
3833 >            throw new NullPointerException();
3834 >        new ForEachValueTask<K,V>
3835 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3836 >             action).invoke();
3837      }
3838  
3839      /**
3840       * Performs the given action for each non-null transformation
3841       * of each value.
3842       *
3843 +     * @param parallelismThreshold the (estimated) number of elements
3844 +     * needed for this operation to be executed in parallel
3845       * @param transformer a function returning the transformation
3846       * for an element, or null if there is no transformation (in
3847       * which case the action is not applied)
3848       * @param action the action
3849 +     * @since 1.8
3850       */
3851 <    public <U> void forEachValueSequentially
3852 <        (Function<? super V, ? extends U> transformer,
3853 <         Consumer<? super U> action) {
3851 >    public <U> void forEachValue(long parallelismThreshold,
3852 >                                 Function<? super V, ? extends U> transformer,
3853 >                                 Consumer<? super U> action) {
3854          if (transformer == null || action == null)
3855              throw new NullPointerException();
3856 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3857 <        V v; U u;
3858 <        while ((v = it.advanceValue()) != null) {
3763 <            if ((u = transformer.apply(v)) != null)
3764 <                action.accept(u);
3765 <        }
3856 >        new ForEachTransformedValueTask<K,V,U>
3857 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3858 >             transformer, action).invoke();
3859      }
3860  
3861      /**
3862       * Returns a non-null result from applying the given search
3863 <     * function on each value, or null if none.
3863 >     * function on each value, or null if none.  Upon success,
3864 >     * further element processing is suppressed and the results of
3865 >     * any other parallel invocations of the search function are
3866 >     * ignored.
3867       *
3868 +     * @param parallelismThreshold the (estimated) number of elements
3869 +     * needed for this operation to be executed in parallel
3870       * @param searchFunction a function returning a non-null
3871       * result on success, else null
3872       * @return a non-null result from applying the given search
3873       * function on each value, or null if none
3874 +     * @since 1.8
3875       */
3876 <    public <U> U searchValuesSequentially
3877 <        (Function<? super V, ? extends U> searchFunction) {
3876 >    public <U> U searchValues(long parallelismThreshold,
3877 >                              Function<? super V, ? extends U> searchFunction) {
3878          if (searchFunction == null) throw new NullPointerException();
3879 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3880 <        V v; U u;
3881 <        while ((v = it.advanceValue()) != null) {
3783 <            if ((u = searchFunction.apply(v)) != null)
3784 <                return u;
3785 <        }
3786 <        return null;
3879 >        return new SearchValuesTask<K,V,U>
3880 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3881 >             searchFunction, new AtomicReference<U>()).invoke();
3882      }
3883  
3884      /**
3885       * Returns the result of accumulating all values using the
3886       * given reducer to combine values, or null if none.
3887       *
3888 +     * @param parallelismThreshold the (estimated) number of elements
3889 +     * needed for this operation to be executed in parallel
3890       * @param reducer a commutative associative combining function
3891       * @return the result of accumulating all values
3892 +     * @since 1.8
3893       */
3894 <    public V reduceValuesSequentially
3895 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
3894 >    public V reduceValues(long parallelismThreshold,
3895 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
3896          if (reducer == null) throw new NullPointerException();
3897 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3898 <        V r = null; V v;
3899 <        while ((v = it.advanceValue()) != null)
3802 <            r = (r == null) ? v : reducer.apply(r, v);
3803 <        return r;
3897 >        return new ReduceValuesTask<K,V>
3898 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3899 >             null, reducer).invoke();
3900      }
3901  
3902      /**
# Line 3808 | Line 3904 | public class ConcurrentHashMap<K,V>
3904       * of all values using the given reducer to combine values, or
3905       * null if none.
3906       *
3907 +     * @param parallelismThreshold the (estimated) number of elements
3908 +     * needed for this operation to be executed in parallel
3909       * @param transformer a function returning the transformation
3910       * for an element, or null if there is no transformation (in
3911       * which case it is not combined)
3912       * @param reducer a commutative associative combining function
3913       * @return the result of accumulating the given transformation
3914       * of all values
3915 +     * @since 1.8
3916       */
3917 <    public <U> U reduceValuesSequentially
3918 <        (Function<? super V, ? extends U> transformer,
3919 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
3917 >    public <U> U reduceValues(long parallelismThreshold,
3918 >                              Function<? super V, ? extends U> transformer,
3919 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
3920          if (transformer == null || reducer == null)
3921              throw new NullPointerException();
3922 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3923 <        U r = null, u; V v;
3924 <        while ((v = it.advanceValue()) != null) {
3826 <            if ((u = transformer.apply(v)) != null)
3827 <                r = (r == null) ? u : reducer.apply(r, u);
3828 <        }
3829 <        return r;
3922 >        return new MapReduceValuesTask<K,V,U>
3923 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3924 >             null, transformer, reducer).invoke();
3925      }
3926  
3927      /**
# Line 3834 | Line 3929 | public class ConcurrentHashMap<K,V>
3929       * of all values using the given reducer to combine values,
3930       * and the given basis as an identity value.
3931       *
3932 +     * @param parallelismThreshold the (estimated) number of elements
3933 +     * needed for this operation to be executed in parallel
3934       * @param transformer a function returning the transformation
3935       * for an element
3936       * @param basis the identity (initial default value) for the reduction
3937       * @param reducer a commutative associative combining function
3938       * @return the result of accumulating the given transformation
3939       * of all values
3940 +     * @since 1.8
3941       */
3942 <    public double reduceValuesToDoubleSequentially
3943 <        (ToDoubleFunction<? super V> transformer,
3944 <         double basis,
3945 <         DoubleBinaryOperator reducer) {
3942 >    public double reduceValuesToDouble(long parallelismThreshold,
3943 >                                       ToDoubleFunction<? super V> transformer,
3944 >                                       double basis,
3945 >                                       DoubleBinaryOperator reducer) {
3946          if (transformer == null || reducer == null)
3947              throw new NullPointerException();
3948 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3949 <        double r = basis; V v;
3950 <        while ((v = it.advanceValue()) != null)
3853 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3854 <        return r;
3948 >        return new MapReduceValuesToDoubleTask<K,V>
3949 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3950 >             null, transformer, basis, reducer).invoke();
3951      }
3952  
3953      /**
# Line 3859 | Line 3955 | public class ConcurrentHashMap<K,V>
3955       * of all values using the given reducer to combine values,
3956       * and the given basis as an identity value.
3957       *
3958 +     * @param parallelismThreshold the (estimated) number of elements
3959 +     * needed for this operation to be executed in parallel
3960       * @param transformer a function returning the transformation
3961       * for an element
3962       * @param basis the identity (initial default value) for the reduction
3963       * @param reducer a commutative associative combining function
3964       * @return the result of accumulating the given transformation
3965       * of all values
3966 +     * @since 1.8
3967       */
3968 <    public long reduceValuesToLongSequentially
3969 <        (ToLongFunction<? super V> transformer,
3970 <         long basis,
3971 <         LongBinaryOperator reducer) {
3968 >    public long reduceValuesToLong(long parallelismThreshold,
3969 >                                   ToLongFunction<? super V> transformer,
3970 >                                   long basis,
3971 >                                   LongBinaryOperator reducer) {
3972          if (transformer == null || reducer == null)
3973              throw new NullPointerException();
3974 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3975 <        long r = basis; V v;
3976 <        while ((v = it.advanceValue()) != null)
3878 <            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3879 <        return r;
3974 >        return new MapReduceValuesToLongTask<K,V>
3975 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3976 >             null, transformer, basis, reducer).invoke();
3977      }
3978  
3979      /**
# Line 3884 | Line 3981 | public class ConcurrentHashMap<K,V>
3981       * of all values using the given reducer to combine values,
3982       * and the given basis as an identity value.
3983       *
3984 +     * @param parallelismThreshold the (estimated) number of elements
3985 +     * needed for this operation to be executed in parallel
3986       * @param transformer a function returning the transformation
3987       * for an element
3988       * @param basis the identity (initial default value) for the reduction
3989       * @param reducer a commutative associative combining function
3990       * @return the result of accumulating the given transformation
3991       * of all values
3992 +     * @since 1.8
3993       */
3994 <    public int reduceValuesToIntSequentially
3995 <        (ToIntFunction<? super V> transformer,
3996 <         int basis,
3997 <         IntBinaryOperator reducer) {
3994 >    public int reduceValuesToInt(long parallelismThreshold,
3995 >                                 ToIntFunction<? super V> transformer,
3996 >                                 int basis,
3997 >                                 IntBinaryOperator reducer) {
3998          if (transformer == null || reducer == null)
3999              throw new NullPointerException();
4000 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4001 <        int r = basis; V v;
4002 <        while ((v = it.advanceValue()) != null)
3903 <            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3904 <        return r;
4000 >        return new MapReduceValuesToIntTask<K,V>
4001 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4002 >             null, transformer, basis, reducer).invoke();
4003      }
4004  
4005      /**
4006       * Performs the given action for each entry.
4007       *
4008 +     * @param parallelismThreshold the (estimated) number of elements
4009 +     * needed for this operation to be executed in parallel
4010       * @param action the action
4011 +     * @since 1.8
4012       */
4013 <    public void forEachEntrySequentially
4014 <        (Consumer<? super Map.Entry<K,V>> action) {
4013 >    public void forEachEntry(long parallelismThreshold,
4014 >                             Consumer<? super Map.Entry<K,V>> action) {
4015          if (action == null) throw new NullPointerException();
4016 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4017 <        V v;
3917 <        while ((v = it.advanceValue()) != null)
3918 <            action.accept(entryFor(it.nextKey, v));
4016 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4017 >                                  action).invoke();
4018      }
4019  
4020      /**
4021       * Performs the given action for each non-null transformation
4022       * of each entry.
4023       *
4024 +     * @param parallelismThreshold the (estimated) number of elements
4025 +     * needed for this operation to be executed in parallel
4026       * @param transformer a function returning the transformation
4027       * for an element, or null if there is no transformation (in
4028       * which case the action is not applied)
4029       * @param action the action
4030 +     * @since 1.8
4031       */
4032 <    public <U> void forEachEntrySequentially
4033 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4034 <         Consumer<? super U> action) {
4032 >    public <U> void forEachEntry(long parallelismThreshold,
4033 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4034 >                                 Consumer<? super U> action) {
4035          if (transformer == null || action == null)
4036              throw new NullPointerException();
4037 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4038 <        V v; U u;
4039 <        while ((v = it.advanceValue()) != null) {
3938 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3939 <                action.accept(u);
3940 <        }
4037 >        new ForEachTransformedEntryTask<K,V,U>
4038 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4039 >             transformer, action).invoke();
4040      }
4041  
4042      /**
4043       * Returns a non-null result from applying the given search
4044 <     * function on each entry, or null if none.
4044 >     * function on each entry, or null if none.  Upon success,
4045 >     * further element processing is suppressed and the results of
4046 >     * any other parallel invocations of the search function are
4047 >     * ignored.
4048       *
4049 +     * @param parallelismThreshold the (estimated) number of elements
4050 +     * needed for this operation to be executed in parallel
4051       * @param searchFunction a function returning a non-null
4052       * result on success, else null
4053       * @return a non-null result from applying the given search
4054       * function on each entry, or null if none
4055 +     * @since 1.8
4056       */
4057 <    public <U> U searchEntriesSequentially
4058 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4057 >    public <U> U searchEntries(long parallelismThreshold,
4058 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4059          if (searchFunction == null) throw new NullPointerException();
4060 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4061 <        V v; U u;
4062 <        while ((v = it.advanceValue()) != null) {
3958 <            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3959 <                return u;
3960 <        }
3961 <        return null;
4060 >        return new SearchEntriesTask<K,V,U>
4061 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4062 >             searchFunction, new AtomicReference<U>()).invoke();
4063      }
4064  
4065      /**
4066       * Returns the result of accumulating all entries using the
4067       * given reducer to combine values, or null if none.
4068       *
4069 +     * @param parallelismThreshold the (estimated) number of elements
4070 +     * needed for this operation to be executed in parallel
4071       * @param reducer a commutative associative combining function
4072       * @return the result of accumulating all entries
4073 +     * @since 1.8
4074       */
4075 <    public Map.Entry<K,V> reduceEntriesSequentially
4076 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4075 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4076 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4077          if (reducer == null) throw new NullPointerException();
4078 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4079 <        Map.Entry<K,V> r = null; V v;
4080 <        while ((v = it.advanceValue()) != null) {
3977 <            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3978 <            r = (r == null) ? u : reducer.apply(r, u);
3979 <        }
3980 <        return r;
4078 >        return new ReduceEntriesTask<K,V>
4079 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4080 >             null, reducer).invoke();
4081      }
4082  
4083      /**
# Line 3985 | Line 4085 | public class ConcurrentHashMap<K,V>
4085       * of all entries using the given reducer to combine values,
4086       * or null if none.
4087       *
4088 +     * @param parallelismThreshold the (estimated) number of elements
4089 +     * needed for this operation to be executed in parallel
4090       * @param transformer a function returning the transformation
4091       * for an element, or null if there is no transformation (in
4092       * which case it is not combined)
4093       * @param reducer a commutative associative combining function
4094       * @return the result of accumulating the given transformation
4095       * of all entries
4096 +     * @since 1.8
4097       */
4098 <    public <U> U reduceEntriesSequentially
4099 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4100 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4098 >    public <U> U reduceEntries(long parallelismThreshold,
4099 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4100 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4101          if (transformer == null || reducer == null)
4102              throw new NullPointerException();
4103 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4104 <        U r = null, u; V v;
4105 <        while ((v = it.advanceValue()) != null) {
4003 <            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
4004 <                r = (r == null) ? u : reducer.apply(r, u);
4005 <        }
4006 <        return r;
4103 >        return new MapReduceEntriesTask<K,V,U>
4104 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4105 >             null, transformer, reducer).invoke();
4106      }
4107  
4108      /**
# Line 4011 | Line 4110 | public class ConcurrentHashMap<K,V>
4110       * of all entries using the given reducer to combine values,
4111       * and the given basis as an identity value.
4112       *
4113 +     * @param parallelismThreshold the (estimated) number of elements
4114 +     * needed for this operation to be executed in parallel
4115       * @param transformer a function returning the transformation
4116       * for an element
4117       * @param basis the identity (initial default value) for the reduction
4118       * @param reducer a commutative associative combining function
4119       * @return the result of accumulating the given transformation
4120       * of all entries
4121 +     * @since 1.8
4122       */
4123 <    public double reduceEntriesToDoubleSequentially
4124 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4125 <         double basis,
4126 <         DoubleBinaryOperator reducer) {
4123 >    public double reduceEntriesToDouble(long parallelismThreshold,
4124 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4125 >                                        double basis,
4126 >                                        DoubleBinaryOperator reducer) {
4127          if (transformer == null || reducer == null)
4128              throw new NullPointerException();
4129 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4130 <        double r = basis; V v;
4131 <        while ((v = it.advanceValue()) != null)
4030 <            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
4031 <        return r;
4129 >        return new MapReduceEntriesToDoubleTask<K,V>
4130 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4131 >             null, transformer, basis, reducer).invoke();
4132      }
4133  
4134      /**
# Line 4036 | Line 4136 | public class ConcurrentHashMap<K,V>
4136       * of all entries using the given reducer to combine values,
4137       * and the given basis as an identity value.
4138       *
4139 +     * @param parallelismThreshold the (estimated) number of elements
4140 +     * needed for this operation to be executed in parallel
4141       * @param transformer a function returning the transformation
4142       * for an element
4143       * @param basis the identity (initial default value) for the reduction
4144       * @param reducer a commutative associative combining function
4145       * @return the result of accumulating the given transformation
4146       * of all entries
4147 +     * @since 1.8
4148       */
4149 <    public long reduceEntriesToLongSequentially
4150 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4151 <         long basis,
4152 <         LongBinaryOperator reducer) {
4149 >    public long reduceEntriesToLong(long parallelismThreshold,
4150 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4151 >                                    long basis,
4152 >                                    LongBinaryOperator reducer) {
4153          if (transformer == null || reducer == null)
4154              throw new NullPointerException();
4155 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4156 <        long r = basis; V v;
4157 <        while ((v = it.advanceValue()) != null)
4055 <            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
4056 <        return r;
4155 >        return new MapReduceEntriesToLongTask<K,V>
4156 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4157 >             null, transformer, basis, reducer).invoke();
4158      }
4159  
4160      /**
# Line 4061 | Line 4162 | public class ConcurrentHashMap<K,V>
4162       * of all entries using the given reducer to combine values,
4163       * and the given basis as an identity value.
4164       *
4165 +     * @param parallelismThreshold the (estimated) number of elements
4166 +     * needed for this operation to be executed in parallel
4167       * @param transformer a function returning the transformation
4168       * for an element
4169       * @param basis the identity (initial default value) for the reduction
4170       * @param reducer a commutative associative combining function
4171       * @return the result of accumulating the given transformation
4172       * of all entries
4173 +     * @since 1.8
4174       */
4175 <    public int reduceEntriesToIntSequentially
4176 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4177 <         int basis,
4178 <         IntBinaryOperator reducer) {
4175 >    public int reduceEntriesToInt(long parallelismThreshold,
4176 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4177 >                                  int basis,
4178 >                                  IntBinaryOperator reducer) {
4179          if (transformer == null || reducer == null)
4180              throw new NullPointerException();
4181 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4182 <        int r = basis; V v;
4183 <        while ((v = it.advanceValue()) != null)
4080 <            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
4081 <        return r;
4082 <    }
4083 <
4084 <    // Parallel bulk operations
4085 <
4086 <    /**
4087 <     * Performs the given action for each (key, value).
4088 <     *
4089 <     * @param action the action
4090 <     */
4091 <    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
4092 <        ForkJoinTasks.forEach
4093 <            (this, action).invoke();
4094 <    }
4095 <
4096 <    /**
4097 <     * Performs the given action for each non-null transformation
4098 <     * of each (key, value).
4099 <     *
4100 <     * @param transformer a function returning the transformation
4101 <     * for an element, or null if there is no transformation (in
4102 <     * which case the action is not applied)
4103 <     * @param action the action
4104 <     */
4105 <    public <U> void forEachInParallel
4106 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4107 <                            Consumer<? super U> action) {
4108 <        ForkJoinTasks.forEach
4109 <            (this, transformer, action).invoke();
4110 <    }
4111 <
4112 <    /**
4113 <     * Returns a non-null result from applying the given search
4114 <     * function on each (key, value), or null if none.  Upon
4115 <     * success, further element processing is suppressed and the
4116 <     * results of any other parallel invocations of the search
4117 <     * function are ignored.
4118 <     *
4119 <     * @param searchFunction a function returning a non-null
4120 <     * result on success, else null
4121 <     * @return a non-null result from applying the given search
4122 <     * function on each (key, value), or null if none
4123 <     */
4124 <    public <U> U searchInParallel
4125 <        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4126 <        return ForkJoinTasks.search
4127 <            (this, searchFunction).invoke();
4128 <    }
4129 <
4130 <    /**
4131 <     * Returns the result of accumulating the given transformation
4132 <     * of all (key, value) pairs using the given reducer to
4133 <     * combine values, or null if none.
4134 <     *
4135 <     * @param transformer a function returning the transformation
4136 <     * for an element, or null if there is no transformation (in
4137 <     * which case it is not combined)
4138 <     * @param reducer a commutative associative combining function
4139 <     * @return the result of accumulating the given transformation
4140 <     * of all (key, value) pairs
4141 <     */
4142 <    public <U> U reduceInParallel
4143 <        (BiFunction<? super K, ? super V, ? extends U> transformer,
4144 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4145 <        return ForkJoinTasks.reduce
4146 <            (this, transformer, reducer).invoke();
4147 <    }
4148 <
4149 <    /**
4150 <     * Returns the result of accumulating the given transformation
4151 <     * of all (key, value) pairs using the given reducer to
4152 <     * combine values, and the given basis as an identity value.
4153 <     *
4154 <     * @param transformer a function returning the transformation
4155 <     * for an element
4156 <     * @param basis the identity (initial default value) for the reduction
4157 <     * @param reducer a commutative associative combining function
4158 <     * @return the result of accumulating the given transformation
4159 <     * of all (key, value) pairs
4160 <     */
4161 <    public double reduceToDoubleInParallel
4162 <        (ToDoubleBiFunction<? super K, ? super V> transformer,
4163 <         double basis,
4164 <         DoubleBinaryOperator reducer) {
4165 <        return ForkJoinTasks.reduceToDouble
4166 <            (this, transformer, basis, reducer).invoke();
4167 <    }
4168 <
4169 <    /**
4170 <     * Returns the result of accumulating the given transformation
4171 <     * of all (key, value) pairs using the given reducer to
4172 <     * combine values, and the given basis as an identity value.
4173 <     *
4174 <     * @param transformer a function returning the transformation
4175 <     * for an element
4176 <     * @param basis the identity (initial default value) for the reduction
4177 <     * @param reducer a commutative associative combining function
4178 <     * @return the result of accumulating the given transformation
4179 <     * of all (key, value) pairs
4180 <     */
4181 <    public long reduceToLongInParallel
4182 <        (ToLongBiFunction<? super K, ? super V> transformer,
4183 <         long basis,
4184 <         LongBinaryOperator reducer) {
4185 <        return ForkJoinTasks.reduceToLong
4186 <            (this, transformer, basis, reducer).invoke();
4187 <    }
4188 <
4189 <    /**
4190 <     * Returns the result of accumulating the given transformation
4191 <     * of all (key, value) pairs using the given reducer to
4192 <     * combine values, and the given basis as an identity value.
4193 <     *
4194 <     * @param transformer a function returning the transformation
4195 <     * for an element
4196 <     * @param basis the identity (initial default value) for the reduction
4197 <     * @param reducer a commutative associative combining function
4198 <     * @return the result of accumulating the given transformation
4199 <     * of all (key, value) pairs
4200 <     */
4201 <    public int reduceToIntInParallel
4202 <        (ToIntBiFunction<? super K, ? super V> transformer,
4203 <         int basis,
4204 <         IntBinaryOperator reducer) {
4205 <        return ForkJoinTasks.reduceToInt
4206 <            (this, transformer, basis, reducer).invoke();
4207 <    }
4208 <
4209 <    /**
4210 <     * Performs the given action for each key.
4211 <     *
4212 <     * @param action the action
4213 <     */
4214 <    public void forEachKeyInParallel(Consumer<? super K> action) {
4215 <        ForkJoinTasks.forEachKey
4216 <            (this, action).invoke();
4217 <    }
4218 <
4219 <    /**
4220 <     * Performs the given action for each non-null transformation
4221 <     * of each key.
4222 <     *
4223 <     * @param transformer a function returning the transformation
4224 <     * for an element, or null if there is no transformation (in
4225 <     * which case the action is not applied)
4226 <     * @param action the action
4227 <     */
4228 <    public <U> void forEachKeyInParallel
4229 <        (Function<? super K, ? extends U> transformer,
4230 <         Consumer<? super U> action) {
4231 <        ForkJoinTasks.forEachKey
4232 <            (this, transformer, action).invoke();
4233 <    }
4234 <
4235 <    /**
4236 <     * Returns a non-null result from applying the given search
4237 <     * function on each key, or null if none. Upon success,
4238 <     * further element processing is suppressed and the results of
4239 <     * any other parallel invocations of the search function are
4240 <     * ignored.
4241 <     *
4242 <     * @param searchFunction a function returning a non-null
4243 <     * result on success, else null
4244 <     * @return a non-null result from applying the given search
4245 <     * function on each key, or null if none
4246 <     */
4247 <    public <U> U searchKeysInParallel
4248 <        (Function<? super K, ? extends U> searchFunction) {
4249 <        return ForkJoinTasks.searchKeys
4250 <            (this, searchFunction).invoke();
4251 <    }
4252 <
4253 <    /**
4254 <     * Returns the result of accumulating all keys using the given
4255 <     * reducer to combine values, or null if none.
4256 <     *
4257 <     * @param reducer a commutative associative combining function
4258 <     * @return the result of accumulating all keys using the given
4259 <     * reducer to combine values, or null if none
4260 <     */
4261 <    public K reduceKeysInParallel
4262 <        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4263 <        return ForkJoinTasks.reduceKeys
4264 <            (this, reducer).invoke();
4265 <    }
4266 <
4267 <    /**
4268 <     * Returns the result of accumulating the given transformation
4269 <     * of all keys using the given reducer to combine values, or
4270 <     * null if none.
4271 <     *
4272 <     * @param transformer a function returning the transformation
4273 <     * for an element, or null if there is no transformation (in
4274 <     * which case it is not combined)
4275 <     * @param reducer a commutative associative combining function
4276 <     * @return the result of accumulating the given transformation
4277 <     * of all keys
4278 <     */
4279 <    public <U> U reduceKeysInParallel
4280 <        (Function<? super K, ? extends U> transformer,
4281 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4282 <        return ForkJoinTasks.reduceKeys
4283 <            (this, transformer, reducer).invoke();
4284 <    }
4285 <
4286 <    /**
4287 <     * Returns the result of accumulating the given transformation
4288 <     * of all keys using the given reducer to combine values, and
4289 <     * the given basis as an identity value.
4290 <     *
4291 <     * @param transformer a function returning the transformation
4292 <     * for an element
4293 <     * @param basis the identity (initial default value) for the reduction
4294 <     * @param reducer a commutative associative combining function
4295 <     * @return the result of accumulating the given transformation
4296 <     * of all keys
4297 <     */
4298 <    public double reduceKeysToDoubleInParallel
4299 <        (ToDoubleFunction<? super K> transformer,
4300 <         double basis,
4301 <         DoubleBinaryOperator reducer) {
4302 <        return ForkJoinTasks.reduceKeysToDouble
4303 <            (this, transformer, basis, reducer).invoke();
4304 <    }
4305 <
4306 <    /**
4307 <     * Returns the result of accumulating the given transformation
4308 <     * of all keys using the given reducer to combine values, and
4309 <     * the given basis as an identity value.
4310 <     *
4311 <     * @param transformer a function returning the transformation
4312 <     * for an element
4313 <     * @param basis the identity (initial default value) for the reduction
4314 <     * @param reducer a commutative associative combining function
4315 <     * @return the result of accumulating the given transformation
4316 <     * of all keys
4317 <     */
4318 <    public long reduceKeysToLongInParallel
4319 <        (ToLongFunction<? super K> transformer,
4320 <         long basis,
4321 <         LongBinaryOperator reducer) {
4322 <        return ForkJoinTasks.reduceKeysToLong
4323 <            (this, transformer, basis, reducer).invoke();
4324 <    }
4325 <
4326 <    /**
4327 <     * Returns the result of accumulating the given transformation
4328 <     * of all keys using the given reducer to combine values, and
4329 <     * the given basis as an identity value.
4330 <     *
4331 <     * @param transformer a function returning the transformation
4332 <     * for an element
4333 <     * @param basis the identity (initial default value) for the reduction
4334 <     * @param reducer a commutative associative combining function
4335 <     * @return the result of accumulating the given transformation
4336 <     * of all keys
4337 <     */
4338 <    public int reduceKeysToIntInParallel
4339 <        (ToIntFunction<? super K> transformer,
4340 <         int basis,
4341 <         IntBinaryOperator reducer) {
4342 <        return ForkJoinTasks.reduceKeysToInt
4343 <            (this, transformer, basis, reducer).invoke();
4344 <    }
4345 <
4346 <    /**
4347 <     * Performs the given action for each value.
4348 <     *
4349 <     * @param action the action
4350 <     */
4351 <    public void forEachValueInParallel(Consumer<? super V> action) {
4352 <        ForkJoinTasks.forEachValue
4353 <            (this, action).invoke();
4354 <    }
4355 <
4356 <    /**
4357 <     * Performs the given action for each non-null transformation
4358 <     * of each value.
4359 <     *
4360 <     * @param transformer a function returning the transformation
4361 <     * for an element, or null if there is no transformation (in
4362 <     * which case the action is not applied)
4363 <     * @param action the action
4364 <     */
4365 <    public <U> void forEachValueInParallel
4366 <        (Function<? super V, ? extends U> transformer,
4367 <         Consumer<? super U> action) {
4368 <        ForkJoinTasks.forEachValue
4369 <            (this, transformer, action).invoke();
4370 <    }
4371 <
4372 <    /**
4373 <     * Returns a non-null result from applying the given search
4374 <     * function on each value, or null if none.  Upon success,
4375 <     * further element processing is suppressed and the results of
4376 <     * any other parallel invocations of the search function are
4377 <     * ignored.
4378 <     *
4379 <     * @param searchFunction a function returning a non-null
4380 <     * result on success, else null
4381 <     * @return a non-null result from applying the given search
4382 <     * function on each value, or null if none
4383 <     */
4384 <    public <U> U searchValuesInParallel
4385 <        (Function<? super V, ? extends U> searchFunction) {
4386 <        return ForkJoinTasks.searchValues
4387 <            (this, searchFunction).invoke();
4388 <    }
4389 <
4390 <    /**
4391 <     * Returns the result of accumulating all values using the
4392 <     * given reducer to combine values, or null if none.
4393 <     *
4394 <     * @param reducer a commutative associative combining function
4395 <     * @return the result of accumulating all values
4396 <     */
4397 <    public V reduceValuesInParallel
4398 <        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4399 <        return ForkJoinTasks.reduceValues
4400 <            (this, reducer).invoke();
4401 <    }
4402 <
4403 <    /**
4404 <     * Returns the result of accumulating the given transformation
4405 <     * of all values using the given reducer to combine values, or
4406 <     * null if none.
4407 <     *
4408 <     * @param transformer a function returning the transformation
4409 <     * for an element, or null if there is no transformation (in
4410 <     * which case it is not combined)
4411 <     * @param reducer a commutative associative combining function
4412 <     * @return the result of accumulating the given transformation
4413 <     * of all values
4414 <     */
4415 <    public <U> U reduceValuesInParallel
4416 <        (Function<? super V, ? extends U> transformer,
4417 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4418 <        return ForkJoinTasks.reduceValues
4419 <            (this, transformer, reducer).invoke();
4420 <    }
4421 <
4422 <    /**
4423 <     * Returns the result of accumulating the given transformation
4424 <     * of all values using the given reducer to combine values,
4425 <     * and the given basis as an identity value.
4426 <     *
4427 <     * @param transformer a function returning the transformation
4428 <     * for an element
4429 <     * @param basis the identity (initial default value) for the reduction
4430 <     * @param reducer a commutative associative combining function
4431 <     * @return the result of accumulating the given transformation
4432 <     * of all values
4433 <     */
4434 <    public double reduceValuesToDoubleInParallel
4435 <        (ToDoubleFunction<? super V> transformer,
4436 <         double basis,
4437 <         DoubleBinaryOperator reducer) {
4438 <        return ForkJoinTasks.reduceValuesToDouble
4439 <            (this, transformer, basis, reducer).invoke();
4440 <    }
4441 <
4442 <    /**
4443 <     * Returns the result of accumulating the given transformation
4444 <     * of all values using the given reducer to combine values,
4445 <     * and the given basis as an identity value.
4446 <     *
4447 <     * @param transformer a function returning the transformation
4448 <     * for an element
4449 <     * @param basis the identity (initial default value) for the reduction
4450 <     * @param reducer a commutative associative combining function
4451 <     * @return the result of accumulating the given transformation
4452 <     * of all values
4453 <     */
4454 <    public long reduceValuesToLongInParallel
4455 <        (ToLongFunction<? super V> transformer,
4456 <         long basis,
4457 <         LongBinaryOperator reducer) {
4458 <        return ForkJoinTasks.reduceValuesToLong
4459 <            (this, transformer, basis, reducer).invoke();
4460 <    }
4461 <
4462 <    /**
4463 <     * Returns the result of accumulating the given transformation
4464 <     * of all values using the given reducer to combine values,
4465 <     * and the given basis as an identity value.
4466 <     *
4467 <     * @param transformer a function returning the transformation
4468 <     * for an element
4469 <     * @param basis the identity (initial default value) for the reduction
4470 <     * @param reducer a commutative associative combining function
4471 <     * @return the result of accumulating the given transformation
4472 <     * of all values
4473 <     */
4474 <    public int reduceValuesToIntInParallel
4475 <        (ToIntFunction<? super V> transformer,
4476 <         int basis,
4477 <         IntBinaryOperator reducer) {
4478 <        return ForkJoinTasks.reduceValuesToInt
4479 <            (this, transformer, basis, reducer).invoke();
4480 <    }
4481 <
4482 <    /**
4483 <     * Performs the given action for each entry.
4484 <     *
4485 <     * @param action the action
4486 <     */
4487 <    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4488 <        ForkJoinTasks.forEachEntry
4489 <            (this, action).invoke();
4490 <    }
4491 <
4492 <    /**
4493 <     * Performs the given action for each non-null transformation
4494 <     * of each entry.
4495 <     *
4496 <     * @param transformer a function returning the transformation
4497 <     * for an element, or null if there is no transformation (in
4498 <     * which case the action is not applied)
4499 <     * @param action the action
4500 <     */
4501 <    public <U> void forEachEntryInParallel
4502 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4503 <         Consumer<? super U> action) {
4504 <        ForkJoinTasks.forEachEntry
4505 <            (this, transformer, action).invoke();
4506 <    }
4507 <
4508 <    /**
4509 <     * Returns a non-null result from applying the given search
4510 <     * function on each entry, or null if none.  Upon success,
4511 <     * further element processing is suppressed and the results of
4512 <     * any other parallel invocations of the search function are
4513 <     * ignored.
4514 <     *
4515 <     * @param searchFunction a function returning a non-null
4516 <     * result on success, else null
4517 <     * @return a non-null result from applying the given search
4518 <     * function on each entry, or null if none
4519 <     */
4520 <    public <U> U searchEntriesInParallel
4521 <        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4522 <        return ForkJoinTasks.searchEntries
4523 <            (this, searchFunction).invoke();
4524 <    }
4525 <
4526 <    /**
4527 <     * Returns the result of accumulating all entries using the
4528 <     * given reducer to combine values, or null if none.
4529 <     *
4530 <     * @param reducer a commutative associative combining function
4531 <     * @return the result of accumulating all entries
4532 <     */
4533 <    public Map.Entry<K,V> reduceEntriesInParallel
4534 <        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4535 <        return ForkJoinTasks.reduceEntries
4536 <            (this, reducer).invoke();
4537 <    }
4538 <
4539 <    /**
4540 <     * Returns the result of accumulating the given transformation
4541 <     * of all entries using the given reducer to combine values,
4542 <     * or null if none.
4543 <     *
4544 <     * @param transformer a function returning the transformation
4545 <     * for an element, or null if there is no transformation (in
4546 <     * which case it is not combined)
4547 <     * @param reducer a commutative associative combining function
4548 <     * @return the result of accumulating the given transformation
4549 <     * of all entries
4550 <     */
4551 <    public <U> U reduceEntriesInParallel
4552 <        (Function<Map.Entry<K,V>, ? extends U> transformer,
4553 <         BiFunction<? super U, ? super U, ? extends U> reducer) {
4554 <        return ForkJoinTasks.reduceEntries
4555 <            (this, transformer, reducer).invoke();
4556 <    }
4557 <
4558 <    /**
4559 <     * Returns the result of accumulating the given transformation
4560 <     * of all entries using the given reducer to combine values,
4561 <     * and the given basis as an identity value.
4562 <     *
4563 <     * @param transformer a function returning the transformation
4564 <     * for an element
4565 <     * @param basis the identity (initial default value) for the reduction
4566 <     * @param reducer a commutative associative combining function
4567 <     * @return the result of accumulating the given transformation
4568 <     * of all entries
4569 <     */
4570 <    public double reduceEntriesToDoubleInParallel
4571 <        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4572 <         double basis,
4573 <         DoubleBinaryOperator reducer) {
4574 <        return ForkJoinTasks.reduceEntriesToDouble
4575 <            (this, transformer, basis, reducer).invoke();
4576 <    }
4577 <
4578 <    /**
4579 <     * Returns the result of accumulating the given transformation
4580 <     * of all entries using the given reducer to combine values,
4581 <     * and the given basis as an identity value.
4582 <     *
4583 <     * @param transformer a function returning the transformation
4584 <     * for an element
4585 <     * @param basis the identity (initial default value) for the reduction
4586 <     * @param reducer a commutative associative combining function
4587 <     * @return the result of accumulating the given transformation
4588 <     * of all entries
4589 <     */
4590 <    public long reduceEntriesToLongInParallel
4591 <        (ToLongFunction<Map.Entry<K,V>> transformer,
4592 <         long basis,
4593 <         LongBinaryOperator reducer) {
4594 <        return ForkJoinTasks.reduceEntriesToLong
4595 <            (this, transformer, basis, reducer).invoke();
4596 <    }
4597 <
4598 <    /**
4599 <     * Returns the result of accumulating the given transformation
4600 <     * of all entries using the given reducer to combine values,
4601 <     * and the given basis as an identity value.
4602 <     *
4603 <     * @param transformer a function returning the transformation
4604 <     * for an element
4605 <     * @param basis the identity (initial default value) for the reduction
4606 <     * @param reducer a commutative associative combining function
4607 <     * @return the result of accumulating the given transformation
4608 <     * of all entries
4609 <     */
4610 <    public int reduceEntriesToIntInParallel
4611 <        (ToIntFunction<Map.Entry<K,V>> transformer,
4612 <         int basis,
4613 <         IntBinaryOperator reducer) {
4614 <        return ForkJoinTasks.reduceEntriesToInt
4615 <            (this, transformer, basis, reducer).invoke();
4181 >        return new MapReduceEntriesToIntTask<K,V>
4182 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4183 >             null, transformer, basis, reducer).invoke();
4184      }
4185  
4186  
# Line 4621 | Line 4189 | public class ConcurrentHashMap<K,V>
4189      /**
4190       * Base class for views.
4191       */
4192 <    abstract static class CHMCollectionView<K,V,E>
4193 <            implements Collection<E>, java.io.Serializable {
4192 >    abstract static class CollectionView<K,V,E>
4193 >        implements Collection<E>, java.io.Serializable {
4194          private static final long serialVersionUID = 7249069246763182397L;
4195          final ConcurrentHashMap<K,V> map;
4196 <        CHMCollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4196 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4197  
4198          /**
4199           * Returns the map backing this view.
# Line 4771 | Line 4339 | public class ConcurrentHashMap<K,V>
4339  
4340      }
4341  
4774    abstract static class CHMSetView<K,V,E>
4775            extends CHMCollectionView<K,V,E>
4776            implements Set<E>, java.io.Serializable {
4777        private static final long serialVersionUID = 7249069246763182397L;
4778        CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4779
4780        // Implement Set API
4781
4782        /**
4783         * Implements {@link Set#hashCode()}.
4784         * @return the hash code value for this set
4785         */
4786        public final int hashCode() {
4787            int h = 0;
4788            for (E e : this)
4789                h += e.hashCode();
4790            return h;
4791        }
4792
4793        /**
4794         * Implements {@link Set#equals(Object)}.
4795         * @param o object to be compared for equality with this set
4796         * @return {@code true} if the specified object is equal to this set
4797        */
4798        public final boolean equals(Object o) {
4799            Set<?> c;
4800            return ((o instanceof Set) &&
4801                    ((c = (Set<?>)o) == this ||
4802                     (containsAll(c) && c.containsAll(this))));
4803        }
4804    }
4805
4342      /**
4343       * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4344       * which additions may optionally be enabled by mapping to a
# Line 4811 | Line 4347 | public class ConcurrentHashMap<K,V>
4347       * {@link #keySet(Object) keySet(V)},
4348       * {@link #newKeySet() newKeySet()},
4349       * {@link #newKeySet(int) newKeySet(int)}.
4350 +     *
4351 +     * @since 1.8
4352       */
4353 <    public static class KeySetView<K,V>
4354 <            extends CHMSetView<K,V,K>
4817 <            implements Set<K>, java.io.Serializable {
4353 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4354 >        implements Set<K>, java.io.Serializable {
4355          private static final long serialVersionUID = 7249069246763182397L;
4356          private final V value;
4357          KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
# Line 4851 | Line 4388 | public class ConcurrentHashMap<K,V>
4388          /**
4389           * @return an iterator over the keys of the backing map
4390           */
4391 <        public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4391 >        public Iterator<K> iterator() {
4392 >            Node<K,V>[] t;
4393 >            ConcurrentHashMap<K,V> m = map;
4394 >            int f = (t = m.table) == null ? 0 : t.length;
4395 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4396 >        }
4397  
4398          /**
4399           * Adds the specified key to this set view by mapping the key to
# Line 4867 | Line 4409 | public class ConcurrentHashMap<K,V>
4409              V v;
4410              if ((v = value) == null)
4411                  throw new UnsupportedOperationException();
4412 <            return map.internalPut(e, v, true) == null;
4412 >            return map.putVal(e, v, true) == null;
4413          }
4414  
4415          /**
# Line 4887 | Line 4429 | public class ConcurrentHashMap<K,V>
4429              if ((v = value) == null)
4430                  throw new UnsupportedOperationException();
4431              for (K e : c) {
4432 <                if (map.internalPut(e, v, true) == null)
4432 >                if (map.putVal(e, v, true) == null)
4433                      added = true;
4434              }
4435              return added;
4436          }
4437  
4438 +        public int hashCode() {
4439 +            int h = 0;
4440 +            for (K e : this)
4441 +                h += e.hashCode();
4442 +            return h;
4443 +        }
4444 +
4445 +        public boolean equals(Object o) {
4446 +            Set<?> c;
4447 +            return ((o instanceof Set) &&
4448 +                    ((c = (Set<?>)o) == this ||
4449 +                     (containsAll(c) && c.containsAll(this))));
4450 +        }
4451 +
4452          public Spliterator<K> spliterator() {
4453 <            return new KeyIterator<>(map, null);
4453 >            Node<K,V>[] t;
4454 >            ConcurrentHashMap<K,V> m = map;
4455 >            long n = m.sumCount();
4456 >            int f = (t = m.table) == null ? 0 : t.length;
4457 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4458          }
4459  
4460 +        public void forEach(Consumer<? super K> action) {
4461 +            if (action == null) throw new NullPointerException();
4462 +            Node<K,V>[] t;
4463 +            if ((t = map.table) != null) {
4464 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4465 +                for (Node<K,V> p; (p = it.advance()) != null; )
4466 +                    action.accept(p.key);
4467 +            }
4468 +        }
4469      }
4470  
4471      /**
4472       * A view of a ConcurrentHashMap as a {@link Collection} of
4473       * values, in which additions are disabled. This class cannot be
4474       * directly instantiated. See {@link #values()}.
4906     *
4907     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4908     * that will never throw {@link ConcurrentModificationException},
4909     * and guarantees to traverse elements as they existed upon
4910     * construction of the iterator, and may (but is not guaranteed to)
4911     * reflect any modifications subsequent to construction.
4475       */
4476 <    public static final class ValuesView<K,V>
4477 <            extends CHMCollectionView<K,V,V>
4915 <            implements Collection<V>, java.io.Serializable {
4476 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4477 >        implements Collection<V>, java.io.Serializable {
4478          private static final long serialVersionUID = 2249069246763182397L;
4479          ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4480          public final boolean contains(Object o) {
4481              return map.containsValue(o);
4482          }
4483 +
4484          public final boolean remove(Object o) {
4485              if (o != null) {
4486                  for (Iterator<V> it = iterator(); it.hasNext();) {
# Line 4930 | Line 4493 | public class ConcurrentHashMap<K,V>
4493              return false;
4494          }
4495  
4933        /**
4934         * @return an iterator over the values of the backing map
4935         */
4496          public final Iterator<V> iterator() {
4497 <            return new ValueIterator<K,V>(map);
4497 >            ConcurrentHashMap<K,V> m = map;
4498 >            Node<K,V>[] t;
4499 >            int f = (t = m.table) == null ? 0 : t.length;
4500 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4501          }
4502  
4940        /** Always throws {@link UnsupportedOperationException}. */
4503          public final boolean add(V e) {
4504              throw new UnsupportedOperationException();
4505          }
4944        /** Always throws {@link UnsupportedOperationException}. */
4506          public final boolean addAll(Collection<? extends V> c) {
4507              throw new UnsupportedOperationException();
4508          }
4509  
4510          public Spliterator<V> spliterator() {
4511 <            return new ValueIterator<K,V>(map, null);
4511 >            Node<K,V>[] t;
4512 >            ConcurrentHashMap<K,V> m = map;
4513 >            long n = m.sumCount();
4514 >            int f = (t = m.table) == null ? 0 : t.length;
4515 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4516          }
4517  
4518 +        public void forEach(Consumer<? super V> action) {
4519 +            if (action == null) throw new NullPointerException();
4520 +            Node<K,V>[] t;
4521 +            if ((t = map.table) != null) {
4522 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4523 +                for (Node<K,V> p; (p = it.advance()) != null; )
4524 +                    action.accept(p.val);
4525 +            }
4526 +        }
4527      }
4528  
4529      /**
# Line 4957 | Line 4531 | public class ConcurrentHashMap<K,V>
4531       * entries.  This class cannot be directly instantiated. See
4532       * {@link #entrySet()}.
4533       */
4534 <    public static final class EntrySetView<K,V>
4535 <            extends CHMSetView<K,V,Map.Entry<K,V>>
4962 <            implements Set<Map.Entry<K,V>>, java.io.Serializable {
4534 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4535 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4536          private static final long serialVersionUID = 2249069246763182397L;
4537          EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4538  
4539 <        public final boolean contains(Object o) {
4539 >        public boolean contains(Object o) {
4540              Object k, v, r; Map.Entry<?,?> e;
4541              return ((o instanceof Map.Entry) &&
4542                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4971 | Line 4544 | public class ConcurrentHashMap<K,V>
4544                      (v = e.getValue()) != null &&
4545                      (v == r || v.equals(r)));
4546          }
4547 <        public final boolean remove(Object o) {
4547 >
4548 >        public boolean remove(Object o) {
4549              Object k, v; Map.Entry<?,?> e;
4550              return ((o instanceof Map.Entry) &&
4551                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4982 | Line 4556 | public class ConcurrentHashMap<K,V>
4556          /**
4557           * @return an iterator over the entries of the backing map
4558           */
4559 <        public final Iterator<Map.Entry<K,V>> iterator() {
4560 <            return new EntryIterator<K,V>(map);
4559 >        public Iterator<Map.Entry<K,V>> iterator() {
4560 >            ConcurrentHashMap<K,V> m = map;
4561 >            Node<K,V>[] t;
4562 >            int f = (t = m.table) == null ? 0 : t.length;
4563 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4564          }
4565  
4566 <        /**
4567 <         * Adds the specified mapping to this view.
4991 <         *
4992 <         * @param e mapping to be added
4993 <         * @return {@code true} if this set changed as a result of the call
4994 <         * @throws NullPointerException if the entry, its key, or its
4995 <         * value is null
4996 <         */
4997 <        public final boolean add(Entry<K,V> e) {
4998 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4566 >        public boolean add(Entry<K,V> e) {
4567 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4568          }
4569  
4570 <        /**
5002 <         * Adds all of the mappings in the specified collection to this
5003 <         * set, as if by calling {@link #add(Map.Entry)} on each one.
5004 <         * @param c the mappings to be inserted into this set
5005 <         * @return {@code true} if this set changed as a result of the call
5006 <         * @throws NullPointerException if the collection or any of its
5007 <         * entries, keys, or values are null
5008 <         */
5009 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4570 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4571              boolean added = false;
4572              for (Entry<K,V> e : c) {
4573                  if (add(e))
# Line 5015 | Line 4576 | public class ConcurrentHashMap<K,V>
4576              return added;
4577          }
4578  
4579 <        public Spliterator<Map.Entry<K,V>> spliterator() {
4580 <            return new EntryIterator<K,V>(map, null);
4581 <        }
4582 <
4583 <    }
4584 <
4585 <    // ---------------------------------------------------------------------
4586 <
4587 <    /**
4588 <     * Predefined tasks for performing bulk parallel operations on
5028 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
5029 <     * for bulk operations. Each method has the same name, but returns
5030 <     * a task rather than invoking it. These methods may be useful in
5031 <     * custom applications such as submitting a task without waiting
5032 <     * for completion, using a custom pool, or combining with other
5033 <     * tasks.
5034 <     */
5035 <    public static class ForkJoinTasks {
5036 <        private ForkJoinTasks() {}
5037 <
5038 <        /**
5039 <         * Returns a task that when invoked, performs the given
5040 <         * action for each (key, value)
5041 <         *
5042 <         * @param map the map
5043 <         * @param action the action
5044 <         * @return the task
5045 <         */
5046 <        public static <K,V> ForkJoinTask<Void> forEach
5047 <            (ConcurrentHashMap<K,V> map,
5048 <             BiConsumer<? super K, ? super V> action) {
5049 <            if (action == null) throw new NullPointerException();
5050 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
5051 <        }
5052 <
5053 <        /**
5054 <         * Returns a task that when invoked, performs the given
5055 <         * action for each non-null transformation of each (key, value)
5056 <         *
5057 <         * @param map the map
5058 <         * @param transformer a function returning the transformation
5059 <         * for an element, or null if there is no transformation (in
5060 <         * which case the action is not applied)
5061 <         * @param action the action
5062 <         * @return the task
5063 <         */
5064 <        public static <K,V,U> ForkJoinTask<Void> forEach
5065 <            (ConcurrentHashMap<K,V> map,
5066 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5067 <             Consumer<? super U> action) {
5068 <            if (transformer == null || action == null)
5069 <                throw new NullPointerException();
5070 <            return new ForEachTransformedMappingTask<K,V,U>
5071 <                (map, null, -1, transformer, action);
5072 <        }
5073 <
5074 <        /**
5075 <         * Returns a task that when invoked, returns a non-null result
5076 <         * from applying the given search function on each (key,
5077 <         * value), or null if none. Upon success, further element
5078 <         * processing is suppressed and the results of any other
5079 <         * parallel invocations of the search function are ignored.
5080 <         *
5081 <         * @param map the map
5082 <         * @param searchFunction a function returning a non-null
5083 <         * result on success, else null
5084 <         * @return the task
5085 <         */
5086 <        public static <K,V,U> ForkJoinTask<U> search
5087 <            (ConcurrentHashMap<K,V> map,
5088 <             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
5089 <            if (searchFunction == null) throw new NullPointerException();
5090 <            return new SearchMappingsTask<K,V,U>
5091 <                (map, null, -1, searchFunction,
5092 <                 new AtomicReference<U>());
5093 <        }
5094 <
5095 <        /**
5096 <         * Returns a task that when invoked, returns the result of
5097 <         * accumulating the given transformation of all (key, value) pairs
5098 <         * using the given reducer to combine values, or null if none.
5099 <         *
5100 <         * @param map the map
5101 <         * @param transformer a function returning the transformation
5102 <         * for an element, or null if there is no transformation (in
5103 <         * which case it is not combined)
5104 <         * @param reducer a commutative associative combining function
5105 <         * @return the task
5106 <         */
5107 <        public static <K,V,U> ForkJoinTask<U> reduce
5108 <            (ConcurrentHashMap<K,V> map,
5109 <             BiFunction<? super K, ? super V, ? extends U> transformer,
5110 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5111 <            if (transformer == null || reducer == null)
5112 <                throw new NullPointerException();
5113 <            return new MapReduceMappingsTask<K,V,U>
5114 <                (map, null, -1, null, transformer, reducer);
5115 <        }
5116 <
5117 <        /**
5118 <         * Returns a task that when invoked, returns the result of
5119 <         * accumulating the given transformation of all (key, value) pairs
5120 <         * using the given reducer to combine values, and the given
5121 <         * basis as an identity value.
5122 <         *
5123 <         * @param map the map
5124 <         * @param transformer a function returning the transformation
5125 <         * for an element
5126 <         * @param basis the identity (initial default value) for the reduction
5127 <         * @param reducer a commutative associative combining function
5128 <         * @return the task
5129 <         */
5130 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
5131 <            (ConcurrentHashMap<K,V> map,
5132 <             ToDoubleBiFunction<? super K, ? super V> transformer,
5133 <             double basis,
5134 <             DoubleBinaryOperator reducer) {
5135 <            if (transformer == null || reducer == null)
5136 <                throw new NullPointerException();
5137 <            return new MapReduceMappingsToDoubleTask<K,V>
5138 <                (map, null, -1, null, transformer, basis, reducer);
5139 <        }
5140 <
5141 <        /**
5142 <         * Returns a task that when invoked, returns the result of
5143 <         * accumulating the given transformation of all (key, value) pairs
5144 <         * using the given reducer to combine values, and the given
5145 <         * basis as an identity value.
5146 <         *
5147 <         * @param map the map
5148 <         * @param transformer a function returning the transformation
5149 <         * for an element
5150 <         * @param basis the identity (initial default value) for the reduction
5151 <         * @param reducer a commutative associative combining function
5152 <         * @return the task
5153 <         */
5154 <        public static <K,V> ForkJoinTask<Long> reduceToLong
5155 <            (ConcurrentHashMap<K,V> map,
5156 <             ToLongBiFunction<? super K, ? super V> transformer,
5157 <             long basis,
5158 <             LongBinaryOperator reducer) {
5159 <            if (transformer == null || reducer == null)
5160 <                throw new NullPointerException();
5161 <            return new MapReduceMappingsToLongTask<K,V>
5162 <                (map, null, -1, null, transformer, basis, reducer);
5163 <        }
5164 <
5165 <        /**
5166 <         * Returns a task that when invoked, returns the result of
5167 <         * accumulating the given transformation of all (key, value) pairs
5168 <         * using the given reducer to combine values, and the given
5169 <         * basis as an identity value.
5170 <         *
5171 <         * @param map the map
5172 <         * @param transformer a function returning the transformation
5173 <         * for an element
5174 <         * @param basis the identity (initial default value) for the reduction
5175 <         * @param reducer a commutative associative combining function
5176 <         * @return the task
5177 <         */
5178 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5179 <            (ConcurrentHashMap<K,V> map,
5180 <             ToIntBiFunction<? super K, ? super V> transformer,
5181 <             int basis,
5182 <             IntBinaryOperator reducer) {
5183 <            if (transformer == null || reducer == null)
5184 <                throw new NullPointerException();
5185 <            return new MapReduceMappingsToIntTask<K,V>
5186 <                (map, null, -1, null, transformer, basis, reducer);
5187 <        }
5188 <
5189 <        /**
5190 <         * Returns a task that when invoked, performs the given action
5191 <         * for each key.
5192 <         *
5193 <         * @param map the map
5194 <         * @param action the action
5195 <         * @return the task
5196 <         */
5197 <        public static <K,V> ForkJoinTask<Void> forEachKey
5198 <            (ConcurrentHashMap<K,V> map,
5199 <             Consumer<? super K> action) {
5200 <            if (action == null) throw new NullPointerException();
5201 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
5202 <        }
5203 <
5204 <        /**
5205 <         * Returns a task that when invoked, performs the given action
5206 <         * for each non-null transformation of each key.
5207 <         *
5208 <         * @param map the map
5209 <         * @param transformer a function returning the transformation
5210 <         * for an element, or null if there is no transformation (in
5211 <         * which case the action is not applied)
5212 <         * @param action the action
5213 <         * @return the task
5214 <         */
5215 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5216 <            (ConcurrentHashMap<K,V> map,
5217 <             Function<? super K, ? extends U> transformer,
5218 <             Consumer<? super U> action) {
5219 <            if (transformer == null || action == null)
5220 <                throw new NullPointerException();
5221 <            return new ForEachTransformedKeyTask<K,V,U>
5222 <                (map, null, -1, transformer, action);
5223 <        }
5224 <
5225 <        /**
5226 <         * Returns a task that when invoked, returns a non-null result
5227 <         * from applying the given search function on each key, or
5228 <         * null if none.  Upon success, further element processing is
5229 <         * suppressed and the results of any other parallel
5230 <         * invocations of the search function are ignored.
5231 <         *
5232 <         * @param map the map
5233 <         * @param searchFunction a function returning a non-null
5234 <         * result on success, else null
5235 <         * @return the task
5236 <         */
5237 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5238 <            (ConcurrentHashMap<K,V> map,
5239 <             Function<? super K, ? extends U> searchFunction) {
5240 <            if (searchFunction == null) throw new NullPointerException();
5241 <            return new SearchKeysTask<K,V,U>
5242 <                (map, null, -1, searchFunction,
5243 <                 new AtomicReference<U>());
5244 <        }
5245 <
5246 <        /**
5247 <         * Returns a task that when invoked, returns the result of
5248 <         * accumulating all keys using the given reducer to combine
5249 <         * values, or null if none.
5250 <         *
5251 <         * @param map the map
5252 <         * @param reducer a commutative associative combining function
5253 <         * @return the task
5254 <         */
5255 <        public static <K,V> ForkJoinTask<K> reduceKeys
5256 <            (ConcurrentHashMap<K,V> map,
5257 <             BiFunction<? super K, ? super K, ? extends K> reducer) {
5258 <            if (reducer == null) throw new NullPointerException();
5259 <            return new ReduceKeysTask<K,V>
5260 <                (map, null, -1, null, reducer);
5261 <        }
5262 <
5263 <        /**
5264 <         * Returns a task that when invoked, returns the result of
5265 <         * accumulating the given transformation of all keys using the given
5266 <         * reducer to combine values, or null if none.
5267 <         *
5268 <         * @param map the map
5269 <         * @param transformer a function returning the transformation
5270 <         * for an element, or null if there is no transformation (in
5271 <         * which case it is not combined)
5272 <         * @param reducer a commutative associative combining function
5273 <         * @return the task
5274 <         */
5275 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5276 <            (ConcurrentHashMap<K,V> map,
5277 <             Function<? super K, ? extends U> transformer,
5278 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5279 <            if (transformer == null || reducer == null)
5280 <                throw new NullPointerException();
5281 <            return new MapReduceKeysTask<K,V,U>
5282 <                (map, null, -1, null, transformer, reducer);
5283 <        }
5284 <
5285 <        /**
5286 <         * Returns a task that when invoked, returns the result of
5287 <         * accumulating the given transformation of all keys using the given
5288 <         * reducer to combine values, and the given basis as an
5289 <         * identity value.
5290 <         *
5291 <         * @param map the map
5292 <         * @param transformer a function returning the transformation
5293 <         * for an element
5294 <         * @param basis the identity (initial default value) for the reduction
5295 <         * @param reducer a commutative associative combining function
5296 <         * @return the task
5297 <         */
5298 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5299 <            (ConcurrentHashMap<K,V> map,
5300 <             ToDoubleFunction<? super K> transformer,
5301 <             double basis,
5302 <             DoubleBinaryOperator reducer) {
5303 <            if (transformer == null || reducer == null)
5304 <                throw new NullPointerException();
5305 <            return new MapReduceKeysToDoubleTask<K,V>
5306 <                (map, null, -1, null, transformer, basis, reducer);
5307 <        }
5308 <
5309 <        /**
5310 <         * Returns a task that when invoked, returns the result of
5311 <         * accumulating the given transformation of all keys using the given
5312 <         * reducer to combine values, and the given basis as an
5313 <         * identity value.
5314 <         *
5315 <         * @param map the map
5316 <         * @param transformer a function returning the transformation
5317 <         * for an element
5318 <         * @param basis the identity (initial default value) for the reduction
5319 <         * @param reducer a commutative associative combining function
5320 <         * @return the task
5321 <         */
5322 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5323 <            (ConcurrentHashMap<K,V> map,
5324 <             ToLongFunction<? super K> transformer,
5325 <             long basis,
5326 <             LongBinaryOperator reducer) {
5327 <            if (transformer == null || reducer == null)
5328 <                throw new NullPointerException();
5329 <            return new MapReduceKeysToLongTask<K,V>
5330 <                (map, null, -1, null, transformer, basis, reducer);
5331 <        }
5332 <
5333 <        /**
5334 <         * Returns a task that when invoked, returns the result of
5335 <         * accumulating the given transformation of all keys using the given
5336 <         * reducer to combine values, and the given basis as an
5337 <         * identity value.
5338 <         *
5339 <         * @param map the map
5340 <         * @param transformer a function returning the transformation
5341 <         * for an element
5342 <         * @param basis the identity (initial default value) for the reduction
5343 <         * @param reducer a commutative associative combining function
5344 <         * @return the task
5345 <         */
5346 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5347 <            (ConcurrentHashMap<K,V> map,
5348 <             ToIntFunction<? super K> transformer,
5349 <             int basis,
5350 <             IntBinaryOperator reducer) {
5351 <            if (transformer == null || reducer == null)
5352 <                throw new NullPointerException();
5353 <            return new MapReduceKeysToIntTask<K,V>
5354 <                (map, null, -1, null, transformer, basis, reducer);
5355 <        }
5356 <
5357 <        /**
5358 <         * Returns a task that when invoked, performs the given action
5359 <         * for each value.
5360 <         *
5361 <         * @param map the map
5362 <         * @param action the action
5363 <         * @return the task
5364 <         */
5365 <        public static <K,V> ForkJoinTask<Void> forEachValue
5366 <            (ConcurrentHashMap<K,V> map,
5367 <             Consumer<? super V> action) {
5368 <            if (action == null) throw new NullPointerException();
5369 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5370 <        }
5371 <
5372 <        /**
5373 <         * Returns a task that when invoked, performs the given action
5374 <         * for each non-null transformation of each value.
5375 <         *
5376 <         * @param map the map
5377 <         * @param transformer a function returning the transformation
5378 <         * for an element, or null if there is no transformation (in
5379 <         * which case the action is not applied)
5380 <         * @param action the action
5381 <         * @return the task
5382 <         */
5383 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5384 <            (ConcurrentHashMap<K,V> map,
5385 <             Function<? super V, ? extends U> transformer,
5386 <             Consumer<? super U> action) {
5387 <            if (transformer == null || action == null)
5388 <                throw new NullPointerException();
5389 <            return new ForEachTransformedValueTask<K,V,U>
5390 <                (map, null, -1, transformer, action);
5391 <        }
5392 <
5393 <        /**
5394 <         * Returns a task that when invoked, returns a non-null result
5395 <         * from applying the given search function on each value, or
5396 <         * null if none.  Upon success, further element processing is
5397 <         * suppressed and the results of any other parallel
5398 <         * invocations of the search function are ignored.
5399 <         *
5400 <         * @param map the map
5401 <         * @param searchFunction a function returning a non-null
5402 <         * result on success, else null
5403 <         * @return the task
5404 <         */
5405 <        public static <K,V,U> ForkJoinTask<U> searchValues
5406 <            (ConcurrentHashMap<K,V> map,
5407 <             Function<? super V, ? extends U> searchFunction) {
5408 <            if (searchFunction == null) throw new NullPointerException();
5409 <            return new SearchValuesTask<K,V,U>
5410 <                (map, null, -1, searchFunction,
5411 <                 new AtomicReference<U>());
5412 <        }
5413 <
5414 <        /**
5415 <         * Returns a task that when invoked, returns the result of
5416 <         * accumulating all values using the given reducer to combine
5417 <         * values, or null if none.
5418 <         *
5419 <         * @param map the map
5420 <         * @param reducer a commutative associative combining function
5421 <         * @return the task
5422 <         */
5423 <        public static <K,V> ForkJoinTask<V> reduceValues
5424 <            (ConcurrentHashMap<K,V> map,
5425 <             BiFunction<? super V, ? super V, ? extends V> reducer) {
5426 <            if (reducer == null) throw new NullPointerException();
5427 <            return new ReduceValuesTask<K,V>
5428 <                (map, null, -1, null, reducer);
5429 <        }
5430 <
5431 <        /**
5432 <         * Returns a task that when invoked, returns the result of
5433 <         * accumulating the given transformation of all values using the
5434 <         * given reducer to combine values, or null if none.
5435 <         *
5436 <         * @param map the map
5437 <         * @param transformer a function returning the transformation
5438 <         * for an element, or null if there is no transformation (in
5439 <         * which case it is not combined)
5440 <         * @param reducer a commutative associative combining function
5441 <         * @return the task
5442 <         */
5443 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5444 <            (ConcurrentHashMap<K,V> map,
5445 <             Function<? super V, ? extends U> transformer,
5446 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5447 <            if (transformer == null || reducer == null)
5448 <                throw new NullPointerException();
5449 <            return new MapReduceValuesTask<K,V,U>
5450 <                (map, null, -1, null, transformer, reducer);
5451 <        }
5452 <
5453 <        /**
5454 <         * Returns a task that when invoked, returns the result of
5455 <         * accumulating the given transformation of all values using the
5456 <         * given reducer to combine values, and the given basis as an
5457 <         * identity value.
5458 <         *
5459 <         * @param map the map
5460 <         * @param transformer a function returning the transformation
5461 <         * for an element
5462 <         * @param basis the identity (initial default value) for the reduction
5463 <         * @param reducer a commutative associative combining function
5464 <         * @return the task
5465 <         */
5466 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5467 <            (ConcurrentHashMap<K,V> map,
5468 <             ToDoubleFunction<? super V> transformer,
5469 <             double basis,
5470 <             DoubleBinaryOperator reducer) {
5471 <            if (transformer == null || reducer == null)
5472 <                throw new NullPointerException();
5473 <            return new MapReduceValuesToDoubleTask<K,V>
5474 <                (map, null, -1, null, transformer, basis, reducer);
4579 >        public final int hashCode() {
4580 >            int h = 0;
4581 >            Node<K,V>[] t;
4582 >            if ((t = map.table) != null) {
4583 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4584 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4585 >                    h += p.hashCode();
4586 >                }
4587 >            }
4588 >            return h;
4589          }
4590  
4591 <        /**
4592 <         * Returns a task that when invoked, returns the result of
4593 <         * accumulating the given transformation of all values using the
4594 <         * given reducer to combine values, and the given basis as an
4595 <         * identity value.
5482 <         *
5483 <         * @param map the map
5484 <         * @param transformer a function returning the transformation
5485 <         * for an element
5486 <         * @param basis the identity (initial default value) for the reduction
5487 <         * @param reducer a commutative associative combining function
5488 <         * @return the task
5489 <         */
5490 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5491 <            (ConcurrentHashMap<K,V> map,
5492 <             ToLongFunction<? super V> transformer,
5493 <             long basis,
5494 <             LongBinaryOperator reducer) {
5495 <            if (transformer == null || reducer == null)
5496 <                throw new NullPointerException();
5497 <            return new MapReduceValuesToLongTask<K,V>
5498 <                (map, null, -1, null, transformer, basis, reducer);
4591 >        public final boolean equals(Object o) {
4592 >            Set<?> c;
4593 >            return ((o instanceof Set) &&
4594 >                    ((c = (Set<?>)o) == this ||
4595 >                     (containsAll(c) && c.containsAll(this))));
4596          }
4597  
4598 <        /**
4599 <         * Returns a task that when invoked, returns the result of
4600 <         * accumulating the given transformation of all values using the
4601 <         * given reducer to combine values, and the given basis as an
4602 <         * identity value.
4603 <         *
5507 <         * @param map the map
5508 <         * @param transformer a function returning the transformation
5509 <         * for an element
5510 <         * @param basis the identity (initial default value) for the reduction
5511 <         * @param reducer a commutative associative combining function
5512 <         * @return the task
5513 <         */
5514 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5515 <            (ConcurrentHashMap<K,V> map,
5516 <             ToIntFunction<? super V> transformer,
5517 <             int basis,
5518 <             IntBinaryOperator reducer) {
5519 <            if (transformer == null || reducer == null)
5520 <                throw new NullPointerException();
5521 <            return new MapReduceValuesToIntTask<K,V>
5522 <                (map, null, -1, null, transformer, basis, reducer);
4598 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4599 >            Node<K,V>[] t;
4600 >            ConcurrentHashMap<K,V> m = map;
4601 >            long n = m.sumCount();
4602 >            int f = (t = m.table) == null ? 0 : t.length;
4603 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4604          }
4605  
4606 <        /**
5526 <         * Returns a task that when invoked, perform the given action
5527 <         * for each entry.
5528 <         *
5529 <         * @param map the map
5530 <         * @param action the action
5531 <         * @return the task
5532 <         */
5533 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5534 <            (ConcurrentHashMap<K,V> map,
5535 <             Consumer<? super Map.Entry<K,V>> action) {
4606 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4607              if (action == null) throw new NullPointerException();
4608 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
4609 <        }
4610 <
4611 <        /**
4612 <         * Returns a task that when invoked, perform the given action
4613 <         * for each non-null transformation of each entry.
5543 <         *
5544 <         * @param map the map
5545 <         * @param transformer a function returning the transformation
5546 <         * for an element, or null if there is no transformation (in
5547 <         * which case the action is not applied)
5548 <         * @param action the action
5549 <         * @return the task
5550 <         */
5551 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5552 <            (ConcurrentHashMap<K,V> map,
5553 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5554 <             Consumer<? super U> action) {
5555 <            if (transformer == null || action == null)
5556 <                throw new NullPointerException();
5557 <            return new ForEachTransformedEntryTask<K,V,U>
5558 <                (map, null, -1, transformer, action);
5559 <        }
5560 <
5561 <        /**
5562 <         * Returns a task that when invoked, returns a non-null result
5563 <         * from applying the given search function on each entry, or
5564 <         * null if none.  Upon success, further element processing is
5565 <         * suppressed and the results of any other parallel
5566 <         * invocations of the search function are ignored.
5567 <         *
5568 <         * @param map the map
5569 <         * @param searchFunction a function returning a non-null
5570 <         * result on success, else null
5571 <         * @return the task
5572 <         */
5573 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5574 <            (ConcurrentHashMap<K,V> map,
5575 <             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5576 <            if (searchFunction == null) throw new NullPointerException();
5577 <            return new SearchEntriesTask<K,V,U>
5578 <                (map, null, -1, searchFunction,
5579 <                 new AtomicReference<U>());
5580 <        }
5581 <
5582 <        /**
5583 <         * Returns a task that when invoked, returns the result of
5584 <         * accumulating all entries using the given reducer to combine
5585 <         * values, or null if none.
5586 <         *
5587 <         * @param map the map
5588 <         * @param reducer a commutative associative combining function
5589 <         * @return the task
5590 <         */
5591 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5592 <            (ConcurrentHashMap<K,V> map,
5593 <             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5594 <            if (reducer == null) throw new NullPointerException();
5595 <            return new ReduceEntriesTask<K,V>
5596 <                (map, null, -1, null, reducer);
4608 >            Node<K,V>[] t;
4609 >            if ((t = map.table) != null) {
4610 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4611 >                for (Node<K,V> p; (p = it.advance()) != null; )
4612 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4613 >            }
4614          }
4615  
4616 <        /**
5600 <         * Returns a task that when invoked, returns the result of
5601 <         * accumulating the given transformation of all entries using the
5602 <         * given reducer to combine values, or null if none.
5603 <         *
5604 <         * @param map the map
5605 <         * @param transformer a function returning the transformation
5606 <         * for an element, or null if there is no transformation (in
5607 <         * which case it is not combined)
5608 <         * @param reducer a commutative associative combining function
5609 <         * @return the task
5610 <         */
5611 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5612 <            (ConcurrentHashMap<K,V> map,
5613 <             Function<Map.Entry<K,V>, ? extends U> transformer,
5614 <             BiFunction<? super U, ? super U, ? extends U> reducer) {
5615 <            if (transformer == null || reducer == null)
5616 <                throw new NullPointerException();
5617 <            return new MapReduceEntriesTask<K,V,U>
5618 <                (map, null, -1, null, transformer, reducer);
5619 <        }
4616 >    }
4617  
4618 <        /**
5622 <         * Returns a task that when invoked, returns the result of
5623 <         * accumulating the given transformation of all entries using the
5624 <         * given reducer to combine values, and the given basis as an
5625 <         * identity value.
5626 <         *
5627 <         * @param map the map
5628 <         * @param transformer a function returning the transformation
5629 <         * for an element
5630 <         * @param basis the identity (initial default value) for the reduction
5631 <         * @param reducer a commutative associative combining function
5632 <         * @return the task
5633 <         */
5634 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5635 <            (ConcurrentHashMap<K,V> map,
5636 <             ToDoubleFunction<Map.Entry<K,V>> transformer,
5637 <             double basis,
5638 <             DoubleBinaryOperator reducer) {
5639 <            if (transformer == null || reducer == null)
5640 <                throw new NullPointerException();
5641 <            return new MapReduceEntriesToDoubleTask<K,V>
5642 <                (map, null, -1, null, transformer, basis, reducer);
5643 <        }
4618 >    // -------------------------------------------------------
4619  
4620 <        /**
4621 <         * Returns a task that when invoked, returns the result of
4622 <         * accumulating the given transformation of all entries using the
4623 <         * given reducer to combine values, and the given basis as an
4624 <         * identity value.
4625 <         *
4626 <         * @param map the map
4627 <         * @param transformer a function returning the transformation
4628 <         * for an element
4629 <         * @param basis the identity (initial default value) for the reduction
4630 <         * @param reducer a commutative associative combining function
4631 <         * @return the task
4632 <         */
4633 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4634 <            (ConcurrentHashMap<K,V> map,
4635 <             ToLongFunction<Map.Entry<K,V>> transformer,
4636 <             long basis,
4637 <             LongBinaryOperator reducer) {
4638 <            if (transformer == null || reducer == null)
4639 <                throw new NullPointerException();
4640 <            return new MapReduceEntriesToLongTask<K,V>
4641 <                (map, null, -1, null, transformer, basis, reducer);
4620 >    /**
4621 >     * Base class for bulk tasks. Repeats some fields and code from
4622 >     * class Traverser, because we need to subclass CountedCompleter.
4623 >     */
4624 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4625 >        Node<K,V>[] tab;        // same as Traverser
4626 >        Node<K,V> next;
4627 >        int index;
4628 >        int baseIndex;
4629 >        int baseLimit;
4630 >        final int baseSize;
4631 >        int batch;              // split control
4632 >
4633 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4634 >            super(par);
4635 >            this.batch = b;
4636 >            this.index = this.baseIndex = i;
4637 >            if ((this.tab = t) == null)
4638 >                this.baseSize = this.baseLimit = 0;
4639 >            else if (par == null)
4640 >                this.baseSize = this.baseLimit = t.length;
4641 >            else {
4642 >                this.baseLimit = f;
4643 >                this.baseSize = par.baseSize;
4644 >            }
4645          }
4646  
4647          /**
4648 <         * Returns a task that when invoked, returns the result of
5671 <         * accumulating the given transformation of all entries using the
5672 <         * given reducer to combine values, and the given basis as an
5673 <         * identity value.
5674 <         *
5675 <         * @param map the map
5676 <         * @param transformer a function returning the transformation
5677 <         * for an element
5678 <         * @param basis the identity (initial default value) for the reduction
5679 <         * @param reducer a commutative associative combining function
5680 <         * @return the task
4648 >         * Same as Traverser version
4649           */
4650 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4651 <            (ConcurrentHashMap<K,V> map,
4652 <             ToIntFunction<Map.Entry<K,V>> transformer,
4653 <             int basis,
4654 <             IntBinaryOperator reducer) {
4655 <            if (transformer == null || reducer == null)
4656 <                throw new NullPointerException();
4657 <            return new MapReduceEntriesToIntTask<K,V>
4658 <                (map, null, -1, null, transformer, basis, reducer);
4650 >        final Node<K,V> advance() {
4651 >            Node<K,V> e;
4652 >            if ((e = next) != null)
4653 >                e = e.next;
4654 >            for (;;) {
4655 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4656 >                if (e != null)
4657 >                    return next = e;
4658 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4659 >                    (n = t.length) <= (i = index) || i < 0)
4660 >                    return next = null;
4661 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4662 >                    if (e instanceof ForwardingNode) {
4663 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4664 >                        e = null;
4665 >                        continue;
4666 >                    }
4667 >                    else if (e instanceof TreeBin)
4668 >                        e = ((TreeBin<K,V>)e).first;
4669 >                    else
4670 >                        e = null;
4671 >                }
4672 >                if ((index += baseSize) >= n)
4673 >                    index = ++baseIndex;    // visit upper slots if present
4674 >            }
4675          }
4676      }
4677  
5694    // -------------------------------------------------------
5695
4678      /*
4679       * Task classes. Coded in a regular but ugly format/style to
4680       * simplify checks that each variant differs in the right way from
# Line 5700 | Line 4682 | public class ConcurrentHashMap<K,V>
4682       * that we've already null-checked task arguments, so we force
4683       * simplest hoisted bypass to help avoid convoluted traps.
4684       */
4685 <
4686 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4687 <        extends Traverser<K,V,Void> {
4685 >    @SuppressWarnings("serial")
4686 >    static final class ForEachKeyTask<K,V>
4687 >        extends BulkTask<K,V,Void> {
4688          final Consumer<? super K> action;
4689          ForEachKeyTask
4690 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4690 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4691               Consumer<? super K> action) {
4692 <            super(m, p, b);
4692 >            super(p, b, i, f, t);
4693              this.action = action;
4694          }
4695          public final void compute() {
4696              final Consumer<? super K> action;
4697              if ((action = this.action) != null) {
4698 <                for (int b; (b = preSplit()) > 0;)
4699 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4700 <                forEachKey(action);
4698 >                for (int i = baseIndex, f, h; batch > 0 &&
4699 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4700 >                    addToPendingCount(1);
4701 >                    new ForEachKeyTask<K,V>
4702 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4703 >                         action).fork();
4704 >                }
4705 >                for (Node<K,V> p; (p = advance()) != null;)
4706 >                    action.accept(p.key);
4707                  propagateCompletion();
4708              }
4709          }
4710      }
4711  
4712 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4713 <        extends Traverser<K,V,Void> {
4712 >    @SuppressWarnings("serial")
4713 >    static final class ForEachValueTask<K,V>
4714 >        extends BulkTask<K,V,Void> {
4715          final Consumer<? super V> action;
4716          ForEachValueTask
4717 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4717 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4718               Consumer<? super V> action) {
4719 <            super(m, p, b);
4719 >            super(p, b, i, f, t);
4720              this.action = action;
4721          }
4722          public final void compute() {
4723              final Consumer<? super V> action;
4724              if ((action = this.action) != null) {
4725 <                for (int b; (b = preSplit()) > 0;)
4726 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4727 <                forEachValue(action);
4725 >                for (int i = baseIndex, f, h; batch > 0 &&
4726 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4727 >                    addToPendingCount(1);
4728 >                    new ForEachValueTask<K,V>
4729 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4730 >                         action).fork();
4731 >                }
4732 >                for (Node<K,V> p; (p = advance()) != null;)
4733 >                    action.accept(p.val);
4734                  propagateCompletion();
4735              }
4736          }
4737      }
4738  
4739 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4740 <        extends Traverser<K,V,Void> {
4739 >    @SuppressWarnings("serial")
4740 >    static final class ForEachEntryTask<K,V>
4741 >        extends BulkTask<K,V,Void> {
4742          final Consumer<? super Entry<K,V>> action;
4743          ForEachEntryTask
4744 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4744 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4745               Consumer<? super Entry<K,V>> action) {
4746 <            super(m, p, b);
4746 >            super(p, b, i, f, t);
4747              this.action = action;
4748          }
4749          public final void compute() {
4750              final Consumer<? super Entry<K,V>> action;
4751              if ((action = this.action) != null) {
4752 <                for (int b; (b = preSplit()) > 0;)
4753 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4754 <                V v;
4755 <                while ((v = advanceValue()) != null)
4756 <                    action.accept(entryFor(nextKey, v));
4752 >                for (int i = baseIndex, f, h; batch > 0 &&
4753 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4754 >                    addToPendingCount(1);
4755 >                    new ForEachEntryTask<K,V>
4756 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4757 >                         action).fork();
4758 >                }
4759 >                for (Node<K,V> p; (p = advance()) != null; )
4760 >                    action.accept(p);
4761                  propagateCompletion();
4762              }
4763          }
4764      }
4765  
4766 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4767 <        extends Traverser<K,V,Void> {
4766 >    @SuppressWarnings("serial")
4767 >    static final class ForEachMappingTask<K,V>
4768 >        extends BulkTask<K,V,Void> {
4769          final BiConsumer<? super K, ? super V> action;
4770          ForEachMappingTask
4771 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4771 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4772               BiConsumer<? super K,? super V> action) {
4773 <            super(m, p, b);
4773 >            super(p, b, i, f, t);
4774              this.action = action;
4775          }
4776          public final void compute() {
4777              final BiConsumer<? super K, ? super V> action;
4778              if ((action = this.action) != null) {
4779 <                for (int b; (b = preSplit()) > 0;)
4780 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4781 <                V v;
4782 <                while ((v = advanceValue()) != null)
4783 <                    action.accept(nextKey, v);
4779 >                for (int i = baseIndex, f, h; batch > 0 &&
4780 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4781 >                    addToPendingCount(1);
4782 >                    new ForEachMappingTask<K,V>
4783 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4784 >                         action).fork();
4785 >                }
4786 >                for (Node<K,V> p; (p = advance()) != null; )
4787 >                    action.accept(p.key, p.val);
4788                  propagateCompletion();
4789              }
4790          }
4791      }
4792  
4793 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4794 <        extends Traverser<K,V,Void> {
4793 >    @SuppressWarnings("serial")
4794 >    static final class ForEachTransformedKeyTask<K,V,U>
4795 >        extends BulkTask<K,V,Void> {
4796          final Function<? super K, ? extends U> transformer;
4797          final Consumer<? super U> action;
4798          ForEachTransformedKeyTask
4799 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4799 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4800               Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4801 <            super(m, p, b);
4801 >            super(p, b, i, f, t);
4802              this.transformer = transformer; this.action = action;
4803          }
4804          public final void compute() {
# Line 5800 | Line 4806 | public class ConcurrentHashMap<K,V>
4806              final Consumer<? super U> action;
4807              if ((transformer = this.transformer) != null &&
4808                  (action = this.action) != null) {
4809 <                for (int b; (b = preSplit()) > 0;)
4809 >                for (int i = baseIndex, f, h; batch > 0 &&
4810 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4811 >                    addToPendingCount(1);
4812                      new ForEachTransformedKeyTask<K,V,U>
4813 <                        (map, this, b, transformer, action).fork();
4814 <                K k; U u;
4815 <                while ((k = advanceKey()) != null) {
4816 <                    if ((u = transformer.apply(k)) != null)
4813 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4814 >                         transformer, action).fork();
4815 >                }
4816 >                for (Node<K,V> p; (p = advance()) != null; ) {
4817 >                    U u;
4818 >                    if ((u = transformer.apply(p.key)) != null)
4819                          action.accept(u);
4820                  }
4821                  propagateCompletion();
# Line 5813 | Line 4823 | public class ConcurrentHashMap<K,V>
4823          }
4824      }
4825  
4826 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4827 <        extends Traverser<K,V,Void> {
4826 >    @SuppressWarnings("serial")
4827 >    static final class ForEachTransformedValueTask<K,V,U>
4828 >        extends BulkTask<K,V,Void> {
4829          final Function<? super V, ? extends U> transformer;
4830          final Consumer<? super U> action;
4831          ForEachTransformedValueTask
4832 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4832 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4833               Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4834 <            super(m, p, b);
4834 >            super(p, b, i, f, t);
4835              this.transformer = transformer; this.action = action;
4836          }
4837          public final void compute() {
# Line 5828 | Line 4839 | public class ConcurrentHashMap<K,V>
4839              final Consumer<? super U> action;
4840              if ((transformer = this.transformer) != null &&
4841                  (action = this.action) != null) {
4842 <                for (int b; (b = preSplit()) > 0;)
4842 >                for (int i = baseIndex, f, h; batch > 0 &&
4843 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4844 >                    addToPendingCount(1);
4845                      new ForEachTransformedValueTask<K,V,U>
4846 <                        (map, this, b, transformer, action).fork();
4847 <                V v; U u;
4848 <                while ((v = advanceValue()) != null) {
4849 <                    if ((u = transformer.apply(v)) != null)
4846 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4847 >                         transformer, action).fork();
4848 >                }
4849 >                for (Node<K,V> p; (p = advance()) != null; ) {
4850 >                    U u;
4851 >                    if ((u = transformer.apply(p.val)) != null)
4852                          action.accept(u);
4853                  }
4854                  propagateCompletion();
# Line 5841 | Line 4856 | public class ConcurrentHashMap<K,V>
4856          }
4857      }
4858  
4859 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4860 <        extends Traverser<K,V,Void> {
4859 >    @SuppressWarnings("serial")
4860 >    static final class ForEachTransformedEntryTask<K,V,U>
4861 >        extends BulkTask<K,V,Void> {
4862          final Function<Map.Entry<K,V>, ? extends U> transformer;
4863          final Consumer<? super U> action;
4864          ForEachTransformedEntryTask
4865 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4865 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4866               Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4867 <            super(m, p, b);
4867 >            super(p, b, i, f, t);
4868              this.transformer = transformer; this.action = action;
4869          }
4870          public final void compute() {
# Line 5856 | Line 4872 | public class ConcurrentHashMap<K,V>
4872              final Consumer<? super U> action;
4873              if ((transformer = this.transformer) != null &&
4874                  (action = this.action) != null) {
4875 <                for (int b; (b = preSplit()) > 0;)
4875 >                for (int i = baseIndex, f, h; batch > 0 &&
4876 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4877 >                    addToPendingCount(1);
4878                      new ForEachTransformedEntryTask<K,V,U>
4879 <                        (map, this, b, transformer, action).fork();
4880 <                V v; U u;
4881 <                while ((v = advanceValue()) != null) {
4882 <                    if ((u = transformer.apply(entryFor(nextKey,
4883 <                                                        v))) != null)
4879 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4880 >                         transformer, action).fork();
4881 >                }
4882 >                for (Node<K,V> p; (p = advance()) != null; ) {
4883 >                    U u;
4884 >                    if ((u = transformer.apply(p)) != null)
4885                          action.accept(u);
4886                  }
4887                  propagateCompletion();
# Line 5870 | Line 4889 | public class ConcurrentHashMap<K,V>
4889          }
4890      }
4891  
4892 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4893 <        extends Traverser<K,V,Void> {
4892 >    @SuppressWarnings("serial")
4893 >    static final class ForEachTransformedMappingTask<K,V,U>
4894 >        extends BulkTask<K,V,Void> {
4895          final BiFunction<? super K, ? super V, ? extends U> transformer;
4896          final Consumer<? super U> action;
4897          ForEachTransformedMappingTask
4898 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4898 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4899               BiFunction<? super K, ? super V, ? extends U> transformer,
4900               Consumer<? super U> action) {
4901 <            super(m, p, b);
4901 >            super(p, b, i, f, t);
4902              this.transformer = transformer; this.action = action;
4903          }
4904          public final void compute() {
# Line 5886 | Line 4906 | public class ConcurrentHashMap<K,V>
4906              final Consumer<? super U> action;
4907              if ((transformer = this.transformer) != null &&
4908                  (action = this.action) != null) {
4909 <                for (int b; (b = preSplit()) > 0;)
4909 >                for (int i = baseIndex, f, h; batch > 0 &&
4910 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4911 >                    addToPendingCount(1);
4912                      new ForEachTransformedMappingTask<K,V,U>
4913 <                        (map, this, b, transformer, action).fork();
4914 <                V v; U u;
4915 <                while ((v = advanceValue()) != null) {
4916 <                    if ((u = transformer.apply(nextKey, v)) != null)
4913 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4914 >                         transformer, action).fork();
4915 >                }
4916 >                for (Node<K,V> p; (p = advance()) != null; ) {
4917 >                    U u;
4918 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4919                          action.accept(u);
4920                  }
4921                  propagateCompletion();
# Line 5899 | Line 4923 | public class ConcurrentHashMap<K,V>
4923          }
4924      }
4925  
4926 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4927 <        extends Traverser<K,V,U> {
4926 >    @SuppressWarnings("serial")
4927 >    static final class SearchKeysTask<K,V,U>
4928 >        extends BulkTask<K,V,U> {
4929          final Function<? super K, ? extends U> searchFunction;
4930          final AtomicReference<U> result;
4931          SearchKeysTask
4932 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4932 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4933               Function<? super K, ? extends U> searchFunction,
4934               AtomicReference<U> result) {
4935 <            super(m, p, b);
4935 >            super(p, b, i, f, t);
4936              this.searchFunction = searchFunction; this.result = result;
4937          }
4938          public final U getRawResult() { return result.get(); }
# Line 5916 | Line 4941 | public class ConcurrentHashMap<K,V>
4941              final AtomicReference<U> result;
4942              if ((searchFunction = this.searchFunction) != null &&
4943                  (result = this.result) != null) {
4944 <                for (int b;;) {
4944 >                for (int i = baseIndex, f, h; batch > 0 &&
4945 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4946                      if (result.get() != null)
4947                          return;
4948 <                    if ((b = preSplit()) <= 0)
5923 <                        break;
4948 >                    addToPendingCount(1);
4949                      new SearchKeysTask<K,V,U>
4950 <                        (map, this, b, searchFunction, result).fork();
4950 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4951 >                         searchFunction, result).fork();
4952                  }
4953                  while (result.get() == null) {
4954 <                    K k; U u;
4955 <                    if ((k = advanceKey()) == null) {
4954 >                    U u;
4955 >                    Node<K,V> p;
4956 >                    if ((p = advance()) == null) {
4957                          propagateCompletion();
4958                          break;
4959                      }
4960 <                    if ((u = searchFunction.apply(k)) != null) {
4960 >                    if ((u = searchFunction.apply(p.key)) != null) {
4961                          if (result.compareAndSet(null, u))
4962                              quietlyCompleteRoot();
4963                          break;
# Line 5940 | Line 4967 | public class ConcurrentHashMap<K,V>
4967          }
4968      }
4969  
4970 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4971 <        extends Traverser<K,V,U> {
4970 >    @SuppressWarnings("serial")
4971 >    static final class SearchValuesTask<K,V,U>
4972 >        extends BulkTask<K,V,U> {
4973          final Function<? super V, ? extends U> searchFunction;
4974          final AtomicReference<U> result;
4975          SearchValuesTask
4976 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
4976 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4977               Function<? super V, ? extends U> searchFunction,
4978               AtomicReference<U> result) {
4979 <            super(m, p, b);
4979 >            super(p, b, i, f, t);
4980              this.searchFunction = searchFunction; this.result = result;
4981          }
4982          public final U getRawResult() { return result.get(); }
# Line 5957 | Line 4985 | public class ConcurrentHashMap<K,V>
4985              final AtomicReference<U> result;
4986              if ((searchFunction = this.searchFunction) != null &&
4987                  (result = this.result) != null) {
4988 <                for (int b;;) {
4988 >                for (int i = baseIndex, f, h; batch > 0 &&
4989 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4990                      if (result.get() != null)
4991                          return;
4992 <                    if ((b = preSplit()) <= 0)
5964 <                        break;
4992 >                    addToPendingCount(1);
4993                      new SearchValuesTask<K,V,U>
4994 <                        (map, this, b, searchFunction, result).fork();
4994 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4995 >                         searchFunction, result).fork();
4996                  }
4997                  while (result.get() == null) {
4998 <                    V v; U u;
4999 <                    if ((v = advanceValue()) == null) {
4998 >                    U u;
4999 >                    Node<K,V> p;
5000 >                    if ((p = advance()) == null) {
5001                          propagateCompletion();
5002                          break;
5003                      }
5004 <                    if ((u = searchFunction.apply(v)) != null) {
5004 >                    if ((u = searchFunction.apply(p.val)) != null) {
5005                          if (result.compareAndSet(null, u))
5006                              quietlyCompleteRoot();
5007                          break;
# Line 5981 | Line 5011 | public class ConcurrentHashMap<K,V>
5011          }
5012      }
5013  
5014 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5015 <        extends Traverser<K,V,U> {
5014 >    @SuppressWarnings("serial")
5015 >    static final class SearchEntriesTask<K,V,U>
5016 >        extends BulkTask<K,V,U> {
5017          final Function<Entry<K,V>, ? extends U> searchFunction;
5018          final AtomicReference<U> result;
5019          SearchEntriesTask
5020 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5020 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5021               Function<Entry<K,V>, ? extends U> searchFunction,
5022               AtomicReference<U> result) {
5023 <            super(m, p, b);
5023 >            super(p, b, i, f, t);
5024              this.searchFunction = searchFunction; this.result = result;
5025          }
5026          public final U getRawResult() { return result.get(); }
# Line 5998 | Line 5029 | public class ConcurrentHashMap<K,V>
5029              final AtomicReference<U> result;
5030              if ((searchFunction = this.searchFunction) != null &&
5031                  (result = this.result) != null) {
5032 <                for (int b;;) {
5032 >                for (int i = baseIndex, f, h; batch > 0 &&
5033 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5034                      if (result.get() != null)
5035                          return;
5036 <                    if ((b = preSplit()) <= 0)
6005 <                        break;
5036 >                    addToPendingCount(1);
5037                      new SearchEntriesTask<K,V,U>
5038 <                        (map, this, b, searchFunction, result).fork();
5038 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5039 >                         searchFunction, result).fork();
5040                  }
5041                  while (result.get() == null) {
5042 <                    V v; U u;
5043 <                    if ((v = advanceValue()) == null) {
5042 >                    U u;
5043 >                    Node<K,V> p;
5044 >                    if ((p = advance()) == null) {
5045                          propagateCompletion();
5046                          break;
5047                      }
5048 <                    if ((u = searchFunction.apply(entryFor(nextKey,
6016 <                                                           v))) != null) {
5048 >                    if ((u = searchFunction.apply(p)) != null) {
5049                          if (result.compareAndSet(null, u))
5050                              quietlyCompleteRoot();
5051                          return;
# Line 6023 | Line 5055 | public class ConcurrentHashMap<K,V>
5055          }
5056      }
5057  
5058 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5059 <        extends Traverser<K,V,U> {
5058 >    @SuppressWarnings("serial")
5059 >    static final class SearchMappingsTask<K,V,U>
5060 >        extends BulkTask<K,V,U> {
5061          final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5062          final AtomicReference<U> result;
5063          SearchMappingsTask
5064 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5064 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5065               BiFunction<? super K, ? super V, ? extends U> searchFunction,
5066               AtomicReference<U> result) {
5067 <            super(m, p, b);
5067 >            super(p, b, i, f, t);
5068              this.searchFunction = searchFunction; this.result = result;
5069          }
5070          public final U getRawResult() { return result.get(); }
# Line 6040 | Line 5073 | public class ConcurrentHashMap<K,V>
5073              final AtomicReference<U> result;
5074              if ((searchFunction = this.searchFunction) != null &&
5075                  (result = this.result) != null) {
5076 <                for (int b;;) {
5076 >                for (int i = baseIndex, f, h; batch > 0 &&
5077 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5078                      if (result.get() != null)
5079                          return;
5080 <                    if ((b = preSplit()) <= 0)
6047 <                        break;
5080 >                    addToPendingCount(1);
5081                      new SearchMappingsTask<K,V,U>
5082 <                        (map, this, b, searchFunction, result).fork();
5082 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5083 >                         searchFunction, result).fork();
5084                  }
5085                  while (result.get() == null) {
5086 <                    V v; U u;
5087 <                    if ((v = advanceValue()) == null) {
5086 >                    U u;
5087 >                    Node<K,V> p;
5088 >                    if ((p = advance()) == null) {
5089                          propagateCompletion();
5090                          break;
5091                      }
5092 <                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5092 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5093                          if (result.compareAndSet(null, u))
5094                              quietlyCompleteRoot();
5095                          break;
# Line 6064 | Line 5099 | public class ConcurrentHashMap<K,V>
5099          }
5100      }
5101  
5102 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5103 <        extends Traverser<K,V,K> {
5102 >    @SuppressWarnings("serial")
5103 >    static final class ReduceKeysTask<K,V>
5104 >        extends BulkTask<K,V,K> {
5105          final BiFunction<? super K, ? super K, ? extends K> reducer;
5106          K result;
5107          ReduceKeysTask<K,V> rights, nextRight;
5108          ReduceKeysTask
5109 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5109 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5110               ReduceKeysTask<K,V> nextRight,
5111               BiFunction<? super K, ? super K, ? extends K> reducer) {
5112 <            super(m, p, b); this.nextRight = nextRight;
5112 >            super(p, b, i, f, t); this.nextRight = nextRight;
5113              this.reducer = reducer;
5114          }
5115          public final K getRawResult() { return result; }
5116 <        @SuppressWarnings("unchecked") public final void compute() {
5116 >        public final void compute() {
5117              final BiFunction<? super K, ? super K, ? extends K> reducer;
5118              if ((reducer = this.reducer) != null) {
5119 <                for (int b; (b = preSplit()) > 0;)
5119 >                for (int i = baseIndex, f, h; batch > 0 &&
5120 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5121 >                    addToPendingCount(1);
5122                      (rights = new ReduceKeysTask<K,V>
5123 <                     (map, this, b, rights, reducer)).fork();
5124 <                K u, r = null;
5125 <                while ((u = advanceKey()) != null) {
5123 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5124 >                      rights, reducer)).fork();
5125 >                }
5126 >                K r = null;
5127 >                for (Node<K,V> p; (p = advance()) != null; ) {
5128 >                    K u = p.key;
5129                      r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5130                  }
5131                  result = r;
5132                  CountedCompleter<?> c;
5133                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5134 <                    ReduceKeysTask<K,V>
5134 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5135                          t = (ReduceKeysTask<K,V>)c,
5136                          s = t.rights;
5137                      while (s != null) {
# Line 6105 | Line 5146 | public class ConcurrentHashMap<K,V>
5146          }
5147      }
5148  
5149 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5150 <        extends Traverser<K,V,V> {
5149 >    @SuppressWarnings("serial")
5150 >    static final class ReduceValuesTask<K,V>
5151 >        extends BulkTask<K,V,V> {
5152          final BiFunction<? super V, ? super V, ? extends V> reducer;
5153          V result;
5154          ReduceValuesTask<K,V> rights, nextRight;
5155          ReduceValuesTask
5156 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5156 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5157               ReduceValuesTask<K,V> nextRight,
5158               BiFunction<? super V, ? super V, ? extends V> reducer) {
5159 <            super(m, p, b); this.nextRight = nextRight;
5159 >            super(p, b, i, f, t); this.nextRight = nextRight;
5160              this.reducer = reducer;
5161          }
5162          public final V getRawResult() { return result; }
5163 <        @SuppressWarnings("unchecked") public final void compute() {
5163 >        public final void compute() {
5164              final BiFunction<? super V, ? super V, ? extends V> reducer;
5165              if ((reducer = this.reducer) != null) {
5166 <                for (int b; (b = preSplit()) > 0;)
5166 >                for (int i = baseIndex, f, h; batch > 0 &&
5167 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5168 >                    addToPendingCount(1);
5169                      (rights = new ReduceValuesTask<K,V>
5170 <                     (map, this, b, rights, reducer)).fork();
5171 <                V r = null, v;
5172 <                while ((v = advanceValue()) != null)
5170 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5171 >                      rights, reducer)).fork();
5172 >                }
5173 >                V r = null;
5174 >                for (Node<K,V> p; (p = advance()) != null; ) {
5175 >                    V v = p.val;
5176                      r = (r == null) ? v : reducer.apply(r, v);
5177 +                }
5178                  result = r;
5179                  CountedCompleter<?> c;
5180                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5181 <                    ReduceValuesTask<K,V>
5181 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5182                          t = (ReduceValuesTask<K,V>)c,
5183                          s = t.rights;
5184                      while (s != null) {
# Line 6145 | Line 5193 | public class ConcurrentHashMap<K,V>
5193          }
5194      }
5195  
5196 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5197 <        extends Traverser<K,V,Map.Entry<K,V>> {
5196 >    @SuppressWarnings("serial")
5197 >    static final class ReduceEntriesTask<K,V>
5198 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5199          final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5200          Map.Entry<K,V> result;
5201          ReduceEntriesTask<K,V> rights, nextRight;
5202          ReduceEntriesTask
5203 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5203 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5204               ReduceEntriesTask<K,V> nextRight,
5205               BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5206 <            super(m, p, b); this.nextRight = nextRight;
5206 >            super(p, b, i, f, t); this.nextRight = nextRight;
5207              this.reducer = reducer;
5208          }
5209          public final Map.Entry<K,V> getRawResult() { return result; }
5210 <        @SuppressWarnings("unchecked") public final void compute() {
5210 >        public final void compute() {
5211              final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5212              if ((reducer = this.reducer) != null) {
5213 <                for (int b; (b = preSplit()) > 0;)
5213 >                for (int i = baseIndex, f, h; batch > 0 &&
5214 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5215 >                    addToPendingCount(1);
5216                      (rights = new ReduceEntriesTask<K,V>
5217 <                     (map, this, b, rights, reducer)).fork();
5218 <                Map.Entry<K,V> r = null;
6168 <                V v;
6169 <                while ((v = advanceValue()) != null) {
6170 <                    Map.Entry<K,V> u = entryFor(nextKey, v);
6171 <                    r = (r == null) ? u : reducer.apply(r, u);
5217 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5218 >                      rights, reducer)).fork();
5219                  }
5220 +                Map.Entry<K,V> r = null;
5221 +                for (Node<K,V> p; (p = advance()) != null; )
5222 +                    r = (r == null) ? p : reducer.apply(r, p);
5223                  result = r;
5224                  CountedCompleter<?> c;
5225                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5226 <                    ReduceEntriesTask<K,V>
5226 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5227                          t = (ReduceEntriesTask<K,V>)c,
5228                          s = t.rights;
5229                      while (s != null) {
# Line 6188 | Line 5238 | public class ConcurrentHashMap<K,V>
5238          }
5239      }
5240  
5241 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5242 <        extends Traverser<K,V,U> {
5241 >    @SuppressWarnings("serial")
5242 >    static final class MapReduceKeysTask<K,V,U>
5243 >        extends BulkTask<K,V,U> {
5244          final Function<? super K, ? extends U> transformer;
5245          final BiFunction<? super U, ? super U, ? extends U> reducer;
5246          U result;
5247          MapReduceKeysTask<K,V,U> rights, nextRight;
5248          MapReduceKeysTask
5249 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5249 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5250               MapReduceKeysTask<K,V,U> nextRight,
5251               Function<? super K, ? extends U> transformer,
5252               BiFunction<? super U, ? super U, ? extends U> reducer) {
5253 <            super(m, p, b); this.nextRight = nextRight;
5253 >            super(p, b, i, f, t); this.nextRight = nextRight;
5254              this.transformer = transformer;
5255              this.reducer = reducer;
5256          }
5257          public final U getRawResult() { return result; }
5258 <        @SuppressWarnings("unchecked") public final void compute() {
5258 >        public final void compute() {
5259              final Function<? super K, ? extends U> transformer;
5260              final BiFunction<? super U, ? super U, ? extends U> reducer;
5261              if ((transformer = this.transformer) != null &&
5262                  (reducer = this.reducer) != null) {
5263 <                for (int b; (b = preSplit()) > 0;)
5263 >                for (int i = baseIndex, f, h; batch > 0 &&
5264 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5265 >                    addToPendingCount(1);
5266                      (rights = new MapReduceKeysTask<K,V,U>
5267 <                     (map, this, b, rights, transformer, reducer)).fork();
5268 <                K k; U r = null, u;
5269 <                while ((k = advanceKey()) != null) {
5270 <                    if ((u = transformer.apply(k)) != null)
5267 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5268 >                      rights, transformer, reducer)).fork();
5269 >                }
5270 >                U r = null;
5271 >                for (Node<K,V> p; (p = advance()) != null; ) {
5272 >                    U u;
5273 >                    if ((u = transformer.apply(p.key)) != null)
5274                          r = (r == null) ? u : reducer.apply(r, u);
5275                  }
5276                  result = r;
5277                  CountedCompleter<?> c;
5278                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5279 <                    MapReduceKeysTask<K,V,U>
5279 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5280                          t = (MapReduceKeysTask<K,V,U>)c,
5281                          s = t.rights;
5282                      while (s != null) {
# Line 6235 | Line 5291 | public class ConcurrentHashMap<K,V>
5291          }
5292      }
5293  
5294 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5295 <        extends Traverser<K,V,U> {
5294 >    @SuppressWarnings("serial")
5295 >    static final class MapReduceValuesTask<K,V,U>
5296 >        extends BulkTask<K,V,U> {
5297          final Function<? super V, ? extends U> transformer;
5298          final BiFunction<? super U, ? super U, ? extends U> reducer;
5299          U result;
5300          MapReduceValuesTask<K,V,U> rights, nextRight;
5301          MapReduceValuesTask
5302 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5302 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5303               MapReduceValuesTask<K,V,U> nextRight,
5304               Function<? super V, ? extends U> transformer,
5305               BiFunction<? super U, ? super U, ? extends U> reducer) {
5306 <            super(m, p, b); this.nextRight = nextRight;
5306 >            super(p, b, i, f, t); this.nextRight = nextRight;
5307              this.transformer = transformer;
5308              this.reducer = reducer;
5309          }
5310          public final U getRawResult() { return result; }
5311 <        @SuppressWarnings("unchecked") public final void compute() {
5311 >        public final void compute() {
5312              final Function<? super V, ? extends U> transformer;
5313              final BiFunction<? super U, ? super U, ? extends U> reducer;
5314              if ((transformer = this.transformer) != null &&
5315                  (reducer = this.reducer) != null) {
5316 <                for (int b; (b = preSplit()) > 0;)
5316 >                for (int i = baseIndex, f, h; batch > 0 &&
5317 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5318 >                    addToPendingCount(1);
5319                      (rights = new MapReduceValuesTask<K,V,U>
5320 <                     (map, this, b, rights, transformer, reducer)).fork();
5321 <                U r = null, u;
5322 <                V v;
5323 <                while ((v = advanceValue()) != null) {
5324 <                    if ((u = transformer.apply(v)) != null)
5320 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5321 >                      rights, transformer, reducer)).fork();
5322 >                }
5323 >                U r = null;
5324 >                for (Node<K,V> p; (p = advance()) != null; ) {
5325 >                    U u;
5326 >                    if ((u = transformer.apply(p.val)) != null)
5327                          r = (r == null) ? u : reducer.apply(r, u);
5328                  }
5329                  result = r;
5330                  CountedCompleter<?> c;
5331                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5332 <                    MapReduceValuesTask<K,V,U>
5332 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5333                          t = (MapReduceValuesTask<K,V,U>)c,
5334                          s = t.rights;
5335                      while (s != null) {
# Line 6283 | Line 5344 | public class ConcurrentHashMap<K,V>
5344          }
5345      }
5346  
5347 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5348 <        extends Traverser<K,V,U> {
5347 >    @SuppressWarnings("serial")
5348 >    static final class MapReduceEntriesTask<K,V,U>
5349 >        extends BulkTask<K,V,U> {
5350          final Function<Map.Entry<K,V>, ? extends U> transformer;
5351          final BiFunction<? super U, ? super U, ? extends U> reducer;
5352          U result;
5353          MapReduceEntriesTask<K,V,U> rights, nextRight;
5354          MapReduceEntriesTask
5355 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5355 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5356               MapReduceEntriesTask<K,V,U> nextRight,
5357               Function<Map.Entry<K,V>, ? extends U> transformer,
5358               BiFunction<? super U, ? super U, ? extends U> reducer) {
5359 <            super(m, p, b); this.nextRight = nextRight;
5359 >            super(p, b, i, f, t); this.nextRight = nextRight;
5360              this.transformer = transformer;
5361              this.reducer = reducer;
5362          }
5363          public final U getRawResult() { return result; }
5364 <        @SuppressWarnings("unchecked") public final void compute() {
5364 >        public final void compute() {
5365              final Function<Map.Entry<K,V>, ? extends U> transformer;
5366              final BiFunction<? super U, ? super U, ? extends U> reducer;
5367              if ((transformer = this.transformer) != null &&
5368                  (reducer = this.reducer) != null) {
5369 <                for (int b; (b = preSplit()) > 0;)
5369 >                for (int i = baseIndex, f, h; batch > 0 &&
5370 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5371 >                    addToPendingCount(1);
5372                      (rights = new MapReduceEntriesTask<K,V,U>
5373 <                     (map, this, b, rights, transformer, reducer)).fork();
5374 <                U r = null, u;
5375 <                V v;
5376 <                while ((v = advanceValue()) != null) {
5377 <                    if ((u = transformer.apply(entryFor(nextKey,
5378 <                                                        v))) != null)
5373 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5374 >                      rights, transformer, reducer)).fork();
5375 >                }
5376 >                U r = null;
5377 >                for (Node<K,V> p; (p = advance()) != null; ) {
5378 >                    U u;
5379 >                    if ((u = transformer.apply(p)) != null)
5380                          r = (r == null) ? u : reducer.apply(r, u);
5381                  }
5382                  result = r;
5383                  CountedCompleter<?> c;
5384                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5385 <                    MapReduceEntriesTask<K,V,U>
5385 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5386                          t = (MapReduceEntriesTask<K,V,U>)c,
5387                          s = t.rights;
5388                      while (s != null) {
# Line 6332 | Line 5397 | public class ConcurrentHashMap<K,V>
5397          }
5398      }
5399  
5400 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5401 <        extends Traverser<K,V,U> {
5400 >    @SuppressWarnings("serial")
5401 >    static final class MapReduceMappingsTask<K,V,U>
5402 >        extends BulkTask<K,V,U> {
5403          final BiFunction<? super K, ? super V, ? extends U> transformer;
5404          final BiFunction<? super U, ? super U, ? extends U> reducer;
5405          U result;
5406          MapReduceMappingsTask<K,V,U> rights, nextRight;
5407          MapReduceMappingsTask
5408 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5408 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5409               MapReduceMappingsTask<K,V,U> nextRight,
5410               BiFunction<? super K, ? super V, ? extends U> transformer,
5411               BiFunction<? super U, ? super U, ? extends U> reducer) {
5412 <            super(m, p, b); this.nextRight = nextRight;
5412 >            super(p, b, i, f, t); this.nextRight = nextRight;
5413              this.transformer = transformer;
5414              this.reducer = reducer;
5415          }
5416          public final U getRawResult() { return result; }
5417 <        @SuppressWarnings("unchecked") public final void compute() {
5417 >        public final void compute() {
5418              final BiFunction<? super K, ? super V, ? extends U> transformer;
5419              final BiFunction<? super U, ? super U, ? extends U> reducer;
5420              if ((transformer = this.transformer) != null &&
5421                  (reducer = this.reducer) != null) {
5422 <                for (int b; (b = preSplit()) > 0;)
5422 >                for (int i = baseIndex, f, h; batch > 0 &&
5423 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5424 >                    addToPendingCount(1);
5425                      (rights = new MapReduceMappingsTask<K,V,U>
5426 <                     (map, this, b, rights, transformer, reducer)).fork();
5427 <                U r = null, u;
5428 <                V v;
5429 <                while ((v = advanceValue()) != null) {
5430 <                    if ((u = transformer.apply(nextKey, v)) != null)
5426 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5427 >                      rights, transformer, reducer)).fork();
5428 >                }
5429 >                U r = null;
5430 >                for (Node<K,V> p; (p = advance()) != null; ) {
5431 >                    U u;
5432 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5433                          r = (r == null) ? u : reducer.apply(r, u);
5434                  }
5435                  result = r;
5436                  CountedCompleter<?> c;
5437                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5438 <                    MapReduceMappingsTask<K,V,U>
5438 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5439                          t = (MapReduceMappingsTask<K,V,U>)c,
5440                          s = t.rights;
5441                      while (s != null) {
# Line 6380 | Line 5450 | public class ConcurrentHashMap<K,V>
5450          }
5451      }
5452  
5453 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5454 <        extends Traverser<K,V,Double> {
5453 >    @SuppressWarnings("serial")
5454 >    static final class MapReduceKeysToDoubleTask<K,V>
5455 >        extends BulkTask<K,V,Double> {
5456          final ToDoubleFunction<? super K> transformer;
5457          final DoubleBinaryOperator reducer;
5458          final double basis;
5459          double result;
5460          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5461          MapReduceKeysToDoubleTask
5462 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5462 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5463               MapReduceKeysToDoubleTask<K,V> nextRight,
5464               ToDoubleFunction<? super K> transformer,
5465               double basis,
5466               DoubleBinaryOperator reducer) {
5467 <            super(m, p, b); this.nextRight = nextRight;
5467 >            super(p, b, i, f, t); this.nextRight = nextRight;
5468              this.transformer = transformer;
5469              this.basis = basis; this.reducer = reducer;
5470          }
5471          public final Double getRawResult() { return result; }
5472 <        @SuppressWarnings("unchecked") public final void compute() {
5472 >        public final void compute() {
5473              final ToDoubleFunction<? super K> transformer;
5474              final DoubleBinaryOperator reducer;
5475              if ((transformer = this.transformer) != null &&
5476                  (reducer = this.reducer) != null) {
5477                  double r = this.basis;
5478 <                for (int b; (b = preSplit()) > 0;)
5478 >                for (int i = baseIndex, f, h; batch > 0 &&
5479 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5480 >                    addToPendingCount(1);
5481                      (rights = new MapReduceKeysToDoubleTask<K,V>
5482 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5483 <                K k;
5484 <                while ((k = advanceKey()) != null)
5485 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
5482 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5483 >                      rights, transformer, r, reducer)).fork();
5484 >                }
5485 >                for (Node<K,V> p; (p = advance()) != null; )
5486 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5487                  result = r;
5488                  CountedCompleter<?> c;
5489                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5490 <                    MapReduceKeysToDoubleTask<K,V>
5490 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5491                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5492                          s = t.rights;
5493                      while (s != null) {
# Line 6425 | Line 5499 | public class ConcurrentHashMap<K,V>
5499          }
5500      }
5501  
5502 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5503 <        extends Traverser<K,V,Double> {
5502 >    @SuppressWarnings("serial")
5503 >    static final class MapReduceValuesToDoubleTask<K,V>
5504 >        extends BulkTask<K,V,Double> {
5505          final ToDoubleFunction<? super V> transformer;
5506          final DoubleBinaryOperator reducer;
5507          final double basis;
5508          double result;
5509          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5510          MapReduceValuesToDoubleTask
5511 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5511 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5512               MapReduceValuesToDoubleTask<K,V> nextRight,
5513               ToDoubleFunction<? super V> transformer,
5514               double basis,
5515               DoubleBinaryOperator reducer) {
5516 <            super(m, p, b); this.nextRight = nextRight;
5516 >            super(p, b, i, f, t); this.nextRight = nextRight;
5517              this.transformer = transformer;
5518              this.basis = basis; this.reducer = reducer;
5519          }
5520          public final Double getRawResult() { return result; }
5521 <        @SuppressWarnings("unchecked") public final void compute() {
5521 >        public final void compute() {
5522              final ToDoubleFunction<? super V> transformer;
5523              final DoubleBinaryOperator reducer;
5524              if ((transformer = this.transformer) != null &&
5525                  (reducer = this.reducer) != null) {
5526                  double r = this.basis;
5527 <                for (int b; (b = preSplit()) > 0;)
5527 >                for (int i = baseIndex, f, h; batch > 0 &&
5528 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5529 >                    addToPendingCount(1);
5530                      (rights = new MapReduceValuesToDoubleTask<K,V>
5531 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5532 <                V v;
5533 <                while ((v = advanceValue()) != null)
5534 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
5531 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5532 >                      rights, transformer, r, reducer)).fork();
5533 >                }
5534 >                for (Node<K,V> p; (p = advance()) != null; )
5535 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5536                  result = r;
5537                  CountedCompleter<?> c;
5538                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5539 <                    MapReduceValuesToDoubleTask<K,V>
5539 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5540                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5541                          s = t.rights;
5542                      while (s != null) {
# Line 6470 | Line 5548 | public class ConcurrentHashMap<K,V>
5548          }
5549      }
5550  
5551 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5552 <        extends Traverser<K,V,Double> {
5551 >    @SuppressWarnings("serial")
5552 >    static final class MapReduceEntriesToDoubleTask<K,V>
5553 >        extends BulkTask<K,V,Double> {
5554          final ToDoubleFunction<Map.Entry<K,V>> transformer;
5555          final DoubleBinaryOperator reducer;
5556          final double basis;
5557          double result;
5558          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5559          MapReduceEntriesToDoubleTask
5560 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5560 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5561               MapReduceEntriesToDoubleTask<K,V> nextRight,
5562               ToDoubleFunction<Map.Entry<K,V>> transformer,
5563               double basis,
5564               DoubleBinaryOperator reducer) {
5565 <            super(m, p, b); this.nextRight = nextRight;
5565 >            super(p, b, i, f, t); this.nextRight = nextRight;
5566              this.transformer = transformer;
5567              this.basis = basis; this.reducer = reducer;
5568          }
5569          public final Double getRawResult() { return result; }
5570 <        @SuppressWarnings("unchecked") public final void compute() {
5570 >        public final void compute() {
5571              final ToDoubleFunction<Map.Entry<K,V>> transformer;
5572              final DoubleBinaryOperator reducer;
5573              if ((transformer = this.transformer) != null &&
5574                  (reducer = this.reducer) != null) {
5575                  double r = this.basis;
5576 <                for (int b; (b = preSplit()) > 0;)
5576 >                for (int i = baseIndex, f, h; batch > 0 &&
5577 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5578 >                    addToPendingCount(1);
5579                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5580 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5581 <                V v;
5582 <                while ((v = advanceValue()) != null)
5583 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
5584 <                                                                    v)));
5580 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5581 >                      rights, transformer, r, reducer)).fork();
5582 >                }
5583 >                for (Node<K,V> p; (p = advance()) != null; )
5584 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5585                  result = r;
5586                  CountedCompleter<?> c;
5587                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5588 <                    MapReduceEntriesToDoubleTask<K,V>
5588 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5589                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5590                          s = t.rights;
5591                      while (s != null) {
# Line 6516 | Line 5597 | public class ConcurrentHashMap<K,V>
5597          }
5598      }
5599  
5600 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5601 <        extends Traverser<K,V,Double> {
5600 >    @SuppressWarnings("serial")
5601 >    static final class MapReduceMappingsToDoubleTask<K,V>
5602 >        extends BulkTask<K,V,Double> {
5603          final ToDoubleBiFunction<? super K, ? super V> transformer;
5604          final DoubleBinaryOperator reducer;
5605          final double basis;
5606          double result;
5607          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5608          MapReduceMappingsToDoubleTask
5609 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5609 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5610               MapReduceMappingsToDoubleTask<K,V> nextRight,
5611               ToDoubleBiFunction<? super K, ? super V> transformer,
5612               double basis,
5613               DoubleBinaryOperator reducer) {
5614 <            super(m, p, b); this.nextRight = nextRight;
5614 >            super(p, b, i, f, t); this.nextRight = nextRight;
5615              this.transformer = transformer;
5616              this.basis = basis; this.reducer = reducer;
5617          }
5618          public final Double getRawResult() { return result; }
5619 <        @SuppressWarnings("unchecked") public final void compute() {
5619 >        public final void compute() {
5620              final ToDoubleBiFunction<? super K, ? super V> transformer;
5621              final DoubleBinaryOperator reducer;
5622              if ((transformer = this.transformer) != null &&
5623                  (reducer = this.reducer) != null) {
5624                  double r = this.basis;
5625 <                for (int b; (b = preSplit()) > 0;)
5625 >                for (int i = baseIndex, f, h; batch > 0 &&
5626 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5627 >                    addToPendingCount(1);
5628                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5629 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5630 <                V v;
5631 <                while ((v = advanceValue()) != null)
5632 <                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
5629 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5630 >                      rights, transformer, r, reducer)).fork();
5631 >                }
5632 >                for (Node<K,V> p; (p = advance()) != null; )
5633 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5634                  result = r;
5635                  CountedCompleter<?> c;
5636                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5637 <                    MapReduceMappingsToDoubleTask<K,V>
5637 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5638                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5639                          s = t.rights;
5640                      while (s != null) {
# Line 6561 | Line 5646 | public class ConcurrentHashMap<K,V>
5646          }
5647      }
5648  
5649 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5650 <        extends Traverser<K,V,Long> {
5649 >    @SuppressWarnings("serial")
5650 >    static final class MapReduceKeysToLongTask<K,V>
5651 >        extends BulkTask<K,V,Long> {
5652          final ToLongFunction<? super K> transformer;
5653          final LongBinaryOperator reducer;
5654          final long basis;
5655          long result;
5656          MapReduceKeysToLongTask<K,V> rights, nextRight;
5657          MapReduceKeysToLongTask
5658 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5658 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5659               MapReduceKeysToLongTask<K,V> nextRight,
5660               ToLongFunction<? super K> transformer,
5661               long basis,
5662               LongBinaryOperator reducer) {
5663 <            super(m, p, b); this.nextRight = nextRight;
5663 >            super(p, b, i, f, t); this.nextRight = nextRight;
5664              this.transformer = transformer;
5665              this.basis = basis; this.reducer = reducer;
5666          }
5667          public final Long getRawResult() { return result; }
5668 <        @SuppressWarnings("unchecked") public final void compute() {
5668 >        public final void compute() {
5669              final ToLongFunction<? super K> transformer;
5670              final LongBinaryOperator reducer;
5671              if ((transformer = this.transformer) != null &&
5672                  (reducer = this.reducer) != null) {
5673                  long r = this.basis;
5674 <                for (int b; (b = preSplit()) > 0;)
5674 >                for (int i = baseIndex, f, h; batch > 0 &&
5675 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5676 >                    addToPendingCount(1);
5677                      (rights = new MapReduceKeysToLongTask<K,V>
5678 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5679 <                K k;
5680 <                while ((k = advanceKey()) != null)
5681 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(k));
5678 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5679 >                      rights, transformer, r, reducer)).fork();
5680 >                }
5681 >                for (Node<K,V> p; (p = advance()) != null; )
5682 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5683                  result = r;
5684                  CountedCompleter<?> c;
5685                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5686 <                    MapReduceKeysToLongTask<K,V>
5686 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5687                          t = (MapReduceKeysToLongTask<K,V>)c,
5688                          s = t.rights;
5689                      while (s != null) {
# Line 6606 | Line 5695 | public class ConcurrentHashMap<K,V>
5695          }
5696      }
5697  
5698 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5699 <        extends Traverser<K,V,Long> {
5698 >    @SuppressWarnings("serial")
5699 >    static final class MapReduceValuesToLongTask<K,V>
5700 >        extends BulkTask<K,V,Long> {
5701          final ToLongFunction<? super V> transformer;
5702          final LongBinaryOperator reducer;
5703          final long basis;
5704          long result;
5705          MapReduceValuesToLongTask<K,V> rights, nextRight;
5706          MapReduceValuesToLongTask
5707 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5707 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5708               MapReduceValuesToLongTask<K,V> nextRight,
5709               ToLongFunction<? super V> transformer,
5710               long basis,
5711               LongBinaryOperator reducer) {
5712 <            super(m, p, b); this.nextRight = nextRight;
5712 >            super(p, b, i, f, t); this.nextRight = nextRight;
5713              this.transformer = transformer;
5714              this.basis = basis; this.reducer = reducer;
5715          }
5716          public final Long getRawResult() { return result; }
5717 <        @SuppressWarnings("unchecked") public final void compute() {
5717 >        public final void compute() {
5718              final ToLongFunction<? super V> transformer;
5719              final LongBinaryOperator reducer;
5720              if ((transformer = this.transformer) != null &&
5721                  (reducer = this.reducer) != null) {
5722                  long r = this.basis;
5723 <                for (int b; (b = preSplit()) > 0;)
5723 >                for (int i = baseIndex, f, h; batch > 0 &&
5724 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5725 >                    addToPendingCount(1);
5726                      (rights = new MapReduceValuesToLongTask<K,V>
5727 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5728 <                V v;
5729 <                while ((v = advanceValue()) != null)
5730 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
5727 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5728 >                      rights, transformer, r, reducer)).fork();
5729 >                }
5730 >                for (Node<K,V> p; (p = advance()) != null; )
5731 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5732                  result = r;
5733                  CountedCompleter<?> c;
5734                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5735 <                    MapReduceValuesToLongTask<K,V>
5735 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5736                          t = (MapReduceValuesToLongTask<K,V>)c,
5737                          s = t.rights;
5738                      while (s != null) {
# Line 6651 | Line 5744 | public class ConcurrentHashMap<K,V>
5744          }
5745      }
5746  
5747 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5748 <        extends Traverser<K,V,Long> {
5747 >    @SuppressWarnings("serial")
5748 >    static final class MapReduceEntriesToLongTask<K,V>
5749 >        extends BulkTask<K,V,Long> {
5750          final ToLongFunction<Map.Entry<K,V>> transformer;
5751          final LongBinaryOperator reducer;
5752          final long basis;
5753          long result;
5754          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5755          MapReduceEntriesToLongTask
5756 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5756 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5757               MapReduceEntriesToLongTask<K,V> nextRight,
5758               ToLongFunction<Map.Entry<K,V>> transformer,
5759               long basis,
5760               LongBinaryOperator reducer) {
5761 <            super(m, p, b); this.nextRight = nextRight;
5761 >            super(p, b, i, f, t); this.nextRight = nextRight;
5762              this.transformer = transformer;
5763              this.basis = basis; this.reducer = reducer;
5764          }
5765          public final Long getRawResult() { return result; }
5766 <        @SuppressWarnings("unchecked") public final void compute() {
5766 >        public final void compute() {
5767              final ToLongFunction<Map.Entry<K,V>> transformer;
5768              final LongBinaryOperator reducer;
5769              if ((transformer = this.transformer) != null &&
5770                  (reducer = this.reducer) != null) {
5771                  long r = this.basis;
5772 <                for (int b; (b = preSplit()) > 0;)
5772 >                for (int i = baseIndex, f, h; batch > 0 &&
5773 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5774 >                    addToPendingCount(1);
5775                      (rights = new MapReduceEntriesToLongTask<K,V>
5776 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5777 <                V v;
5778 <                while ((v = advanceValue()) != null)
5779 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
5776 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5777 >                      rights, transformer, r, reducer)).fork();
5778 >                }
5779 >                for (Node<K,V> p; (p = advance()) != null; )
5780 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5781                  result = r;
5782                  CountedCompleter<?> c;
5783                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5784 <                    MapReduceEntriesToLongTask<K,V>
5784 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5785                          t = (MapReduceEntriesToLongTask<K,V>)c,
5786                          s = t.rights;
5787                      while (s != null) {
# Line 6696 | Line 5793 | public class ConcurrentHashMap<K,V>
5793          }
5794      }
5795  
5796 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5797 <        extends Traverser<K,V,Long> {
5796 >    @SuppressWarnings("serial")
5797 >    static final class MapReduceMappingsToLongTask<K,V>
5798 >        extends BulkTask<K,V,Long> {
5799          final ToLongBiFunction<? super K, ? super V> transformer;
5800          final LongBinaryOperator reducer;
5801          final long basis;
5802          long result;
5803          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5804          MapReduceMappingsToLongTask
5805 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5805 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5806               MapReduceMappingsToLongTask<K,V> nextRight,
5807               ToLongBiFunction<? super K, ? super V> transformer,
5808               long basis,
5809               LongBinaryOperator reducer) {
5810 <            super(m, p, b); this.nextRight = nextRight;
5810 >            super(p, b, i, f, t); this.nextRight = nextRight;
5811              this.transformer = transformer;
5812              this.basis = basis; this.reducer = reducer;
5813          }
5814          public final Long getRawResult() { return result; }
5815 <        @SuppressWarnings("unchecked") public final void compute() {
5815 >        public final void compute() {
5816              final ToLongBiFunction<? super K, ? super V> transformer;
5817              final LongBinaryOperator reducer;
5818              if ((transformer = this.transformer) != null &&
5819                  (reducer = this.reducer) != null) {
5820                  long r = this.basis;
5821 <                for (int b; (b = preSplit()) > 0;)
5821 >                for (int i = baseIndex, f, h; batch > 0 &&
5822 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5823 >                    addToPendingCount(1);
5824                      (rights = new MapReduceMappingsToLongTask<K,V>
5825 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5826 <                V v;
5827 <                while ((v = advanceValue()) != null)
5828 <                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
5825 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5826 >                      rights, transformer, r, reducer)).fork();
5827 >                }
5828 >                for (Node<K,V> p; (p = advance()) != null; )
5829 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
5830                  result = r;
5831                  CountedCompleter<?> c;
5832                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5833 <                    MapReduceMappingsToLongTask<K,V>
5833 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5834                          t = (MapReduceMappingsToLongTask<K,V>)c,
5835                          s = t.rights;
5836                      while (s != null) {
# Line 6741 | Line 5842 | public class ConcurrentHashMap<K,V>
5842          }
5843      }
5844  
5845 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5846 <        extends Traverser<K,V,Integer> {
5845 >    @SuppressWarnings("serial")
5846 >    static final class MapReduceKeysToIntTask<K,V>
5847 >        extends BulkTask<K,V,Integer> {
5848          final ToIntFunction<? super K> transformer;
5849          final IntBinaryOperator reducer;
5850          final int basis;
5851          int result;
5852          MapReduceKeysToIntTask<K,V> rights, nextRight;
5853          MapReduceKeysToIntTask
5854 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5854 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5855               MapReduceKeysToIntTask<K,V> nextRight,
5856               ToIntFunction<? super K> transformer,
5857               int basis,
5858               IntBinaryOperator reducer) {
5859 <            super(m, p, b); this.nextRight = nextRight;
5859 >            super(p, b, i, f, t); this.nextRight = nextRight;
5860              this.transformer = transformer;
5861              this.basis = basis; this.reducer = reducer;
5862          }
5863          public final Integer getRawResult() { return result; }
5864 <        @SuppressWarnings("unchecked") public final void compute() {
5864 >        public final void compute() {
5865              final ToIntFunction<? super K> transformer;
5866              final IntBinaryOperator reducer;
5867              if ((transformer = this.transformer) != null &&
5868                  (reducer = this.reducer) != null) {
5869                  int r = this.basis;
5870 <                for (int b; (b = preSplit()) > 0;)
5870 >                for (int i = baseIndex, f, h; batch > 0 &&
5871 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5872 >                    addToPendingCount(1);
5873                      (rights = new MapReduceKeysToIntTask<K,V>
5874 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5875 <                K k;
5876 <                while ((k = advanceKey()) != null)
5877 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(k));
5874 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5875 >                      rights, transformer, r, reducer)).fork();
5876 >                }
5877 >                for (Node<K,V> p; (p = advance()) != null; )
5878 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
5879                  result = r;
5880                  CountedCompleter<?> c;
5881                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5882 <                    MapReduceKeysToIntTask<K,V>
5882 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5883                          t = (MapReduceKeysToIntTask<K,V>)c,
5884                          s = t.rights;
5885                      while (s != null) {
# Line 6786 | Line 5891 | public class ConcurrentHashMap<K,V>
5891          }
5892      }
5893  
5894 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5895 <        extends Traverser<K,V,Integer> {
5894 >    @SuppressWarnings("serial")
5895 >    static final class MapReduceValuesToIntTask<K,V>
5896 >        extends BulkTask<K,V,Integer> {
5897          final ToIntFunction<? super V> transformer;
5898          final IntBinaryOperator reducer;
5899          final int basis;
5900          int result;
5901          MapReduceValuesToIntTask<K,V> rights, nextRight;
5902          MapReduceValuesToIntTask
5903 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5903 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5904               MapReduceValuesToIntTask<K,V> nextRight,
5905               ToIntFunction<? super V> transformer,
5906               int basis,
5907               IntBinaryOperator reducer) {
5908 <            super(m, p, b); this.nextRight = nextRight;
5908 >            super(p, b, i, f, t); this.nextRight = nextRight;
5909              this.transformer = transformer;
5910              this.basis = basis; this.reducer = reducer;
5911          }
5912          public final Integer getRawResult() { return result; }
5913 <        @SuppressWarnings("unchecked") public final void compute() {
5913 >        public final void compute() {
5914              final ToIntFunction<? super V> transformer;
5915              final IntBinaryOperator reducer;
5916              if ((transformer = this.transformer) != null &&
5917                  (reducer = this.reducer) != null) {
5918                  int r = this.basis;
5919 <                for (int b; (b = preSplit()) > 0;)
5919 >                for (int i = baseIndex, f, h; batch > 0 &&
5920 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5921 >                    addToPendingCount(1);
5922                      (rights = new MapReduceValuesToIntTask<K,V>
5923 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5924 <                V v;
5925 <                while ((v = advanceValue()) != null)
5926 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
5923 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5924 >                      rights, transformer, r, reducer)).fork();
5925 >                }
5926 >                for (Node<K,V> p; (p = advance()) != null; )
5927 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5928                  result = r;
5929                  CountedCompleter<?> c;
5930                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5931 <                    MapReduceValuesToIntTask<K,V>
5931 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5932                          t = (MapReduceValuesToIntTask<K,V>)c,
5933                          s = t.rights;
5934                      while (s != null) {
# Line 6831 | Line 5940 | public class ConcurrentHashMap<K,V>
5940          }
5941      }
5942  
5943 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5944 <        extends Traverser<K,V,Integer> {
5943 >    @SuppressWarnings("serial")
5944 >    static final class MapReduceEntriesToIntTask<K,V>
5945 >        extends BulkTask<K,V,Integer> {
5946          final ToIntFunction<Map.Entry<K,V>> transformer;
5947          final IntBinaryOperator reducer;
5948          final int basis;
5949          int result;
5950          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5951          MapReduceEntriesToIntTask
5952 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5952 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5953               MapReduceEntriesToIntTask<K,V> nextRight,
5954               ToIntFunction<Map.Entry<K,V>> transformer,
5955               int basis,
5956               IntBinaryOperator reducer) {
5957 <            super(m, p, b); this.nextRight = nextRight;
5957 >            super(p, b, i, f, t); this.nextRight = nextRight;
5958              this.transformer = transformer;
5959              this.basis = basis; this.reducer = reducer;
5960          }
5961          public final Integer getRawResult() { return result; }
5962 <        @SuppressWarnings("unchecked") public final void compute() {
5962 >        public final void compute() {
5963              final ToIntFunction<Map.Entry<K,V>> transformer;
5964              final IntBinaryOperator reducer;
5965              if ((transformer = this.transformer) != null &&
5966                  (reducer = this.reducer) != null) {
5967                  int r = this.basis;
5968 <                for (int b; (b = preSplit()) > 0;)
5968 >                for (int i = baseIndex, f, h; batch > 0 &&
5969 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5970 >                    addToPendingCount(1);
5971                      (rights = new MapReduceEntriesToIntTask<K,V>
5972 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5973 <                V v;
5974 <                while ((v = advanceValue()) != null)
5975 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
5976 <                                                                    v)));
5972 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5973 >                      rights, transformer, r, reducer)).fork();
5974 >                }
5975 >                for (Node<K,V> p; (p = advance()) != null; )
5976 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5977                  result = r;
5978                  CountedCompleter<?> c;
5979                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5980 <                    MapReduceEntriesToIntTask<K,V>
5980 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5981                          t = (MapReduceEntriesToIntTask<K,V>)c,
5982                          s = t.rights;
5983                      while (s != null) {
# Line 6877 | Line 5989 | public class ConcurrentHashMap<K,V>
5989          }
5990      }
5991  
5992 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5993 <        extends Traverser<K,V,Integer> {
5992 >    @SuppressWarnings("serial")
5993 >    static final class MapReduceMappingsToIntTask<K,V>
5994 >        extends BulkTask<K,V,Integer> {
5995          final ToIntBiFunction<? super K, ? super V> transformer;
5996          final IntBinaryOperator reducer;
5997          final int basis;
5998          int result;
5999          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6000          MapReduceMappingsToIntTask
6001 <            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6001 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6002               MapReduceMappingsToIntTask<K,V> nextRight,
6003               ToIntBiFunction<? super K, ? super V> transformer,
6004               int basis,
6005               IntBinaryOperator reducer) {
6006 <            super(m, p, b); this.nextRight = nextRight;
6006 >            super(p, b, i, f, t); this.nextRight = nextRight;
6007              this.transformer = transformer;
6008              this.basis = basis; this.reducer = reducer;
6009          }
6010          public final Integer getRawResult() { return result; }
6011 <        @SuppressWarnings("unchecked") public final void compute() {
6011 >        public final void compute() {
6012              final ToIntBiFunction<? super K, ? super V> transformer;
6013              final IntBinaryOperator reducer;
6014              if ((transformer = this.transformer) != null &&
6015                  (reducer = this.reducer) != null) {
6016                  int r = this.basis;
6017 <                for (int b; (b = preSplit()) > 0;)
6017 >                for (int i = baseIndex, f, h; batch > 0 &&
6018 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6019 >                    addToPendingCount(1);
6020                      (rights = new MapReduceMappingsToIntTask<K,V>
6021 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6022 <                V v;
6023 <                while ((v = advanceValue()) != null)
6024 <                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6021 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6022 >                      rights, transformer, r, reducer)).fork();
6023 >                }
6024 >                for (Node<K,V> p; (p = advance()) != null; )
6025 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6026                  result = r;
6027                  CountedCompleter<?> c;
6028                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6029 <                    MapReduceMappingsToIntTask<K,V>
6029 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6030                          t = (MapReduceMappingsToIntTask<K,V>)c,
6031                          s = t.rights;
6032                      while (s != null) {
# Line 6947 | Line 6063 | public class ConcurrentHashMap<K,V>
6063                  (k.getDeclaredField("baseCount"));
6064              CELLSBUSY = U.objectFieldOffset
6065                  (k.getDeclaredField("cellsBusy"));
6066 <            Class<?> ck = Cell.class;
6066 >            Class<?> ck = CounterCell.class;
6067              CELLVALUE = U.objectFieldOffset
6068                  (ck.getDeclaredField("value"));
6069 <            Class<?> sc = Node[].class;
6070 <            ABASE = U.arrayBaseOffset(sc);
6071 <            int scale = U.arrayIndexScale(sc);
6069 >            Class<?> ak = Node[].class;
6070 >            ABASE = U.arrayBaseOffset(ak);
6071 >            int scale = U.arrayIndexScale(ak);
6072              if ((scale & (scale - 1)) != 0)
6073                  throw new Error("data type scale not a power of two");
6074              ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
# Line 6960 | Line 6076 | public class ConcurrentHashMap<K,V>
6076              throw new Error(e);
6077          }
6078      }
6963
6079   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines