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

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.85 by jsr166, Wed Jan 2 07:43:49 2013 UTC vs.
Revision 1.110 by dl, Thu Jul 4 18:34:49 2013 UTC

# Line 6 | Line 6
6  
7   package jsr166e;
8  
9 < import java.util.Comparator;
9 > import jsr166e.ForkJoinPool;
10 >
11 > import java.io.ObjectStreamField;
12 > import java.io.Serializable;
13 > import java.lang.reflect.ParameterizedType;
14 > import java.lang.reflect.Type;
15   import java.util.Arrays;
11 import java.util.Map;
12 import java.util.Set;
16   import java.util.Collection;
17 < import java.util.AbstractMap;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
17 < import java.util.Hashtable;
17 > import java.util.Comparator;
18 > import java.util.ConcurrentModificationException;
19 > import java.util.Enumeration;
20   import java.util.HashMap;
21 + import java.util.Hashtable;
22   import java.util.Iterator;
23 < import java.util.Enumeration;
21 < import java.util.ConcurrentModificationException;
23 > import java.util.Map;
24   import java.util.NoSuchElementException;
25 + import java.util.Set;
26   import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 import java.util.concurrent.atomic.AtomicInteger;
27   import java.util.concurrent.atomic.AtomicReference;
28 < import java.io.Serializable;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 > import java.util.concurrent.locks.LockSupport;
30 > import java.util.concurrent.locks.ReentrantLock;
31  
32   /**
33   * A hash table supporting full concurrency of retrievals and
# Line 78 | Line 81 | import java.io.Serializable;
81   * expected {@code concurrencyLevel} as an additional hint for
82   * internal sizing.  Note that using many keys with exactly the same
83   * {@code hashCode()} is a sure way to slow down performance of any
84 < * hash table.
84 > * hash table. To ameliorate impact, when keys are {@link Comparable},
85 > * this class may use comparison order among keys to help break ties.
86   *
87   * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
88   * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
# Line 86 | Line 90 | import java.io.Serializable;
90   * mapped values are (perhaps transiently) not used or all take the
91   * same mapping value.
92   *
89 * <p>A ConcurrentHashMapV8 can be used as scalable frequency map (a
90 * form of histogram or multiset) by using {@link LongAdder} values
91 * and initializing via {@link #computeIfAbsent}. For example, to add
92 * a count to a {@code ConcurrentHashMapV8<String,LongAdder> freqs}, you
93 * can use {@code freqs.computeIfAbsent(k -> new
94 * LongAdder()).increment();}
95 *
93   * <p>This class and its views and iterators implement all of the
94   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
95   * interfaces.
# Line 100 | Line 97 | import java.io.Serializable;
97   * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
98   * does <em>not</em> allow {@code null} to be used as a key or value.
99   *
100 < * <p>ConcurrentHashMapV8s support sequential and parallel operations
101 < * bulk operations. (Parallel forms use the {@link
102 < * ForkJoinPool#commonPool()}). Tasks that may be used in other
103 < * contexts are available in class {@link ForkJoinTasks}. These
104 < * operations are designed to be safely, and often sensibly, applied
105 < * even with maps that are being concurrently updated by other
106 < * threads; for example, when computing a snapshot summary of the
107 < * values in a shared registry.  There are three kinds of operation,
108 < * each with four forms, accepting functions with Keys, Values,
109 < * Entries, and (Key, Value) arguments and/or return values. Because
110 < * the elements of a ConcurrentHashMapV8 are not ordered in any
111 < * particular way, and may be processed in different orders in
112 < * different parallel executions, the correctness of supplied
113 < * functions should not depend on any ordering, or on any other
114 < * objects or values that may transiently change while computation is
118 < * in progress; and except for forEach actions, should ideally be
119 < * side-effect-free.
100 > * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
101 > * operations that are designed
102 > * to be safely, and often sensibly, applied even with maps that are
103 > * being concurrently updated by other threads; for example, when
104 > * computing a snapshot summary of the values in a shared registry.
105 > * There are three kinds of operation, each with four forms, accepting
106 > * functions with Keys, Values, Entries, and (Key, Value) arguments
107 > * and/or return values. Because the elements of a ConcurrentHashMapV8
108 > * are not ordered in any particular way, and may be processed in
109 > * different orders in different parallel executions, the correctness
110 > * of supplied functions should not depend on any ordering, or on any
111 > * other objects or values that may transiently change while
112 > * computation is in progress; and except for forEach actions, should
113 > * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
114 > * objects do not support method {@code setValue}.
115   *
116   * <ul>
117   * <li> forEach: Perform a given action on each element.
# Line 143 | Line 138 | import java.io.Serializable;
138   * <li> Reductions to scalar doubles, longs, and ints, using a
139   * given basis value.</li>
140   *
146 * </li>
141   * </ul>
142 + * </li>
143   * </ul>
144   *
145 + * <p>These bulk operations accept a {@code parallelismThreshold}
146 + * argument. Methods proceed sequentially if the current map size is
147 + * estimated to be less than the given threshold. Using a value of
148 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
149 + * of {@code 1} results in maximal parallelism by partitioning into
150 + * enough subtasks to fully utilize the {@link
151 + * ForkJoinPool#commonPool()} that is used for all parallel
152 + * computations. Normally, you would initially choose one of these
153 + * extreme values, and then measure performance of using in-between
154 + * values that trade off overhead versus throughput.
155 + *
156   * <p>The concurrency properties of bulk operations follow
157   * from those of ConcurrentHashMapV8: Any non-null result returned
158   * from {@code get(key)} and related access methods bears a
# Line 212 | Line 218 | import java.io.Serializable;
218   * @param <K> the type of keys maintained by this map
219   * @param <V> the type of mapped values
220   */
221 < public class ConcurrentHashMapV8<K, V>
222 <    implements ConcurrentMap<K, V>, Serializable {
221 > public class ConcurrentHashMapV8<K,V>
222 >    implements ConcurrentMap<K,V>, Serializable {
223      private static final long serialVersionUID = 7249069246763182397L;
224  
225      /**
226 <     * A partitionable iterator. A Spliterator can be traversed
227 <     * directly, but can also be partitioned (before traversal) by
228 <     * creating another Spliterator that covers a non-overlapping
223 <     * portion of the elements, and so may be amenable to parallel
224 <     * execution.
225 <     *
226 <     * <p>This interface exports a subset of expected JDK8
227 <     * functionality.
228 <     *
229 <     * <p>Sample usage: Here is one (of the several) ways to compute
230 <     * the sum of the values held in a map using the ForkJoin
231 <     * framework. As illustrated here, Spliterators are well suited to
232 <     * designs in which a task repeatedly splits off half its work
233 <     * into forked subtasks until small enough to process directly,
234 <     * and then joins these subtasks. Variants of this style can also
235 <     * be used in completion-based designs.
236 <     *
237 <     * <pre>
238 <     * {@code ConcurrentHashMapV8<String, Long> m = ...
239 <     * // split as if have 8 * parallelism, for load balance
240 <     * int n = m.size();
241 <     * int p = aForkJoinPool.getParallelism() * 8;
242 <     * int split = (n < p)? n : p;
243 <     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
244 <     * // ...
245 <     * static class SumValues extends RecursiveTask<Long> {
246 <     *   final Spliterator<Long> s;
247 <     *   final int split;             // split while > 1
248 <     *   final SumValues nextJoin;    // records forked subtasks to join
249 <     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
250 <     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
251 <     *   }
252 <     *   public Long compute() {
253 <     *     long sum = 0;
254 <     *     SumValues subtasks = null; // fork subtasks
255 <     *     for (int s = split >>> 1; s > 0; s >>>= 1)
256 <     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
257 <     *     while (s.hasNext())        // directly process remaining elements
258 <     *       sum += s.next();
259 <     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
260 <     *       sum += t.join();         // collect subtask results
261 <     *     return sum;
262 <     *   }
263 <     * }
264 <     * }</pre>
226 >     * An object for traversing and partitioning elements of a source.
227 >     * This interface provides a subset of the functionality of JDK8
228 >     * java.util.Spliterator.
229       */
230 <    public static interface Spliterator<T> extends Iterator<T> {
230 >    public static interface ConcurrentHashMapSpliterator<T> {
231          /**
232 <         * Returns a Spliterator covering approximately half of the
233 <         * elements, guaranteed not to overlap with those subsequently
234 <         * returned by this Spliterator.  After invoking this method,
235 <         * the current Spliterator will <em>not</em> produce any of
236 <         * the elements of the returned Spliterator, but the two
237 <         * Spliterators together will produce all of the elements that
238 <         * would have been produced by this Spliterator had this
239 <         * method not been called. The exact number of elements
240 <         * produced by the returned Spliterator is not guaranteed, and
277 <         * may be zero (i.e., with {@code hasNext()} reporting {@code
278 <         * false}) if this Spliterator cannot be further split.
279 <         *
280 <         * @return a Spliterator covering approximately half of the
281 <         * elements
282 <         * @throws IllegalStateException if this Spliterator has
283 <         * already commenced traversing elements
232 >         * If possible, returns a new spliterator covering
233 >         * approximately one half of the elements, which will not be
234 >         * covered by this spliterator. Returns null if cannot be
235 >         * split.
236 >         */
237 >        ConcurrentHashMapSpliterator<T> trySplit();
238 >        /**
239 >         * Returns an estimate of the number of elements covered by
240 >         * this Spliterator.
241           */
242 <        Spliterator<T> split();
242 >        long estimateSize();
243 >
244 >        /** Applies the action to each untraversed element */
245 >        void forEachRemaining(Action<? super T> action);
246 >        /** If an element remains, applies the action and returns true. */
247 >        boolean tryAdvance(Action<? super T> action);
248      }
249  
250 +    // Sams
251 +    /** Interface describing a void action of one argument */
252 +    public interface Action<A> { void apply(A a); }
253 +    /** Interface describing a void action of two arguments */
254 +    public interface BiAction<A,B> { void apply(A a, B b); }
255 +    /** Interface describing a function of one argument */
256 +    public interface Fun<A,T> { T apply(A a); }
257 +    /** Interface describing a function of two arguments */
258 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
259 +    /** Interface describing a function mapping its argument to a double */
260 +    public interface ObjectToDouble<A> { double apply(A a); }
261 +    /** Interface describing a function mapping its argument to a long */
262 +    public interface ObjectToLong<A> { long apply(A a); }
263 +    /** Interface describing a function mapping its argument to an int */
264 +    public interface ObjectToInt<A> {int apply(A a); }
265 +    /** Interface describing a function mapping two arguments to a double */
266 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
267 +    /** Interface describing a function mapping two arguments to a long */
268 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
269 +    /** Interface describing a function mapping two arguments to an int */
270 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
271 +    /** Interface describing a function mapping two doubles to a double */
272 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
273 +    /** Interface describing a function mapping two longs to a long */
274 +    public interface LongByLongToLong { long apply(long a, long b); }
275 +    /** Interface describing a function mapping two ints to an int */
276 +    public interface IntByIntToInt { int apply(int a, int b); }
277 +
278      /*
279       * Overview:
280       *
# Line 295 | Line 285 | public class ConcurrentHashMapV8<K, V>
285       * the same or better than java.util.HashMap, and to support high
286       * initial insertion rates on an empty table by many threads.
287       *
288 <     * Each key-value mapping is held in a Node.  Because Node key
289 <     * fields can contain special values, they are defined using plain
290 <     * Object types (not type "K"). This leads to a lot of explicit
291 <     * casting (and many explicit warning suppressions to tell
292 <     * compilers not to complain about it). It also allows some of the
293 <     * public methods to be factored into a smaller number of internal
294 <     * methods (although sadly not so for the five variants of
295 <     * put-related operations). The validation-based approach
296 <     * explained below leads to a lot of code sprawl because
297 <     * retry-control precludes factoring into smaller methods.
288 >     * This map usually acts as a binned (bucketed) hash table.  Each
289 >     * key-value mapping is held in a Node.  Most nodes are instances
290 >     * of the basic Node class with hash, key, value, and next
291 >     * fields. However, various subclasses exist: TreeNodes are
292 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
293 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
294 >     * of bins during resizing. ReservationNodes are used as
295 >     * placeholders while establishing values in computeIfAbsent and
296 >     * related methods.  The types TreeBin, ForwardingNode, and
297 >     * ReservationNode do not hold normal user keys, values, or
298 >     * hashes, and are readily distinguishable during search etc
299 >     * because they have negative hash fields and null key and value
300 >     * fields. (These special nodes are either uncommon or transient,
301 >     * so the impact of carrying around some unused fields is
302 >     * insignificant.)
303       *
304       * The table is lazily initialized to a power-of-two size upon the
305       * first insertion.  Each bin in the table normally contains a
# Line 312 | Line 307 | public class ConcurrentHashMapV8<K, V>
307       * Table accesses require volatile/atomic reads, writes, and
308       * CASes.  Because there is no other way to arrange this without
309       * adding further indirections, we use intrinsics
310 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
316 <     * are always accurately traversable under volatile reads, so long
317 <     * as lookups check hash code and non-nullness of value before
318 <     * checking key equality.
310 >     * (sun.misc.Unsafe) operations.
311       *
312       * We use the top (sign) bit of Node hash fields for control
313       * purposes -- it is available anyway because of addressing
314 <     * constraints.  Nodes with negative hash fields are forwarding
315 <     * nodes to either TreeBins or resized tables.  The lower 31 bits
324 <     * of each normal Node's hash field contain a transformation of
325 <     * the key's hash code.
314 >     * constraints.  Nodes with negative hash fields are specially
315 >     * handled or ignored in map methods.
316       *
317       * Insertion (via put or its variants) of the first node in an
318       * empty bin is performed by just CASing it to the bin.  This is
# Line 339 | Line 329 | public class ConcurrentHashMapV8<K, V>
329       * validate that it is still the first node after locking it, and
330       * retry if not. Because new nodes are always appended to lists,
331       * once a node is first in a bin, it remains first until deleted
332 <     * or the bin becomes invalidated (upon resizing).  However,
343 <     * operations that only conditionally update may inspect nodes
344 <     * until the point of update. This is a converse of sorts to the
345 <     * lazy locking technique described by Herlihy & Shavit.
332 >     * or the bin becomes invalidated (upon resizing).
333       *
334       * The main disadvantage of per-bin locks is that other update
335       * operations on other nodes in a bin list protected by the same
# Line 375 | Line 362 | public class ConcurrentHashMapV8<K, V>
362       * sometimes deviate significantly from uniform randomness.  This
363       * includes the case when N > (1<<30), so some keys MUST collide.
364       * Similarly for dumb or hostile usages in which multiple keys are
365 <     * designed to have identical hash codes. Also, although we guard
366 <     * against the worst effects of this (see method spread), sets of
367 <     * hashes may differ only in bits that do not impact their bin
368 <     * index for a given power-of-two mask.  So we use a secondary
369 <     * strategy that applies when the number of nodes in a bin exceeds
370 <     * a threshold, and at least one of the keys implements
384 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
385 <     * (a specialized form of red-black trees), bounding search time
386 <     * to O(log N).  Each search step in a TreeBin is around twice as
365 >     * designed to have identical hash codes or ones that differs only
366 >     * in masked-out high bits. So we use a secondary strategy that
367 >     * applies when the number of nodes in a bin exceeds a
368 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
369 >     * specialized form of red-black trees), bounding search time to
370 >     * O(log N).  Each search step in a TreeBin is at least twice as
371       * slow as in a regular list, but given that N cannot exceed
372       * (1<<64) (before running out of addresses) this bounds search
373       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 456 | Line 440 | public class ConcurrentHashMapV8<K, V>
440       * bin already holding two or more nodes. Under uniform hash
441       * distributions, the probability of this occurring at threshold
442       * is around 13%, meaning that only about 1 in 8 puts check
443 <     * threshold (and after resizing, many fewer do so). The bulk
444 <     * putAll operation further reduces contention by only committing
445 <     * count updates upon these size checks.
443 >     * threshold (and after resizing, many fewer do so).
444 >     *
445 >     * TreeBins use a special form of comparison for search and
446 >     * related operations (which is the main reason we cannot use
447 >     * existing collections such as TreeMaps). TreeBins contain
448 >     * Comparable elements, but may contain others, as well as
449 >     * elements that are Comparable but not necessarily Comparable
450 >     * for the same T, so we cannot invoke compareTo among them. To
451 >     * handle this, the tree is ordered primarily by hash value, then
452 >     * by Comparable.compareTo order if applicable.  On lookup at a
453 >     * node, if elements are not comparable or compare as 0 then both
454 >     * left and right children may need to be searched in the case of
455 >     * tied hash values. (This corresponds to the full list search
456 >     * that would be necessary if all elements were non-Comparable and
457 >     * had tied hashes.)  The red-black balancing code is updated from
458 >     * pre-jdk-collections
459 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
460 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
461 >     * Algorithms" (CLR).
462 >     *
463 >     * TreeBins also require an additional locking mechanism.  While
464 >     * list traversal is always possible by readers even during
465 >     * updates, tree traversal is not, mainly because of tree-rotations
466 >     * that may change the root node and/or its linkages.  TreeBins
467 >     * include a simple read-write lock mechanism parasitic on the
468 >     * main bin-synchronization strategy: Structural adjustments
469 >     * associated with an insertion or removal are already bin-locked
470 >     * (and so cannot conflict with other writers) but must wait for
471 >     * ongoing readers to finish. Since there can be only one such
472 >     * waiter, we use a simple scheme using a single "waiter" field to
473 >     * block writers.  However, readers need never block.  If the root
474 >     * lock is held, they proceed along the slow traversal path (via
475 >     * next-pointers) until the lock becomes available or the list is
476 >     * exhausted, whichever comes first. These cases are not fast, but
477 >     * maximize aggregate expected throughput.
478       *
479       * Maintaining API and serialization compatibility with previous
480       * versions of this class introduces several oddities. Mainly: We
# Line 468 | Line 484 | public class ConcurrentHashMapV8<K, V>
484       * time that we can guarantee to honor it.) We also declare an
485       * unused "Segment" class that is instantiated in minimal form
486       * only when serializing.
487 +     *
488 +     * This file is organized to make things a little easier to follow
489 +     * while reading than they might otherwise: First the main static
490 +     * declarations and utilities, then fields, then main public
491 +     * methods (with a few factorings of multiple public methods into
492 +     * internal ones), then sizing methods, trees, traversers, and
493 +     * bulk operations.
494       */
495  
496      /* ---------------- Constants -------------- */
# Line 510 | Line 533 | public class ConcurrentHashMapV8<K, V>
533  
534      /**
535       * The bin count threshold for using a tree rather than list for a
536 <     * bin.  The value reflects the approximate break-even point for
537 <     * using tree-based operations.
536 >     * bin.  Bins are converted to trees when adding an element to a
537 >     * bin with at least this many nodes. The value must be greater
538 >     * than 2, and should be at least 8 to mesh with assumptions in
539 >     * tree removal about conversion back to plain bins upon
540 >     * shrinkage.
541 >     */
542 >    static final int TREEIFY_THRESHOLD = 8;
543 >
544 >    /**
545 >     * The bin count threshold for untreeifying a (split) bin during a
546 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
547 >     * most 6 to mesh with shrinkage detection under removal.
548       */
549 <    private static final int TREE_THRESHOLD = 8;
549 >    static final int UNTREEIFY_THRESHOLD = 6;
550 >
551 >    /**
552 >     * The smallest table capacity for which bins may be treeified.
553 >     * (Otherwise the table is resized if too many nodes in a bin.)
554 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
555 >     * conflicts between resizing and treeification thresholds.
556 >     */
557 >    static final int MIN_TREEIFY_CAPACITY = 64;
558  
559      /**
560       * Minimum number of rebinnings per transfer step. Ranges are
# Line 527 | Line 568 | public class ConcurrentHashMapV8<K, V>
568      /*
569       * Encodings for Node hash fields. See above for explanation.
570       */
571 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
571 >    static final int MOVED     = -1; // hash for forwarding nodes
572 >    static final int TREEBIN   = -2; // hash for roots of trees
573 >    static final int RESERVED  = -3; // hash for transient reservations
574      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
575  
576      /** Number of CPUS, to place bounds on some sizings */
577      static final int NCPU = Runtime.getRuntime().availableProcessors();
578  
579 <    /* ---------------- Counters -------------- */
579 >    /** For serialization compatibility. */
580 >    private static final ObjectStreamField[] serialPersistentFields = {
581 >        new ObjectStreamField("segments", Segment[].class),
582 >        new ObjectStreamField("segmentMask", Integer.TYPE),
583 >        new ObjectStreamField("segmentShift", Integer.TYPE)
584 >    };
585  
586 <    // Adapted from LongAdder and Striped64.
539 <    // See their internal docs for explanation.
586 >    /* ---------------- Nodes -------------- */
587  
588 <    // A padded cell for distributing counts
589 <    static final class CounterCell {
590 <        volatile long p0, p1, p2, p3, p4, p5, p6;
591 <        volatile long value;
592 <        volatile long q0, q1, q2, q3, q4, q5, q6;
593 <        CounterCell(long x) { value = x; }
588 >    /**
589 >     * Key-value entry.  This class is never exported out as a
590 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
591 >     * MapEntry below), but can be used for read-only traversals used
592 >     * in bulk tasks.  Subclasses of Node with a negative hash field
593 >     * are special, and contain null keys and values (but are never
594 >     * exported).  Otherwise, keys and vals are never null.
595 >     */
596 >    static class Node<K,V> implements Map.Entry<K,V> {
597 >        final int hash;
598 >        final K key;
599 >        volatile V val;
600 >        volatile Node<K,V> next;
601 >
602 >        Node(int hash, K key, V val, Node<K,V> next) {
603 >            this.hash = hash;
604 >            this.key = key;
605 >            this.val = val;
606 >            this.next = next;
607 >        }
608 >
609 >        public final K getKey()       { return key; }
610 >        public final V getValue()     { return val; }
611 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
612 >        public final String toString(){ return key + "=" + val; }
613 >        public final V setValue(V value) {
614 >            throw new UnsupportedOperationException();
615 >        }
616 >
617 >        public final boolean equals(Object o) {
618 >            Object k, v, u; Map.Entry<?,?> e;
619 >            return ((o instanceof Map.Entry) &&
620 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
621 >                    (v = e.getValue()) != null &&
622 >                    (k == key || k.equals(key)) &&
623 >                    (v == (u = val) || v.equals(u)));
624 >        }
625 >
626 >        /**
627 >         * Virtualized support for map.get(); overridden in subclasses.
628 >         */
629 >        Node<K,V> find(int h, Object k) {
630 >            Node<K,V> e = this;
631 >            if (k != null) {
632 >                do {
633 >                    K ek;
634 >                    if (e.hash == h &&
635 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
636 >                        return e;
637 >                } while ((e = e.next) != null);
638 >            }
639 >            return null;
640 >        }
641      }
642  
643 +    /* ---------------- Static utilities -------------- */
644 +
645      /**
646 <     * Holder for the thread-local hash code determining which
647 <     * CounterCell to use. The code is initialized via the
648 <     * counterHashCodeGenerator, but may be moved upon collisions.
646 >     * Spreads (XORs) higher bits of hash to lower and also forces top
647 >     * bit to 0. Because the table uses power-of-two masking, sets of
648 >     * hashes that vary only in bits above the current mask will
649 >     * always collide. (Among known examples are sets of Float keys
650 >     * holding consecutive whole numbers in small tables.)  So we
651 >     * apply a transform that spreads the impact of higher bits
652 >     * downward. There is a tradeoff between speed, utility, and
653 >     * quality of bit-spreading. Because many common sets of hashes
654 >     * are already reasonably distributed (so don't benefit from
655 >     * spreading), and because we use trees to handle large sets of
656 >     * collisions in bins, we just XOR some shifted bits in the
657 >     * cheapest possible way to reduce systematic lossage, as well as
658 >     * to incorporate impact of the highest bits that would otherwise
659 >     * never be used in index calculations because of table bounds.
660       */
661 <    static final class CounterHashCode {
662 <        int code;
661 >    static final int spread(int h) {
662 >        return (h ^ (h >>> 16)) & HASH_BITS;
663      }
664  
665      /**
666 <     * Generates initial value for per-thread CounterHashCodes
666 >     * Returns a power of two table size for the given desired capacity.
667 >     * See Hackers Delight, sec 3.2
668       */
669 <    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
669 >    private static final int tableSizeFor(int c) {
670 >        int n = c - 1;
671 >        n |= n >>> 1;
672 >        n |= n >>> 2;
673 >        n |= n >>> 4;
674 >        n |= n >>> 8;
675 >        n |= n >>> 16;
676 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
677 >    }
678  
679      /**
680 <     * Increment for counterHashCodeGenerator. See class ThreadLocal
681 <     * for explanation.
680 >     * Returns x's Class if it is of the form "class C implements
681 >     * Comparable<C>", else null.
682       */
683 <    static final int SEED_INCREMENT = 0x61c88647;
683 >    static Class<?> comparableClassFor(Object x) {
684 >        if (x instanceof Comparable) {
685 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
686 >            if ((c = x.getClass()) == String.class) // bypass checks
687 >                return c;
688 >            if ((ts = c.getGenericInterfaces()) != null) {
689 >                for (int i = 0; i < ts.length; ++i) {
690 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
691 >                        ((p = (ParameterizedType)t).getRawType() ==
692 >                         Comparable.class) &&
693 >                        (as = p.getActualTypeArguments()) != null &&
694 >                        as.length == 1 && as[0] == c) // type arg is c
695 >                        return c;
696 >                }
697 >            }
698 >        }
699 >        return null;
700 >    }
701  
702      /**
703 <     * Per-thread counter hash codes. Shared across all instances
703 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
704 >     * class), else 0.
705       */
706 <    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
707 <        new ThreadLocal<CounterHashCode>();
706 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
707 >    static int compareComparables(Class<?> kc, Object k, Object x) {
708 >        return (x == null || x.getClass() != kc ? 0 :
709 >                ((Comparable)k).compareTo(x));
710 >    }
711 >
712 >    /* ---------------- Table element access -------------- */
713 >
714 >    /*
715 >     * Volatile access methods are used for table elements as well as
716 >     * elements of in-progress next table while resizing.  All uses of
717 >     * the tab arguments must be null checked by callers.  All callers
718 >     * also paranoically precheck that tab's length is not zero (or an
719 >     * equivalent check), thus ensuring that any index argument taking
720 >     * the form of a hash value anded with (length - 1) is a valid
721 >     * index.  Note that, to be correct wrt arbitrary concurrency
722 >     * errors by users, these checks must operate on local variables,
723 >     * which accounts for some odd-looking inline assignments below.
724 >     * Note that calls to setTabAt always occur within locked regions,
725 >     * and so in principle require only release ordering, not need
726 >     * full volatile semantics, but are currently coded as volatile
727 >     * writes to be conservative.
728 >     */
729 >
730 >    @SuppressWarnings("unchecked")
731 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
732 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
733 >    }
734 >
735 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
736 >                                        Node<K,V> c, Node<K,V> v) {
737 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
738 >    }
739 >
740 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
741 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
742 >    }
743  
744      /* ---------------- Fields -------------- */
745  
# Line 578 | Line 747 | public class ConcurrentHashMapV8<K, V>
747       * The array of bins. Lazily initialized upon first insertion.
748       * Size is always a power of two. Accessed directly by iterators.
749       */
750 <    transient volatile Node<V>[] table;
750 >    transient volatile Node<K,V>[] table;
751  
752      /**
753       * The next table to use; non-null only while resizing.
754       */
755 <    private transient volatile Node<V>[] nextTable;
755 >    private transient volatile Node<K,V>[] nextTable;
756  
757      /**
758       * Base counter value, used mainly when there is no contention,
# Line 613 | Line 782 | public class ConcurrentHashMapV8<K, V>
782      private transient volatile int transferOrigin;
783  
784      /**
785 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
785 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
786       */
787 <    private transient volatile int counterBusy;
787 >    private transient volatile int cellsBusy;
788  
789      /**
790       * Table of counter cells. When non-null, size is a power of 2.
# Line 627 | Line 796 | public class ConcurrentHashMapV8<K, V>
796      private transient ValuesView<K,V> values;
797      private transient EntrySetView<K,V> entrySet;
798  
630    /** For serialization compatibility. Null unless serialized; see below */
631    private Segment<K,V>[] segments;
799  
800 <    /* ---------------- Table element access -------------- */
800 >    /* ---------------- Public operations -------------- */
801  
802 <    /*
803 <     * Volatile access methods are used for table elements as well as
804 <     * elements of in-progress next table while resizing.  Uses are
805 <     * null checked by callers, and implicitly bounds-checked, relying
639 <     * on the invariants that tab arrays have non-zero size, and all
640 <     * indices are masked with (tab.length - 1) which is never
641 <     * negative and always less than length. Note that, to be correct
642 <     * wrt arbitrary concurrency errors by users, bounds checks must
643 <     * operate on local variables, which accounts for some odd-looking
644 <     * inline assignments below.
645 <     */
646 <
647 <    @SuppressWarnings("unchecked") static final <V> Node<V> tabAt
648 <        (Node<V>[] tab, int i) { // used by Traverser
649 <        return (Node<V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
802 >    /**
803 >     * Creates a new, empty map with the default initial table size (16).
804 >     */
805 >    public ConcurrentHashMapV8() {
806      }
807  
808 <    private static final <V> boolean casTabAt
809 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
810 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
808 >    /**
809 >     * Creates a new, empty map with an initial table size
810 >     * accommodating the specified number of elements without the need
811 >     * to dynamically resize.
812 >     *
813 >     * @param initialCapacity The implementation performs internal
814 >     * sizing to accommodate this many elements.
815 >     * @throws IllegalArgumentException if the initial capacity of
816 >     * elements is negative
817 >     */
818 >    public ConcurrentHashMapV8(int initialCapacity) {
819 >        if (initialCapacity < 0)
820 >            throw new IllegalArgumentException();
821 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
822 >                   MAXIMUM_CAPACITY :
823 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
824 >        this.sizeCtl = cap;
825      }
826  
827 <    private static final <V> void setTabAt
828 <        (Node<V>[] tab, int i, Node<V> v) {
829 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
827 >    /**
828 >     * Creates a new map with the same mappings as the given map.
829 >     *
830 >     * @param m the map
831 >     */
832 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
833 >        this.sizeCtl = DEFAULT_CAPACITY;
834 >        putAll(m);
835      }
836  
662    /* ---------------- Nodes -------------- */
663
837      /**
838 <     * Key-value entry. Note that this is never exported out as a
839 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
840 <     * field of MOVED are special, and do not contain user keys or
841 <     * values.  Otherwise, keys are never null, and null val fields
842 <     * indicate that a node is in the process of being deleted or
843 <     * created. For purposes of read-only access, a key may be read
844 <     * before a val, but can only be used after checking val to be
845 <     * non-null.
838 >     * Creates a new, empty map with an initial table size based on
839 >     * the given number of elements ({@code initialCapacity}) and
840 >     * initial table density ({@code loadFactor}).
841 >     *
842 >     * @param initialCapacity the initial capacity. The implementation
843 >     * performs internal sizing to accommodate this many elements,
844 >     * given the specified load factor.
845 >     * @param loadFactor the load factor (table density) for
846 >     * establishing the initial table size
847 >     * @throws IllegalArgumentException if the initial capacity of
848 >     * elements is negative or the load factor is nonpositive
849 >     *
850 >     * @since 1.6
851       */
852 <    static class Node<V> {
853 <        final int hash;
854 <        final Object key;
677 <        volatile V val;
678 <        volatile Node<V> next;
852 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
853 >        this(initialCapacity, loadFactor, 1);
854 >    }
855  
856 <        Node(int hash, Object key, V val, Node<V> next) {
857 <            this.hash = hash;
858 <            this.key = key;
859 <            this.val = val;
860 <            this.next = next;
861 <        }
856 >    /**
857 >     * Creates a new, empty map with an initial table size based on
858 >     * the given number of elements ({@code initialCapacity}), table
859 >     * density ({@code loadFactor}), and number of concurrently
860 >     * updating threads ({@code concurrencyLevel}).
861 >     *
862 >     * @param initialCapacity the initial capacity. The implementation
863 >     * performs internal sizing to accommodate this many elements,
864 >     * given the specified load factor.
865 >     * @param loadFactor the load factor (table density) for
866 >     * establishing the initial table size
867 >     * @param concurrencyLevel the estimated number of concurrently
868 >     * updating threads. The implementation may use this value as
869 >     * a sizing hint.
870 >     * @throws IllegalArgumentException if the initial capacity is
871 >     * negative or the load factor or concurrencyLevel are
872 >     * nonpositive
873 >     */
874 >    public ConcurrentHashMapV8(int initialCapacity,
875 >                             float loadFactor, int concurrencyLevel) {
876 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
877 >            throw new IllegalArgumentException();
878 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
879 >            initialCapacity = concurrencyLevel;   // as estimated threads
880 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
881 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
882 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
883 >        this.sizeCtl = cap;
884      }
885  
886 <    /* ---------------- TreeBins -------------- */
886 >    // Original (since JDK1.2) Map methods
887  
888      /**
889 <     * Nodes for use in TreeBins
889 >     * {@inheritDoc}
890       */
891 <    static final class TreeNode<V> extends Node<V> {
892 <        TreeNode<V> parent;  // red-black tree links
893 <        TreeNode<V> left;
894 <        TreeNode<V> right;
895 <        TreeNode<V> prev;    // needed to unlink next upon deletion
896 <        boolean red;
891 >    public int size() {
892 >        long n = sumCount();
893 >        return ((n < 0L) ? 0 :
894 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
895 >                (int)n);
896 >    }
897  
898 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
899 <            super(hash, key, val, next);
900 <            this.parent = parent;
901 <        }
898 >    /**
899 >     * {@inheritDoc}
900 >     */
901 >    public boolean isEmpty() {
902 >        return sumCount() <= 0L; // ignore transient negative values
903      }
904  
905      /**
906 <     * A specialized form of red-black tree for use in bins
907 <     * whose size exceeds a threshold.
906 >     * Returns the value to which the specified key is mapped,
907 >     * or {@code null} if this map contains no mapping for the key.
908       *
909 <     * TreeBins use a special form of comparison for search and
910 <     * related operations (which is the main reason we cannot use
911 <     * existing collections such as TreeMaps). TreeBins contain
912 <     * Comparable elements, but may contain others, as well as
714 <     * elements that are Comparable but not necessarily Comparable<T>
715 <     * for the same T, so we cannot invoke compareTo among them. To
716 <     * handle this, the tree is ordered primarily by hash value, then
717 <     * by getClass().getName() order, and then by Comparator order
718 <     * among elements of the same class.  On lookup at a node, if
719 <     * elements are not comparable or compare as 0, both left and
720 <     * right children may need to be searched in the case of tied hash
721 <     * values. (This corresponds to the full list search that would be
722 <     * necessary if all elements were non-Comparable and had tied
723 <     * hashes.)  The red-black balancing code is updated from
724 <     * pre-jdk-collections
725 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
726 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
727 <     * Algorithms" (CLR).
909 >     * <p>More formally, if this map contains a mapping from a key
910 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
911 >     * then this method returns {@code v}; otherwise it returns
912 >     * {@code null}.  (There can be at most one such mapping.)
913       *
914 <     * TreeBins also maintain a separate locking discipline than
730 <     * regular bins. Because they are forwarded via special MOVED
731 <     * nodes at bin heads (which can never change once established),
732 <     * we cannot use those nodes as locks. Instead, TreeBin
733 <     * extends AbstractQueuedSynchronizer to support a simple form of
734 <     * read-write lock. For update operations and table validation,
735 <     * the exclusive form of lock behaves in the same way as bin-head
736 <     * locks. However, lookups use shared read-lock mechanics to allow
737 <     * multiple readers in the absence of writers.  Additionally,
738 <     * these lookups do not ever block: While the lock is not
739 <     * available, they proceed along the slow traversal path (via
740 <     * next-pointers) until the lock becomes available or the list is
741 <     * exhausted, whichever comes first. (These cases are not fast,
742 <     * but maximize aggregate expected throughput.)  The AQS mechanics
743 <     * for doing this are straightforward.  The lock state is held as
744 <     * AQS getState().  Read counts are negative; the write count (1)
745 <     * is positive.  There are no signalling preferences among readers
746 <     * and writers. Since we don't need to export full Lock API, we
747 <     * just override the minimal AQS methods and use them directly.
914 >     * @throws NullPointerException if the specified key is null
915       */
916 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
917 <        private static final long serialVersionUID = 2249069246763182397L;
918 <        transient TreeNode<V> root;  // root of tree
919 <        transient TreeNode<V> first; // head of next-pointer list
920 <
921 <        /* AQS overrides */
922 <        public final boolean isHeldExclusively() { return getState() > 0; }
923 <        public final boolean tryAcquire(int ignore) {
924 <            if (compareAndSetState(0, 1)) {
925 <                setExclusiveOwnerThread(Thread.currentThread());
926 <                return true;
927 <            }
928 <            return false;
929 <        }
930 <        public final boolean tryRelease(int ignore) {
764 <            setExclusiveOwnerThread(null);
765 <            setState(0);
766 <            return true;
767 <        }
768 <        public final int tryAcquireShared(int ignore) {
769 <            for (int c;;) {
770 <                if ((c = getState()) > 0)
771 <                    return -1;
772 <                if (compareAndSetState(c, c -1))
773 <                    return 1;
774 <            }
775 <        }
776 <        public final boolean tryReleaseShared(int ignore) {
777 <            int c;
778 <            do {} while (!compareAndSetState(c = getState(), c + 1));
779 <            return c == -1;
780 <        }
781 <
782 <        /** From CLR */
783 <        private void rotateLeft(TreeNode<V> p) {
784 <            if (p != null) {
785 <                TreeNode<V> r = p.right, pp, rl;
786 <                if ((rl = p.right = r.left) != null)
787 <                    rl.parent = p;
788 <                if ((pp = r.parent = p.parent) == null)
789 <                    root = r;
790 <                else if (pp.left == p)
791 <                    pp.left = r;
792 <                else
793 <                    pp.right = r;
794 <                r.left = p;
795 <                p.parent = r;
796 <            }
797 <        }
798 <
799 <        /** From CLR */
800 <        private void rotateRight(TreeNode<V> p) {
801 <            if (p != null) {
802 <                TreeNode<V> l = p.left, pp, lr;
803 <                if ((lr = p.left = l.right) != null)
804 <                    lr.parent = p;
805 <                if ((pp = l.parent = p.parent) == null)
806 <                    root = l;
807 <                else if (pp.right == p)
808 <                    pp.right = l;
809 <                else
810 <                    pp.left = l;
811 <                l.right = p;
812 <                p.parent = l;
916 >    public V get(Object key) {
917 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
918 >        int h = spread(key.hashCode());
919 >        if ((tab = table) != null && (n = tab.length) > 0 &&
920 >            (e = tabAt(tab, (n - 1) & h)) != null) {
921 >            if ((eh = e.hash) == h) {
922 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
923 >                    return e.val;
924 >            }
925 >            else if (eh < 0)
926 >                return (p = e.find(h, key)) != null ? p.val : null;
927 >            while ((e = e.next) != null) {
928 >                if (e.hash == h &&
929 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
930 >                    return e.val;
931              }
932          }
933 +        return null;
934 +    }
935  
936 <        /**
937 <         * Returns the TreeNode (or null if not found) for the given key
938 <         * starting at given root.
939 <         */
940 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
941 <            (int h, Object k, TreeNode<V> p) {
942 <            Class<?> c = k.getClass();
943 <            while (p != null) {
944 <                int dir, ph;  Object pk; Class<?> pc;
945 <                if ((ph = p.hash) == h) {
946 <                    if ((pk = p.key) == k || k.equals(pk))
947 <                        return p;
828 <                    if (c != (pc = pk.getClass()) ||
829 <                        !(k instanceof Comparable) ||
830 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
831 <                        if ((dir = (c == pc) ? 0 :
832 <                             c.getName().compareTo(pc.getName())) == 0) {
833 <                            TreeNode<V> r = null, pl, pr; // check both sides
834 <                            if ((pr = p.right) != null && h >= pr.hash &&
835 <                                (r = getTreeNode(h, k, pr)) != null)
836 <                                return r;
837 <                            else if ((pl = p.left) != null && h <= pl.hash)
838 <                                dir = -1;
839 <                            else // nothing there
840 <                                return null;
841 <                        }
842 <                    }
843 <                }
844 <                else
845 <                    dir = (h < ph) ? -1 : 1;
846 <                p = (dir > 0) ? p.right : p.left;
847 <            }
848 <            return null;
849 <        }
936 >    /**
937 >     * Tests if the specified object is a key in this table.
938 >     *
939 >     * @param  key possible key
940 >     * @return {@code true} if and only if the specified object
941 >     *         is a key in this table, as determined by the
942 >     *         {@code equals} method; {@code false} otherwise
943 >     * @throws NullPointerException if the specified key is null
944 >     */
945 >    public boolean containsKey(Object key) {
946 >        return get(key) != null;
947 >    }
948  
949 <        /**
950 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
951 <         * read-lock to call getTreeNode, but during failure to get
952 <         * lock, searches along next links.
953 <         */
954 <        final V getValue(int h, Object k) {
955 <            Node<V> r = null;
956 <            int c = getState(); // Must read lock state first
957 <            for (Node<V> e = first; e != null; e = e.next) {
958 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
959 <                    try {
960 <                        r = getTreeNode(h, k, root);
961 <                    } finally {
962 <                        releaseShared(0);
963 <                    }
964 <                    break;
965 <                }
966 <                else if (e.hash == h && k.equals(e.key)) {
967 <                    r = e;
968 <                    break;
871 <                }
872 <                else
873 <                    c = getState();
949 >    /**
950 >     * Returns {@code true} if this map maps one or more keys to the
951 >     * specified value. Note: This method may require a full traversal
952 >     * of the map, and is much slower than method {@code containsKey}.
953 >     *
954 >     * @param value value whose presence in this map is to be tested
955 >     * @return {@code true} if this map maps one or more keys to the
956 >     *         specified value
957 >     * @throws NullPointerException if the specified value is null
958 >     */
959 >    public boolean containsValue(Object value) {
960 >        if (value == null)
961 >            throw new NullPointerException();
962 >        Node<K,V>[] t;
963 >        if ((t = table) != null) {
964 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
965 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
966 >                V v;
967 >                if ((v = p.val) == value || (v != null && value.equals(v)))
968 >                    return true;
969              }
875            return r == null ? null : r.val;
970          }
971 +        return false;
972 +    }
973  
974 <        /**
975 <         * Finds or adds a node.
976 <         * @return null if added
977 <         */
978 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
979 <            (int h, Object k, V v) {
980 <            Class<?> c = k.getClass();
981 <            TreeNode<V> pp = root, p = null;
982 <            int dir = 0;
983 <            while (pp != null) { // find existing node or leaf to insert at
984 <                int ph;  Object pk; Class<?> pc;
985 <                p = pp;
986 <                if ((ph = p.hash) == h) {
987 <                    if ((pk = p.key) == k || k.equals(pk))
988 <                        return p;
989 <                    if (c != (pc = pk.getClass()) ||
894 <                        !(k instanceof Comparable) ||
895 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
896 <                        TreeNode<V> s = null, r = null, pr;
897 <                        if ((dir = (c == pc) ? 0 :
898 <                             c.getName().compareTo(pc.getName())) == 0) {
899 <                            if ((pr = p.right) != null && h >= pr.hash &&
900 <                                (r = getTreeNode(h, k, pr)) != null)
901 <                                return r;
902 <                            else // continue left
903 <                                dir = -1;
904 <                        }
905 <                        else if ((pr = p.right) != null && h >= pr.hash)
906 <                            s = pr;
907 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
908 <                            return r;
909 <                    }
910 <                }
911 <                else
912 <                    dir = (h < ph) ? -1 : 1;
913 <                pp = (dir > 0) ? p.right : p.left;
914 <            }
915 <
916 <            TreeNode<V> f = first;
917 <            TreeNode<V> x = first = new TreeNode<V>(h, k, v, f, p);
918 <            if (p == null)
919 <                root = x;
920 <            else { // attach and rebalance; adapted from CLR
921 <                TreeNode<V> xp, xpp;
922 <                if (f != null)
923 <                    f.prev = x;
924 <                if (dir <= 0)
925 <                    p.left = x;
926 <                else
927 <                    p.right = x;
928 <                x.red = true;
929 <                while (x != null && (xp = x.parent) != null && xp.red &&
930 <                       (xpp = xp.parent) != null) {
931 <                    TreeNode<V> xppl = xpp.left;
932 <                    if (xp == xppl) {
933 <                        TreeNode<V> y = xpp.right;
934 <                        if (y != null && y.red) {
935 <                            y.red = false;
936 <                            xp.red = false;
937 <                            xpp.red = true;
938 <                            x = xpp;
939 <                        }
940 <                        else {
941 <                            if (x == xp.right) {
942 <                                rotateLeft(x = xp);
943 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
944 <                            }
945 <                            if (xp != null) {
946 <                                xp.red = false;
947 <                                if (xpp != null) {
948 <                                    xpp.red = true;
949 <                                    rotateRight(xpp);
950 <                                }
951 <                            }
952 <                        }
953 <                    }
954 <                    else {
955 <                        TreeNode<V> y = xppl;
956 <                        if (y != null && y.red) {
957 <                            y.red = false;
958 <                            xp.red = false;
959 <                            xpp.red = true;
960 <                            x = xpp;
961 <                        }
962 <                        else {
963 <                            if (x == xp.left) {
964 <                                rotateRight(x = xp);
965 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
966 <                            }
967 <                            if (xp != null) {
968 <                                xp.red = false;
969 <                                if (xpp != null) {
970 <                                    xpp.red = true;
971 <                                    rotateLeft(xpp);
972 <                                }
973 <                            }
974 <                        }
975 <                    }
976 <                }
977 <                TreeNode<V> r = root;
978 <                if (r != null && r.red)
979 <                    r.red = false;
980 <            }
981 <            return null;
982 <        }
974 >    /**
975 >     * Maps the specified key to the specified value in this table.
976 >     * Neither the key nor the value can be null.
977 >     *
978 >     * <p>The value can be retrieved by calling the {@code get} method
979 >     * with a key that is equal to the original key.
980 >     *
981 >     * @param key key with which the specified value is to be associated
982 >     * @param value value to be associated with the specified key
983 >     * @return the previous value associated with {@code key}, or
984 >     *         {@code null} if there was no mapping for {@code key}
985 >     * @throws NullPointerException if the specified key or value is null
986 >     */
987 >    public V put(K key, V value) {
988 >        return putVal(key, value, false);
989 >    }
990  
991 <        /**
992 <         * Removes the given node, that must be present before this
993 <         * call.  This is messier than typical red-black deletion code
994 <         * because we cannot swap the contents of an interior node
995 <         * with a leaf successor that is pinned by "next" pointers
996 <         * that are accessible independently of lock. So instead we
997 <         * swap the tree linkages.
998 <         */
999 <        final void deleteTreeNode(TreeNode<V> p) {
1000 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
1001 <            TreeNode<V> pred = p.prev;
1002 <            if (pred == null)
1003 <                first = next;
997 <            else
998 <                pred.next = next;
999 <            if (next != null)
1000 <                next.prev = pred;
1001 <            TreeNode<V> replacement;
1002 <            TreeNode<V> pl = p.left;
1003 <            TreeNode<V> pr = p.right;
1004 <            if (pl != null && pr != null) {
1005 <                TreeNode<V> s = pr, sl;
1006 <                while ((sl = s.left) != null) // find successor
1007 <                    s = sl;
1008 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1009 <                TreeNode<V> sr = s.right;
1010 <                TreeNode<V> pp = p.parent;
1011 <                if (s == pr) { // p was s's direct parent
1012 <                    p.parent = s;
1013 <                    s.right = p;
1014 <                }
1015 <                else {
1016 <                    TreeNode<V> sp = s.parent;
1017 <                    if ((p.parent = sp) != null) {
1018 <                        if (s == sp.left)
1019 <                            sp.left = p;
1020 <                        else
1021 <                            sp.right = p;
1022 <                    }
1023 <                    if ((s.right = pr) != null)
1024 <                        pr.parent = s;
1025 <                }
1026 <                p.left = null;
1027 <                if ((p.right = sr) != null)
1028 <                    sr.parent = p;
1029 <                if ((s.left = pl) != null)
1030 <                    pl.parent = s;
1031 <                if ((s.parent = pp) == null)
1032 <                    root = s;
1033 <                else if (p == pp.left)
1034 <                    pp.left = s;
1035 <                else
1036 <                    pp.right = s;
1037 <                replacement = sr;
1038 <            }
1039 <            else
1040 <                replacement = (pl != null) ? pl : pr;
1041 <            TreeNode<V> pp = p.parent;
1042 <            if (replacement == null) {
1043 <                if (pp == null) {
1044 <                    root = null;
1045 <                    return;
1046 <                }
1047 <                replacement = p;
991 >    /** Implementation for put and putIfAbsent */
992 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
993 >        if (key == null || value == null) throw new NullPointerException();
994 >        int hash = spread(key.hashCode());
995 >        int binCount = 0;
996 >        for (Node<K,V>[] tab = table;;) {
997 >            Node<K,V> f; int n, i, fh;
998 >            if (tab == null || (n = tab.length) == 0)
999 >                tab = initTable();
1000 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1001 >                if (casTabAt(tab, i, null,
1002 >                             new Node<K,V>(hash, key, value, null)))
1003 >                    break;                   // no lock when adding to empty bin
1004              }
1005 +            else if ((fh = f.hash) == MOVED)
1006 +                tab = helpTransfer(tab, f);
1007              else {
1008 <                replacement.parent = pp;
1009 <                if (pp == null)
1010 <                    root = replacement;
1011 <                else if (p == pp.left)
1012 <                    pp.left = replacement;
1013 <                else
1014 <                    pp.right = replacement;
1015 <                p.left = p.right = p.parent = null;
1016 <            }
1017 <            if (!p.red) { // rebalance, from CLR
1018 <                TreeNode<V> x = replacement;
1019 <                while (x != null) {
1020 <                    TreeNode<V> xp, xpl;
1021 <                    if (x.red || (xp = x.parent) == null) {
1064 <                        x.red = false;
1065 <                        break;
1066 <                    }
1067 <                    if (x == (xpl = xp.left)) {
1068 <                        TreeNode<V> sib = xp.right;
1069 <                        if (sib != null && sib.red) {
1070 <                            sib.red = false;
1071 <                            xp.red = true;
1072 <                            rotateLeft(xp);
1073 <                            sib = (xp = x.parent) == null ? null : xp.right;
1074 <                        }
1075 <                        if (sib == null)
1076 <                            x = xp;
1077 <                        else {
1078 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1079 <                            if ((sr == null || !sr.red) &&
1080 <                                (sl == null || !sl.red)) {
1081 <                                sib.red = true;
1082 <                                x = xp;
1083 <                            }
1084 <                            else {
1085 <                                if (sr == null || !sr.red) {
1086 <                                    if (sl != null)
1087 <                                        sl.red = false;
1088 <                                    sib.red = true;
1089 <                                    rotateRight(sib);
1090 <                                    sib = (xp = x.parent) == null ?
1091 <                                        null : xp.right;
1092 <                                }
1093 <                                if (sib != null) {
1094 <                                    sib.red = (xp == null) ? false : xp.red;
1095 <                                    if ((sr = sib.right) != null)
1096 <                                        sr.red = false;
1008 >                V oldVal = null;
1009 >                synchronized (f) {
1010 >                    if (tabAt(tab, i) == f) {
1011 >                        if (fh >= 0) {
1012 >                            binCount = 1;
1013 >                            for (Node<K,V> e = f;; ++binCount) {
1014 >                                K ek;
1015 >                                if (e.hash == hash &&
1016 >                                    ((ek = e.key) == key ||
1017 >                                     (ek != null && key.equals(ek)))) {
1018 >                                    oldVal = e.val;
1019 >                                    if (!onlyIfAbsent)
1020 >                                        e.val = value;
1021 >                                    break;
1022                                  }
1023 <                                if (xp != null) {
1024 <                                    xp.red = false;
1025 <                                    rotateLeft(xp);
1023 >                                Node<K,V> pred = e;
1024 >                                if ((e = e.next) == null) {
1025 >                                    pred.next = new Node<K,V>(hash, key,
1026 >                                                              value, null);
1027 >                                    break;
1028                                  }
1102                                x = root;
1029                              }
1030                          }
1031 <                    }
1032 <                    else { // symmetric
1033 <                        TreeNode<V> sib = xpl;
1034 <                        if (sib != null && sib.red) {
1035 <                            sib.red = false;
1036 <                            xp.red = true;
1037 <                            rotateRight(xp);
1038 <                            sib = (xp = x.parent) == null ? null : xp.left;
1113 <                        }
1114 <                        if (sib == null)
1115 <                            x = xp;
1116 <                        else {
1117 <                            TreeNode<V> sl = sib.left, sr = sib.right;
1118 <                            if ((sl == null || !sl.red) &&
1119 <                                (sr == null || !sr.red)) {
1120 <                                sib.red = true;
1121 <                                x = xp;
1122 <                            }
1123 <                            else {
1124 <                                if (sl == null || !sl.red) {
1125 <                                    if (sr != null)
1126 <                                        sr.red = false;
1127 <                                    sib.red = true;
1128 <                                    rotateLeft(sib);
1129 <                                    sib = (xp = x.parent) == null ?
1130 <                                        null : xp.left;
1131 <                                }
1132 <                                if (sib != null) {
1133 <                                    sib.red = (xp == null) ? false : xp.red;
1134 <                                    if ((sl = sib.left) != null)
1135 <                                        sl.red = false;
1136 <                                }
1137 <                                if (xp != null) {
1138 <                                    xp.red = false;
1139 <                                    rotateRight(xp);
1140 <                                }
1141 <                                x = root;
1031 >                        else if (f instanceof TreeBin) {
1032 >                            Node<K,V> p;
1033 >                            binCount = 2;
1034 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1035 >                                                           value)) != null) {
1036 >                                oldVal = p.val;
1037 >                                if (!onlyIfAbsent)
1038 >                                    p.val = value;
1039                              }
1040                          }
1041                      }
1042                  }
1043 <            }
1044 <            if (p == replacement && (pp = p.parent) != null) {
1045 <                if (p == pp.left) // detach pointers
1046 <                    pp.left = null;
1047 <                else if (p == pp.right)
1048 <                    pp.right = null;
1049 <                p.parent = null;
1043 >                if (binCount != 0) {
1044 >                    if (binCount >= TREEIFY_THRESHOLD)
1045 >                        treeifyBin(tab, i);
1046 >                    if (oldVal != null)
1047 >                        return oldVal;
1048 >                    break;
1049 >                }
1050              }
1051          }
1052 +        addCount(1L, binCount);
1053 +        return null;
1054      }
1055  
1157    /* ---------------- Collision reduction methods -------------- */
1158
1056      /**
1057 <     * Spreads higher bits to lower, and also forces top bit to 0.
1058 <     * Because the table uses power-of-two masking, sets of hashes
1059 <     * that vary only in bits above the current mask will always
1060 <     * collide. (Among known examples are sets of Float keys holding
1061 <     * consecutive whole numbers in small tables.)  To counter this,
1165 <     * we apply a transform that spreads the impact of higher bits
1166 <     * downward. There is a tradeoff between speed, utility, and
1167 <     * quality of bit-spreading. Because many common sets of hashes
1168 <     * are already reasonably distributed across bits (so don't benefit
1169 <     * from spreading), and because we use trees to handle large sets
1170 <     * of collisions in bins, we don't need excessively high quality.
1057 >     * Copies all of the mappings from the specified map to this one.
1058 >     * These mappings replace any mappings that this map had for any of the
1059 >     * keys currently in the specified map.
1060 >     *
1061 >     * @param m mappings to be stored in this map
1062       */
1063 <    private static final int spread(int h) {
1064 <        h ^= (h >>> 18) ^ (h >>> 12);
1065 <        return (h ^ (h >>> 10)) & HASH_BITS;
1063 >    public void putAll(Map<? extends K, ? extends V> m) {
1064 >        tryPresize(m.size());
1065 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1066 >            putVal(e.getKey(), e.getValue(), false);
1067      }
1068  
1069      /**
1070 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1071 <     * only when locked.
1070 >     * Removes the key (and its corresponding value) from this map.
1071 >     * This method does nothing if the key is not in the map.
1072 >     *
1073 >     * @param  key the key that needs to be removed
1074 >     * @return the previous value associated with {@code key}, or
1075 >     *         {@code null} if there was no mapping for {@code key}
1076 >     * @throws NullPointerException if the specified key is null
1077       */
1078 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1079 <        if (key instanceof Comparable) {
1183 <            TreeBin<V> t = new TreeBin<V>();
1184 <            for (Node<V> e = tabAt(tab, index); e != null; e = e.next)
1185 <                t.putTreeNode(e.hash, e.key, e.val);
1186 <            setTabAt(tab, index, new Node<V>(MOVED, t, null, null));
1187 <        }
1188 <    }
1189 <
1190 <    /* ---------------- Internal access and update methods -------------- */
1191 <
1192 <    /** Implementation for get and containsKey */
1193 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1194 <        int h = spread(k.hashCode());
1195 <        retry: for (Node<V>[] tab = table; tab != null;) {
1196 <            Node<V> e; Object ek; V ev; int eh; // locals to read fields once
1197 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1198 <                if ((eh = e.hash) < 0) {
1199 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1200 <                        return ((TreeBin<V>)ek).getValue(h, k);
1201 <                    else {                      // restart with new table
1202 <                        tab = (Node<V>[])ek;
1203 <                        continue retry;
1204 <                    }
1205 <                }
1206 <                else if (eh == h && (ev = e.val) != null &&
1207 <                         ((ek = e.key) == k || k.equals(ek)))
1208 <                    return ev;
1209 <            }
1210 <            break;
1211 <        }
1212 <        return null;
1078 >    public V remove(Object key) {
1079 >        return replaceNode(key, null, null);
1080      }
1081  
1082      /**
# Line 1217 | Line 1084 | public class ConcurrentHashMapV8<K, V>
1084       * Replaces node value with v, conditional upon match of cv if
1085       * non-null.  If resulting value is null, delete.
1086       */
1087 <    @SuppressWarnings("unchecked") private final V internalReplace
1088 <        (Object k, V v, Object cv) {
1089 <        int h = spread(k.hashCode());
1090 <        V oldVal = null;
1091 <        for (Node<V>[] tab = table;;) {
1092 <            Node<V> f; int i, fh; Object fk;
1226 <            if (tab == null ||
1227 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1087 >    final V replaceNode(Object key, V value, Object cv) {
1088 >        int hash = spread(key.hashCode());
1089 >        for (Node<K,V>[] tab = table;;) {
1090 >            Node<K,V> f; int n, i, fh;
1091 >            if (tab == null || (n = tab.length) == 0 ||
1092 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1093                  break;
1094 <            else if ((fh = f.hash) < 0) {
1095 <                if ((fk = f.key) instanceof TreeBin) {
1096 <                    TreeBin<V> t = (TreeBin<V>)fk;
1097 <                    boolean validated = false;
1098 <                    boolean deleted = false;
1099 <                    t.acquire(0);
1100 <                    try {
1101 <                        if (tabAt(tab, i) == f) {
1094 >            else if ((fh = f.hash) == MOVED)
1095 >                tab = helpTransfer(tab, f);
1096 >            else {
1097 >                V oldVal = null;
1098 >                boolean validated = false;
1099 >                synchronized (f) {
1100 >                    if (tabAt(tab, i) == f) {
1101 >                        if (fh >= 0) {
1102 >                            validated = true;
1103 >                            for (Node<K,V> e = f, pred = null;;) {
1104 >                                K ek;
1105 >                                if (e.hash == hash &&
1106 >                                    ((ek = e.key) == key ||
1107 >                                     (ek != null && key.equals(ek)))) {
1108 >                                    V ev = e.val;
1109 >                                    if (cv == null || cv == ev ||
1110 >                                        (ev != null && cv.equals(ev))) {
1111 >                                        oldVal = ev;
1112 >                                        if (value != null)
1113 >                                            e.val = value;
1114 >                                        else if (pred != null)
1115 >                                            pred.next = e.next;
1116 >                                        else
1117 >                                            setTabAt(tab, i, e.next);
1118 >                                    }
1119 >                                    break;
1120 >                                }
1121 >                                pred = e;
1122 >                                if ((e = e.next) == null)
1123 >                                    break;
1124 >                            }
1125 >                        }
1126 >                        else if (f instanceof TreeBin) {
1127                              validated = true;
1128 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1129 <                            if (p != null) {
1128 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1129 >                            TreeNode<K,V> r, p;
1130 >                            if ((r = t.root) != null &&
1131 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1132                                  V pv = p.val;
1133 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1133 >                                if (cv == null || cv == pv ||
1134 >                                    (pv != null && cv.equals(pv))) {
1135                                      oldVal = pv;
1136 <                                    if ((p.val = v) == null) {
1137 <                                        deleted = true;
1138 <                                        t.deleteTreeNode(p);
1139 <                                    }
1136 >                                    if (value != null)
1137 >                                        p.val = value;
1138 >                                    else if (t.removeTreeNode(p))
1139 >                                        setTabAt(tab, i, untreeify(t.first));
1140                                  }
1141                              }
1142                          }
1250                    } finally {
1251                        t.release(0);
1143                      }
1144 <                    if (validated) {
1145 <                        if (deleted)
1144 >                }
1145 >                if (validated) {
1146 >                    if (oldVal != null) {
1147 >                        if (value == null)
1148                              addCount(-1L, -1);
1149 <                        break;
1149 >                        return oldVal;
1150                      }
1151 +                    break;
1152                  }
1259                else
1260                    tab = (Node<V>[])fk;
1153              }
1154 <            else if (fh != h && f.next == null) // precheck
1155 <                break;                          // rules out possible existence
1154 >        }
1155 >        return null;
1156 >    }
1157 >
1158 >    /**
1159 >     * Removes all of the mappings from this map.
1160 >     */
1161 >    public void clear() {
1162 >        long delta = 0L; // negative number of deletions
1163 >        int i = 0;
1164 >        Node<K,V>[] tab = table;
1165 >        while (tab != null && i < tab.length) {
1166 >            int fh;
1167 >            Node<K,V> f = tabAt(tab, i);
1168 >            if (f == null)
1169 >                ++i;
1170 >            else if ((fh = f.hash) == MOVED) {
1171 >                tab = helpTransfer(tab, f);
1172 >                i = 0; // restart
1173 >            }
1174              else {
1265                boolean validated = false;
1266                boolean deleted = false;
1175                  synchronized (f) {
1176                      if (tabAt(tab, i) == f) {
1177 <                        validated = true;
1178 <                        for (Node<V> e = f, pred = null;;) {
1179 <                            Object ek; V ev;
1180 <                            if (e.hash == h &&
1181 <                                ((ev = e.val) != null) &&
1182 <                                ((ek = e.key) == k || k.equals(ek))) {
1275 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1276 <                                    oldVal = ev;
1277 <                                    if ((e.val = v) == null) {
1278 <                                        deleted = true;
1279 <                                        Node<V> en = e.next;
1280 <                                        if (pred != null)
1281 <                                            pred.next = en;
1282 <                                        else
1283 <                                            setTabAt(tab, i, en);
1284 <                                    }
1285 <                                }
1286 <                                break;
1287 <                            }
1288 <                            pred = e;
1289 <                            if ((e = e.next) == null)
1290 <                                break;
1177 >                        Node<K,V> p = (fh >= 0 ? f :
1178 >                                       (f instanceof TreeBin) ?
1179 >                                       ((TreeBin<K,V>)f).first : null);
1180 >                        while (p != null) {
1181 >                            --delta;
1182 >                            p = p.next;
1183                          }
1184 +                        setTabAt(tab, i++, null);
1185                      }
1186                  }
1187 <                if (validated) {
1188 <                    if (deleted)
1189 <                        addCount(-1L, -1);
1187 >            }
1188 >        }
1189 >        if (delta != 0L)
1190 >            addCount(delta, -1);
1191 >    }
1192 >
1193 >    /**
1194 >     * Returns a {@link Set} view of the keys contained in this map.
1195 >     * The set is backed by the map, so changes to the map are
1196 >     * reflected in the set, and vice-versa. The set supports element
1197 >     * removal, which removes the corresponding mapping from this map,
1198 >     * via the {@code Iterator.remove}, {@code Set.remove},
1199 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1200 >     * operations.  It does not support the {@code add} or
1201 >     * {@code addAll} operations.
1202 >     *
1203 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1204 >     * that will never throw {@link ConcurrentModificationException},
1205 >     * and guarantees to traverse elements as they existed upon
1206 >     * construction of the iterator, and may (but is not guaranteed to)
1207 >     * reflect any modifications subsequent to construction.
1208 >     *
1209 >     * @return the set view
1210 >     */
1211 >    public KeySetView<K,V> keySet() {
1212 >        KeySetView<K,V> ks;
1213 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1214 >    }
1215 >
1216 >    /**
1217 >     * Returns a {@link Collection} view of the values contained in this map.
1218 >     * The collection is backed by the map, so changes to the map are
1219 >     * reflected in the collection, and vice-versa.  The collection
1220 >     * supports element removal, which removes the corresponding
1221 >     * mapping from this map, via the {@code Iterator.remove},
1222 >     * {@code Collection.remove}, {@code removeAll},
1223 >     * {@code retainAll}, and {@code clear} operations.  It does not
1224 >     * support the {@code add} or {@code addAll} operations.
1225 >     *
1226 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1227 >     * that will never throw {@link ConcurrentModificationException},
1228 >     * and guarantees to traverse elements as they existed upon
1229 >     * construction of the iterator, and may (but is not guaranteed to)
1230 >     * reflect any modifications subsequent to construction.
1231 >     *
1232 >     * @return the collection view
1233 >     */
1234 >    public Collection<V> values() {
1235 >        ValuesView<K,V> vs;
1236 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1237 >    }
1238 >
1239 >    /**
1240 >     * Returns a {@link Set} view of the mappings contained in this map.
1241 >     * The set is backed by the map, so changes to the map are
1242 >     * reflected in the set, and vice-versa.  The set supports element
1243 >     * removal, which removes the corresponding mapping from the map,
1244 >     * via the {@code Iterator.remove}, {@code Set.remove},
1245 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1246 >     * operations.
1247 >     *
1248 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1249 >     * that will never throw {@link ConcurrentModificationException},
1250 >     * and guarantees to traverse elements as they existed upon
1251 >     * construction of the iterator, and may (but is not guaranteed to)
1252 >     * reflect any modifications subsequent to construction.
1253 >     *
1254 >     * @return the set view
1255 >     */
1256 >    public Set<Map.Entry<K,V>> entrySet() {
1257 >        EntrySetView<K,V> es;
1258 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1259 >    }
1260 >
1261 >    /**
1262 >     * Returns the hash code value for this {@link Map}, i.e.,
1263 >     * the sum of, for each key-value pair in the map,
1264 >     * {@code key.hashCode() ^ value.hashCode()}.
1265 >     *
1266 >     * @return the hash code value for this map
1267 >     */
1268 >    public int hashCode() {
1269 >        int h = 0;
1270 >        Node<K,V>[] t;
1271 >        if ((t = table) != null) {
1272 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1273 >            for (Node<K,V> p; (p = it.advance()) != null; )
1274 >                h += p.key.hashCode() ^ p.val.hashCode();
1275 >        }
1276 >        return h;
1277 >    }
1278 >
1279 >    /**
1280 >     * Returns a string representation of this map.  The string
1281 >     * representation consists of a list of key-value mappings (in no
1282 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1283 >     * mappings are separated by the characters {@code ", "} (comma
1284 >     * and space).  Each key-value mapping is rendered as the key
1285 >     * followed by an equals sign ("{@code =}") followed by the
1286 >     * associated value.
1287 >     *
1288 >     * @return a string representation of this map
1289 >     */
1290 >    public String toString() {
1291 >        Node<K,V>[] t;
1292 >        int f = (t = table) == null ? 0 : t.length;
1293 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1294 >        StringBuilder sb = new StringBuilder();
1295 >        sb.append('{');
1296 >        Node<K,V> p;
1297 >        if ((p = it.advance()) != null) {
1298 >            for (;;) {
1299 >                K k = p.key;
1300 >                V v = p.val;
1301 >                sb.append(k == this ? "(this Map)" : k);
1302 >                sb.append('=');
1303 >                sb.append(v == this ? "(this Map)" : v);
1304 >                if ((p = it.advance()) == null)
1305                      break;
1306 <                }
1306 >                sb.append(',').append(' ');
1307              }
1308          }
1309 <        return oldVal;
1309 >        return sb.append('}').toString();
1310      }
1311  
1312 <    /*
1313 <     * Internal versions of insertion methods
1314 <     * All have the same basic structure as the first (internalPut):
1315 <     *  1. If table uninitialized, create
1316 <     *  2. If bin empty, try to CAS new node
1317 <     *  3. If bin stale, use new table
1318 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1319 <     *  5. Lock and validate; if valid, scan and add or update
1320 <     *
1321 <     * The putAll method differs mainly in attempting to pre-allocate
1322 <     * enough table space, and also more lazily performs count updates
1323 <     * and checks.
1324 <     *
1325 <     * Most of the function-accepting methods can't be factored nicely
1326 <     * because they require different functional forms, so instead
1327 <     * sprawl out similar mechanics.
1312 >    /**
1313 >     * Compares the specified object with this map for equality.
1314 >     * Returns {@code true} if the given object is a map with the same
1315 >     * mappings as this map.  This operation may return misleading
1316 >     * results if either map is concurrently modified during execution
1317 >     * of this method.
1318 >     *
1319 >     * @param o object to be compared for equality with this map
1320 >     * @return {@code true} if the specified object is equal to this map
1321 >     */
1322 >    public boolean equals(Object o) {
1323 >        if (o != this) {
1324 >            if (!(o instanceof Map))
1325 >                return false;
1326 >            Map<?,?> m = (Map<?,?>) o;
1327 >            Node<K,V>[] t;
1328 >            int f = (t = table) == null ? 0 : t.length;
1329 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1330 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1331 >                V val = p.val;
1332 >                Object v = m.get(p.key);
1333 >                if (v == null || (v != val && !v.equals(val)))
1334 >                    return false;
1335 >            }
1336 >            for (Map.Entry<?,?> e : m.entrySet()) {
1337 >                Object mk, mv, v;
1338 >                if ((mk = e.getKey()) == null ||
1339 >                    (mv = e.getValue()) == null ||
1340 >                    (v = get(mk)) == null ||
1341 >                    (mv != v && !mv.equals(v)))
1342 >                    return false;
1343 >            }
1344 >        }
1345 >        return true;
1346 >    }
1347 >
1348 >    /**
1349 >     * Stripped-down version of helper class used in previous version,
1350 >     * declared for the sake of serialization compatibility
1351       */
1352 +    static class Segment<K,V> extends ReentrantLock implements Serializable {
1353 +        private static final long serialVersionUID = 2249069246763182397L;
1354 +        final float loadFactor;
1355 +        Segment(float lf) { this.loadFactor = lf; }
1356 +    }
1357  
1358 <    /** Implementation for put and putIfAbsent */
1359 <    @SuppressWarnings("unchecked") private final V internalPut
1360 <        (K k, V v, boolean onlyIfAbsent) {
1361 <        if (k == null || v == null) throw new NullPointerException();
1362 <        int h = spread(k.hashCode());
1363 <        int len = 0;
1364 <        for (Node<V>[] tab = table;;) {
1365 <            int i, fh; Node<V> f; Object fk; V fv;
1366 <            if (tab == null)
1367 <                tab = initTable();
1368 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1369 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1370 <                    break;                   // no lock when adding to empty bin
1358 >    /**
1359 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1360 >     * stream (i.e., serializes it).
1361 >     * @param s the stream
1362 >     * @serialData
1363 >     * the key (Object) and value (Object)
1364 >     * for each key-value mapping, followed by a null pair.
1365 >     * The key-value mappings are emitted in no particular order.
1366 >     */
1367 >    private void writeObject(java.io.ObjectOutputStream s)
1368 >        throws java.io.IOException {
1369 >        // For serialization compatibility
1370 >        // Emulate segment calculation from previous version of this class
1371 >        int sshift = 0;
1372 >        int ssize = 1;
1373 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1374 >            ++sshift;
1375 >            ssize <<= 1;
1376 >        }
1377 >        int segmentShift = 32 - sshift;
1378 >        int segmentMask = ssize - 1;
1379 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1380 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1381 >        for (int i = 0; i < segments.length; ++i)
1382 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1383 >        s.putFields().put("segments", segments);
1384 >        s.putFields().put("segmentShift", segmentShift);
1385 >        s.putFields().put("segmentMask", segmentMask);
1386 >        s.writeFields();
1387 >
1388 >        Node<K,V>[] t;
1389 >        if ((t = table) != null) {
1390 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1391 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1392 >                s.writeObject(p.key);
1393 >                s.writeObject(p.val);
1394              }
1395 <            else if ((fh = f.hash) < 0) {
1396 <                if ((fk = f.key) instanceof TreeBin) {
1397 <                    TreeBin<V> t = (TreeBin<V>)fk;
1398 <                    V oldVal = null;
1399 <                    t.acquire(0);
1400 <                    try {
1401 <                        if (tabAt(tab, i) == f) {
1402 <                            len = 2;
1403 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1404 <                            if (p != null) {
1405 <                                oldVal = p.val;
1406 <                                if (!onlyIfAbsent)
1407 <                                    p.val = v;
1408 <                            }
1409 <                        }
1410 <                    } finally {
1411 <                        t.release(0);
1412 <                    }
1413 <                    if (len != 0) {
1414 <                        if (oldVal != null)
1415 <                            return oldVal;
1416 <                        break;
1417 <                    }
1418 <                }
1419 <                else
1420 <                    tab = (Node<V>[])fk;
1395 >        }
1396 >        s.writeObject(null);
1397 >        s.writeObject(null);
1398 >        segments = null; // throw away
1399 >    }
1400 >
1401 >    /**
1402 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1403 >     * @param s the stream
1404 >     */
1405 >    private void readObject(java.io.ObjectInputStream s)
1406 >        throws java.io.IOException, ClassNotFoundException {
1407 >        /*
1408 >         * To improve performance in typical cases, we create nodes
1409 >         * while reading, then place in table once size is known.
1410 >         * However, we must also validate uniqueness and deal with
1411 >         * overpopulated bins while doing so, which requires
1412 >         * specialized versions of putVal mechanics.
1413 >         */
1414 >        sizeCtl = -1; // force exclusion for table construction
1415 >        s.defaultReadObject();
1416 >        long size = 0L;
1417 >        Node<K,V> p = null;
1418 >        for (;;) {
1419 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1420 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1421 >            if (k != null && v != null) {
1422 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1423 >                ++size;
1424              }
1425 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1426 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1427 <                return fv;
1425 >            else
1426 >                break;
1427 >        }
1428 >        if (size == 0L)
1429 >            sizeCtl = 0;
1430 >        else {
1431 >            int n;
1432 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1433 >                n = MAXIMUM_CAPACITY;
1434              else {
1435 <                V oldVal = null;
1436 <                synchronized (f) {
1437 <                    if (tabAt(tab, i) == f) {
1438 <                        len = 1;
1439 <                        for (Node<V> e = f;; ++len) {
1440 <                            Object ek; V ev;
1441 <                            if (e.hash == h &&
1442 <                                (ev = e.val) != null &&
1443 <                                ((ek = e.key) == k || k.equals(ek))) {
1444 <                                oldVal = ev;
1445 <                                if (!onlyIfAbsent)
1446 <                                    e.val = v;
1435 >                int sz = (int)size;
1436 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1437 >            }
1438 >            @SuppressWarnings({"rawtypes","unchecked"})
1439 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1440 >            int mask = n - 1;
1441 >            long added = 0L;
1442 >            while (p != null) {
1443 >                boolean insertAtFront;
1444 >                Node<K,V> next = p.next, first;
1445 >                int h = p.hash, j = h & mask;
1446 >                if ((first = tabAt(tab, j)) == null)
1447 >                    insertAtFront = true;
1448 >                else {
1449 >                    K k = p.key;
1450 >                    if (first.hash < 0) {
1451 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1452 >                        if (t.putTreeVal(h, k, p.val) == null)
1453 >                            ++added;
1454 >                        insertAtFront = false;
1455 >                    }
1456 >                    else {
1457 >                        int binCount = 0;
1458 >                        insertAtFront = true;
1459 >                        Node<K,V> q; K qk;
1460 >                        for (q = first; q != null; q = q.next) {
1461 >                            if (q.hash == h &&
1462 >                                ((qk = q.key) == k ||
1463 >                                 (qk != null && k.equals(qk)))) {
1464 >                                insertAtFront = false;
1465                                  break;
1466                              }
1467 <                            Node<V> last = e;
1468 <                            if ((e = e.next) == null) {
1469 <                                last.next = new Node<V>(h, k, v, null);
1470 <                                if (len >= TREE_THRESHOLD)
1471 <                                    replaceWithTreeBin(tab, i, k);
1472 <                                break;
1467 >                            ++binCount;
1468 >                        }
1469 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1470 >                            insertAtFront = false;
1471 >                            ++added;
1472 >                            p.next = first;
1473 >                            TreeNode<K,V> hd = null, tl = null;
1474 >                            for (q = p; q != null; q = q.next) {
1475 >                                TreeNode<K,V> t = new TreeNode<K,V>
1476 >                                    (q.hash, q.key, q.val, null, null);
1477 >                                if ((t.prev = tl) == null)
1478 >                                    hd = t;
1479 >                                else
1480 >                                    tl.next = t;
1481 >                                tl = t;
1482                              }
1483 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1484                          }
1485                      }
1486                  }
1487 <                if (len != 0) {
1488 <                    if (oldVal != null)
1489 <                        return oldVal;
1490 <                    break;
1487 >                if (insertAtFront) {
1488 >                    ++added;
1489 >                    p.next = first;
1490 >                    setTabAt(tab, j, p);
1491                  }
1492 +                p = next;
1493              }
1494 +            table = tab;
1495 +            sizeCtl = n - (n >>> 2);
1496 +            baseCount = added;
1497          }
1398        addCount(1L, len);
1399        return null;
1498      }
1499  
1500 <    /** Implementation for computeIfAbsent */
1501 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1502 <        (K k, Fun<? super K, ? extends V> mf) {
1503 <        if (k == null || mf == null)
1500 >    // ConcurrentMap methods
1501 >
1502 >    /**
1503 >     * {@inheritDoc}
1504 >     *
1505 >     * @return the previous value associated with the specified key,
1506 >     *         or {@code null} if there was no mapping for the key
1507 >     * @throws NullPointerException if the specified key or value is null
1508 >     */
1509 >    public V putIfAbsent(K key, V value) {
1510 >        return putVal(key, value, true);
1511 >    }
1512 >
1513 >    /**
1514 >     * {@inheritDoc}
1515 >     *
1516 >     * @throws NullPointerException if the specified key is null
1517 >     */
1518 >    public boolean remove(Object key, Object value) {
1519 >        if (key == null)
1520              throw new NullPointerException();
1521 <        int h = spread(k.hashCode());
1521 >        return value != null && replaceNode(key, null, value) != null;
1522 >    }
1523 >
1524 >    /**
1525 >     * {@inheritDoc}
1526 >     *
1527 >     * @throws NullPointerException if any of the arguments are null
1528 >     */
1529 >    public boolean replace(K key, V oldValue, V newValue) {
1530 >        if (key == null || oldValue == null || newValue == null)
1531 >            throw new NullPointerException();
1532 >        return replaceNode(key, newValue, oldValue) != null;
1533 >    }
1534 >
1535 >    /**
1536 >     * {@inheritDoc}
1537 >     *
1538 >     * @return the previous value associated with the specified key,
1539 >     *         or {@code null} if there was no mapping for the key
1540 >     * @throws NullPointerException if the specified key or value is null
1541 >     */
1542 >    public V replace(K key, V value) {
1543 >        if (key == null || value == null)
1544 >            throw new NullPointerException();
1545 >        return replaceNode(key, value, null);
1546 >    }
1547 >
1548 >    // Overrides of JDK8+ Map extension method defaults
1549 >
1550 >    /**
1551 >     * Returns the value to which the specified key is mapped, or the
1552 >     * given default value if this map contains no mapping for the
1553 >     * key.
1554 >     *
1555 >     * @param key the key whose associated value is to be returned
1556 >     * @param defaultValue the value to return if this map contains
1557 >     * no mapping for the given key
1558 >     * @return the mapping for the key, if present; else the default value
1559 >     * @throws NullPointerException if the specified key is null
1560 >     */
1561 >    public V getOrDefault(Object key, V defaultValue) {
1562 >        V v;
1563 >        return (v = get(key)) == null ? defaultValue : v;
1564 >    }
1565 >
1566 >    public void forEach(BiAction<? super K, ? super V> action) {
1567 >        if (action == null) throw new NullPointerException();
1568 >        Node<K,V>[] t;
1569 >        if ((t = table) != null) {
1570 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1571 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1572 >                action.apply(p.key, p.val);
1573 >            }
1574 >        }
1575 >    }
1576 >
1577 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1578 >        if (function == null) throw new NullPointerException();
1579 >        Node<K,V>[] t;
1580 >        if ((t = table) != null) {
1581 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1582 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1583 >                V oldValue = p.val;
1584 >                for (K key = p.key;;) {
1585 >                    V newValue = function.apply(key, oldValue);
1586 >                    if (newValue == null)
1587 >                        throw new NullPointerException();
1588 >                    if (replaceNode(key, newValue, oldValue) != null ||
1589 >                        (oldValue = get(key)) == null)
1590 >                        break;
1591 >                }
1592 >            }
1593 >        }
1594 >    }
1595 >
1596 >    /**
1597 >     * If the specified key is not already associated with a value,
1598 >     * attempts to compute its value using the given mapping function
1599 >     * and enters it into this map unless {@code null}.  The entire
1600 >     * method invocation is performed atomically, so the function is
1601 >     * applied at most once per key.  Some attempted update operations
1602 >     * on this map by other threads may be blocked while computation
1603 >     * is in progress, so the computation should be short and simple,
1604 >     * and must not attempt to update any other mappings of this map.
1605 >     *
1606 >     * @param key key with which the specified value is to be associated
1607 >     * @param mappingFunction the function to compute a value
1608 >     * @return the current (existing or computed) value associated with
1609 >     *         the specified key, or null if the computed value is null
1610 >     * @throws NullPointerException if the specified key or mappingFunction
1611 >     *         is null
1612 >     * @throws IllegalStateException if the computation detectably
1613 >     *         attempts a recursive update to this map that would
1614 >     *         otherwise never complete
1615 >     * @throws RuntimeException or Error if the mappingFunction does so,
1616 >     *         in which case the mapping is left unestablished
1617 >     */
1618 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1619 >        if (key == null || mappingFunction == null)
1620 >            throw new NullPointerException();
1621 >        int h = spread(key.hashCode());
1622          V val = null;
1623 <        int len = 0;
1624 <        for (Node<V>[] tab = table;;) {
1625 <            Node<V> f; int i; Object fk;
1626 <            if (tab == null)
1623 >        int binCount = 0;
1624 >        for (Node<K,V>[] tab = table;;) {
1625 >            Node<K,V> f; int n, i, fh;
1626 >            if (tab == null || (n = tab.length) == 0)
1627                  tab = initTable();
1628 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1629 <                Node<V> node = new Node<V>(h, k, null, null);
1630 <                synchronized (node) {
1631 <                    if (casTabAt(tab, i, null, node)) {
1632 <                        len = 1;
1628 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1629 >                Node<K,V> r = new ReservationNode<K,V>();
1630 >                synchronized (r) {
1631 >                    if (casTabAt(tab, i, null, r)) {
1632 >                        binCount = 1;
1633 >                        Node<K,V> node = null;
1634                          try {
1635 <                            if ((val = mf.apply(k)) != null)
1636 <                                node.val = val;
1635 >                            if ((val = mappingFunction.apply(key)) != null)
1636 >                                node = new Node<K,V>(h, key, val, null);
1637                          } finally {
1638 <                            if (val == null)
1424 <                                setTabAt(tab, i, null);
1638 >                            setTabAt(tab, i, node);
1639                          }
1640                      }
1641                  }
1642 <                if (len != 0)
1642 >                if (binCount != 0)
1643                      break;
1644              }
1645 <            else if (f.hash < 0) {
1646 <                if ((fk = f.key) instanceof TreeBin) {
1647 <                    TreeBin<V> t = (TreeBin<V>)fk;
1648 <                    boolean added = false;
1649 <                    t.acquire(0);
1650 <                    try {
1651 <                        if (tabAt(tab, i) == f) {
1652 <                            len = 1;
1653 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1654 <                            if (p != null)
1645 >            else if ((fh = f.hash) == MOVED)
1646 >                tab = helpTransfer(tab, f);
1647 >            else {
1648 >                boolean added = false;
1649 >                synchronized (f) {
1650 >                    if (tabAt(tab, i) == f) {
1651 >                        if (fh >= 0) {
1652 >                            binCount = 1;
1653 >                            for (Node<K,V> e = f;; ++binCount) {
1654 >                                K ek; V ev;
1655 >                                if (e.hash == h &&
1656 >                                    ((ek = e.key) == key ||
1657 >                                     (ek != null && key.equals(ek)))) {
1658 >                                    val = e.val;
1659 >                                    break;
1660 >                                }
1661 >                                Node<K,V> pred = e;
1662 >                                if ((e = e.next) == null) {
1663 >                                    if ((val = mappingFunction.apply(key)) != null) {
1664 >                                        added = true;
1665 >                                        pred.next = new Node<K,V>(h, key, val, null);
1666 >                                    }
1667 >                                    break;
1668 >                                }
1669 >                            }
1670 >                        }
1671 >                        else if (f instanceof TreeBin) {
1672 >                            binCount = 2;
1673 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1674 >                            TreeNode<K,V> r, p;
1675 >                            if ((r = t.root) != null &&
1676 >                                (p = r.findTreeNode(h, key, null)) != null)
1677                                  val = p.val;
1678 <                            else if ((val = mf.apply(k)) != null) {
1678 >                            else if ((val = mappingFunction.apply(key)) != null) {
1679                                  added = true;
1680 <                                len = 2;
1445 <                                t.putTreeNode(h, k, val);
1680 >                                t.putTreeVal(h, key, val);
1681                              }
1682                          }
1448                    } finally {
1449                        t.release(0);
1450                    }
1451                    if (len != 0) {
1452                        if (!added)
1453                            return val;
1454                        break;
1683                      }
1684                  }
1685 <                else
1686 <                    tab = (Node<V>[])fk;
1685 >                if (binCount != 0) {
1686 >                    if (binCount >= TREEIFY_THRESHOLD)
1687 >                        treeifyBin(tab, i);
1688 >                    if (!added)
1689 >                        return val;
1690 >                    break;
1691 >                }
1692              }
1693 +        }
1694 +        if (val != null)
1695 +            addCount(1L, binCount);
1696 +        return val;
1697 +    }
1698 +
1699 +    /**
1700 +     * If the value for the specified key is present, attempts to
1701 +     * compute a new mapping given the key and its current mapped
1702 +     * value.  The entire method invocation is performed atomically.
1703 +     * Some attempted update operations on this map by other threads
1704 +     * may be blocked while computation is in progress, so the
1705 +     * computation should be short and simple, and must not attempt to
1706 +     * update any other mappings of this map.
1707 +     *
1708 +     * @param key key with which a value may be associated
1709 +     * @param remappingFunction the function to compute a value
1710 +     * @return the new value associated with the specified key, or null if none
1711 +     * @throws NullPointerException if the specified key or remappingFunction
1712 +     *         is null
1713 +     * @throws IllegalStateException if the computation detectably
1714 +     *         attempts a recursive update to this map that would
1715 +     *         otherwise never complete
1716 +     * @throws RuntimeException or Error if the remappingFunction does so,
1717 +     *         in which case the mapping is unchanged
1718 +     */
1719 +    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1720 +        if (key == null || remappingFunction == null)
1721 +            throw new NullPointerException();
1722 +        int h = spread(key.hashCode());
1723 +        V val = null;
1724 +        int delta = 0;
1725 +        int binCount = 0;
1726 +        for (Node<K,V>[] tab = table;;) {
1727 +            Node<K,V> f; int n, i, fh;
1728 +            if (tab == null || (n = tab.length) == 0)
1729 +                tab = initTable();
1730 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1731 +                break;
1732 +            else if ((fh = f.hash) == MOVED)
1733 +                tab = helpTransfer(tab, f);
1734              else {
1461                for (Node<V> e = f; e != null; e = e.next) { // prescan
1462                    Object ek; V ev;
1463                    if (e.hash == h && (ev = e.val) != null &&
1464                        ((ek = e.key) == k || k.equals(ek)))
1465                        return ev;
1466                }
1467                boolean added = false;
1735                  synchronized (f) {
1736                      if (tabAt(tab, i) == f) {
1737 <                        len = 1;
1738 <                        for (Node<V> e = f;; ++len) {
1739 <                            Object ek; V ev;
1740 <                            if (e.hash == h &&
1741 <                                (ev = e.val) != null &&
1742 <                                ((ek = e.key) == k || k.equals(ek))) {
1743 <                                val = ev;
1744 <                                break;
1737 >                        if (fh >= 0) {
1738 >                            binCount = 1;
1739 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1740 >                                K ek;
1741 >                                if (e.hash == h &&
1742 >                                    ((ek = e.key) == key ||
1743 >                                     (ek != null && key.equals(ek)))) {
1744 >                                    val = remappingFunction.apply(key, e.val);
1745 >                                    if (val != null)
1746 >                                        e.val = val;
1747 >                                    else {
1748 >                                        delta = -1;
1749 >                                        Node<K,V> en = e.next;
1750 >                                        if (pred != null)
1751 >                                            pred.next = en;
1752 >                                        else
1753 >                                            setTabAt(tab, i, en);
1754 >                                    }
1755 >                                    break;
1756 >                                }
1757 >                                pred = e;
1758 >                                if ((e = e.next) == null)
1759 >                                    break;
1760                              }
1761 <                            Node<V> last = e;
1762 <                            if ((e = e.next) == null) {
1763 <                                if ((val = mf.apply(k)) != null) {
1764 <                                    added = true;
1765 <                                    last.next = new Node<V>(h, k, val, null);
1766 <                                    if (len >= TREE_THRESHOLD)
1767 <                                        replaceWithTreeBin(tab, i, k);
1761 >                        }
1762 >                        else if (f instanceof TreeBin) {
1763 >                            binCount = 2;
1764 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1765 >                            TreeNode<K,V> r, p;
1766 >                            if ((r = t.root) != null &&
1767 >                                (p = r.findTreeNode(h, key, null)) != null) {
1768 >                                val = remappingFunction.apply(key, p.val);
1769 >                                if (val != null)
1770 >                                    p.val = val;
1771 >                                else {
1772 >                                    delta = -1;
1773 >                                    if (t.removeTreeNode(p))
1774 >                                        setTabAt(tab, i, untreeify(t.first));
1775                                  }
1487                                break;
1776                              }
1777                          }
1778                      }
1779                  }
1780 <                if (len != 0) {
1493 <                    if (!added)
1494 <                        return val;
1780 >                if (binCount != 0)
1781                      break;
1496                }
1782              }
1783          }
1784 <        if (val != null)
1785 <            addCount(1L, len);
1784 >        if (delta != 0)
1785 >            addCount((long)delta, binCount);
1786          return val;
1787      }
1788  
1789 <    /** Implementation for compute */
1790 <    @SuppressWarnings("unchecked") private final V internalCompute
1791 <        (K k, boolean onlyIfPresent,
1792 <         BiFun<? super K, ? super V, ? extends V> mf) {
1793 <        if (k == null || mf == null)
1789 >    /**
1790 >     * Attempts to compute a mapping for the specified key and its
1791 >     * current mapped value (or {@code null} if there is no current
1792 >     * mapping). The entire method invocation is performed atomically.
1793 >     * Some attempted update operations on this map by other threads
1794 >     * may be blocked while computation is in progress, so the
1795 >     * computation should be short and simple, and must not attempt to
1796 >     * update any other mappings of this Map.
1797 >     *
1798 >     * @param key key with which the specified value is to be associated
1799 >     * @param remappingFunction the function to compute a value
1800 >     * @return the new value associated with the specified key, or null if none
1801 >     * @throws NullPointerException if the specified key or remappingFunction
1802 >     *         is null
1803 >     * @throws IllegalStateException if the computation detectably
1804 >     *         attempts a recursive update to this map that would
1805 >     *         otherwise never complete
1806 >     * @throws RuntimeException or Error if the remappingFunction does so,
1807 >     *         in which case the mapping is unchanged
1808 >     */
1809 >    public V compute(K key,
1810 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1811 >        if (key == null || remappingFunction == null)
1812              throw new NullPointerException();
1813 <        int h = spread(k.hashCode());
1813 >        int h = spread(key.hashCode());
1814          V val = null;
1815          int delta = 0;
1816 <        int len = 0;
1817 <        for (Node<V>[] tab = table;;) {
1818 <            Node<V> f; int i, fh; Object fk;
1819 <            if (tab == null)
1816 >        int binCount = 0;
1817 >        for (Node<K,V>[] tab = table;;) {
1818 >            Node<K,V> f; int n, i, fh;
1819 >            if (tab == null || (n = tab.length) == 0)
1820                  tab = initTable();
1821 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1822 <                if (onlyIfPresent)
1823 <                    break;
1824 <                Node<V> node = new Node<V>(h, k, null, null);
1825 <                synchronized (node) {
1826 <                    if (casTabAt(tab, i, null, node)) {
1821 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1822 >                Node<K,V> r = new ReservationNode<K,V>();
1823 >                synchronized (r) {
1824 >                    if (casTabAt(tab, i, null, r)) {
1825 >                        binCount = 1;
1826 >                        Node<K,V> node = null;
1827                          try {
1828 <                            len = 1;
1526 <                            if ((val = mf.apply(k, null)) != null) {
1527 <                                node.val = val;
1828 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1829                                  delta = 1;
1830 +                                node = new Node<K,V>(h, key, val, null);
1831                              }
1832                          } finally {
1833 <                            if (delta == 0)
1532 <                                setTabAt(tab, i, null);
1833 >                            setTabAt(tab, i, node);
1834                          }
1835                      }
1836                  }
1837 <                if (len != 0)
1837 >                if (binCount != 0)
1838                      break;
1839              }
1840 <            else if ((fh = f.hash) < 0) {
1841 <                if ((fk = f.key) instanceof TreeBin) {
1842 <                    TreeBin<V> t = (TreeBin<V>)fk;
1843 <                    t.acquire(0);
1844 <                    try {
1845 <                        if (tabAt(tab, i) == f) {
1846 <                            len = 1;
1847 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1848 <                            if (p == null && onlyIfPresent)
1849 <                                break;
1840 >            else if ((fh = f.hash) == MOVED)
1841 >                tab = helpTransfer(tab, f);
1842 >            else {
1843 >                synchronized (f) {
1844 >                    if (tabAt(tab, i) == f) {
1845 >                        if (fh >= 0) {
1846 >                            binCount = 1;
1847 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1848 >                                K ek;
1849 >                                if (e.hash == h &&
1850 >                                    ((ek = e.key) == key ||
1851 >                                     (ek != null && key.equals(ek)))) {
1852 >                                    val = remappingFunction.apply(key, e.val);
1853 >                                    if (val != null)
1854 >                                        e.val = val;
1855 >                                    else {
1856 >                                        delta = -1;
1857 >                                        Node<K,V> en = e.next;
1858 >                                        if (pred != null)
1859 >                                            pred.next = en;
1860 >                                        else
1861 >                                            setTabAt(tab, i, en);
1862 >                                    }
1863 >                                    break;
1864 >                                }
1865 >                                pred = e;
1866 >                                if ((e = e.next) == null) {
1867 >                                    val = remappingFunction.apply(key, null);
1868 >                                    if (val != null) {
1869 >                                        delta = 1;
1870 >                                        pred.next =
1871 >                                            new Node<K,V>(h, key, val, null);
1872 >                                    }
1873 >                                    break;
1874 >                                }
1875 >                            }
1876 >                        }
1877 >                        else if (f instanceof TreeBin) {
1878 >                            binCount = 1;
1879 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1880 >                            TreeNode<K,V> r, p;
1881 >                            if ((r = t.root) != null)
1882 >                                p = r.findTreeNode(h, key, null);
1883 >                            else
1884 >                                p = null;
1885                              V pv = (p == null) ? null : p.val;
1886 <                            if ((val = mf.apply(k, pv)) != null) {
1886 >                            val = remappingFunction.apply(key, pv);
1887 >                            if (val != null) {
1888                                  if (p != null)
1889                                      p.val = val;
1890                                  else {
1554                                    len = 2;
1891                                      delta = 1;
1892 <                                    t.putTreeNode(h, k, val);
1892 >                                    t.putTreeVal(h, key, val);
1893                                  }
1894                              }
1895                              else if (p != null) {
1896                                  delta = -1;
1897 <                                t.deleteTreeNode(p);
1897 >                                if (t.removeTreeNode(p))
1898 >                                    setTabAt(tab, i, untreeify(t.first));
1899                              }
1900                          }
1564                    } finally {
1565                        t.release(0);
1901                      }
1567                    if (len != 0)
1568                        break;
1902                  }
1903 <                else
1904 <                    tab = (Node<V>[])fk;
1905 <            }
1573 <            else {
1574 <                synchronized (f) {
1575 <                    if (tabAt(tab, i) == f) {
1576 <                        len = 1;
1577 <                        for (Node<V> e = f, pred = null;; ++len) {
1578 <                            Object ek; V ev;
1579 <                            if (e.hash == h &&
1580 <                                (ev = e.val) != null &&
1581 <                                ((ek = e.key) == k || k.equals(ek))) {
1582 <                                val = mf.apply(k, ev);
1583 <                                if (val != null)
1584 <                                    e.val = val;
1585 <                                else {
1586 <                                    delta = -1;
1587 <                                    Node<V> en = e.next;
1588 <                                    if (pred != null)
1589 <                                        pred.next = en;
1590 <                                    else
1591 <                                        setTabAt(tab, i, en);
1592 <                                }
1593 <                                break;
1594 <                            }
1595 <                            pred = e;
1596 <                            if ((e = e.next) == null) {
1597 <                                if (!onlyIfPresent &&
1598 <                                    (val = mf.apply(k, null)) != null) {
1599 <                                    pred.next = new Node<V>(h, k, val, null);
1600 <                                    delta = 1;
1601 <                                    if (len >= TREE_THRESHOLD)
1602 <                                        replaceWithTreeBin(tab, i, k);
1603 <                                }
1604 <                                break;
1605 <                            }
1606 <                        }
1607 <                    }
1608 <                }
1609 <                if (len != 0)
1903 >                if (binCount != 0) {
1904 >                    if (binCount >= TREEIFY_THRESHOLD)
1905 >                        treeifyBin(tab, i);
1906                      break;
1907 +                }
1908              }
1909          }
1910          if (delta != 0)
1911 <            addCount((long)delta, len);
1911 >            addCount((long)delta, binCount);
1912          return val;
1913      }
1914  
1915 <    /** Implementation for merge */
1916 <    @SuppressWarnings("unchecked") private final V internalMerge
1917 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1918 <        if (k == null || v == null || mf == null)
1915 >    /**
1916 >     * If the specified key is not already associated with a
1917 >     * (non-null) value, associates it with the given value.
1918 >     * Otherwise, replaces the value with the results of the given
1919 >     * remapping function, or removes if {@code null}. The entire
1920 >     * method invocation is performed atomically.  Some attempted
1921 >     * update operations on this map by other threads may be blocked
1922 >     * while computation is in progress, so the computation should be
1923 >     * short and simple, and must not attempt to update any other
1924 >     * mappings of this Map.
1925 >     *
1926 >     * @param key key with which the specified value is to be associated
1927 >     * @param value the value to use if absent
1928 >     * @param remappingFunction the function to recompute a value if present
1929 >     * @return the new value associated with the specified key, or null if none
1930 >     * @throws NullPointerException if the specified key or the
1931 >     *         remappingFunction is null
1932 >     * @throws RuntimeException or Error if the remappingFunction does so,
1933 >     *         in which case the mapping is unchanged
1934 >     */
1935 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1936 >        if (key == null || value == null || remappingFunction == null)
1937              throw new NullPointerException();
1938 <        int h = spread(k.hashCode());
1938 >        int h = spread(key.hashCode());
1939          V val = null;
1940          int delta = 0;
1941 <        int len = 0;
1942 <        for (Node<V>[] tab = table;;) {
1943 <            int i; Node<V> f; Object fk; V fv;
1944 <            if (tab == null)
1941 >        int binCount = 0;
1942 >        for (Node<K,V>[] tab = table;;) {
1943 >            Node<K,V> f; int n, i, fh;
1944 >            if (tab == null || (n = tab.length) == 0)
1945                  tab = initTable();
1946 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1947 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1946 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1947 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1948                      delta = 1;
1949 <                    val = v;
1949 >                    val = value;
1950                      break;
1951                  }
1952              }
1953 <            else if (f.hash < 0) {
1954 <                if ((fk = f.key) instanceof TreeBin) {
1955 <                    TreeBin<V> t = (TreeBin<V>)fk;
1956 <                    t.acquire(0);
1957 <                    try {
1958 <                        if (tabAt(tab, i) == f) {
1959 <                            len = 1;
1960 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1961 <                            val = (p == null) ? v : mf.apply(p.val, v);
1953 >            else if ((fh = f.hash) == MOVED)
1954 >                tab = helpTransfer(tab, f);
1955 >            else {
1956 >                synchronized (f) {
1957 >                    if (tabAt(tab, i) == f) {
1958 >                        if (fh >= 0) {
1959 >                            binCount = 1;
1960 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1961 >                                K ek;
1962 >                                if (e.hash == h &&
1963 >                                    ((ek = e.key) == key ||
1964 >                                     (ek != null && key.equals(ek)))) {
1965 >                                    val = remappingFunction.apply(e.val, value);
1966 >                                    if (val != null)
1967 >                                        e.val = val;
1968 >                                    else {
1969 >                                        delta = -1;
1970 >                                        Node<K,V> en = e.next;
1971 >                                        if (pred != null)
1972 >                                            pred.next = en;
1973 >                                        else
1974 >                                            setTabAt(tab, i, en);
1975 >                                    }
1976 >                                    break;
1977 >                                }
1978 >                                pred = e;
1979 >                                if ((e = e.next) == null) {
1980 >                                    delta = 1;
1981 >                                    val = value;
1982 >                                    pred.next =
1983 >                                        new Node<K,V>(h, key, val, null);
1984 >                                    break;
1985 >                                }
1986 >                            }
1987 >                        }
1988 >                        else if (f instanceof TreeBin) {
1989 >                            binCount = 2;
1990 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1991 >                            TreeNode<K,V> r = t.root;
1992 >                            TreeNode<K,V> p = (r == null) ? null :
1993 >                                r.findTreeNode(h, key, null);
1994 >                            val = (p == null) ? value :
1995 >                                remappingFunction.apply(p.val, value);
1996                              if (val != null) {
1997                                  if (p != null)
1998                                      p.val = val;
1999                                  else {
1651                                    len = 2;
2000                                      delta = 1;
2001 <                                    t.putTreeNode(h, k, val);
2001 >                                    t.putTreeVal(h, key, val);
2002                                  }
2003                              }
2004                              else if (p != null) {
2005                                  delta = -1;
2006 <                                t.deleteTreeNode(p);
2006 >                                if (t.removeTreeNode(p))
2007 >                                    setTabAt(tab, i, untreeify(t.first));
2008                              }
2009                          }
1661                    } finally {
1662                        t.release(0);
2010                      }
1664                    if (len != 0)
1665                        break;
2011                  }
2012 <                else
2013 <                    tab = (Node<V>[])fk;
2014 <            }
1670 <            else {
1671 <                synchronized (f) {
1672 <                    if (tabAt(tab, i) == f) {
1673 <                        len = 1;
1674 <                        for (Node<V> e = f, pred = null;; ++len) {
1675 <                            Object ek; V ev;
1676 <                            if (e.hash == h &&
1677 <                                (ev = e.val) != null &&
1678 <                                ((ek = e.key) == k || k.equals(ek))) {
1679 <                                val = mf.apply(ev, v);
1680 <                                if (val != null)
1681 <                                    e.val = val;
1682 <                                else {
1683 <                                    delta = -1;
1684 <                                    Node<V> en = e.next;
1685 <                                    if (pred != null)
1686 <                                        pred.next = en;
1687 <                                    else
1688 <                                        setTabAt(tab, i, en);
1689 <                                }
1690 <                                break;
1691 <                            }
1692 <                            pred = e;
1693 <                            if ((e = e.next) == null) {
1694 <                                val = v;
1695 <                                pred.next = new Node<V>(h, k, val, null);
1696 <                                delta = 1;
1697 <                                if (len >= TREE_THRESHOLD)
1698 <                                    replaceWithTreeBin(tab, i, k);
1699 <                                break;
1700 <                            }
1701 <                        }
1702 <                    }
1703 <                }
1704 <                if (len != 0)
2012 >                if (binCount != 0) {
2013 >                    if (binCount >= TREEIFY_THRESHOLD)
2014 >                        treeifyBin(tab, i);
2015                      break;
2016 +                }
2017              }
2018          }
2019          if (delta != 0)
2020 <            addCount((long)delta, len);
2020 >            addCount((long)delta, binCount);
2021          return val;
2022      }
2023  
2024 <    /** Implementation for putAll */
2025 <    @SuppressWarnings("unchecked") private final void internalPutAll
2026 <        (Map<? extends K, ? extends V> m) {
2027 <        tryPresize(m.size());
2028 <        long delta = 0L;     // number of uncommitted additions
2029 <        boolean npe = false; // to throw exception on exit for nulls
2030 <        try {                // to clean up counts on other exceptions
2031 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2032 <                Object k; V v;
2033 <                if (entry == null || (k = entry.getKey()) == null ||
2034 <                    (v = entry.getValue()) == null) {
2035 <                    npe = true;
2036 <                    break;
2037 <                }
2038 <                int h = spread(k.hashCode());
2039 <                for (Node<V>[] tab = table;;) {
2040 <                    int i; Node<V> f; int fh; Object fk;
2041 <                    if (tab == null)
2042 <                        tab = initTable();
2043 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2044 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2045 <                            ++delta;
2046 <                            break;
2047 <                        }
2048 <                    }
2049 <                    else if ((fh = f.hash) < 0) {
2050 <                        if ((fk = f.key) instanceof TreeBin) {
2051 <                            TreeBin<V> t = (TreeBin<V>)fk;
2052 <                            boolean validated = false;
2053 <                            t.acquire(0);
2054 <                            try {
2055 <                                if (tabAt(tab, i) == f) {
2056 <                                    validated = true;
2057 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2058 <                                    if (p != null)
2059 <                                        p.val = v;
2060 <                                    else {
2061 <                                        t.putTreeNode(h, k, v);
2062 <                                        ++delta;
2063 <                                    }
2064 <                                }
2065 <                            } finally {
2066 <                                t.release(0);
2067 <                            }
2068 <                            if (validated)
2069 <                                break;
2070 <                        }
2071 <                        else
2072 <                            tab = (Node<V>[])fk;
2073 <                    }
2074 <                    else {
2075 <                        int len = 0;
2076 <                        synchronized (f) {
2077 <                            if (tabAt(tab, i) == f) {
2078 <                                len = 1;
2079 <                                for (Node<V> e = f;; ++len) {
2080 <                                    Object ek; V ev;
2081 <                                    if (e.hash == h &&
2082 <                                        (ev = e.val) != null &&
2083 <                                        ((ek = e.key) == k || k.equals(ek))) {
2084 <                                        e.val = v;
2085 <                                        break;
2086 <                                    }
2087 <                                    Node<V> last = e;
2088 <                                    if ((e = e.next) == null) {
2089 <                                        ++delta;
2090 <                                        last.next = new Node<V>(h, k, v, null);
2091 <                                        if (len >= TREE_THRESHOLD)
2092 <                                            replaceWithTreeBin(tab, i, k);
2093 <                                        break;
2094 <                                    }
2095 <                                }
2096 <                            }
2097 <                        }
2098 <                        if (len != 0) {
2099 <                            if (len > 1)
2100 <                                addCount(delta, len);
2101 <                            break;
2102 <                        }
2103 <                    }
2104 <                }
2105 <            }
2106 <        } finally {
2107 <            if (delta != 0L)
2108 <                addCount(delta, 2);
2109 <        }
2110 <        if (npe)
2024 >    // Hashtable legacy methods
2025 >
2026 >    /**
2027 >     * Legacy method testing if some key maps into the specified value
2028 >     * in this table.  This method is identical in functionality to
2029 >     * {@link #containsValue(Object)}, and exists solely to ensure
2030 >     * full compatibility with class {@link java.util.Hashtable},
2031 >     * which supported this method prior to introduction of the
2032 >     * Java Collections framework.
2033 >     *
2034 >     * @param  value a value to search for
2035 >     * @return {@code true} if and only if some key maps to the
2036 >     *         {@code value} argument in this table as
2037 >     *         determined by the {@code equals} method;
2038 >     *         {@code false} otherwise
2039 >     * @throws NullPointerException if the specified value is null
2040 >     */
2041 >    @Deprecated public boolean contains(Object value) {
2042 >        return containsValue(value);
2043 >    }
2044 >
2045 >    /**
2046 >     * Returns an enumeration of the keys in this table.
2047 >     *
2048 >     * @return an enumeration of the keys in this table
2049 >     * @see #keySet()
2050 >     */
2051 >    public Enumeration<K> keys() {
2052 >        Node<K,V>[] t;
2053 >        int f = (t = table) == null ? 0 : t.length;
2054 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2055 >    }
2056 >
2057 >    /**
2058 >     * Returns an enumeration of the values in this table.
2059 >     *
2060 >     * @return an enumeration of the values in this table
2061 >     * @see #values()
2062 >     */
2063 >    public Enumeration<V> elements() {
2064 >        Node<K,V>[] t;
2065 >        int f = (t = table) == null ? 0 : t.length;
2066 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2067 >    }
2068 >
2069 >    // ConcurrentHashMapV8-only methods
2070 >
2071 >    /**
2072 >     * Returns the number of mappings. This method should be used
2073 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2074 >     * contain more mappings than can be represented as an int. The
2075 >     * value returned is an estimate; the actual count may differ if
2076 >     * there are concurrent insertions or removals.
2077 >     *
2078 >     * @return the number of mappings
2079 >     * @since 1.8
2080 >     */
2081 >    public long mappingCount() {
2082 >        long n = sumCount();
2083 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2084 >    }
2085 >
2086 >    /**
2087 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2088 >     * from the given type to {@code Boolean.TRUE}.
2089 >     *
2090 >     * @return the new set
2091 >     * @since 1.8
2092 >     */
2093 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2094 >        return new KeySetView<K,Boolean>
2095 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2096 >    }
2097 >
2098 >    /**
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2100 >     * from the given type to {@code Boolean.TRUE}.
2101 >     *
2102 >     * @param initialCapacity The implementation performs internal
2103 >     * sizing to accommodate this many elements.
2104 >     * @throws IllegalArgumentException if the initial capacity of
2105 >     * elements is negative
2106 >     * @return the new set
2107 >     * @since 1.8
2108 >     */
2109 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2110 >        return new KeySetView<K,Boolean>
2111 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2112 >    }
2113 >
2114 >    /**
2115 >     * Returns a {@link Set} view of the keys in this map, using the
2116 >     * given common mapped value for any additions (i.e., {@link
2117 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2118 >     * This is of course only appropriate if it is acceptable to use
2119 >     * the same value for all additions from this view.
2120 >     *
2121 >     * @param mappedValue the mapped value to use for any additions
2122 >     * @return the set view
2123 >     * @throws NullPointerException if the mappedValue is null
2124 >     */
2125 >    public KeySetView<K,V> keySet(V mappedValue) {
2126 >        if (mappedValue == null)
2127              throw new NullPointerException();
2128 +        return new KeySetView<K,V>(this, mappedValue);
2129      }
2130  
2131 +    /* ---------------- Special Nodes -------------- */
2132 +
2133      /**
2134 <     * Implementation for clear. Steps through each bin, removing all
1805 <     * nodes.
2134 >     * A node inserted at head of bins during transfer operations.
2135       */
2136 <    @SuppressWarnings("unchecked") private final void internalClear() {
2137 <        long delta = 0L; // negative number of deletions
2138 <        int i = 0;
2139 <        Node<V>[] tab = table;
2140 <        while (tab != null && i < tab.length) {
2141 <            Node<V> f = tabAt(tab, i);
2142 <            if (f == null)
2143 <                ++i;
2144 <            else if (f.hash < 0) {
2145 <                Object fk;
2146 <                if ((fk = f.key) instanceof TreeBin) {
2147 <                    TreeBin<V> t = (TreeBin<V>)fk;
2148 <                    t.acquire(0);
2149 <                    try {
2150 <                        if (tabAt(tab, i) == f) {
2151 <                            for (Node<V> p = t.first; p != null; p = p.next) {
2152 <                                if (p.val != null) { // (currently always true)
2153 <                                    p.val = null;
2154 <                                    --delta;
2155 <                                }
2156 <                            }
2157 <                            t.first = null;
2158 <                            t.root = null;
1830 <                            ++i;
1831 <                        }
1832 <                    } finally {
1833 <                        t.release(0);
1834 <                    }
1835 <                }
1836 <                else
1837 <                    tab = (Node<V>[])fk;
1838 <            }
1839 <            else {
1840 <                synchronized (f) {
1841 <                    if (tabAt(tab, i) == f) {
1842 <                        for (Node<V> e = f; e != null; e = e.next) {
1843 <                            if (e.val != null) {  // (currently always true)
1844 <                                e.val = null;
1845 <                                --delta;
1846 <                            }
2136 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2137 >        final Node<K,V>[] nextTable;
2138 >        ForwardingNode(Node<K,V>[] tab) {
2139 >            super(MOVED, null, null, null);
2140 >            this.nextTable = tab;
2141 >        }
2142 >
2143 >        Node<K,V> find(int h, Object k) {
2144 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2145 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2146 >                Node<K,V> e; int n;
2147 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2148 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2149 >                    return null;
2150 >                for (;;) {
2151 >                    int eh; K ek;
2152 >                    if ((eh = e.hash) == h &&
2153 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2154 >                        return e;
2155 >                    if (eh < 0) {
2156 >                        if (e instanceof ForwardingNode) {
2157 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2158 >                            continue outer;
2159                          }
2160 <                        setTabAt(tab, i, null);
2161 <                        ++i;
2160 >                        else
2161 >                            return e.find(h, k);
2162                      }
2163 +                    if ((e = e.next) == null)
2164 +                        return null;
2165                  }
2166              }
2167          }
1854        if (delta != 0L)
1855            addCount(delta, -1);
2168      }
2169  
1858    /* ---------------- Table Initialization and Resizing -------------- */
1859
2170      /**
2171 <     * Returns a power of two table size for the given desired capacity.
1862 <     * See Hackers Delight, sec 3.2
2171 >     * A place-holder node used in computeIfAbsent and compute
2172       */
2173 <    private static final int tableSizeFor(int c) {
2174 <        int n = c - 1;
2175 <        n |= n >>> 1;
2176 <        n |= n >>> 2;
2177 <        n |= n >>> 4;
2178 <        n |= n >>> 8;
2179 <        n |= n >>> 16;
2180 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2173 >    static final class ReservationNode<K,V> extends Node<K,V> {
2174 >        ReservationNode() {
2175 >            super(RESERVED, null, null, null);
2176 >        }
2177 >
2178 >        Node<K,V> find(int h, Object k) {
2179 >            return null;
2180 >        }
2181      }
2182  
2183 +    /* ---------------- Table Initialization and Resizing -------------- */
2184 +
2185      /**
2186       * Initializes table, using the size recorded in sizeCtl.
2187       */
2188 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2189 <        Node<V>[] tab; int sc;
2190 <        while ((tab = table) == null) {
2188 >    private final Node<K,V>[] initTable() {
2189 >        Node<K,V>[] tab; int sc;
2190 >        while ((tab = table) == null || tab.length == 0) {
2191              if ((sc = sizeCtl) < 0)
2192                  Thread.yield(); // lost initialization race; just spin
2193              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2194                  try {
2195 <                    if ((tab = table) == null) {
2195 >                    if ((tab = table) == null || tab.length == 0) {
2196                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2197 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2198 <                        table = tab = (Node<V>[])tb;
2197 >                        @SuppressWarnings({"rawtypes","unchecked"})
2198 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2199 >                        table = tab = nt;
2200                          sc = n - (n >>> 2);
2201                      }
2202                  } finally {
# Line 1925 | Line 2237 | public class ConcurrentHashMapV8<K, V>
2237              s = sumCount();
2238          }
2239          if (check >= 0) {
2240 <            Node<V>[] tab, nt; int sc;
2240 >            Node<K,V>[] tab, nt; int sc;
2241              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2242                     tab.length < MAXIMUM_CAPACITY) {
2243                  if (sc < 0) {
# Line 1943 | Line 2255 | public class ConcurrentHashMapV8<K, V>
2255      }
2256  
2257      /**
2258 +     * Helps transfer if a resize is in progress.
2259 +     */
2260 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2261 +        Node<K,V>[] nextTab; int sc;
2262 +        if ((f instanceof ForwardingNode) &&
2263 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2264 +            if (nextTab == nextTable && tab == table &&
2265 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2266 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2267 +                transfer(tab, nextTab);
2268 +            return nextTab;
2269 +        }
2270 +        return table;
2271 +    }
2272 +
2273 +    /**
2274       * Tries to presize table to accommodate the given number of elements.
2275       *
2276       * @param size number of elements (doesn't need to be perfectly accurate)
2277       */
2278 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2278 >    private final void tryPresize(int size) {
2279          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2280              tableSizeFor(size + (size >>> 1) + 1);
2281          int sc;
2282          while ((sc = sizeCtl) >= 0) {
2283 <            Node<V>[] tab = table; int n;
2283 >            Node<K,V>[] tab = table; int n;
2284              if (tab == null || (n = tab.length) == 0) {
2285                  n = (sc > c) ? sc : c;
2286                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2287                      try {
2288                          if (table == tab) {
2289 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2290 <                            table = (Node<V>[])tb;
2289 >                            @SuppressWarnings({"rawtypes","unchecked"})
2290 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2291 >                            table = nt;
2292                              sc = n - (n >>> 2);
2293                          }
2294                      } finally {
# Line 1975 | Line 2304 | public class ConcurrentHashMapV8<K, V>
2304          }
2305      }
2306  
2307 <    /*
2307 >    /**
2308       * Moves and/or copies the nodes in each bin to new table. See
2309       * above for explanation.
2310       */
2311 <    @SuppressWarnings("unchecked") private final void transfer
1983 <        (Node<V>[] tab, Node<V>[] nextTab) {
2311 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2312          int n = tab.length, stride;
2313          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2314              stride = MIN_TRANSFER_STRIDE; // subdivide range
2315          if (nextTab == null) {            // initiating
2316              try {
2317 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2318 <                nextTab = (Node<V>[])tb;
2317 >                @SuppressWarnings({"rawtypes","unchecked"})
2318 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2319 >                nextTab = nt;
2320              } catch (Throwable ex) {      // try to cope with OOME
2321                  sizeCtl = Integer.MAX_VALUE;
2322                  return;
# Line 1995 | Line 2324 | public class ConcurrentHashMapV8<K, V>
2324              nextTable = nextTab;
2325              transferOrigin = n;
2326              transferIndex = n;
2327 <            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2327 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2328              for (int k = n; k > 0;) {    // progressively reveal ready slots
2329                  int nextk = (k > stride) ? k - stride : 0;
2330                  for (int m = nextk; m < k; ++m)
# Line 2006 | Line 2335 | public class ConcurrentHashMapV8<K, V>
2335              }
2336          }
2337          int nextn = nextTab.length;
2338 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2338 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2339          boolean advance = true;
2340 +        boolean finishing = false; // to ensure sweep before committing nextTab
2341          for (int i = 0, bound = 0;;) {
2342 <            int nextIndex, nextBound; Node<V> f; Object fk;
2342 >            int nextIndex, nextBound, fh; Node<K,V> f;
2343              while (advance) {
2344 <                if (--i >= bound)
2344 >                if (--i >= bound || finishing)
2345                      advance = false;
2346                  else if ((nextIndex = transferIndex) <= transferOrigin) {
2347                      i = -1;
# Line 2027 | Line 2357 | public class ConcurrentHashMapV8<K, V>
2357                  }
2358              }
2359              if (i < 0 || i >= n || i + n >= nextn) {
2360 +                if (finishing) {
2361 +                    nextTable = null;
2362 +                    table = nextTab;
2363 +                    sizeCtl = (n << 1) - (n >>> 1);
2364 +                    return;
2365 +                }
2366                  for (int sc;;) {
2367                      if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2368 <                        if (sc == -1) {
2369 <                            nextTable = null;
2370 <                            table = nextTab;
2371 <                            sizeCtl = (n << 1) - (n >>> 1);
2372 <                        }
2037 <                        return;
2368 >                        if (sc != -1)
2369 >                            return;
2370 >                        finishing = advance = true;
2371 >                        i = n; // recheck before commit
2372 >                        break;
2373                      }
2374                  }
2375              }
# Line 2045 | Line 2380 | public class ConcurrentHashMapV8<K, V>
2380                      advance = true;
2381                  }
2382              }
2383 <            else if (f.hash >= 0) {
2383 >            else if ((fh = f.hash) == MOVED)
2384 >                advance = true; // already processed
2385 >            else {
2386                  synchronized (f) {
2387                      if (tabAt(tab, i) == f) {
2388 <                        int runBit = f.hash & n;
2389 <                        Node<V> lastRun = f, lo = null, hi = null;
2390 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2391 <                            int b = p.hash & n;
2392 <                            if (b != runBit) {
2393 <                                runBit = b;
2394 <                                lastRun = p;
2388 >                        Node<K,V> ln, hn;
2389 >                        if (fh >= 0) {
2390 >                            int runBit = fh & n;
2391 >                            Node<K,V> lastRun = f;
2392 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2393 >                                int b = p.hash & n;
2394 >                                if (b != runBit) {
2395 >                                    runBit = b;
2396 >                                    lastRun = p;
2397 >                                }
2398                              }
2399 <                        }
2400 <                        if (runBit == 0)
2401 <                            lo = lastRun;
2062 <                        else
2063 <                            hi = lastRun;
2064 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
2065 <                            int ph = p.hash;
2066 <                            Object pk = p.key; V pv = p.val;
2067 <                            if ((ph & n) == 0)
2068 <                                lo = new Node<V>(ph, pk, pv, lo);
2069 <                            else
2070 <                                hi = new Node<V>(ph, pk, pv, hi);
2071 <                        }
2072 <                        setTabAt(nextTab, i, lo);
2073 <                        setTabAt(nextTab, i + n, hi);
2074 <                        setTabAt(tab, i, fwd);
2075 <                        advance = true;
2076 <                    }
2077 <                }
2078 <            }
2079 <            else if ((fk = f.key) instanceof TreeBin) {
2080 <                TreeBin<V> t = (TreeBin<V>)fk;
2081 <                t.acquire(0);
2082 <                try {
2083 <                    if (tabAt(tab, i) == f) {
2084 <                        TreeBin<V> lt = new TreeBin<V>();
2085 <                        TreeBin<V> ht = new TreeBin<V>();
2086 <                        int lc = 0, hc = 0;
2087 <                        for (Node<V> e = t.first; e != null; e = e.next) {
2088 <                            int h = e.hash;
2089 <                            Object k = e.key; V v = e.val;
2090 <                            if ((h & n) == 0) {
2091 <                                ++lc;
2092 <                                lt.putTreeNode(h, k, v);
2399 >                            if (runBit == 0) {
2400 >                                ln = lastRun;
2401 >                                hn = null;
2402                              }
2403                              else {
2404 <                                ++hc;
2405 <                                ht.putTreeNode(h, k, v);
2404 >                                hn = lastRun;
2405 >                                ln = null;
2406                              }
2407 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2408 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2409 +                                if ((ph & n) == 0)
2410 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2411 +                                else
2412 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2413 +                            }
2414 +                            setTabAt(nextTab, i, ln);
2415 +                            setTabAt(nextTab, i + n, hn);
2416 +                            setTabAt(tab, i, fwd);
2417 +                            advance = true;
2418                          }
2419 <                        Node<V> ln, hn; // throw away trees if too small
2420 <                        if (lc < TREE_THRESHOLD) {
2421 <                            ln = null;
2422 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2423 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2424 <                        }
2425 <                        else
2426 <                            ln = new Node<V>(MOVED, lt, null, null);
2427 <                        setTabAt(nextTab, i, ln);
2428 <                        if (hc < TREE_THRESHOLD) {
2429 <                            hn = null;
2430 <                            for (Node<V> p = ht.first; p != null; p = p.next)
2431 <                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2419 >                        else if (f instanceof TreeBin) {
2420 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2421 >                            TreeNode<K,V> lo = null, loTail = null;
2422 >                            TreeNode<K,V> hi = null, hiTail = null;
2423 >                            int lc = 0, hc = 0;
2424 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2425 >                                int h = e.hash;
2426 >                                TreeNode<K,V> p = new TreeNode<K,V>
2427 >                                    (h, e.key, e.val, null, null);
2428 >                                if ((h & n) == 0) {
2429 >                                    if ((p.prev = loTail) == null)
2430 >                                        lo = p;
2431 >                                    else
2432 >                                        loTail.next = p;
2433 >                                    loTail = p;
2434 >                                    ++lc;
2435 >                                }
2436 >                                else {
2437 >                                    if ((p.prev = hiTail) == null)
2438 >                                        hi = p;
2439 >                                    else
2440 >                                        hiTail.next = p;
2441 >                                    hiTail = p;
2442 >                                    ++hc;
2443 >                                }
2444 >                            }
2445 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2446 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2447 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2448 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2449 >                            setTabAt(nextTab, i, ln);
2450 >                            setTabAt(nextTab, i + n, hn);
2451 >                            setTabAt(tab, i, fwd);
2452 >                            advance = true;
2453                          }
2113                        else
2114                            hn = new Node<V>(MOVED, ht, null, null);
2115                        setTabAt(nextTab, i + n, hn);
2116                        setTabAt(tab, i, fwd);
2117                        advance = true;
2454                      }
2119                } finally {
2120                    t.release(0);
2455                  }
2456              }
2123            else
2124                advance = true; // already processed
2457          }
2458      }
2459  
2460 <    /* ---------------- Counter support -------------- */
2460 >    /* ---------------- Conversion from/to TreeBins -------------- */
2461  
2462 <    final long sumCount() {
2463 <        CounterCell[] as = counterCells; CounterCell a;
2464 <        long sum = baseCount;
2465 <        if (as != null) {
2466 <            for (int i = 0; i < as.length; ++i) {
2467 <                if ((a = as[i]) != null)
2468 <                    sum += a.value;
2462 >    /**
2463 >     * Replaces all linked nodes in bin at given index unless table is
2464 >     * too small, in which case resizes instead.
2465 >     */
2466 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2467 >        Node<K,V> b; int n, sc;
2468 >        if (tab != null) {
2469 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2470 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2471 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2472 >                    transfer(tab, null);
2473              }
2474 <        }
2475 <        return sum;
2476 <    }
2477 <
2478 <    // See LongAdder version for explanation
2479 <    private final void fullAddCount(long x, CounterHashCode hc,
2480 <                                    boolean wasUncontended) {
2481 <        int h;
2482 <        if (hc == null) {
2483 <            hc = new CounterHashCode();
2484 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2485 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2486 <            threadCounterHashCode.set(hc);
2151 <        }
2152 <        else
2153 <            h = hc.code;
2154 <        boolean collide = false;                // True if last slot nonempty
2155 <        for (;;) {
2156 <            CounterCell[] as; CounterCell a; int n; long v;
2157 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2158 <                if ((a = as[(n - 1) & h]) == null) {
2159 <                    if (counterBusy == 0) {            // Try to attach new Cell
2160 <                        CounterCell r = new CounterCell(x); // Optimistic create
2161 <                        if (counterBusy == 0 &&
2162 <                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2163 <                            boolean created = false;
2164 <                            try {               // Recheck under lock
2165 <                                CounterCell[] rs; int m, j;
2166 <                                if ((rs = counterCells) != null &&
2167 <                                    (m = rs.length) > 0 &&
2168 <                                    rs[j = (m - 1) & h] == null) {
2169 <                                    rs[j] = r;
2170 <                                    created = true;
2171 <                                }
2172 <                            } finally {
2173 <                                counterBusy = 0;
2174 <                            }
2175 <                            if (created)
2176 <                                break;
2177 <                            continue;           // Slot is now non-empty
2178 <                        }
2179 <                    }
2180 <                    collide = false;
2181 <                }
2182 <                else if (!wasUncontended)       // CAS already known to fail
2183 <                    wasUncontended = true;      // Continue after rehash
2184 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2185 <                    break;
2186 <                else if (counterCells != as || n >= NCPU)
2187 <                    collide = false;            // At max size or stale
2188 <                else if (!collide)
2189 <                    collide = true;
2190 <                else if (counterBusy == 0 &&
2191 <                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2192 <                    try {
2193 <                        if (counterCells == as) {// Expand table unless stale
2194 <                            CounterCell[] rs = new CounterCell[n << 1];
2195 <                            for (int i = 0; i < n; ++i)
2196 <                                rs[i] = as[i];
2197 <                            counterCells = rs;
2474 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2475 >                synchronized (b) {
2476 >                    if (tabAt(tab, index) == b) {
2477 >                        TreeNode<K,V> hd = null, tl = null;
2478 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2479 >                            TreeNode<K,V> p =
2480 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2481 >                                                  null, null);
2482 >                            if ((p.prev = tl) == null)
2483 >                                hd = p;
2484 >                            else
2485 >                                tl.next = p;
2486 >                            tl = p;
2487                          }
2488 <                    } finally {
2200 <                        counterBusy = 0;
2201 <                    }
2202 <                    collide = false;
2203 <                    continue;                   // Retry with expanded table
2204 <                }
2205 <                h ^= h << 13;                   // Rehash
2206 <                h ^= h >>> 17;
2207 <                h ^= h << 5;
2208 <            }
2209 <            else if (counterBusy == 0 && counterCells == as &&
2210 <                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2211 <                boolean init = false;
2212 <                try {                           // Initialize table
2213 <                    if (counterCells == as) {
2214 <                        CounterCell[] rs = new CounterCell[2];
2215 <                        rs[h & 1] = new CounterCell(x);
2216 <                        counterCells = rs;
2217 <                        init = true;
2488 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2489                      }
2219                } finally {
2220                    counterBusy = 0;
2490                  }
2222                if (init)
2223                    break;
2491              }
2225            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2226                break;                          // Fall back on using base
2492          }
2228        hc.code = h;                            // Record index for next time
2493      }
2494  
2495 <    /* ----------------Table Traversal -------------- */
2495 >    /**
2496 >     * Returns a list on non-TreeNodes replacing those in given list.
2497 >     */
2498 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2499 >        Node<K,V> hd = null, tl = null;
2500 >        for (Node<K,V> q = b; q != null; q = q.next) {
2501 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2502 >            if (tl == null)
2503 >                hd = p;
2504 >            else
2505 >                tl.next = p;
2506 >            tl = p;
2507 >        }
2508 >        return hd;
2509 >    }
2510 >
2511 >    /* ---------------- TreeNodes -------------- */
2512  
2513      /**
2514 <     * Encapsulates traversal for methods such as containsValue; also
2515 <     * serves as a base class for other iterators and bulk tasks.
2516 <     *
2517 <     * At each step, the iterator snapshots the key ("nextKey") and
2518 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2519 <     * snapshot, has a non-null user value). Because val fields can
2520 <     * change (including to null, indicating deletion), field nextVal
2521 <     * might not be accurate at point of use, but still maintains the
2242 <     * weak consistency property of holding a value that was once
2243 <     * valid. To support iterator.remove, the nextKey field is not
2244 <     * updated (nulled out) when the iterator cannot advance.
2245 <     *
2246 <     * Internal traversals directly access these fields, as in:
2247 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2248 <     *
2249 <     * Exported iterators must track whether the iterator has advanced
2250 <     * (in hasNext vs next) (by setting/checking/nulling field
2251 <     * nextVal), and then extract key, value, or key-value pairs as
2252 <     * return values of next().
2253 <     *
2254 <     * The iterator visits once each still-valid node that was
2255 <     * reachable upon iterator construction. It might miss some that
2256 <     * were added to a bin after the bin was visited, which is OK wrt
2257 <     * consistency guarantees. Maintaining this property in the face
2258 <     * of possible ongoing resizes requires a fair amount of
2259 <     * bookkeeping state that is difficult to optimize away amidst
2260 <     * volatile accesses.  Even so, traversal maintains reasonable
2261 <     * throughput.
2262 <     *
2263 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2264 <     * However, if the table has been resized, then all future steps
2265 <     * must traverse both the bin at the current index as well as at
2266 <     * (index + baseSize); and so on for further resizings. To
2267 <     * paranoically cope with potential sharing by users of iterators
2268 <     * across threads, iteration terminates if a bounds checks fails
2269 <     * for a table read.
2270 <     *
2271 <     * This class extends CountedCompleter to streamline parallel
2272 <     * iteration in bulk operations. This adds only a few fields of
2273 <     * space overhead, which is small enough in cases where it is not
2274 <     * needed to not worry about it.  Because CountedCompleter is
2275 <     * Serializable, but iterators need not be, we need to add warning
2276 <     * suppressions.
2277 <     */
2278 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2279 <        extends CountedCompleter<R> {
2280 <        final ConcurrentHashMapV8<K, V> map;
2281 <        Node<V> next;        // the next entry to use
2282 <        Object nextKey;      // cached key field of next
2283 <        V nextVal;           // cached val field of next
2284 <        Node<V>[] tab;       // current table; updated if resized
2285 <        int index;           // index of bin to use next
2286 <        int baseIndex;       // current index of initial table
2287 <        int baseLimit;       // index bound for initial table
2288 <        int baseSize;        // initial table size
2289 <        int batch;           // split control
2514 >     * Nodes for use in TreeBins
2515 >     */
2516 >    static final class TreeNode<K,V> extends Node<K,V> {
2517 >        TreeNode<K,V> parent;  // red-black tree links
2518 >        TreeNode<K,V> left;
2519 >        TreeNode<K,V> right;
2520 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2521 >        boolean red;
2522  
2523 <        /** Creates iterator for all entries in the table. */
2524 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2525 <            this.map = map;
2523 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2524 >                 TreeNode<K,V> parent) {
2525 >            super(hash, key, val, next);
2526 >            this.parent = parent;
2527          }
2528  
2529 <        /** Creates iterator for split() methods and task constructors */
2530 <        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2298 <            super(it);
2299 <            this.batch = batch;
2300 <            if ((this.map = map) != null && it != null) { // split parent
2301 <                Node<V>[] t;
2302 <                if ((t = it.tab) == null &&
2303 <                    (t = it.tab = map.table) != null)
2304 <                    it.baseLimit = it.baseSize = t.length;
2305 <                this.tab = t;
2306 <                this.baseSize = it.baseSize;
2307 <                int hi = this.baseLimit = it.baseLimit;
2308 <                it.baseLimit = this.index = this.baseIndex =
2309 <                    (hi + it.baseIndex + 1) >>> 1;
2310 <            }
2529 >        Node<K,V> find(int h, Object k) {
2530 >            return findTreeNode(h, k, null);
2531          }
2532  
2533          /**
2534 <         * Advances next; returns nextVal or null if terminated.
2535 <         * See above for explanation.
2534 >         * Returns the TreeNode (or null if not found) for the given key
2535 >         * starting at given root.
2536           */
2537 <        @SuppressWarnings("unchecked") final V advance() {
2538 <            Node<V> e = next;
2539 <            V ev = null;
2540 <            outer: do {
2541 <                if (e != null)                  // advance past used/skipped node
2542 <                    e = e.next;
2543 <                while (e == null) {             // get to next non-null bin
2544 <                    ConcurrentHashMapV8<K, V> m;
2545 <                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2546 <                    if ((t = tab) != null)
2547 <                        n = t.length;
2548 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2549 <                        n = baseLimit = baseSize = t.length;
2537 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2538 >            if (k != null) {
2539 >                TreeNode<K,V> p = this;
2540 >                do  {
2541 >                    int ph, dir; K pk; TreeNode<K,V> q;
2542 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2543 >                    if ((ph = p.hash) > h)
2544 >                        p = pl;
2545 >                    else if (ph < h)
2546 >                        p = pr;
2547 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2548 >                        return p;
2549 >                    else if (pl == null && pr == null)
2550 >                        break;
2551 >                    else if ((kc != null ||
2552 >                              (kc = comparableClassFor(k)) != null) &&
2553 >                             (dir = compareComparables(kc, k, pk)) != 0)
2554 >                        p = (dir < 0) ? pl : pr;
2555 >                    else if (pl == null)
2556 >                        p = pr;
2557 >                    else if (pr == null ||
2558 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2559 >                        p = pl;
2560                      else
2561 <                        break outer;
2562 <                    if ((b = baseIndex) >= baseLimit ||
2563 <                        (i = index) < 0 || i >= n)
2564 <                        break outer;
2565 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2566 <                        if ((ek = e.key) instanceof TreeBin)
2567 <                            e = ((TreeBin<V>)ek).first;
2568 <                        else {
2569 <                            tab = (Node<V>[])ek;
2570 <                            continue;           // restarts due to null val
2561 >                        return q;
2562 >                } while (p != null);
2563 >            }
2564 >            return null;
2565 >        }
2566 >    }
2567 >
2568 >    /* ---------------- TreeBins -------------- */
2569 >
2570 >    /**
2571 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2572 >     * keys or values, but instead point to list of TreeNodes and
2573 >     * their root. They also maintain a parasitic read-write lock
2574 >     * forcing writers (who hold bin lock) to wait for readers (who do
2575 >     * not) to complete before tree restructuring operations.
2576 >     */
2577 >    static final class TreeBin<K,V> extends Node<K,V> {
2578 >        TreeNode<K,V> root;
2579 >        volatile TreeNode<K,V> first;
2580 >        volatile Thread waiter;
2581 >        volatile int lockState;
2582 >        // values for lockState
2583 >        static final int WRITER = 1; // set while holding write lock
2584 >        static final int WAITER = 2; // set when waiting for write lock
2585 >        static final int READER = 4; // increment value for setting read lock
2586 >
2587 >        /**
2588 >         * Creates bin with initial set of nodes headed by b.
2589 >         */
2590 >        TreeBin(TreeNode<K,V> b) {
2591 >            super(TREEBIN, null, null, null);
2592 >            this.first = b;
2593 >            TreeNode<K,V> r = null;
2594 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2595 >                next = (TreeNode<K,V>)x.next;
2596 >                x.left = x.right = null;
2597 >                if (r == null) {
2598 >                    x.parent = null;
2599 >                    x.red = false;
2600 >                    r = x;
2601 >                }
2602 >                else {
2603 >                    Object key = x.key;
2604 >                    int hash = x.hash;
2605 >                    Class<?> kc = null;
2606 >                    for (TreeNode<K,V> p = r;;) {
2607 >                        int dir, ph;
2608 >                        if ((ph = p.hash) > hash)
2609 >                            dir = -1;
2610 >                        else if (ph < hash)
2611 >                            dir = 1;
2612 >                        else if ((kc != null ||
2613 >                                  (kc = comparableClassFor(key)) != null))
2614 >                            dir = compareComparables(kc, key, p.key);
2615 >                        else
2616 >                            dir = 0;
2617 >                        TreeNode<K,V> xp = p;
2618 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2619 >                            x.parent = xp;
2620 >                            if (dir <= 0)
2621 >                                xp.left = x;
2622 >                            else
2623 >                                xp.right = x;
2624 >                            r = balanceInsertion(r, x);
2625 >                            break;
2626                          }
2627 <                    }                           // visit upper slots if present
2343 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2627 >                    }
2628                  }
2629 <                nextKey = e.key;
2630 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2347 <            next = e;
2348 <            return nextVal = ev;
2629 >            }
2630 >            this.root = r;
2631          }
2632  
2633 <        public final void remove() {
2634 <            Object k = nextKey;
2635 <            if (k == null && (advance() == null || (k = nextKey) == null))
2636 <                throw new IllegalStateException();
2637 <            map.internalReplace(k, null, null);
2633 >        /**
2634 >         * Acquires write lock for tree restructuring.
2635 >         */
2636 >        private final void lockRoot() {
2637 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2638 >                contendedLock(); // offload to separate method
2639          }
2640  
2641 <        public final boolean hasNext() {
2642 <            return nextVal != null || advance() != null;
2641 >        /**
2642 >         * Releases write lock for tree restructuring.
2643 >         */
2644 >        private final void unlockRoot() {
2645 >            lockState = 0;
2646          }
2647  
2362        public final boolean hasMoreElements() { return hasNext(); }
2363
2364        public void compute() { } // default no-op CountedCompleter body
2365
2648          /**
2649 <         * Returns a batch value > 0 if this task should (and must) be
2368 <         * split, if so, adding to pending count, and in any case
2369 <         * updating batch value. The initial batch value is approx
2370 <         * exp2 of the number of times (minus one) to split task by
2371 <         * two before executing leaf action. This value is faster to
2372 <         * compute and more convenient to use as a guide to splitting
2373 <         * than is the depth, since it is used while dividing by two
2374 <         * anyway.
2649 >         * Possibly blocks awaiting root lock.
2650           */
2651 <        final int preSplit() {
2652 <            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2653 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2654 <                if ((t = tab) == null && (t = tab = m.table) != null)
2655 <                    baseLimit = baseSize = t.length;
2656 <                if (t != null) {
2657 <                    long n = m.sumCount();
2658 <                    int par = ((pool = getPool()) == null) ?
2659 <                        ForkJoinPool.getCommonPoolParallelism() :
2660 <                        pool.getParallelism();
2661 <                    int sp = par << 3; // slack of 8
2662 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2663 <                }
2664 <            }
2665 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2666 <            if ((batch = b) > 0)
2667 <                addToPendingCount(1);
2668 <            return b;
2651 >        private final void contendedLock() {
2652 >            boolean waiting = false;
2653 >            for (int s;;) {
2654 >                if (((s = lockState) & WRITER) == 0) {
2655 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2656 >                        if (waiting)
2657 >                            waiter = null;
2658 >                        return;
2659 >                    }
2660 >                }
2661 >                else if ((s | WAITER) == 0) {
2662 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2663 >                        waiting = true;
2664 >                        waiter = Thread.currentThread();
2665 >                    }
2666 >                }
2667 >                else if (waiting)
2668 >                    LockSupport.park(this);
2669 >            }
2670          }
2671  
2672 <    }
2673 <
2674 <    /* ---------------- Public operations -------------- */
2675 <
2676 <    /**
2677 <     * Creates a new, empty map with the default initial table size (16).
2678 <     */
2679 <    public ConcurrentHashMapV8() {
2680 <    }
2681 <
2682 <    /**
2683 <     * Creates a new, empty map with an initial table size
2684 <     * accommodating the specified number of elements without the need
2685 <     * to dynamically resize.
2686 <     *
2687 <     * @param initialCapacity The implementation performs internal
2688 <     * sizing to accommodate this many elements.
2689 <     * @throws IllegalArgumentException if the initial capacity of
2690 <     * elements is negative
2691 <     */
2692 <    public ConcurrentHashMapV8(int initialCapacity) {
2693 <        if (initialCapacity < 0)
2694 <            throw new IllegalArgumentException();
2695 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2696 <                   MAXIMUM_CAPACITY :
2697 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2698 <        this.sizeCtl = cap;
2699 <    }
2700 <
2701 <    /**
2702 <     * Creates a new map with the same mappings as the given map.
2703 <     *
2704 <     * @param m the map
2705 <     */
2430 <    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2431 <        this.sizeCtl = DEFAULT_CAPACITY;
2432 <        internalPutAll(m);
2433 <    }
2434 <
2435 <    /**
2436 <     * Creates a new, empty map with an initial table size based on
2437 <     * the given number of elements ({@code initialCapacity}) and
2438 <     * initial table density ({@code loadFactor}).
2439 <     *
2440 <     * @param initialCapacity the initial capacity. The implementation
2441 <     * performs internal sizing to accommodate this many elements,
2442 <     * given the specified load factor.
2443 <     * @param loadFactor the load factor (table density) for
2444 <     * establishing the initial table size
2445 <     * @throws IllegalArgumentException if the initial capacity of
2446 <     * elements is negative or the load factor is nonpositive
2447 <     *
2448 <     * @since 1.6
2449 <     */
2450 <    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
2451 <        this(initialCapacity, loadFactor, 1);
2452 <    }
2453 <
2454 <    /**
2455 <     * Creates a new, empty map with an initial table size based on
2456 <     * the given number of elements ({@code initialCapacity}), table
2457 <     * density ({@code loadFactor}), and number of concurrently
2458 <     * updating threads ({@code concurrencyLevel}).
2459 <     *
2460 <     * @param initialCapacity the initial capacity. The implementation
2461 <     * performs internal sizing to accommodate this many elements,
2462 <     * given the specified load factor.
2463 <     * @param loadFactor the load factor (table density) for
2464 <     * establishing the initial table size
2465 <     * @param concurrencyLevel the estimated number of concurrently
2466 <     * updating threads. The implementation may use this value as
2467 <     * a sizing hint.
2468 <     * @throws IllegalArgumentException if the initial capacity is
2469 <     * negative or the load factor or concurrencyLevel are
2470 <     * nonpositive
2471 <     */
2472 <    public ConcurrentHashMapV8(int initialCapacity,
2473 <                               float loadFactor, int concurrencyLevel) {
2474 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2475 <            throw new IllegalArgumentException();
2476 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2477 <            initialCapacity = concurrencyLevel;   // as estimated threads
2478 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2479 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2480 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2481 <        this.sizeCtl = cap;
2482 <    }
2483 <
2484 <    /**
2485 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2486 <     * from the given type to {@code Boolean.TRUE}.
2487 <     *
2488 <     * @return the new set
2489 <     */
2490 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2491 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(),
2492 <                                      Boolean.TRUE);
2493 <    }
2494 <
2495 <    /**
2496 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2497 <     * from the given type to {@code Boolean.TRUE}.
2498 <     *
2499 <     * @param initialCapacity The implementation performs internal
2500 <     * sizing to accommodate this many elements.
2501 <     * @throws IllegalArgumentException if the initial capacity of
2502 <     * elements is negative
2503 <     * @return the new set
2504 <     */
2505 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2506 <        return new KeySetView<K,Boolean>
2507 <            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2508 <    }
2509 <
2510 <    /**
2511 <     * {@inheritDoc}
2512 <     */
2513 <    public boolean isEmpty() {
2514 <        return sumCount() <= 0L; // ignore transient negative values
2515 <    }
2516 <
2517 <    /**
2518 <     * {@inheritDoc}
2519 <     */
2520 <    public int size() {
2521 <        long n = sumCount();
2522 <        return ((n < 0L) ? 0 :
2523 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2524 <                (int)n);
2525 <    }
2526 <
2527 <    /**
2528 <     * Returns the number of mappings. This method should be used
2529 <     * instead of {@link #size} because a ConcurrentHashMapV8 may
2530 <     * contain more mappings than can be represented as an int. The
2531 <     * value returned is an estimate; the actual count may differ if
2532 <     * there are concurrent insertions or removals.
2533 <     *
2534 <     * @return the number of mappings
2535 <     */
2536 <    public long mappingCount() {
2537 <        long n = sumCount();
2538 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2539 <    }
2540 <
2541 <    /**
2542 <     * Returns the value to which the specified key is mapped,
2543 <     * or {@code null} if this map contains no mapping for the key.
2544 <     *
2545 <     * <p>More formally, if this map contains a mapping from a key
2546 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2547 <     * then this method returns {@code v}; otherwise it returns
2548 <     * {@code null}.  (There can be at most one such mapping.)
2549 <     *
2550 <     * @throws NullPointerException if the specified key is null
2551 <     */
2552 <    public V get(Object key) {
2553 <        return internalGet(key);
2554 <    }
2555 <
2556 <    /**
2557 <     * Returns the value to which the specified key is mapped,
2558 <     * or the given defaultValue if this map contains no mapping for the key.
2559 <     *
2560 <     * @param key the key
2561 <     * @param defaultValue the value to return if this map contains
2562 <     * no mapping for the given key
2563 <     * @return the mapping for the key, if present; else the defaultValue
2564 <     * @throws NullPointerException if the specified key is null
2565 <     */
2566 <    public V getValueOrDefault(Object key, V defaultValue) {
2567 <        V v;
2568 <        return (v = internalGet(key)) == null ? defaultValue : v;
2569 <    }
2570 <
2571 <    /**
2572 <     * Tests if the specified object is a key in this table.
2573 <     *
2574 <     * @param  key   possible key
2575 <     * @return {@code true} if and only if the specified object
2576 <     *         is a key in this table, as determined by the
2577 <     *         {@code equals} method; {@code false} otherwise
2578 <     * @throws NullPointerException if the specified key is null
2579 <     */
2580 <    public boolean containsKey(Object key) {
2581 <        return internalGet(key) != null;
2582 <    }
2583 <
2584 <    /**
2585 <     * Returns {@code true} if this map maps one or more keys to the
2586 <     * specified value. Note: This method may require a full traversal
2587 <     * of the map, and is much slower than method {@code containsKey}.
2588 <     *
2589 <     * @param value value whose presence in this map is to be tested
2590 <     * @return {@code true} if this map maps one or more keys to the
2591 <     *         specified value
2592 <     * @throws NullPointerException if the specified value is null
2593 <     */
2594 <    public boolean containsValue(Object value) {
2595 <        if (value == null)
2596 <            throw new NullPointerException();
2597 <        V v;
2598 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2599 <        while ((v = it.advance()) != null) {
2600 <            if (v == value || value.equals(v))
2601 <                return true;
2672 >        /**
2673 >         * Returns matching node or null if none. Tries to search
2674 >         * using tree comparisons from root, but continues linear
2675 >         * search when lock not available.
2676 >         */
2677 >        final Node<K,V> find(int h, Object k) {
2678 >            if (k != null) {
2679 >                for (Node<K,V> e = first; e != null; e = e.next) {
2680 >                    int s; K ek;
2681 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2682 >                        if (e.hash == h &&
2683 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2684 >                            return e;
2685 >                    }
2686 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2687 >                                                 s + READER)) {
2688 >                        TreeNode<K,V> r, p;
2689 >                        try {
2690 >                            p = ((r = root) == null ? null :
2691 >                                 r.findTreeNode(h, k, null));
2692 >                        } finally {
2693 >                            Thread w;
2694 >                            int ls;
2695 >                            do {} while (!U.compareAndSwapInt
2696 >                                         (this, LOCKSTATE,
2697 >                                          ls = lockState, ls - READER));
2698 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2699 >                                LockSupport.unpark(w);
2700 >                        }
2701 >                        return p;
2702 >                    }
2703 >                }
2704 >            }
2705 >            return null;
2706          }
2603        return false;
2604    }
2605
2606    /**
2607     * Legacy method testing if some key maps into the specified value
2608     * in this table.  This method is identical in functionality to
2609     * {@link #containsValue}, and exists solely to ensure
2610     * full compatibility with class {@link java.util.Hashtable},
2611     * which supported this method prior to introduction of the
2612     * Java Collections framework.
2613     *
2614     * @param  value a value to search for
2615     * @return {@code true} if and only if some key maps to the
2616     *         {@code value} argument in this table as
2617     *         determined by the {@code equals} method;
2618     *         {@code false} otherwise
2619     * @throws NullPointerException if the specified value is null
2620     */
2621    @Deprecated public boolean contains(Object value) {
2622        return containsValue(value);
2623    }
2624
2625    /**
2626     * Maps the specified key to the specified value in this table.
2627     * Neither the key nor the value can be null.
2628     *
2629     * <p>The value can be retrieved by calling the {@code get} method
2630     * with a key that is equal to the original key.
2631     *
2632     * @param key key with which the specified value is to be associated
2633     * @param value value to be associated with the specified key
2634     * @return the previous value associated with {@code key}, or
2635     *         {@code null} if there was no mapping for {@code key}
2636     * @throws NullPointerException if the specified key or value is null
2637     */
2638    public V put(K key, V value) {
2639        return internalPut(key, value, false);
2640    }
2707  
2708 <    /**
2709 <     * {@inheritDoc}
2710 <     *
2711 <     * @return the previous value associated with the specified key,
2712 <     *         or {@code null} if there was no mapping for the key
2713 <     * @throws NullPointerException if the specified key or value is null
2714 <     */
2715 <    public V putIfAbsent(K key, V value) {
2716 <        return internalPut(key, value, true);
2717 <    }
2718 <
2719 <    /**
2720 <     * Copies all of the mappings from the specified map to this one.
2721 <     * These mappings replace any mappings that this map had for any of the
2722 <     * keys currently in the specified map.
2723 <     *
2724 <     * @param m mappings to be stored in this map
2725 <     */
2726 <    public void putAll(Map<? extends K, ? extends V> m) {
2727 <        internalPutAll(m);
2728 <    }
2729 <
2730 <    /**
2731 <     * If the specified key is not already associated with a value,
2732 <     * computes its value using the given mappingFunction and enters
2733 <     * it into the map unless null.  This is equivalent to
2734 <     * <pre> {@code
2735 <     * if (map.containsKey(key))
2736 <     *   return map.get(key);
2737 <     * value = mappingFunction.apply(key);
2738 <     * if (value != null)
2739 <     *   map.put(key, value);
2740 <     * return value;}</pre>
2741 <     *
2742 <     * except that the action is performed atomically.  If the
2743 <     * function returns {@code null} no mapping is recorded. If the
2744 <     * function itself throws an (unchecked) exception, the exception
2745 <     * is rethrown to its caller, and no mapping is recorded.  Some
2746 <     * attempted update operations on this map by other threads may be
2747 <     * blocked while computation is in progress, so the computation
2748 <     * should be short and simple, and must not attempt to update any
2749 <     * other mappings of this Map. The most appropriate usage is to
2750 <     * construct a new object serving as an initial mapped value, or
2751 <     * memoized result, as in:
2752 <     *
2753 <     *  <pre> {@code
2754 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2755 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2756 <     *
2757 <     * @param key key with which the specified value is to be associated
2758 <     * @param mappingFunction the function to compute a value
2759 <     * @return the current (existing or computed) value associated with
2760 <     *         the specified key, or null if the computed value is null
2761 <     * @throws NullPointerException if the specified key or mappingFunction
2762 <     *         is null
2697 <     * @throws IllegalStateException if the computation detectably
2698 <     *         attempts a recursive update to this map that would
2699 <     *         otherwise never complete
2700 <     * @throws RuntimeException or Error if the mappingFunction does so,
2701 <     *         in which case the mapping is left unestablished
2702 <     */
2703 <    public V computeIfAbsent
2704 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2705 <        return internalComputeIfAbsent(key, mappingFunction);
2706 <    }
2707 <
2708 <    /**
2709 <     * If the given key is present, computes a new mapping value given a key and
2710 <     * its current mapped value. This is equivalent to
2711 <     *  <pre> {@code
2712 <     *   if (map.containsKey(key)) {
2713 <     *     value = remappingFunction.apply(key, map.get(key));
2714 <     *     if (value != null)
2715 <     *       map.put(key, value);
2716 <     *     else
2717 <     *       map.remove(key);
2718 <     *   }
2719 <     * }</pre>
2720 <     *
2721 <     * except that the action is performed atomically.  If the
2722 <     * function returns {@code null}, the mapping is removed.  If the
2723 <     * function itself throws an (unchecked) exception, the exception
2724 <     * is rethrown to its caller, and the current mapping is left
2725 <     * unchanged.  Some attempted update operations on this map by
2726 <     * other threads may be blocked while computation is in progress,
2727 <     * so the computation should be short and simple, and must not
2728 <     * attempt to update any other mappings of this Map. For example,
2729 <     * to either create or append new messages to a value mapping:
2730 <     *
2731 <     * @param key key with which the specified value is to be associated
2732 <     * @param remappingFunction the function to compute a value
2733 <     * @return the new value associated with the specified key, or null if none
2734 <     * @throws NullPointerException if the specified key or remappingFunction
2735 <     *         is null
2736 <     * @throws IllegalStateException if the computation detectably
2737 <     *         attempts a recursive update to this map that would
2738 <     *         otherwise never complete
2739 <     * @throws RuntimeException or Error if the remappingFunction does so,
2740 <     *         in which case the mapping is unchanged
2741 <     */
2742 <    public V computeIfPresent
2743 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2744 <        return internalCompute(key, true, remappingFunction);
2745 <    }
2746 <
2747 <    /**
2748 <     * Computes a new mapping value given a key and
2749 <     * its current mapped value (or {@code null} if there is no current
2750 <     * mapping). This is equivalent to
2751 <     *  <pre> {@code
2752 <     *   value = remappingFunction.apply(key, map.get(key));
2753 <     *   if (value != null)
2754 <     *     map.put(key, value);
2755 <     *   else
2756 <     *     map.remove(key);
2757 <     * }</pre>
2758 <     *
2759 <     * except that the action is performed atomically.  If the
2760 <     * function returns {@code null}, the mapping is removed.  If the
2761 <     * function itself throws an (unchecked) exception, the exception
2762 <     * is rethrown to its caller, and the current mapping is left
2763 <     * unchanged.  Some attempted update operations on this map by
2764 <     * other threads may be blocked while computation is in progress,
2765 <     * so the computation should be short and simple, and must not
2766 <     * attempt to update any other mappings of this Map. For example,
2767 <     * to either create or append new messages to a value mapping:
2768 <     *
2769 <     * <pre> {@code
2770 <     * Map<Key, String> map = ...;
2771 <     * final String msg = ...;
2772 <     * map.compute(key, new BiFun<Key, String, String>() {
2773 <     *   public String apply(Key k, String v) {
2774 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2775 <     *
2776 <     * @param key key with which the specified value is to be associated
2777 <     * @param remappingFunction the function to compute a value
2778 <     * @return the new value associated with the specified key, or null if none
2779 <     * @throws NullPointerException if the specified key or remappingFunction
2780 <     *         is null
2781 <     * @throws IllegalStateException if the computation detectably
2782 <     *         attempts a recursive update to this map that would
2783 <     *         otherwise never complete
2784 <     * @throws RuntimeException or Error if the remappingFunction does so,
2785 <     *         in which case the mapping is unchanged
2786 <     */
2787 <    public V compute
2788 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2789 <        return internalCompute(key, false, remappingFunction);
2790 <    }
2791 <
2792 <    /**
2793 <     * If the specified key is not already associated
2794 <     * with a value, associate it with the given value.
2795 <     * Otherwise, replace the value with the results of
2796 <     * the given remapping function. This is equivalent to:
2797 <     *  <pre> {@code
2798 <     *   if (!map.containsKey(key))
2799 <     *     map.put(value);
2800 <     *   else {
2801 <     *     newValue = remappingFunction.apply(map.get(key), value);
2802 <     *     if (value != null)
2803 <     *       map.put(key, value);
2804 <     *     else
2805 <     *       map.remove(key);
2806 <     *   }
2807 <     * }</pre>
2808 <     * except that the action is performed atomically.  If the
2809 <     * function returns {@code null}, the mapping is removed.  If the
2810 <     * function itself throws an (unchecked) exception, the exception
2811 <     * is rethrown to its caller, and the current mapping is left
2812 <     * unchanged.  Some attempted update operations on this map by
2813 <     * other threads may be blocked while computation is in progress,
2814 <     * so the computation should be short and simple, and must not
2815 <     * attempt to update any other mappings of this Map.
2816 <     */
2817 <    public V merge
2818 <        (K key, V value,
2819 <         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2820 <        return internalMerge(key, value, remappingFunction);
2821 <    }
2822 <
2823 <    /**
2824 <     * Removes the key (and its corresponding value) from this map.
2825 <     * This method does nothing if the key is not in the map.
2826 <     *
2827 <     * @param  key the key that needs to be removed
2828 <     * @return the previous value associated with {@code key}, or
2829 <     *         {@code null} if there was no mapping for {@code key}
2830 <     * @throws NullPointerException if the specified key is null
2831 <     */
2832 <    public V remove(Object key) {
2833 <        return internalReplace(key, null, null);
2834 <    }
2835 <
2836 <    /**
2837 <     * {@inheritDoc}
2838 <     *
2839 <     * @throws NullPointerException if the specified key is null
2840 <     */
2841 <    public boolean remove(Object key, Object value) {
2842 <        return value != null && internalReplace(key, null, value) != null;
2843 <    }
2708 >        /**
2709 >         * Finds or adds a node.
2710 >         * @return null if added
2711 >         */
2712 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2713 >            Class<?> kc = null;
2714 >            for (TreeNode<K,V> p = root;;) {
2715 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2716 >                if (p == null) {
2717 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2718 >                    break;
2719 >                }
2720 >                else if ((ph = p.hash) > h)
2721 >                    dir = -1;
2722 >                else if (ph < h)
2723 >                    dir = 1;
2724 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2725 >                    return p;
2726 >                else if ((kc == null &&
2727 >                          (kc = comparableClassFor(k)) == null) ||
2728 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2729 >                    if (p.left == null)
2730 >                        dir = 1;
2731 >                    else if ((pr = p.right) == null ||
2732 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2733 >                        dir = -1;
2734 >                    else
2735 >                        return q;
2736 >                }
2737 >                TreeNode<K,V> xp = p;
2738 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2739 >                    TreeNode<K,V> x, f = first;
2740 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2741 >                    if (f != null)
2742 >                        f.prev = x;
2743 >                    if (dir < 0)
2744 >                        xp.left = x;
2745 >                    else
2746 >                        xp.right = x;
2747 >                    if (!xp.red)
2748 >                        x.red = true;
2749 >                    else {
2750 >                        lockRoot();
2751 >                        try {
2752 >                            root = balanceInsertion(root, x);
2753 >                        } finally {
2754 >                            unlockRoot();
2755 >                        }
2756 >                    }
2757 >                    break;
2758 >                }
2759 >            }
2760 >            assert checkInvariants(root);
2761 >            return null;
2762 >        }
2763  
2764 <    /**
2765 <     * {@inheritDoc}
2766 <     *
2767 <     * @throws NullPointerException if any of the arguments are null
2768 <     */
2769 <    public boolean replace(K key, V oldValue, V newValue) {
2770 <        if (key == null || oldValue == null || newValue == null)
2771 <            throw new NullPointerException();
2772 <        return internalReplace(key, newValue, oldValue) != null;
2773 <    }
2764 >        /**
2765 >         * Removes the given node, that must be present before this
2766 >         * call.  This is messier than typical red-black deletion code
2767 >         * because we cannot swap the contents of an interior node
2768 >         * with a leaf successor that is pinned by "next" pointers
2769 >         * that are accessible independently of lock. So instead we
2770 >         * swap the tree linkages.
2771 >         *
2772 >         * @return true if now too small, so should be untreeified
2773 >         */
2774 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2775 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2776 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2777 >            TreeNode<K,V> r, rl;
2778 >            if (pred == null)
2779 >                first = next;
2780 >            else
2781 >                pred.next = next;
2782 >            if (next != null)
2783 >                next.prev = pred;
2784 >            if (first == null) {
2785 >                root = null;
2786 >                return true;
2787 >            }
2788 >            if ((r = root) == null || r.right == null || // too small
2789 >                (rl = r.left) == null || rl.left == null)
2790 >                return true;
2791 >            lockRoot();
2792 >            try {
2793 >                TreeNode<K,V> replacement;
2794 >                TreeNode<K,V> pl = p.left;
2795 >                TreeNode<K,V> pr = p.right;
2796 >                if (pl != null && pr != null) {
2797 >                    TreeNode<K,V> s = pr, sl;
2798 >                    while ((sl = s.left) != null) // find successor
2799 >                        s = sl;
2800 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2801 >                    TreeNode<K,V> sr = s.right;
2802 >                    TreeNode<K,V> pp = p.parent;
2803 >                    if (s == pr) { // p was s's direct parent
2804 >                        p.parent = s;
2805 >                        s.right = p;
2806 >                    }
2807 >                    else {
2808 >                        TreeNode<K,V> sp = s.parent;
2809 >                        if ((p.parent = sp) != null) {
2810 >                            if (s == sp.left)
2811 >                                sp.left = p;
2812 >                            else
2813 >                                sp.right = p;
2814 >                        }
2815 >                        if ((s.right = pr) != null)
2816 >                            pr.parent = s;
2817 >                    }
2818 >                    p.left = null;
2819 >                    if ((p.right = sr) != null)
2820 >                        sr.parent = p;
2821 >                    if ((s.left = pl) != null)
2822 >                        pl.parent = s;
2823 >                    if ((s.parent = pp) == null)
2824 >                        r = s;
2825 >                    else if (p == pp.left)
2826 >                        pp.left = s;
2827 >                    else
2828 >                        pp.right = s;
2829 >                    if (sr != null)
2830 >                        replacement = sr;
2831 >                    else
2832 >                        replacement = p;
2833 >                }
2834 >                else if (pl != null)
2835 >                    replacement = pl;
2836 >                else if (pr != null)
2837 >                    replacement = pr;
2838 >                else
2839 >                    replacement = p;
2840 >                if (replacement != p) {
2841 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2842 >                    if (pp == null)
2843 >                        r = replacement;
2844 >                    else if (p == pp.left)
2845 >                        pp.left = replacement;
2846 >                    else
2847 >                        pp.right = replacement;
2848 >                    p.left = p.right = p.parent = null;
2849 >                }
2850  
2851 <    /**
2857 <     * {@inheritDoc}
2858 <     *
2859 <     * @return the previous value associated with the specified key,
2860 <     *         or {@code null} if there was no mapping for the key
2861 <     * @throws NullPointerException if the specified key or value is null
2862 <     */
2863 <    public V replace(K key, V value) {
2864 <        if (key == null || value == null)
2865 <            throw new NullPointerException();
2866 <        return internalReplace(key, value, null);
2867 <    }
2851 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2852  
2853 <    /**
2854 <     * Removes all of the mappings from this map.
2855 <     */
2856 <    public void clear() {
2857 <        internalClear();
2858 <    }
2853 >                if (p == replacement) {  // detach pointers
2854 >                    TreeNode<K,V> pp;
2855 >                    if ((pp = p.parent) != null) {
2856 >                        if (p == pp.left)
2857 >                            pp.left = null;
2858 >                        else if (p == pp.right)
2859 >                            pp.right = null;
2860 >                        p.parent = null;
2861 >                    }
2862 >                }
2863 >            } finally {
2864 >                unlockRoot();
2865 >            }
2866 >            assert checkInvariants(root);
2867 >            return false;
2868 >        }
2869  
2870 <    /**
2871 <     * Returns a {@link Set} view of the keys contained in this map.
2878 <     * The set is backed by the map, so changes to the map are
2879 <     * reflected in the set, and vice-versa.
2880 <     *
2881 <     * @return the set view
2882 <     */
2883 <    public KeySetView<K,V> keySet() {
2884 <        KeySetView<K,V> ks = keySet;
2885 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2886 <    }
2870 >        /* ------------------------------------------------------------ */
2871 >        // Red-black tree methods, all adapted from CLR
2872  
2873 <    /**
2874 <     * Returns a {@link Set} view of the keys in this map, using the
2875 <     * given common mapped value for any additions (i.e., {@link
2876 <     * Collection#add} and {@link Collection#addAll}). This is of
2877 <     * course only appropriate if it is acceptable to use the same
2878 <     * value for all additions from this view.
2879 <     *
2880 <     * @param mappedValue the mapped value to use for any
2881 <     * additions.
2882 <     * @return the set view
2883 <     * @throws NullPointerException if the mappedValue is null
2884 <     */
2885 <    public KeySetView<K,V> keySet(V mappedValue) {
2886 <        if (mappedValue == null)
2887 <            throw new NullPointerException();
2888 <        return new KeySetView<K,V>(this, mappedValue);
2889 <    }
2873 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2874 >                                              TreeNode<K,V> p) {
2875 >            TreeNode<K,V> r, pp, rl;
2876 >            if (p != null && (r = p.right) != null) {
2877 >                if ((rl = p.right = r.left) != null)
2878 >                    rl.parent = p;
2879 >                if ((pp = r.parent = p.parent) == null)
2880 >                    (root = r).red = false;
2881 >                else if (pp.left == p)
2882 >                    pp.left = r;
2883 >                else
2884 >                    pp.right = r;
2885 >                r.left = p;
2886 >                p.parent = r;
2887 >            }
2888 >            return root;
2889 >        }
2890  
2891 <    /**
2892 <     * Returns a {@link Collection} view of the values contained in this map.
2893 <     * The collection is backed by the map, so changes to the map are
2894 <     * reflected in the collection, and vice-versa.
2895 <     */
2896 <    public ValuesView<K,V> values() {
2897 <        ValuesView<K,V> vs = values;
2898 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2899 <    }
2891 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2892 >                                               TreeNode<K,V> p) {
2893 >            TreeNode<K,V> l, pp, lr;
2894 >            if (p != null && (l = p.left) != null) {
2895 >                if ((lr = p.left = l.right) != null)
2896 >                    lr.parent = p;
2897 >                if ((pp = l.parent = p.parent) == null)
2898 >                    (root = l).red = false;
2899 >                else if (pp.right == p)
2900 >                    pp.right = l;
2901 >                else
2902 >                    pp.left = l;
2903 >                l.right = p;
2904 >                p.parent = l;
2905 >            }
2906 >            return root;
2907 >        }
2908  
2909 <    /**
2910 <     * Returns a {@link Set} view of the mappings contained in this map.
2911 <     * The set is backed by the map, so changes to the map are
2912 <     * reflected in the set, and vice-versa.  The set supports element
2913 <     * removal, which removes the corresponding mapping from the map,
2914 <     * via the {@code Iterator.remove}, {@code Set.remove},
2915 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2916 <     * operations.  It does not support the {@code add} or
2917 <     * {@code addAll} operations.
2918 <     *
2919 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2920 <     * that will never throw {@link ConcurrentModificationException},
2921 <     * and guarantees to traverse elements as they existed upon
2922 <     * construction of the iterator, and may (but is not guaranteed to)
2923 <     * reflect any modifications subsequent to construction.
2924 <     */
2925 <    public Set<Map.Entry<K,V>> entrySet() {
2926 <        EntrySetView<K,V> es = entrySet;
2927 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2928 <    }
2909 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2910 >                                                    TreeNode<K,V> x) {
2911 >            x.red = true;
2912 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2913 >                if ((xp = x.parent) == null) {
2914 >                    x.red = false;
2915 >                    return x;
2916 >                }
2917 >                else if (!xp.red || (xpp = xp.parent) == null)
2918 >                    return root;
2919 >                if (xp == (xppl = xpp.left)) {
2920 >                    if ((xppr = xpp.right) != null && xppr.red) {
2921 >                        xppr.red = false;
2922 >                        xp.red = false;
2923 >                        xpp.red = true;
2924 >                        x = xpp;
2925 >                    }
2926 >                    else {
2927 >                        if (x == xp.right) {
2928 >                            root = rotateLeft(root, x = xp);
2929 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2930 >                        }
2931 >                        if (xp != null) {
2932 >                            xp.red = false;
2933 >                            if (xpp != null) {
2934 >                                xpp.red = true;
2935 >                                root = rotateRight(root, xpp);
2936 >                            }
2937 >                        }
2938 >                    }
2939 >                }
2940 >                else {
2941 >                    if (xppl != null && xppl.red) {
2942 >                        xppl.red = false;
2943 >                        xp.red = false;
2944 >                        xpp.red = true;
2945 >                        x = xpp;
2946 >                    }
2947 >                    else {
2948 >                        if (x == xp.left) {
2949 >                            root = rotateRight(root, x = xp);
2950 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2951 >                        }
2952 >                        if (xp != null) {
2953 >                            xp.red = false;
2954 >                            if (xpp != null) {
2955 >                                xpp.red = true;
2956 >                                root = rotateLeft(root, xpp);
2957 >                            }
2958 >                        }
2959 >                    }
2960 >                }
2961 >            }
2962 >        }
2963  
2964 <    /**
2965 <     * Returns an enumeration of the keys in this table.
2966 <     *
2967 <     * @return an enumeration of the keys in this table
2968 <     * @see #keySet()
2969 <     */
2970 <    public Enumeration<K> keys() {
2971 <        return new KeyIterator<K,V>(this);
2972 <    }
2964 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2965 >                                                   TreeNode<K,V> x) {
2966 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2967 >                if (x == null || x == root)
2968 >                    return root;
2969 >                else if ((xp = x.parent) == null) {
2970 >                    x.red = false;
2971 >                    return x;
2972 >                }
2973 >                else if (x.red) {
2974 >                    x.red = false;
2975 >                    return root;
2976 >                }
2977 >                else if ((xpl = xp.left) == x) {
2978 >                    if ((xpr = xp.right) != null && xpr.red) {
2979 >                        xpr.red = false;
2980 >                        xp.red = true;
2981 >                        root = rotateLeft(root, xp);
2982 >                        xpr = (xp = x.parent) == null ? null : xp.right;
2983 >                    }
2984 >                    if (xpr == null)
2985 >                        x = xp;
2986 >                    else {
2987 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2988 >                        if ((sr == null || !sr.red) &&
2989 >                            (sl == null || !sl.red)) {
2990 >                            xpr.red = true;
2991 >                            x = xp;
2992 >                        }
2993 >                        else {
2994 >                            if (sr == null || !sr.red) {
2995 >                                if (sl != null)
2996 >                                    sl.red = false;
2997 >                                xpr.red = true;
2998 >                                root = rotateRight(root, xpr);
2999 >                                xpr = (xp = x.parent) == null ?
3000 >                                    null : xp.right;
3001 >                            }
3002 >                            if (xpr != null) {
3003 >                                xpr.red = (xp == null) ? false : xp.red;
3004 >                                if ((sr = xpr.right) != null)
3005 >                                    sr.red = false;
3006 >                            }
3007 >                            if (xp != null) {
3008 >                                xp.red = false;
3009 >                                root = rotateLeft(root, xp);
3010 >                            }
3011 >                            x = root;
3012 >                        }
3013 >                    }
3014 >                }
3015 >                else { // symmetric
3016 >                    if (xpl != null && xpl.red) {
3017 >                        xpl.red = false;
3018 >                        xp.red = true;
3019 >                        root = rotateRight(root, xp);
3020 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3021 >                    }
3022 >                    if (xpl == null)
3023 >                        x = xp;
3024 >                    else {
3025 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3026 >                        if ((sl == null || !sl.red) &&
3027 >                            (sr == null || !sr.red)) {
3028 >                            xpl.red = true;
3029 >                            x = xp;
3030 >                        }
3031 >                        else {
3032 >                            if (sl == null || !sl.red) {
3033 >                                if (sr != null)
3034 >                                    sr.red = false;
3035 >                                xpl.red = true;
3036 >                                root = rotateLeft(root, xpl);
3037 >                                xpl = (xp = x.parent) == null ?
3038 >                                    null : xp.left;
3039 >                            }
3040 >                            if (xpl != null) {
3041 >                                xpl.red = (xp == null) ? false : xp.red;
3042 >                                if ((sl = xpl.left) != null)
3043 >                                    sl.red = false;
3044 >                            }
3045 >                            if (xp != null) {
3046 >                                xp.red = false;
3047 >                                root = rotateRight(root, xp);
3048 >                            }
3049 >                            x = root;
3050 >                        }
3051 >                    }
3052 >                }
3053 >            }
3054 >        }
3055  
3056 <    /**
3057 <     * Returns an enumeration of the values in this table.
3058 <     *
3059 <     * @return an enumeration of the values in this table
3060 <     * @see #values()
3061 <     */
3062 <    public Enumeration<V> elements() {
3063 <        return new ValueIterator<K,V>(this);
3064 <    }
3056 >        /**
3057 >         * Recursive invariant check
3058 >         */
3059 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3060 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3061 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3062 >            if (tb != null && tb.next != t)
3063 >                return false;
3064 >            if (tn != null && tn.prev != t)
3065 >                return false;
3066 >            if (tp != null && t != tp.left && t != tp.right)
3067 >                return false;
3068 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3069 >                return false;
3070 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3071 >                return false;
3072 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3073 >                return false;
3074 >            if (tl != null && !checkInvariants(tl))
3075 >                return false;
3076 >            if (tr != null && !checkInvariants(tr))
3077 >                return false;
3078 >            return true;
3079 >        }
3080  
3081 <    /**
3082 <     * Returns a partitionable iterator of the keys in this map.
3083 <     *
3084 <     * @return a partitionable iterator of the keys in this map
3085 <     */
3086 <    public Spliterator<K> keySpliterator() {
3087 <        return new KeyIterator<K,V>(this);
3081 >        private static final sun.misc.Unsafe U;
3082 >        private static final long LOCKSTATE;
3083 >        static {
3084 >            try {
3085 >                U = getUnsafe();
3086 >                Class<?> k = TreeBin.class;
3087 >                LOCKSTATE = U.objectFieldOffset
3088 >                    (k.getDeclaredField("lockState"));
3089 >            } catch (Exception e) {
3090 >                throw new Error(e);
3091 >            }
3092 >        }
3093      }
3094  
3095 <    /**
2967 <     * Returns a partitionable iterator of the values in this map.
2968 <     *
2969 <     * @return a partitionable iterator of the values in this map
2970 <     */
2971 <    public Spliterator<V> valueSpliterator() {
2972 <        return new ValueIterator<K,V>(this);
2973 <    }
3095 >    /* ----------------Table Traversal -------------- */
3096  
3097      /**
3098 <     * Returns a partitionable iterator of the entries in this map.
3098 >     * Encapsulates traversal for methods such as containsValue; also
3099 >     * serves as a base class for other iterators and spliterators.
3100       *
3101 <     * @return a partitionable iterator of the entries in this map
3102 <     */
3103 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3104 <        return new EntryIterator<K,V>(this);
3105 <    }
3106 <
3107 <    /**
3108 <     * Returns the hash code value for this {@link Map}, i.e.,
2986 <     * the sum of, for each key-value pair in the map,
2987 <     * {@code key.hashCode() ^ value.hashCode()}.
3101 >     * Method advance visits once each still-valid node that was
3102 >     * reachable upon iterator construction. It might miss some that
3103 >     * were added to a bin after the bin was visited, which is OK wrt
3104 >     * consistency guarantees. Maintaining this property in the face
3105 >     * of possible ongoing resizes requires a fair amount of
3106 >     * bookkeeping state that is difficult to optimize away amidst
3107 >     * volatile accesses.  Even so, traversal maintains reasonable
3108 >     * throughput.
3109       *
3110 <     * @return the hash code value for this map
3110 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3111 >     * However, if the table has been resized, then all future steps
3112 >     * must traverse both the bin at the current index as well as at
3113 >     * (index + baseSize); and so on for further resizings. To
3114 >     * paranoically cope with potential sharing by users of iterators
3115 >     * across threads, iteration terminates if a bounds checks fails
3116 >     * for a table read.
3117       */
3118 <    public int hashCode() {
3119 <        int h = 0;
3120 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3121 <        V v;
3122 <        while ((v = it.advance()) != null) {
3123 <            h += it.nextKey.hashCode() ^ v.hashCode();
3118 >    static class Traverser<K,V> {
3119 >        Node<K,V>[] tab;        // current table; updated if resized
3120 >        Node<K,V> next;         // the next entry to use
3121 >        int index;              // index of bin to use next
3122 >        int baseIndex;          // current index of initial table
3123 >        int baseLimit;          // index bound for initial table
3124 >        final int baseSize;     // initial table size
3125 >
3126 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3127 >            this.tab = tab;
3128 >            this.baseSize = size;
3129 >            this.baseIndex = this.index = index;
3130 >            this.baseLimit = limit;
3131 >            this.next = null;
3132          }
2998        return h;
2999    }
3133  
3134 <    /**
3135 <     * Returns a string representation of this map.  The string
3136 <     * representation consists of a list of key-value mappings (in no
3137 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3138 <     * mappings are separated by the characters {@code ", "} (comma
3139 <     * and space).  Each key-value mapping is rendered as the key
3140 <     * followed by an equals sign ("{@code =}") followed by the
3008 <     * associated value.
3009 <     *
3010 <     * @return a string representation of this map
3011 <     */
3012 <    public String toString() {
3013 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3014 <        StringBuilder sb = new StringBuilder();
3015 <        sb.append('{');
3016 <        V v;
3017 <        if ((v = it.advance()) != null) {
3134 >        /**
3135 >         * Advances if possible, returning next valid node, or null if none.
3136 >         */
3137 >        final Node<K,V> advance() {
3138 >            Node<K,V> e;
3139 >            if ((e = next) != null)
3140 >                e = e.next;
3141              for (;;) {
3142 <                Object k = it.nextKey;
3143 <                sb.append(k == this ? "(this Map)" : k);
3144 <                sb.append('=');
3145 <                sb.append(v == this ? "(this Map)" : v);
3146 <                if ((v = it.advance()) == null)
3147 <                    break;
3148 <                sb.append(',').append(' ');
3142 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3143 >                if (e != null)
3144 >                    return next = e;
3145 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3146 >                    (n = t.length) <= (i = index) || i < 0)
3147 >                    return next = null;
3148 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3149 >                    if (e instanceof ForwardingNode) {
3150 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3151 >                        e = null;
3152 >                        continue;
3153 >                    }
3154 >                    else if (e instanceof TreeBin)
3155 >                        e = ((TreeBin<K,V>)e).first;
3156 >                    else
3157 >                        e = null;
3158 >                }
3159 >                if ((index += baseSize) >= n)
3160 >                    index = ++baseIndex;    // visit upper slots if present
3161              }
3162          }
3028        return sb.append('}').toString();
3163      }
3164  
3165      /**
3166 <     * Compares the specified object with this map for equality.
3167 <     * Returns {@code true} if the given object is a map with the same
3034 <     * mappings as this map.  This operation may return misleading
3035 <     * results if either map is concurrently modified during execution
3036 <     * of this method.
3037 <     *
3038 <     * @param o object to be compared for equality with this map
3039 <     * @return {@code true} if the specified object is equal to this map
3166 >     * Base of key, value, and entry Iterators. Adds fields to
3167 >     * Traverser to support iterator.remove.
3168       */
3169 <    public boolean equals(Object o) {
3170 <        if (o != this) {
3171 <            if (!(o instanceof Map))
3172 <                return false;
3173 <            Map<?,?> m = (Map<?,?>) o;
3174 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3175 <            V val;
3176 <            while ((val = it.advance()) != null) {
3049 <                Object v = m.get(it.nextKey);
3050 <                if (v == null || (v != val && !v.equals(val)))
3051 <                    return false;
3052 <            }
3053 <            for (Map.Entry<?,?> e : m.entrySet()) {
3054 <                Object mk, mv, v;
3055 <                if ((mk = e.getKey()) == null ||
3056 <                    (mv = e.getValue()) == null ||
3057 <                    (v = internalGet(mk)) == null ||
3058 <                    (mv != v && !mv.equals(v)))
3059 <                    return false;
3060 <            }
3169 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3170 >        final ConcurrentHashMapV8<K,V> map;
3171 >        Node<K,V> lastReturned;
3172 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3173 >                    ConcurrentHashMapV8<K,V> map) {
3174 >            super(tab, size, index, limit);
3175 >            this.map = map;
3176 >            advance();
3177          }
3062        return true;
3063    }
3178  
3179 <    /* ----------------Iterators -------------- */
3179 >        public final boolean hasNext() { return next != null; }
3180 >        public final boolean hasMoreElements() { return next != null; }
3181  
3182 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3183 <        extends Traverser<K,V,Object>
3184 <        implements Spliterator<K>, Enumeration<K> {
3070 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3071 <        KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3072 <            super(map, it, -1);
3073 <        }
3074 <        public KeyIterator<K,V> split() {
3075 <            if (nextKey != null)
3182 >        public final void remove() {
3183 >            Node<K,V> p;
3184 >            if ((p = lastReturned) == null)
3185                  throw new IllegalStateException();
3186 <            return new KeyIterator<K,V>(map, this);
3186 >            lastReturned = null;
3187 >            map.replaceNode(p.key, null, null);
3188          }
3189 <        @SuppressWarnings("unchecked") public final K next() {
3190 <            if (nextVal == null && advance() == null)
3189 >    }
3190 >
3191 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3192 >        implements Iterator<K>, Enumeration<K> {
3193 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3194 >                    ConcurrentHashMapV8<K,V> map) {
3195 >            super(tab, index, size, limit, map);
3196 >        }
3197 >
3198 >        public final K next() {
3199 >            Node<K,V> p;
3200 >            if ((p = next) == null)
3201                  throw new NoSuchElementException();
3202 <            Object k = nextKey;
3203 <            nextVal = null;
3204 <            return (K) k;
3202 >            K k = p.key;
3203 >            lastReturned = p;
3204 >            advance();
3205 >            return k;
3206          }
3207  
3208          public final K nextElement() { return next(); }
3209      }
3210  
3211 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3212 <        extends Traverser<K,V,Object>
3213 <        implements Spliterator<V>, Enumeration<V> {
3214 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3215 <        ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3095 <            super(map, it, -1);
3096 <        }
3097 <        public ValueIterator<K,V> split() {
3098 <            if (nextKey != null)
3099 <                throw new IllegalStateException();
3100 <            return new ValueIterator<K,V>(map, this);
3211 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3212 >        implements Iterator<V>, Enumeration<V> {
3213 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3214 >                      ConcurrentHashMapV8<K,V> map) {
3215 >            super(tab, index, size, limit, map);
3216          }
3217  
3218          public final V next() {
3219 <            V v;
3220 <            if ((v = nextVal) == null && (v = advance()) == null)
3219 >            Node<K,V> p;
3220 >            if ((p = next) == null)
3221                  throw new NoSuchElementException();
3222 <            nextVal = null;
3222 >            V v = p.val;
3223 >            lastReturned = p;
3224 >            advance();
3225              return v;
3226          }
3227  
3228          public final V nextElement() { return next(); }
3229      }
3230  
3231 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3232 <        extends Traverser<K,V,Object>
3233 <        implements Spliterator<Map.Entry<K,V>> {
3234 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3235 <        EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3119 <            super(map, it, -1);
3120 <        }
3121 <        public EntryIterator<K,V> split() {
3122 <            if (nextKey != null)
3123 <                throw new IllegalStateException();
3124 <            return new EntryIterator<K,V>(map, this);
3231 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3232 >        implements Iterator<Map.Entry<K,V>> {
3233 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3234 >                      ConcurrentHashMapV8<K,V> map) {
3235 >            super(tab, index, size, limit, map);
3236          }
3237  
3238 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3239 <            V v;
3240 <            if ((v = nextVal) == null && (v = advance()) == null)
3238 >        public final Map.Entry<K,V> next() {
3239 >            Node<K,V> p;
3240 >            if ((p = next) == null)
3241                  throw new NoSuchElementException();
3242 <            Object k = nextKey;
3243 <            nextVal = null;
3244 <            return new MapEntry<K,V>((K)k, v, map);
3242 >            K k = p.key;
3243 >            V v = p.val;
3244 >            lastReturned = p;
3245 >            advance();
3246 >            return new MapEntry<K,V>(k, v, map);
3247          }
3248      }
3249  
3250      /**
3251 <     * Exported Entry for iterators
3251 >     * Exported Entry for EntryIterator
3252       */
3253 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3253 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3254          final K key; // non-null
3255          V val;       // non-null
3256 <        final ConcurrentHashMapV8<K, V> map;
3257 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3256 >        final ConcurrentHashMapV8<K,V> map;
3257 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3258              this.key = key;
3259              this.val = val;
3260              this.map = map;
3261          }
3262 <        public final K getKey()       { return key; }
3263 <        public final V getValue()     { return val; }
3264 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3265 <        public final String toString(){ return key + "=" + val; }
3262 >        public K getKey()        { return key; }
3263 >        public V getValue()      { return val; }
3264 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3265 >        public String toString() { return key + "=" + val; }
3266  
3267 <        public final boolean equals(Object o) {
3267 >        public boolean equals(Object o) {
3268              Object k, v; Map.Entry<?,?> e;
3269              return ((o instanceof Map.Entry) &&
3270                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3165 | Line 3278 | public class ConcurrentHashMapV8<K, V>
3278           * value to return is somewhat arbitrary here. Since we do not
3279           * necessarily track asynchronous changes, the most recent
3280           * "previous" value could be different from what we return (or
3281 <         * could even have been removed in which case the put will
3281 >         * could even have been removed, in which case the put will
3282           * re-establish). We do not and cannot guarantee more.
3283           */
3284 <        public final V setValue(V value) {
3284 >        public V setValue(V value) {
3285              if (value == null) throw new NullPointerException();
3286              V v = val;
3287              val = value;
# Line 3177 | Line 3290 | public class ConcurrentHashMapV8<K, V>
3290          }
3291      }
3292  
3293 <    /**
3294 <     * Returns exportable snapshot entry for the given key and value
3295 <     * when write-through can't or shouldn't be used.
3296 <     */
3297 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3298 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3299 <    }
3293 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3294 >        implements ConcurrentHashMapSpliterator<K> {
3295 >        long est;               // size estimate
3296 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3297 >                       long est) {
3298 >            super(tab, size, index, limit);
3299 >            this.est = est;
3300 >        }
3301 >
3302 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3303 >            int i, f, h;
3304 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3305 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3306 >                                        f, est >>>= 1);
3307 >        }
3308  
3309 <    /* ---------------- Serialization Support -------------- */
3309 >        public void forEachRemaining(Action<? super K> action) {
3310 >            if (action == null) throw new NullPointerException();
3311 >            for (Node<K,V> p; (p = advance()) != null;)
3312 >                action.apply(p.key);
3313 >        }
3314 >
3315 >        public boolean tryAdvance(Action<? super K> action) {
3316 >            if (action == null) throw new NullPointerException();
3317 >            Node<K,V> p;
3318 >            if ((p = advance()) == null)
3319 >                return false;
3320 >            action.apply(p.key);
3321 >            return true;
3322 >        }
3323 >
3324 >        public long estimateSize() { return est; }
3325  
3190    /**
3191     * Stripped-down version of helper class used in previous version,
3192     * declared for the sake of serialization compatibility
3193     */
3194    static class Segment<K,V> implements Serializable {
3195        private static final long serialVersionUID = 2249069246763182397L;
3196        final float loadFactor;
3197        Segment(float lf) { this.loadFactor = lf; }
3326      }
3327  
3328 <    /**
3329 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3330 <     * stream (i.e., serializes it).
3331 <     * @param s the stream
3332 <     * @serialData
3333 <     * the key (Object) and value (Object)
3334 <     * for each key-value mapping, followed by a null pair.
3207 <     * The key-value mappings are emitted in no particular order.
3208 <     */
3209 <    @SuppressWarnings("unchecked") private void writeObject
3210 <        (java.io.ObjectOutputStream s)
3211 <        throws java.io.IOException {
3212 <        if (segments == null) { // for serialization compatibility
3213 <            segments = (Segment<K,V>[])
3214 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3215 <            for (int i = 0; i < segments.length; ++i)
3216 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3328 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3329 >        implements ConcurrentHashMapSpliterator<V> {
3330 >        long est;               // size estimate
3331 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3332 >                         long est) {
3333 >            super(tab, size, index, limit);
3334 >            this.est = est;
3335          }
3336 <        s.defaultWriteObject();
3337 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3338 <        V v;
3339 <        while ((v = it.advance()) != null) {
3340 <            s.writeObject(it.nextKey);
3341 <            s.writeObject(v);
3336 >
3337 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3338 >            int i, f, h;
3339 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3340 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3341 >                                          f, est >>>= 1);
3342          }
3343 <        s.writeObject(null);
3344 <        s.writeObject(null);
3345 <        segments = null; // throw away
3343 >
3344 >        public void forEachRemaining(Action<? super V> action) {
3345 >            if (action == null) throw new NullPointerException();
3346 >            for (Node<K,V> p; (p = advance()) != null;)
3347 >                action.apply(p.val);
3348 >        }
3349 >
3350 >        public boolean tryAdvance(Action<? super V> action) {
3351 >            if (action == null) throw new NullPointerException();
3352 >            Node<K,V> p;
3353 >            if ((p = advance()) == null)
3354 >                return false;
3355 >            action.apply(p.val);
3356 >            return true;
3357 >        }
3358 >
3359 >        public long estimateSize() { return est; }
3360 >
3361      }
3362  
3363 <    /**
3364 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3365 <     * @param s the stream
3366 <     */
3367 <    @SuppressWarnings("unchecked") private void readObject
3368 <        (java.io.ObjectInputStream s)
3369 <        throws java.io.IOException, ClassNotFoundException {
3370 <        s.defaultReadObject();
3371 <        this.segments = null; // unneeded
3363 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3364 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3365 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3366 >        long est;               // size estimate
3367 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3368 >                         long est, ConcurrentHashMapV8<K,V> map) {
3369 >            super(tab, size, index, limit);
3370 >            this.map = map;
3371 >            this.est = est;
3372 >        }
3373  
3374 <        // Create all nodes, then place in table once size is known
3375 <        long size = 0L;
3376 <        Node<V> p = null;
3377 <        for (;;) {
3378 <            K k = (K) s.readObject();
3245 <            V v = (V) s.readObject();
3246 <            if (k != null && v != null) {
3247 <                int h = spread(k.hashCode());
3248 <                p = new Node<V>(h, k, v, p);
3249 <                ++size;
3250 <            }
3251 <            else
3252 <                break;
3374 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3375 >            int i, f, h;
3376 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3377 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3378 >                                          f, est >>>= 1, map);
3379          }
3380 <        if (p != null) {
3381 <            boolean init = false;
3382 <            int n;
3383 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3384 <                n = MAXIMUM_CAPACITY;
3259 <            else {
3260 <                int sz = (int)size;
3261 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3262 <            }
3263 <            int sc = sizeCtl;
3264 <            boolean collide = false;
3265 <            if (n > sc &&
3266 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3267 <                try {
3268 <                    if (table == null) {
3269 <                        init = true;
3270 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3271 <                        Node<V>[] tab = (Node<V>[])rt;
3272 <                        int mask = n - 1;
3273 <                        while (p != null) {
3274 <                            int j = p.hash & mask;
3275 <                            Node<V> next = p.next;
3276 <                            Node<V> q = p.next = tabAt(tab, j);
3277 <                            setTabAt(tab, j, p);
3278 <                            if (!collide && q != null && q.hash == p.hash)
3279 <                                collide = true;
3280 <                            p = next;
3281 <                        }
3282 <                        table = tab;
3283 <                        addCount(size, -1);
3284 <                        sc = n - (n >>> 2);
3285 <                    }
3286 <                } finally {
3287 <                    sizeCtl = sc;
3288 <                }
3289 <                if (collide) { // rescan and convert to TreeBins
3290 <                    Node<V>[] tab = table;
3291 <                    for (int i = 0; i < tab.length; ++i) {
3292 <                        int c = 0;
3293 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3294 <                            if (++c > TREE_THRESHOLD &&
3295 <                                (e.key instanceof Comparable)) {
3296 <                                replaceWithTreeBin(tab, i, e.key);
3297 <                                break;
3298 <                            }
3299 <                        }
3300 <                    }
3301 <                }
3302 <            }
3303 <            if (!init) { // Can only happen if unsafely published.
3304 <                while (p != null) {
3305 <                    internalPut((K)p.key, p.val, false);
3306 <                    p = p.next;
3307 <                }
3308 <            }
3380 >
3381 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3382 >            if (action == null) throw new NullPointerException();
3383 >            for (Node<K,V> p; (p = advance()) != null; )
3384 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3385          }
3310    }
3386  
3387 <    // -------------------------------------------------------
3387 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3388 >            if (action == null) throw new NullPointerException();
3389 >            Node<K,V> p;
3390 >            if ((p = advance()) == null)
3391 >                return false;
3392 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3393 >            return true;
3394 >        }
3395  
3396 <    // Sams
3315 <    /** Interface describing a void action of one argument */
3316 <    public interface Action<A> { void apply(A a); }
3317 <    /** Interface describing a void action of two arguments */
3318 <    public interface BiAction<A,B> { void apply(A a, B b); }
3319 <    /** Interface describing a function of one argument */
3320 <    public interface Fun<A,T> { T apply(A a); }
3321 <    /** Interface describing a function of two arguments */
3322 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3323 <    /** Interface describing a function of no arguments */
3324 <    public interface Generator<T> { T apply(); }
3325 <    /** Interface describing a function mapping its argument to a double */
3326 <    public interface ObjectToDouble<A> { double apply(A a); }
3327 <    /** Interface describing a function mapping its argument to a long */
3328 <    public interface ObjectToLong<A> { long apply(A a); }
3329 <    /** Interface describing a function mapping its argument to an int */
3330 <    public interface ObjectToInt<A> {int apply(A a); }
3331 <    /** Interface describing a function mapping two arguments to a double */
3332 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3333 <    /** Interface describing a function mapping two arguments to a long */
3334 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3335 <    /** Interface describing a function mapping two arguments to an int */
3336 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3337 <    /** Interface describing a function mapping a double to a double */
3338 <    public interface DoubleToDouble { double apply(double a); }
3339 <    /** Interface describing a function mapping a long to a long */
3340 <    public interface LongToLong { long apply(long a); }
3341 <    /** Interface describing a function mapping an int to an int */
3342 <    public interface IntToInt { int apply(int a); }
3343 <    /** Interface describing a function mapping two doubles to a double */
3344 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3345 <    /** Interface describing a function mapping two longs to a long */
3346 <    public interface LongByLongToLong { long apply(long a, long b); }
3347 <    /** Interface describing a function mapping two ints to an int */
3348 <    public interface IntByIntToInt { int apply(int a, int b); }
3396 >        public long estimateSize() { return est; }
3397  
3398 +    }
3399  
3400 <    // -------------------------------------------------------
3400 >    // Parallel bulk operations
3401  
3402 <    // Sequential bulk operations
3402 >    /**
3403 >     * Computes initial batch value for bulk tasks. The returned value
3404 >     * is approximately exp2 of the number of times (minus one) to
3405 >     * split task by two before executing leaf action. This value is
3406 >     * faster to compute and more convenient to use as a guide to
3407 >     * splitting than is the depth, since it is used while dividing by
3408 >     * two anyway.
3409 >     */
3410 >    final int batchFor(long b) {
3411 >        long n;
3412 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3413 >            return 0;
3414 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3415 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3416 >    }
3417  
3418      /**
3419       * Performs the given action for each (key, value).
3420       *
3421 +     * @param parallelismThreshold the (estimated) number of elements
3422 +     * needed for this operation to be executed in parallel
3423       * @param action the action
3424 +     * @since 1.8
3425       */
3426 <    @SuppressWarnings("unchecked") public void forEachSequentially
3427 <        (BiAction<K,V> action) {
3426 >    public void forEach(long parallelismThreshold,
3427 >                        BiAction<? super K,? super V> action) {
3428          if (action == null) throw new NullPointerException();
3429 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3430 <        V v;
3431 <        while ((v = it.advance()) != null)
3366 <            action.apply((K)it.nextKey, v);
3429 >        new ForEachMappingTask<K,V>
3430 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3431 >             action).invoke();
3432      }
3433  
3434      /**
3435       * Performs the given action for each non-null transformation
3436       * of each (key, value).
3437       *
3438 +     * @param parallelismThreshold the (estimated) number of elements
3439 +     * needed for this operation to be executed in parallel
3440       * @param transformer a function returning the transformation
3441 <     * for an element, or null of there is no transformation (in
3442 <     * which case the action is not applied).
3441 >     * for an element, or null if there is no transformation (in
3442 >     * which case the action is not applied)
3443       * @param action the action
3444 +     * @since 1.8
3445       */
3446 <    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3447 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3448 <         Action<U> action) {
3446 >    public <U> void forEach(long parallelismThreshold,
3447 >                            BiFun<? super K, ? super V, ? extends U> transformer,
3448 >                            Action<? super U> action) {
3449          if (transformer == null || action == null)
3450              throw new NullPointerException();
3451 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3452 <        V v; U u;
3453 <        while ((v = it.advance()) != null) {
3386 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3387 <                action.apply(u);
3388 <        }
3451 >        new ForEachTransformedMappingTask<K,V,U>
3452 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3453 >             transformer, action).invoke();
3454      }
3455  
3456      /**
3457       * Returns a non-null result from applying the given search
3458 <     * function on each (key, value), or null if none.
3458 >     * function on each (key, value), or null if none.  Upon
3459 >     * success, further element processing is suppressed and the
3460 >     * results of any other parallel invocations of the search
3461 >     * function are ignored.
3462       *
3463 +     * @param parallelismThreshold the (estimated) number of elements
3464 +     * needed for this operation to be executed in parallel
3465       * @param searchFunction a function returning a non-null
3466       * result on success, else null
3467       * @return a non-null result from applying the given search
3468       * function on each (key, value), or null if none
3469 +     * @since 1.8
3470       */
3471 <    @SuppressWarnings("unchecked") public <U> U searchSequentially
3472 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3471 >    public <U> U search(long parallelismThreshold,
3472 >                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3473          if (searchFunction == null) throw new NullPointerException();
3474 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3475 <        V v; U u;
3476 <        while ((v = it.advance()) != null) {
3406 <            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3407 <                return u;
3408 <        }
3409 <        return null;
3474 >        return new SearchMappingsTask<K,V,U>
3475 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3476 >             searchFunction, new AtomicReference<U>()).invoke();
3477      }
3478  
3479      /**
# Line 3414 | Line 3481 | public class ConcurrentHashMapV8<K, V>
3481       * of all (key, value) pairs using the given reducer to
3482       * combine values, or null if none.
3483       *
3484 +     * @param parallelismThreshold the (estimated) number of elements
3485 +     * needed for this operation to be executed in parallel
3486       * @param transformer a function returning the transformation
3487 <     * for an element, or null of there is no transformation (in
3488 <     * which case it is not combined).
3487 >     * for an element, or null if there is no transformation (in
3488 >     * which case it is not combined)
3489       * @param reducer a commutative associative combining function
3490       * @return the result of accumulating the given transformation
3491       * of all (key, value) pairs
3492 +     * @since 1.8
3493       */
3494 <    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3495 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3496 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3494 >    public <U> U reduce(long parallelismThreshold,
3495 >                        BiFun<? super K, ? super V, ? extends U> transformer,
3496 >                        BiFun<? super U, ? super U, ? extends U> reducer) {
3497          if (transformer == null || reducer == null)
3498              throw new NullPointerException();
3499 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3500 <        U r = null, u; V v;
3501 <        while ((v = it.advance()) != null) {
3432 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3433 <                r = (r == null) ? u : reducer.apply(r, u);
3434 <        }
3435 <        return r;
3499 >        return new MapReduceMappingsTask<K,V,U>
3500 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3501 >             null, transformer, reducer).invoke();
3502      }
3503  
3504      /**
# Line 3440 | Line 3506 | public class ConcurrentHashMapV8<K, V>
3506       * of all (key, value) pairs using the given reducer to
3507       * combine values, and the given basis as an identity value.
3508       *
3509 +     * @param parallelismThreshold the (estimated) number of elements
3510 +     * needed for this operation to be executed in parallel
3511       * @param transformer a function returning the transformation
3512       * for an element
3513       * @param basis the identity (initial default value) for the reduction
3514       * @param reducer a commutative associative combining function
3515       * @return the result of accumulating the given transformation
3516       * of all (key, value) pairs
3517 +     * @since 1.8
3518       */
3519 <    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3520 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3521 <         double basis,
3522 <         DoubleByDoubleToDouble reducer) {
3519 >    public double reduceToDouble(long parallelismThreshold,
3520 >                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3521 >                                 double basis,
3522 >                                 DoubleByDoubleToDouble reducer) {
3523          if (transformer == null || reducer == null)
3524              throw new NullPointerException();
3525 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3526 <        double r = basis; V v;
3527 <        while ((v = it.advance()) != null)
3459 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3460 <        return r;
3525 >        return new MapReduceMappingsToDoubleTask<K,V>
3526 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3527 >             null, transformer, basis, reducer).invoke();
3528      }
3529  
3530      /**
# Line 3465 | Line 3532 | public class ConcurrentHashMapV8<K, V>
3532       * of all (key, value) pairs using the given reducer to
3533       * combine values, and the given basis as an identity value.
3534       *
3535 +     * @param parallelismThreshold the (estimated) number of elements
3536 +     * needed for this operation to be executed in parallel
3537       * @param transformer a function returning the transformation
3538       * for an element
3539       * @param basis the identity (initial default value) for the reduction
3540       * @param reducer a commutative associative combining function
3541       * @return the result of accumulating the given transformation
3542       * of all (key, value) pairs
3543 +     * @since 1.8
3544       */
3545 <    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3546 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
3547 <         long basis,
3548 <         LongByLongToLong reducer) {
3545 >    public long reduceToLong(long parallelismThreshold,
3546 >                             ObjectByObjectToLong<? super K, ? super V> transformer,
3547 >                             long basis,
3548 >                             LongByLongToLong reducer) {
3549          if (transformer == null || reducer == null)
3550              throw new NullPointerException();
3551 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3552 <        long r = basis; V v;
3553 <        while ((v = it.advance()) != null)
3484 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3485 <        return r;
3551 >        return new MapReduceMappingsToLongTask<K,V>
3552 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3553 >             null, transformer, basis, reducer).invoke();
3554      }
3555  
3556      /**
# Line 3490 | Line 3558 | public class ConcurrentHashMapV8<K, V>
3558       * of all (key, value) pairs using the given reducer to
3559       * combine values, and the given basis as an identity value.
3560       *
3561 +     * @param parallelismThreshold the (estimated) number of elements
3562 +     * needed for this operation to be executed in parallel
3563       * @param transformer a function returning the transformation
3564       * for an element
3565       * @param basis the identity (initial default value) for the reduction
3566       * @param reducer a commutative associative combining function
3567       * @return the result of accumulating the given transformation
3568       * of all (key, value) pairs
3569 +     * @since 1.8
3570       */
3571 <    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3572 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
3573 <         int basis,
3574 <         IntByIntToInt reducer) {
3571 >    public int reduceToInt(long parallelismThreshold,
3572 >                           ObjectByObjectToInt<? super K, ? super V> transformer,
3573 >                           int basis,
3574 >                           IntByIntToInt reducer) {
3575          if (transformer == null || reducer == null)
3576              throw new NullPointerException();
3577 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3578 <        int r = basis; V v;
3579 <        while ((v = it.advance()) != null)
3509 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3510 <        return r;
3577 >        return new MapReduceMappingsToIntTask<K,V>
3578 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3579 >             null, transformer, basis, reducer).invoke();
3580      }
3581  
3582      /**
3583       * Performs the given action for each key.
3584       *
3585 +     * @param parallelismThreshold the (estimated) number of elements
3586 +     * needed for this operation to be executed in parallel
3587       * @param action the action
3588 +     * @since 1.8
3589       */
3590 <    @SuppressWarnings("unchecked") public void forEachKeySequentially
3591 <        (Action<K> action) {
3590 >    public void forEachKey(long parallelismThreshold,
3591 >                           Action<? super K> action) {
3592          if (action == null) throw new NullPointerException();
3593 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3594 <        while (it.advance() != null)
3595 <            action.apply((K)it.nextKey);
3593 >        new ForEachKeyTask<K,V>
3594 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3595 >             action).invoke();
3596      }
3597  
3598      /**
3599       * Performs the given action for each non-null transformation
3600       * of each key.
3601       *
3602 +     * @param parallelismThreshold the (estimated) number of elements
3603 +     * needed for this operation to be executed in parallel
3604       * @param transformer a function returning the transformation
3605 <     * for an element, or null of there is no transformation (in
3606 <     * which case the action is not applied).
3605 >     * for an element, or null if there is no transformation (in
3606 >     * which case the action is not applied)
3607       * @param action the action
3608 +     * @since 1.8
3609       */
3610 <    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3611 <        (Fun<? super K, ? extends U> transformer,
3612 <         Action<U> action) {
3610 >    public <U> void forEachKey(long parallelismThreshold,
3611 >                               Fun<? super K, ? extends U> transformer,
3612 >                               Action<? super U> action) {
3613          if (transformer == null || action == null)
3614              throw new NullPointerException();
3615 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3616 <        U u;
3617 <        while (it.advance() != null) {
3543 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3544 <                action.apply(u);
3545 <        }
3546 <        ForkJoinTasks.forEachKey
3547 <            (this, transformer, action).invoke();
3615 >        new ForEachTransformedKeyTask<K,V,U>
3616 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3617 >             transformer, action).invoke();
3618      }
3619  
3620      /**
3621       * Returns a non-null result from applying the given search
3622 <     * function on each key, or null if none.
3622 >     * function on each key, or null if none. Upon success,
3623 >     * further element processing is suppressed and the results of
3624 >     * any other parallel invocations of the search function are
3625 >     * ignored.
3626       *
3627 +     * @param parallelismThreshold the (estimated) number of elements
3628 +     * needed for this operation to be executed in parallel
3629       * @param searchFunction a function returning a non-null
3630       * result on success, else null
3631       * @return a non-null result from applying the given search
3632       * function on each key, or null if none
3633 +     * @since 1.8
3634       */
3635 <    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3636 <        (Fun<? super K, ? extends U> searchFunction) {
3637 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3638 <        U u;
3639 <        while (it.advance() != null) {
3640 <            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3565 <                return u;
3566 <        }
3567 <        return null;
3635 >    public <U> U searchKeys(long parallelismThreshold,
3636 >                            Fun<? super K, ? extends U> searchFunction) {
3637 >        if (searchFunction == null) throw new NullPointerException();
3638 >        return new SearchKeysTask<K,V,U>
3639 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3640 >             searchFunction, new AtomicReference<U>()).invoke();
3641      }
3642  
3643      /**
3644       * Returns the result of accumulating all keys using the given
3645       * reducer to combine values, or null if none.
3646       *
3647 +     * @param parallelismThreshold the (estimated) number of elements
3648 +     * needed for this operation to be executed in parallel
3649       * @param reducer a commutative associative combining function
3650       * @return the result of accumulating all keys using the given
3651       * reducer to combine values, or null if none
3652 +     * @since 1.8
3653       */
3654 <    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3655 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
3654 >    public K reduceKeys(long parallelismThreshold,
3655 >                        BiFun<? super K, ? super K, ? extends K> reducer) {
3656          if (reducer == null) throw new NullPointerException();
3657 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3658 <        K r = null;
3659 <        while (it.advance() != null) {
3584 <            K u = (K)it.nextKey;
3585 <            r = (r == null) ? u : reducer.apply(r, u);
3586 <        }
3587 <        return r;
3657 >        return new ReduceKeysTask<K,V>
3658 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3659 >             null, reducer).invoke();
3660      }
3661  
3662      /**
# Line 3592 | Line 3664 | public class ConcurrentHashMapV8<K, V>
3664       * of all keys using the given reducer to combine values, or
3665       * null if none.
3666       *
3667 +     * @param parallelismThreshold the (estimated) number of elements
3668 +     * needed for this operation to be executed in parallel
3669       * @param transformer a function returning the transformation
3670 <     * for an element, or null of there is no transformation (in
3671 <     * which case it is not combined).
3670 >     * for an element, or null if there is no transformation (in
3671 >     * which case it is not combined)
3672       * @param reducer a commutative associative combining function
3673       * @return the result of accumulating the given transformation
3674       * of all keys
3675 +     * @since 1.8
3676       */
3677 <    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3678 <        (Fun<? super K, ? extends U> transformer,
3677 >    public <U> U reduceKeys(long parallelismThreshold,
3678 >                            Fun<? super K, ? extends U> transformer,
3679           BiFun<? super U, ? super U, ? extends U> reducer) {
3680          if (transformer == null || reducer == null)
3681              throw new NullPointerException();
3682 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3683 <        U r = null, u;
3684 <        while (it.advance() != null) {
3610 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3611 <                r = (r == null) ? u : reducer.apply(r, u);
3612 <        }
3613 <        return r;
3682 >        return new MapReduceKeysTask<K,V,U>
3683 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3684 >             null, transformer, reducer).invoke();
3685      }
3686  
3687      /**
# Line 3618 | Line 3689 | public class ConcurrentHashMapV8<K, V>
3689       * of all keys using the given reducer to combine values, and
3690       * the given basis as an identity value.
3691       *
3692 +     * @param parallelismThreshold the (estimated) number of elements
3693 +     * needed for this operation to be executed in parallel
3694       * @param transformer a function returning the transformation
3695       * for an element
3696       * @param basis the identity (initial default value) for the reduction
3697       * @param reducer a commutative associative combining function
3698 <     * @return  the result of accumulating the given transformation
3698 >     * @return the result of accumulating the given transformation
3699       * of all keys
3700 +     * @since 1.8
3701       */
3702 <    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3703 <        (ObjectToDouble<? super K> transformer,
3704 <         double basis,
3705 <         DoubleByDoubleToDouble reducer) {
3702 >    public double reduceKeysToDouble(long parallelismThreshold,
3703 >                                     ObjectToDouble<? super K> transformer,
3704 >                                     double basis,
3705 >                                     DoubleByDoubleToDouble reducer) {
3706          if (transformer == null || reducer == null)
3707              throw new NullPointerException();
3708 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3709 <        double r = basis;
3710 <        while (it.advance() != null)
3637 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3638 <        return r;
3708 >        return new MapReduceKeysToDoubleTask<K,V>
3709 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3710 >             null, transformer, basis, reducer).invoke();
3711      }
3712  
3713      /**
# Line 3643 | Line 3715 | public class ConcurrentHashMapV8<K, V>
3715       * of all keys using the given reducer to combine values, and
3716       * the given basis as an identity value.
3717       *
3718 +     * @param parallelismThreshold the (estimated) number of elements
3719 +     * needed for this operation to be executed in parallel
3720       * @param transformer a function returning the transformation
3721       * for an element
3722       * @param basis the identity (initial default value) for the reduction
3723       * @param reducer a commutative associative combining function
3724       * @return the result of accumulating the given transformation
3725       * of all keys
3726 +     * @since 1.8
3727       */
3728 <    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3729 <        (ObjectToLong<? super K> transformer,
3730 <         long basis,
3731 <         LongByLongToLong reducer) {
3728 >    public long reduceKeysToLong(long parallelismThreshold,
3729 >                                 ObjectToLong<? super K> transformer,
3730 >                                 long basis,
3731 >                                 LongByLongToLong reducer) {
3732          if (transformer == null || reducer == null)
3733              throw new NullPointerException();
3734 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3735 <        long r = basis;
3736 <        while (it.advance() != null)
3662 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3663 <        return r;
3734 >        return new MapReduceKeysToLongTask<K,V>
3735 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3736 >             null, transformer, basis, reducer).invoke();
3737      }
3738  
3739      /**
# Line 3668 | Line 3741 | public class ConcurrentHashMapV8<K, V>
3741       * of all keys using the given reducer to combine values, and
3742       * the given basis as an identity value.
3743       *
3744 +     * @param parallelismThreshold the (estimated) number of elements
3745 +     * needed for this operation to be executed in parallel
3746       * @param transformer a function returning the transformation
3747       * for an element
3748       * @param basis the identity (initial default value) for the reduction
3749       * @param reducer a commutative associative combining function
3750       * @return the result of accumulating the given transformation
3751       * of all keys
3752 +     * @since 1.8
3753       */
3754 <    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3755 <        (ObjectToInt<? super K> transformer,
3756 <         int basis,
3757 <         IntByIntToInt reducer) {
3754 >    public int reduceKeysToInt(long parallelismThreshold,
3755 >                               ObjectToInt<? super K> transformer,
3756 >                               int basis,
3757 >                               IntByIntToInt reducer) {
3758          if (transformer == null || reducer == null)
3759              throw new NullPointerException();
3760 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3761 <        int r = basis;
3762 <        while (it.advance() != null)
3687 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3688 <        return r;
3760 >        return new MapReduceKeysToIntTask<K,V>
3761 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3762 >             null, transformer, basis, reducer).invoke();
3763      }
3764  
3765      /**
3766       * Performs the given action for each value.
3767       *
3768 +     * @param parallelismThreshold the (estimated) number of elements
3769 +     * needed for this operation to be executed in parallel
3770       * @param action the action
3771 +     * @since 1.8
3772       */
3773 <    public void forEachValueSequentially(Action<V> action) {
3774 <        if (action == null) throw new NullPointerException();
3775 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3776 <        V v;
3777 <        while ((v = it.advance()) != null)
3778 <            action.apply(v);
3773 >    public void forEachValue(long parallelismThreshold,
3774 >                             Action<? super V> action) {
3775 >        if (action == null)
3776 >            throw new NullPointerException();
3777 >        new ForEachValueTask<K,V>
3778 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3779 >             action).invoke();
3780      }
3781  
3782      /**
3783       * Performs the given action for each non-null transformation
3784       * of each value.
3785       *
3786 +     * @param parallelismThreshold the (estimated) number of elements
3787 +     * needed for this operation to be executed in parallel
3788       * @param transformer a function returning the transformation
3789 <     * for an element, or null of there is no transformation (in
3790 <     * which case the action is not applied).
3789 >     * for an element, or null if there is no transformation (in
3790 >     * which case the action is not applied)
3791 >     * @param action the action
3792 >     * @since 1.8
3793       */
3794 <    public <U> void forEachValueSequentially
3795 <        (Fun<? super V, ? extends U> transformer,
3796 <         Action<U> action) {
3794 >    public <U> void forEachValue(long parallelismThreshold,
3795 >                                 Fun<? super V, ? extends U> transformer,
3796 >                                 Action<? super U> action) {
3797          if (transformer == null || action == null)
3798              throw new NullPointerException();
3799 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3800 <        V v; U u;
3801 <        while ((v = it.advance()) != null) {
3720 <            if ((u = transformer.apply(v)) != null)
3721 <                action.apply(u);
3722 <        }
3799 >        new ForEachTransformedValueTask<K,V,U>
3800 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3801 >             transformer, action).invoke();
3802      }
3803  
3804      /**
3805       * Returns a non-null result from applying the given search
3806 <     * function on each value, or null if none.
3806 >     * function on each value, or null if none.  Upon success,
3807 >     * further element processing is suppressed and the results of
3808 >     * any other parallel invocations of the search function are
3809 >     * ignored.
3810       *
3811 +     * @param parallelismThreshold the (estimated) number of elements
3812 +     * needed for this operation to be executed in parallel
3813       * @param searchFunction a function returning a non-null
3814       * result on success, else null
3815       * @return a non-null result from applying the given search
3816       * function on each value, or null if none
3817 +     * @since 1.8
3818       */
3819 <    public <U> U searchValuesSequentially
3820 <        (Fun<? super V, ? extends U> searchFunction) {
3819 >    public <U> U searchValues(long parallelismThreshold,
3820 >                              Fun<? super V, ? extends U> searchFunction) {
3821          if (searchFunction == null) throw new NullPointerException();
3822 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3823 <        V v; U u;
3824 <        while ((v = it.advance()) != null) {
3740 <            if ((u = searchFunction.apply(v)) != null)
3741 <                return u;
3742 <        }
3743 <        return null;
3822 >        return new SearchValuesTask<K,V,U>
3823 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3824 >             searchFunction, new AtomicReference<U>()).invoke();
3825      }
3826  
3827      /**
3828       * Returns the result of accumulating all values using the
3829       * given reducer to combine values, or null if none.
3830       *
3831 +     * @param parallelismThreshold the (estimated) number of elements
3832 +     * needed for this operation to be executed in parallel
3833       * @param reducer a commutative associative combining function
3834 <     * @return  the result of accumulating all values
3834 >     * @return the result of accumulating all values
3835 >     * @since 1.8
3836       */
3837 <    public V reduceValuesSequentially
3838 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
3837 >    public V reduceValues(long parallelismThreshold,
3838 >                          BiFun<? super V, ? super V, ? extends V> reducer) {
3839          if (reducer == null) throw new NullPointerException();
3840 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3841 <        V r = null; V v;
3842 <        while ((v = it.advance()) != null)
3759 <            r = (r == null) ? v : reducer.apply(r, v);
3760 <        return r;
3840 >        return new ReduceValuesTask<K,V>
3841 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3842 >             null, reducer).invoke();
3843      }
3844  
3845      /**
# Line 3765 | Line 3847 | public class ConcurrentHashMapV8<K, V>
3847       * of all values using the given reducer to combine values, or
3848       * null if none.
3849       *
3850 +     * @param parallelismThreshold the (estimated) number of elements
3851 +     * needed for this operation to be executed in parallel
3852       * @param transformer a function returning the transformation
3853 <     * for an element, or null of there is no transformation (in
3854 <     * which case it is not combined).
3853 >     * for an element, or null if there is no transformation (in
3854 >     * which case it is not combined)
3855       * @param reducer a commutative associative combining function
3856       * @return the result of accumulating the given transformation
3857       * of all values
3858 +     * @since 1.8
3859       */
3860 <    public <U> U reduceValuesSequentially
3861 <        (Fun<? super V, ? extends U> transformer,
3862 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3860 >    public <U> U reduceValues(long parallelismThreshold,
3861 >                              Fun<? super V, ? extends U> transformer,
3862 >                              BiFun<? super U, ? super U, ? extends U> reducer) {
3863          if (transformer == null || reducer == null)
3864              throw new NullPointerException();
3865 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3866 <        U r = null, u; V v;
3867 <        while ((v = it.advance()) != null) {
3783 <            if ((u = transformer.apply(v)) != null)
3784 <                r = (r == null) ? u : reducer.apply(r, u);
3785 <        }
3786 <        return r;
3865 >        return new MapReduceValuesTask<K,V,U>
3866 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3867 >             null, transformer, reducer).invoke();
3868      }
3869  
3870      /**
# Line 3791 | Line 3872 | public class ConcurrentHashMapV8<K, V>
3872       * of all values using the given reducer to combine values,
3873       * and the given basis as an identity value.
3874       *
3875 +     * @param parallelismThreshold the (estimated) number of elements
3876 +     * needed for this operation to be executed in parallel
3877       * @param transformer a function returning the transformation
3878       * for an element
3879       * @param basis the identity (initial default value) for the reduction
3880       * @param reducer a commutative associative combining function
3881       * @return the result of accumulating the given transformation
3882       * of all values
3883 +     * @since 1.8
3884       */
3885 <    public double reduceValuesToDoubleSequentially
3886 <        (ObjectToDouble<? super V> transformer,
3887 <         double basis,
3888 <         DoubleByDoubleToDouble reducer) {
3885 >    public double reduceValuesToDouble(long parallelismThreshold,
3886 >                                       ObjectToDouble<? super V> transformer,
3887 >                                       double basis,
3888 >                                       DoubleByDoubleToDouble reducer) {
3889          if (transformer == null || reducer == null)
3890              throw new NullPointerException();
3891 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3892 <        double r = basis; V v;
3893 <        while ((v = it.advance()) != null)
3810 <            r = reducer.apply(r, transformer.apply(v));
3811 <        return r;
3891 >        return new MapReduceValuesToDoubleTask<K,V>
3892 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3893 >             null, transformer, basis, reducer).invoke();
3894      }
3895  
3896      /**
# Line 3816 | Line 3898 | public class ConcurrentHashMapV8<K, V>
3898       * of all values using the given reducer to combine values,
3899       * and the given basis as an identity value.
3900       *
3901 +     * @param parallelismThreshold the (estimated) number of elements
3902 +     * needed for this operation to be executed in parallel
3903       * @param transformer a function returning the transformation
3904       * for an element
3905       * @param basis the identity (initial default value) for the reduction
3906       * @param reducer a commutative associative combining function
3907       * @return the result of accumulating the given transformation
3908       * of all values
3909 +     * @since 1.8
3910       */
3911 <    public long reduceValuesToLongSequentially
3912 <        (ObjectToLong<? super V> transformer,
3913 <         long basis,
3914 <         LongByLongToLong reducer) {
3911 >    public long reduceValuesToLong(long parallelismThreshold,
3912 >                                   ObjectToLong<? super V> transformer,
3913 >                                   long basis,
3914 >                                   LongByLongToLong reducer) {
3915          if (transformer == null || reducer == null)
3916              throw new NullPointerException();
3917 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3918 <        long r = basis; V v;
3919 <        while ((v = it.advance()) != null)
3835 <            r = reducer.apply(r, transformer.apply(v));
3836 <        return r;
3917 >        return new MapReduceValuesToLongTask<K,V>
3918 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3919 >             null, transformer, basis, reducer).invoke();
3920      }
3921  
3922      /**
# Line 3841 | Line 3924 | public class ConcurrentHashMapV8<K, V>
3924       * of all values using the given reducer to combine values,
3925       * and the given basis as an identity value.
3926       *
3927 +     * @param parallelismThreshold the (estimated) number of elements
3928 +     * needed for this operation to be executed in parallel
3929       * @param transformer a function returning the transformation
3930       * for an element
3931       * @param basis the identity (initial default value) for the reduction
3932       * @param reducer a commutative associative combining function
3933       * @return the result of accumulating the given transformation
3934       * of all values
3935 +     * @since 1.8
3936       */
3937 <    public int reduceValuesToIntSequentially
3938 <        (ObjectToInt<? super V> transformer,
3939 <         int basis,
3940 <         IntByIntToInt reducer) {
3937 >    public int reduceValuesToInt(long parallelismThreshold,
3938 >                                 ObjectToInt<? super V> transformer,
3939 >                                 int basis,
3940 >                                 IntByIntToInt reducer) {
3941          if (transformer == null || reducer == null)
3942              throw new NullPointerException();
3943 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3944 <        int r = basis; V v;
3945 <        while ((v = it.advance()) != null)
3860 <            r = reducer.apply(r, transformer.apply(v));
3861 <        return r;
3943 >        return new MapReduceValuesToIntTask<K,V>
3944 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3945 >             null, transformer, basis, reducer).invoke();
3946      }
3947  
3948      /**
3949       * Performs the given action for each entry.
3950       *
3951 +     * @param parallelismThreshold the (estimated) number of elements
3952 +     * needed for this operation to be executed in parallel
3953       * @param action the action
3954 +     * @since 1.8
3955       */
3956 <    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3957 <        (Action<Map.Entry<K,V>> action) {
3956 >    public void forEachEntry(long parallelismThreshold,
3957 >                             Action<? super Map.Entry<K,V>> action) {
3958          if (action == null) throw new NullPointerException();
3959 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3960 <        V v;
3874 <        while ((v = it.advance()) != null)
3875 <            action.apply(entryFor((K)it.nextKey, v));
3959 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3960 >                                  action).invoke();
3961      }
3962  
3963      /**
3964       * Performs the given action for each non-null transformation
3965       * of each entry.
3966       *
3967 +     * @param parallelismThreshold the (estimated) number of elements
3968 +     * needed for this operation to be executed in parallel
3969       * @param transformer a function returning the transformation
3970 <     * for an element, or null of there is no transformation (in
3971 <     * which case the action is not applied).
3970 >     * for an element, or null if there is no transformation (in
3971 >     * which case the action is not applied)
3972       * @param action the action
3973 +     * @since 1.8
3974       */
3975 <    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3976 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3977 <         Action<U> action) {
3975 >    public <U> void forEachEntry(long parallelismThreshold,
3976 >                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
3977 >                                 Action<? super U> action) {
3978          if (transformer == null || action == null)
3979              throw new NullPointerException();
3980 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3981 <        V v; U u;
3982 <        while ((v = it.advance()) != null) {
3895 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3896 <                action.apply(u);
3897 <        }
3980 >        new ForEachTransformedEntryTask<K,V,U>
3981 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3982 >             transformer, action).invoke();
3983      }
3984  
3985      /**
3986       * Returns a non-null result from applying the given search
3987 <     * function on each entry, or null if none.
3987 >     * function on each entry, or null if none.  Upon success,
3988 >     * further element processing is suppressed and the results of
3989 >     * any other parallel invocations of the search function are
3990 >     * ignored.
3991       *
3992 +     * @param parallelismThreshold the (estimated) number of elements
3993 +     * needed for this operation to be executed in parallel
3994       * @param searchFunction a function returning a non-null
3995       * result on success, else null
3996       * @return a non-null result from applying the given search
3997       * function on each entry, or null if none
3998 +     * @since 1.8
3999       */
4000 <    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
4001 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4000 >    public <U> U searchEntries(long parallelismThreshold,
4001 >                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4002          if (searchFunction == null) throw new NullPointerException();
4003 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4004 <        V v; U u;
4005 <        while ((v = it.advance()) != null) {
3915 <            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3916 <                return u;
3917 <        }
3918 <        return null;
4003 >        return new SearchEntriesTask<K,V,U>
4004 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4005 >             searchFunction, new AtomicReference<U>()).invoke();
4006      }
4007  
4008      /**
4009       * Returns the result of accumulating all entries using the
4010       * given reducer to combine values, or null if none.
4011       *
4012 +     * @param parallelismThreshold the (estimated) number of elements
4013 +     * needed for this operation to be executed in parallel
4014       * @param reducer a commutative associative combining function
4015       * @return the result of accumulating all entries
4016 +     * @since 1.8
4017       */
4018 <    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
4019 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4018 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4019 >                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4020          if (reducer == null) throw new NullPointerException();
4021 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4022 <        Map.Entry<K,V> r = null; V v;
4023 <        while ((v = it.advance()) != null) {
3934 <            Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3935 <            r = (r == null) ? u : reducer.apply(r, u);
3936 <        }
3937 <        return r;
4021 >        return new ReduceEntriesTask<K,V>
4022 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4023 >             null, reducer).invoke();
4024      }
4025  
4026      /**
# Line 3942 | Line 4028 | public class ConcurrentHashMapV8<K, V>
4028       * of all entries using the given reducer to combine values,
4029       * or null if none.
4030       *
4031 +     * @param parallelismThreshold the (estimated) number of elements
4032 +     * needed for this operation to be executed in parallel
4033       * @param transformer a function returning the transformation
4034 <     * for an element, or null of there is no transformation (in
4035 <     * which case it is not combined).
4034 >     * for an element, or null if there is no transformation (in
4035 >     * which case it is not combined)
4036       * @param reducer a commutative associative combining function
4037       * @return the result of accumulating the given transformation
4038       * of all entries
4039 +     * @since 1.8
4040       */
4041 <    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
4042 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4043 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4041 >    public <U> U reduceEntries(long parallelismThreshold,
4042 >                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4043 >                               BiFun<? super U, ? super U, ? extends U> reducer) {
4044          if (transformer == null || reducer == null)
4045              throw new NullPointerException();
4046 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4047 <        U r = null, u; V v;
4048 <        while ((v = it.advance()) != null) {
3960 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3961 <                r = (r == null) ? u : reducer.apply(r, u);
3962 <        }
3963 <        return r;
4046 >        return new MapReduceEntriesTask<K,V,U>
4047 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4048 >             null, transformer, reducer).invoke();
4049      }
4050  
4051      /**
# Line 3968 | Line 4053 | public class ConcurrentHashMapV8<K, V>
4053       * of all entries using the given reducer to combine values,
4054       * and the given basis as an identity value.
4055       *
4056 +     * @param parallelismThreshold the (estimated) number of elements
4057 +     * needed for this operation to be executed in parallel
4058       * @param transformer a function returning the transformation
4059       * for an element
4060       * @param basis the identity (initial default value) for the reduction
4061       * @param reducer a commutative associative combining function
4062       * @return the result of accumulating the given transformation
4063       * of all entries
4064 +     * @since 1.8
4065       */
4066 <    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
4067 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4068 <         double basis,
4069 <         DoubleByDoubleToDouble reducer) {
4066 >    public double reduceEntriesToDouble(long parallelismThreshold,
4067 >                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4068 >                                        double basis,
4069 >                                        DoubleByDoubleToDouble reducer) {
4070          if (transformer == null || reducer == null)
4071              throw new NullPointerException();
4072 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4073 <        double r = basis; V v;
4074 <        while ((v = it.advance()) != null)
3987 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3988 <        return r;
4072 >        return new MapReduceEntriesToDoubleTask<K,V>
4073 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4074 >             null, transformer, basis, reducer).invoke();
4075      }
4076  
4077      /**
# Line 3993 | Line 4079 | public class ConcurrentHashMapV8<K, V>
4079       * of all entries using the given reducer to combine values,
4080       * and the given basis as an identity value.
4081       *
4082 +     * @param parallelismThreshold the (estimated) number of elements
4083 +     * needed for this operation to be executed in parallel
4084       * @param transformer a function returning the transformation
4085       * for an element
4086       * @param basis the identity (initial default value) for the reduction
4087       * @param reducer a commutative associative combining function
4088 <     * @return  the result of accumulating the given transformation
4088 >     * @return the result of accumulating the given transformation
4089       * of all entries
4090 +     * @since 1.8
4091       */
4092 <    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4093 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4094 <         long basis,
4095 <         LongByLongToLong reducer) {
4092 >    public long reduceEntriesToLong(long parallelismThreshold,
4093 >                                    ObjectToLong<Map.Entry<K,V>> transformer,
4094 >                                    long basis,
4095 >                                    LongByLongToLong reducer) {
4096          if (transformer == null || reducer == null)
4097              throw new NullPointerException();
4098 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4099 <        long r = basis; V v;
4100 <        while ((v = it.advance()) != null)
4012 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4013 <        return r;
4098 >        return new MapReduceEntriesToLongTask<K,V>
4099 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4100 >             null, transformer, basis, reducer).invoke();
4101      }
4102  
4103      /**
# Line 4018 | Line 4105 | public class ConcurrentHashMapV8<K, V>
4105       * of all entries using the given reducer to combine values,
4106       * and the given basis as an identity value.
4107       *
4108 +     * @param parallelismThreshold the (estimated) number of elements
4109 +     * needed for this operation to be executed in parallel
4110       * @param transformer a function returning the transformation
4111       * for an element
4112       * @param basis the identity (initial default value) for the reduction
4113       * @param reducer a commutative associative combining function
4114       * @return the result of accumulating the given transformation
4115       * of all entries
4116 +     * @since 1.8
4117       */
4118 <    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4119 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4120 <         int basis,
4121 <         IntByIntToInt reducer) {
4118 >    public int reduceEntriesToInt(long parallelismThreshold,
4119 >                                  ObjectToInt<Map.Entry<K,V>> transformer,
4120 >                                  int basis,
4121 >                                  IntByIntToInt reducer) {
4122          if (transformer == null || reducer == null)
4123              throw new NullPointerException();
4124 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4125 <        int r = basis; V v;
4126 <        while ((v = it.advance()) != null)
4037 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4038 <        return r;
4039 <    }
4040 <
4041 <    // Parallel bulk operations
4042 <
4043 <    /**
4044 <     * Performs the given action for each (key, value).
4045 <     *
4046 <     * @param action the action
4047 <     */
4048 <    public void forEachInParallel(BiAction<K,V> action) {
4049 <        ForkJoinTasks.forEach
4050 <            (this, action).invoke();
4051 <    }
4052 <
4053 <    /**
4054 <     * Performs the given action for each non-null transformation
4055 <     * of each (key, value).
4056 <     *
4057 <     * @param transformer a function returning the transformation
4058 <     * for an element, or null of there is no transformation (in
4059 <     * which case the action is not applied).
4060 <     * @param action the action
4061 <     */
4062 <    public <U> void forEachInParallel
4063 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4064 <                            Action<U> action) {
4065 <        ForkJoinTasks.forEach
4066 <            (this, transformer, action).invoke();
4067 <    }
4068 <
4069 <    /**
4070 <     * Returns a non-null result from applying the given search
4071 <     * function on each (key, value), or null if none.  Upon
4072 <     * success, further element processing is suppressed and the
4073 <     * results of any other parallel invocations of the search
4074 <     * function are ignored.
4075 <     *
4076 <     * @param searchFunction a function returning a non-null
4077 <     * result on success, else null
4078 <     * @return a non-null result from applying the given search
4079 <     * function on each (key, value), or null if none
4080 <     */
4081 <    public <U> U searchInParallel
4082 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4083 <        return ForkJoinTasks.search
4084 <            (this, searchFunction).invoke();
4085 <    }
4086 <
4087 <    /**
4088 <     * Returns the result of accumulating the given transformation
4089 <     * of all (key, value) pairs using the given reducer to
4090 <     * combine values, or null if none.
4091 <     *
4092 <     * @param transformer a function returning the transformation
4093 <     * for an element, or null of there is no transformation (in
4094 <     * which case it is not combined).
4095 <     * @param reducer a commutative associative combining function
4096 <     * @return the result of accumulating the given transformation
4097 <     * of all (key, value) pairs
4098 <     */
4099 <    public <U> U reduceInParallel
4100 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4101 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4102 <        return ForkJoinTasks.reduce
4103 <            (this, transformer, reducer).invoke();
4104 <    }
4105 <
4106 <    /**
4107 <     * Returns the result of accumulating the given transformation
4108 <     * of all (key, value) pairs using the given reducer to
4109 <     * combine values, and the given basis as an identity value.
4110 <     *
4111 <     * @param transformer a function returning the transformation
4112 <     * for an element
4113 <     * @param basis the identity (initial default value) for the reduction
4114 <     * @param reducer a commutative associative combining function
4115 <     * @return the result of accumulating the given transformation
4116 <     * of all (key, value) pairs
4117 <     */
4118 <    public double reduceToDoubleInParallel
4119 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
4120 <         double basis,
4121 <         DoubleByDoubleToDouble reducer) {
4122 <        return ForkJoinTasks.reduceToDouble
4123 <            (this, transformer, basis, reducer).invoke();
4124 <    }
4125 <
4126 <    /**
4127 <     * Returns the result of accumulating the given transformation
4128 <     * of all (key, value) pairs using the given reducer to
4129 <     * combine values, and the given basis as an identity value.
4130 <     *
4131 <     * @param transformer a function returning the transformation
4132 <     * for an element
4133 <     * @param basis the identity (initial default value) for the reduction
4134 <     * @param reducer a commutative associative combining function
4135 <     * @return the result of accumulating the given transformation
4136 <     * of all (key, value) pairs
4137 <     */
4138 <    public long reduceToLongInParallel
4139 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
4140 <         long basis,
4141 <         LongByLongToLong reducer) {
4142 <        return ForkJoinTasks.reduceToLong
4143 <            (this, transformer, basis, reducer).invoke();
4144 <    }
4145 <
4146 <    /**
4147 <     * Returns the result of accumulating the given transformation
4148 <     * of all (key, value) pairs using the given reducer to
4149 <     * combine values, and the given basis as an identity value.
4150 <     *
4151 <     * @param transformer a function returning the transformation
4152 <     * for an element
4153 <     * @param basis the identity (initial default value) for the reduction
4154 <     * @param reducer a commutative associative combining function
4155 <     * @return the result of accumulating the given transformation
4156 <     * of all (key, value) pairs
4157 <     */
4158 <    public int reduceToIntInParallel
4159 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
4160 <         int basis,
4161 <         IntByIntToInt reducer) {
4162 <        return ForkJoinTasks.reduceToInt
4163 <            (this, transformer, basis, reducer).invoke();
4164 <    }
4165 <
4166 <    /**
4167 <     * Performs the given action for each key.
4168 <     *
4169 <     * @param action the action
4170 <     */
4171 <    public void forEachKeyInParallel(Action<K> action) {
4172 <        ForkJoinTasks.forEachKey
4173 <            (this, action).invoke();
4174 <    }
4175 <
4176 <    /**
4177 <     * Performs the given action for each non-null transformation
4178 <     * of each key.
4179 <     *
4180 <     * @param transformer a function returning the transformation
4181 <     * for an element, or null of there is no transformation (in
4182 <     * which case the action is not applied).
4183 <     * @param action the action
4184 <     */
4185 <    public <U> void forEachKeyInParallel
4186 <        (Fun<? super K, ? extends U> transformer,
4187 <         Action<U> action) {
4188 <        ForkJoinTasks.forEachKey
4189 <            (this, transformer, action).invoke();
4190 <    }
4191 <
4192 <    /**
4193 <     * Returns a non-null result from applying the given search
4194 <     * function on each key, or null if none. Upon success,
4195 <     * further element processing is suppressed and the results of
4196 <     * any other parallel invocations of the search function are
4197 <     * ignored.
4198 <     *
4199 <     * @param searchFunction a function returning a non-null
4200 <     * result on success, else null
4201 <     * @return a non-null result from applying the given search
4202 <     * function on each key, or null if none
4203 <     */
4204 <    public <U> U searchKeysInParallel
4205 <        (Fun<? super K, ? extends U> searchFunction) {
4206 <        return ForkJoinTasks.searchKeys
4207 <            (this, searchFunction).invoke();
4208 <    }
4209 <
4210 <    /**
4211 <     * Returns the result of accumulating all keys using the given
4212 <     * reducer to combine values, or null if none.
4213 <     *
4214 <     * @param reducer a commutative associative combining function
4215 <     * @return the result of accumulating all keys using the given
4216 <     * reducer to combine values, or null if none
4217 <     */
4218 <    public K reduceKeysInParallel
4219 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
4220 <        return ForkJoinTasks.reduceKeys
4221 <            (this, reducer).invoke();
4222 <    }
4223 <
4224 <    /**
4225 <     * Returns the result of accumulating the given transformation
4226 <     * of all keys using the given reducer to combine values, or
4227 <     * null if none.
4228 <     *
4229 <     * @param transformer a function returning the transformation
4230 <     * for an element, or null of there is no transformation (in
4231 <     * which case it is not combined).
4232 <     * @param reducer a commutative associative combining function
4233 <     * @return the result of accumulating the given transformation
4234 <     * of all keys
4235 <     */
4236 <    public <U> U reduceKeysInParallel
4237 <        (Fun<? super K, ? extends U> transformer,
4238 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4239 <        return ForkJoinTasks.reduceKeys
4240 <            (this, transformer, reducer).invoke();
4241 <    }
4242 <
4243 <    /**
4244 <     * Returns the result of accumulating the given transformation
4245 <     * of all keys using the given reducer to combine values, and
4246 <     * the given basis as an identity value.
4247 <     *
4248 <     * @param transformer a function returning the transformation
4249 <     * for an element
4250 <     * @param basis the identity (initial default value) for the reduction
4251 <     * @param reducer a commutative associative combining function
4252 <     * @return  the result of accumulating the given transformation
4253 <     * of all keys
4254 <     */
4255 <    public double reduceKeysToDoubleInParallel
4256 <        (ObjectToDouble<? super K> transformer,
4257 <         double basis,
4258 <         DoubleByDoubleToDouble reducer) {
4259 <        return ForkJoinTasks.reduceKeysToDouble
4260 <            (this, transformer, basis, reducer).invoke();
4261 <    }
4262 <
4263 <    /**
4264 <     * Returns the result of accumulating the given transformation
4265 <     * of all keys using the given reducer to combine values, and
4266 <     * the given basis as an identity value.
4267 <     *
4268 <     * @param transformer a function returning the transformation
4269 <     * for an element
4270 <     * @param basis the identity (initial default value) for the reduction
4271 <     * @param reducer a commutative associative combining function
4272 <     * @return the result of accumulating the given transformation
4273 <     * of all keys
4274 <     */
4275 <    public long reduceKeysToLongInParallel
4276 <        (ObjectToLong<? super K> transformer,
4277 <         long basis,
4278 <         LongByLongToLong reducer) {
4279 <        return ForkJoinTasks.reduceKeysToLong
4280 <            (this, transformer, basis, reducer).invoke();
4281 <    }
4282 <
4283 <    /**
4284 <     * Returns the result of accumulating the given transformation
4285 <     * of all keys using the given reducer to combine values, and
4286 <     * the given basis as an identity value.
4287 <     *
4288 <     * @param transformer a function returning the transformation
4289 <     * for an element
4290 <     * @param basis the identity (initial default value) for the reduction
4291 <     * @param reducer a commutative associative combining function
4292 <     * @return the result of accumulating the given transformation
4293 <     * of all keys
4294 <     */
4295 <    public int reduceKeysToIntInParallel
4296 <        (ObjectToInt<? super K> transformer,
4297 <         int basis,
4298 <         IntByIntToInt reducer) {
4299 <        return ForkJoinTasks.reduceKeysToInt
4300 <            (this, transformer, basis, reducer).invoke();
4301 <    }
4302 <
4303 <    /**
4304 <     * Performs the given action for each value.
4305 <     *
4306 <     * @param action the action
4307 <     */
4308 <    public void forEachValueInParallel(Action<V> action) {
4309 <        ForkJoinTasks.forEachValue
4310 <            (this, action).invoke();
4311 <    }
4312 <
4313 <    /**
4314 <     * Performs the given action for each non-null transformation
4315 <     * of each value.
4316 <     *
4317 <     * @param transformer a function returning the transformation
4318 <     * for an element, or null of there is no transformation (in
4319 <     * which case the action is not applied).
4320 <     */
4321 <    public <U> void forEachValueInParallel
4322 <        (Fun<? super V, ? extends U> transformer,
4323 <         Action<U> action) {
4324 <        ForkJoinTasks.forEachValue
4325 <            (this, transformer, action).invoke();
4326 <    }
4327 <
4328 <    /**
4329 <     * Returns a non-null result from applying the given search
4330 <     * function on each value, or null if none.  Upon success,
4331 <     * further element processing is suppressed and the results of
4332 <     * any other parallel invocations of the search function are
4333 <     * ignored.
4334 <     *
4335 <     * @param searchFunction a function returning a non-null
4336 <     * result on success, else null
4337 <     * @return a non-null result from applying the given search
4338 <     * function on each value, or null if none
4339 <     */
4340 <    public <U> U searchValuesInParallel
4341 <        (Fun<? super V, ? extends U> searchFunction) {
4342 <        return ForkJoinTasks.searchValues
4343 <            (this, searchFunction).invoke();
4344 <    }
4345 <
4346 <    /**
4347 <     * Returns the result of accumulating all values using the
4348 <     * given reducer to combine values, or null if none.
4349 <     *
4350 <     * @param reducer a commutative associative combining function
4351 <     * @return  the result of accumulating all values
4352 <     */
4353 <    public V reduceValuesInParallel
4354 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
4355 <        return ForkJoinTasks.reduceValues
4356 <            (this, reducer).invoke();
4357 <    }
4358 <
4359 <    /**
4360 <     * Returns the result of accumulating the given transformation
4361 <     * of all values using the given reducer to combine values, or
4362 <     * null if none.
4363 <     *
4364 <     * @param transformer a function returning the transformation
4365 <     * for an element, or null of there is no transformation (in
4366 <     * which case it is not combined).
4367 <     * @param reducer a commutative associative combining function
4368 <     * @return the result of accumulating the given transformation
4369 <     * of all values
4370 <     */
4371 <    public <U> U reduceValuesInParallel
4372 <        (Fun<? super V, ? extends U> transformer,
4373 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4374 <        return ForkJoinTasks.reduceValues
4375 <            (this, transformer, reducer).invoke();
4376 <    }
4377 <
4378 <    /**
4379 <     * Returns the result of accumulating the given transformation
4380 <     * of all values using the given reducer to combine values,
4381 <     * and the given basis as an identity value.
4382 <     *
4383 <     * @param transformer a function returning the transformation
4384 <     * for an element
4385 <     * @param basis the identity (initial default value) for the reduction
4386 <     * @param reducer a commutative associative combining function
4387 <     * @return the result of accumulating the given transformation
4388 <     * of all values
4389 <     */
4390 <    public double reduceValuesToDoubleInParallel
4391 <        (ObjectToDouble<? super V> transformer,
4392 <         double basis,
4393 <         DoubleByDoubleToDouble reducer) {
4394 <        return ForkJoinTasks.reduceValuesToDouble
4395 <            (this, transformer, basis, reducer).invoke();
4396 <    }
4397 <
4398 <    /**
4399 <     * Returns the result of accumulating the given transformation
4400 <     * of all values using the given reducer to combine values,
4401 <     * and the given basis as an identity value.
4402 <     *
4403 <     * @param transformer a function returning the transformation
4404 <     * for an element
4405 <     * @param basis the identity (initial default value) for the reduction
4406 <     * @param reducer a commutative associative combining function
4407 <     * @return the result of accumulating the given transformation
4408 <     * of all values
4409 <     */
4410 <    public long reduceValuesToLongInParallel
4411 <        (ObjectToLong<? super V> transformer,
4412 <         long basis,
4413 <         LongByLongToLong reducer) {
4414 <        return ForkJoinTasks.reduceValuesToLong
4415 <            (this, transformer, basis, reducer).invoke();
4416 <    }
4417 <
4418 <    /**
4419 <     * Returns the result of accumulating the given transformation
4420 <     * of all values using the given reducer to combine values,
4421 <     * and the given basis as an identity value.
4422 <     *
4423 <     * @param transformer a function returning the transformation
4424 <     * for an element
4425 <     * @param basis the identity (initial default value) for the reduction
4426 <     * @param reducer a commutative associative combining function
4427 <     * @return the result of accumulating the given transformation
4428 <     * of all values
4429 <     */
4430 <    public int reduceValuesToIntInParallel
4431 <        (ObjectToInt<? super V> transformer,
4432 <         int basis,
4433 <         IntByIntToInt reducer) {
4434 <        return ForkJoinTasks.reduceValuesToInt
4435 <            (this, transformer, basis, reducer).invoke();
4436 <    }
4437 <
4438 <    /**
4439 <     * Performs the given action for each entry.
4440 <     *
4441 <     * @param action the action
4442 <     */
4443 <    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4444 <        ForkJoinTasks.forEachEntry
4445 <            (this, action).invoke();
4446 <    }
4447 <
4448 <    /**
4449 <     * Performs the given action for each non-null transformation
4450 <     * of each entry.
4451 <     *
4452 <     * @param transformer a function returning the transformation
4453 <     * for an element, or null of there is no transformation (in
4454 <     * which case the action is not applied).
4455 <     * @param action the action
4456 <     */
4457 <    public <U> void forEachEntryInParallel
4458 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4459 <         Action<U> action) {
4460 <        ForkJoinTasks.forEachEntry
4461 <            (this, transformer, action).invoke();
4462 <    }
4463 <
4464 <    /**
4465 <     * Returns a non-null result from applying the given search
4466 <     * function on each entry, or null if none.  Upon success,
4467 <     * further element processing is suppressed and the results of
4468 <     * any other parallel invocations of the search function are
4469 <     * ignored.
4470 <     *
4471 <     * @param searchFunction a function returning a non-null
4472 <     * result on success, else null
4473 <     * @return a non-null result from applying the given search
4474 <     * function on each entry, or null if none
4475 <     */
4476 <    public <U> U searchEntriesInParallel
4477 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4478 <        return ForkJoinTasks.searchEntries
4479 <            (this, searchFunction).invoke();
4480 <    }
4481 <
4482 <    /**
4483 <     * Returns the result of accumulating all entries using the
4484 <     * given reducer to combine values, or null if none.
4485 <     *
4486 <     * @param reducer a commutative associative combining function
4487 <     * @return the result of accumulating all entries
4488 <     */
4489 <    public Map.Entry<K,V> reduceEntriesInParallel
4490 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4491 <        return ForkJoinTasks.reduceEntries
4492 <            (this, reducer).invoke();
4493 <    }
4494 <
4495 <    /**
4496 <     * Returns the result of accumulating the given transformation
4497 <     * of all entries using the given reducer to combine values,
4498 <     * or null if none.
4499 <     *
4500 <     * @param transformer a function returning the transformation
4501 <     * for an element, or null of there is no transformation (in
4502 <     * which case it is not combined).
4503 <     * @param reducer a commutative associative combining function
4504 <     * @return the result of accumulating the given transformation
4505 <     * of all entries
4506 <     */
4507 <    public <U> U reduceEntriesInParallel
4508 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4509 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4510 <        return ForkJoinTasks.reduceEntries
4511 <            (this, transformer, reducer).invoke();
4512 <    }
4513 <
4514 <    /**
4515 <     * Returns the result of accumulating the given transformation
4516 <     * of all entries using the given reducer to combine values,
4517 <     * and the given basis as an identity value.
4518 <     *
4519 <     * @param transformer a function returning the transformation
4520 <     * for an element
4521 <     * @param basis the identity (initial default value) for the reduction
4522 <     * @param reducer a commutative associative combining function
4523 <     * @return the result of accumulating the given transformation
4524 <     * of all entries
4525 <     */
4526 <    public double reduceEntriesToDoubleInParallel
4527 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4528 <         double basis,
4529 <         DoubleByDoubleToDouble reducer) {
4530 <        return ForkJoinTasks.reduceEntriesToDouble
4531 <            (this, transformer, basis, reducer).invoke();
4532 <    }
4533 <
4534 <    /**
4535 <     * Returns the result of accumulating the given transformation
4536 <     * of all entries using the given reducer to combine values,
4537 <     * and the given basis as an identity value.
4538 <     *
4539 <     * @param transformer a function returning the transformation
4540 <     * for an element
4541 <     * @param basis the identity (initial default value) for the reduction
4542 <     * @param reducer a commutative associative combining function
4543 <     * @return  the result of accumulating the given transformation
4544 <     * of all entries
4545 <     */
4546 <    public long reduceEntriesToLongInParallel
4547 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4548 <         long basis,
4549 <         LongByLongToLong reducer) {
4550 <        return ForkJoinTasks.reduceEntriesToLong
4551 <            (this, transformer, basis, reducer).invoke();
4552 <    }
4553 <
4554 <    /**
4555 <     * Returns the result of accumulating the given transformation
4556 <     * of all entries using the given reducer to combine values,
4557 <     * and the given basis as an identity value.
4558 <     *
4559 <     * @param transformer a function returning the transformation
4560 <     * for an element
4561 <     * @param basis the identity (initial default value) for the reduction
4562 <     * @param reducer a commutative associative combining function
4563 <     * @return the result of accumulating the given transformation
4564 <     * of all entries
4565 <     */
4566 <    public int reduceEntriesToIntInParallel
4567 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4568 <         int basis,
4569 <         IntByIntToInt reducer) {
4570 <        return ForkJoinTasks.reduceEntriesToInt
4571 <            (this, transformer, basis, reducer).invoke();
4124 >        return new MapReduceEntriesToIntTask<K,V>
4125 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4126 >             null, transformer, basis, reducer).invoke();
4127      }
4128  
4129  
# Line 4577 | Line 4132 | public class ConcurrentHashMapV8<K, V>
4132      /**
4133       * Base class for views.
4134       */
4135 <    static abstract class CHMView<K, V> {
4136 <        final ConcurrentHashMapV8<K, V> map;
4137 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4135 >    abstract static class CollectionView<K,V,E>
4136 >        implements Collection<E>, java.io.Serializable {
4137 >        private static final long serialVersionUID = 7249069246763182397L;
4138 >        final ConcurrentHashMapV8<K,V> map;
4139 >        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4140  
4141          /**
4142           * Returns the map backing this view.
# Line 4588 | Line 4145 | public class ConcurrentHashMapV8<K, V>
4145           */
4146          public ConcurrentHashMapV8<K,V> getMap() { return map; }
4147  
4148 <        public final int size()                 { return map.size(); }
4149 <        public final boolean isEmpty()          { return map.isEmpty(); }
4150 <        public final void clear()               { map.clear(); }
4148 >        /**
4149 >         * Removes all of the elements from this view, by removing all
4150 >         * the mappings from the map backing this view.
4151 >         */
4152 >        public final void clear()      { map.clear(); }
4153 >        public final int size()        { return map.size(); }
4154 >        public final boolean isEmpty() { return map.isEmpty(); }
4155  
4156          // implementations below rely on concrete classes supplying these
4157 <        abstract public Iterator<?> iterator();
4158 <        abstract public boolean contains(Object o);
4159 <        abstract public boolean remove(Object o);
4157 >        // abstract methods
4158 >        /**
4159 >         * Returns a "weakly consistent" iterator that will never
4160 >         * throw {@link ConcurrentModificationException}, and
4161 >         * guarantees to traverse elements as they existed upon
4162 >         * construction of the iterator, and may (but is not
4163 >         * guaranteed to) reflect any modifications subsequent to
4164 >         * construction.
4165 >         */
4166 >        public abstract Iterator<E> iterator();
4167 >        public abstract boolean contains(Object o);
4168 >        public abstract boolean remove(Object o);
4169  
4170          private static final String oomeMsg = "Required array size too large";
4171  
4172          public final Object[] toArray() {
4173              long sz = map.mappingCount();
4174 <            if (sz > (long)(MAX_ARRAY_SIZE))
4174 >            if (sz > MAX_ARRAY_SIZE)
4175                  throw new OutOfMemoryError(oomeMsg);
4176              int n = (int)sz;
4177              Object[] r = new Object[n];
4178              int i = 0;
4179 <            Iterator<?> it = iterator();
4610 <            while (it.hasNext()) {
4179 >            for (E e : this) {
4180                  if (i == n) {
4181                      if (n >= MAX_ARRAY_SIZE)
4182                          throw new OutOfMemoryError(oomeMsg);
# Line 4617 | Line 4186 | public class ConcurrentHashMapV8<K, V>
4186                          n += (n >>> 1) + 1;
4187                      r = Arrays.copyOf(r, n);
4188                  }
4189 <                r[i++] = it.next();
4189 >                r[i++] = e;
4190              }
4191              return (i == n) ? r : Arrays.copyOf(r, i);
4192          }
4193  
4194 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4194 >        @SuppressWarnings("unchecked")
4195 >        public final <T> T[] toArray(T[] a) {
4196              long sz = map.mappingCount();
4197 <            if (sz > (long)(MAX_ARRAY_SIZE))
4197 >            if (sz > MAX_ARRAY_SIZE)
4198                  throw new OutOfMemoryError(oomeMsg);
4199              int m = (int)sz;
4200              T[] r = (a.length >= m) ? a :
# Line 4632 | Line 4202 | public class ConcurrentHashMapV8<K, V>
4202                  .newInstance(a.getClass().getComponentType(), m);
4203              int n = r.length;
4204              int i = 0;
4205 <            Iterator<?> it = iterator();
4636 <            while (it.hasNext()) {
4205 >            for (E e : this) {
4206                  if (i == n) {
4207                      if (n >= MAX_ARRAY_SIZE)
4208                          throw new OutOfMemoryError(oomeMsg);
# Line 4643 | Line 4212 | public class ConcurrentHashMapV8<K, V>
4212                          n += (n >>> 1) + 1;
4213                      r = Arrays.copyOf(r, n);
4214                  }
4215 <                r[i++] = (T)it.next();
4215 >                r[i++] = (T)e;
4216              }
4217              if (a == r && i < n) {
4218                  r[i] = null; // null-terminate
# Line 4652 | Line 4221 | public class ConcurrentHashMapV8<K, V>
4221              return (i == n) ? r : Arrays.copyOf(r, i);
4222          }
4223  
4224 <        public final int hashCode() {
4225 <            int h = 0;
4226 <            for (Iterator<?> it = iterator(); it.hasNext();)
4227 <                h += it.next().hashCode();
4228 <            return h;
4229 <        }
4230 <
4224 >        /**
4225 >         * Returns a string representation of this collection.
4226 >         * The string representation consists of the string representations
4227 >         * of the collection's elements in the order they are returned by
4228 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4229 >         * Adjacent elements are separated by the characters {@code ", "}
4230 >         * (comma and space).  Elements are converted to strings as by
4231 >         * {@link String#valueOf(Object)}.
4232 >         *
4233 >         * @return a string representation of this collection
4234 >         */
4235          public final String toString() {
4236              StringBuilder sb = new StringBuilder();
4237              sb.append('[');
4238 <            Iterator<?> it = iterator();
4238 >            Iterator<E> it = iterator();
4239              if (it.hasNext()) {
4240                  for (;;) {
4241                      Object e = it.next();
# Line 4677 | Line 4250 | public class ConcurrentHashMapV8<K, V>
4250  
4251          public final boolean containsAll(Collection<?> c) {
4252              if (c != this) {
4253 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4681 <                    Object e = it.next();
4253 >                for (Object e : c) {
4254                      if (e == null || !contains(e))
4255                          return false;
4256                  }
# Line 4688 | Line 4260 | public class ConcurrentHashMapV8<K, V>
4260  
4261          public final boolean removeAll(Collection<?> c) {
4262              boolean modified = false;
4263 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4263 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4264                  if (c.contains(it.next())) {
4265                      it.remove();
4266                      modified = true;
# Line 4699 | Line 4271 | public class ConcurrentHashMapV8<K, V>
4271  
4272          public final boolean retainAll(Collection<?> c) {
4273              boolean modified = false;
4274 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4274 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4275                  if (!c.contains(it.next())) {
4276                      it.remove();
4277                      modified = true;
# Line 4713 | Line 4285 | public class ConcurrentHashMapV8<K, V>
4285      /**
4286       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4287       * which additions may optionally be enabled by mapping to a
4288 <     * common value.  This class cannot be directly instantiated. See
4289 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4290 <     * {@link #newKeySet(int)}.
4288 >     * common value.  This class cannot be directly instantiated.
4289 >     * See {@link #keySet() keySet()},
4290 >     * {@link #keySet(Object) keySet(V)},
4291 >     * {@link #newKeySet() newKeySet()},
4292 >     * {@link #newKeySet(int) newKeySet(int)}.
4293 >     *
4294 >     * @since 1.8
4295       */
4296 <    public static class KeySetView<K,V> extends CHMView<K,V>
4296 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4297          implements Set<K>, java.io.Serializable {
4298          private static final long serialVersionUID = 7249069246763182397L;
4299          private final V value;
4300 <        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4300 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4301              super(map);
4302              this.value = value;
4303          }
# Line 4731 | Line 4307 | public class ConcurrentHashMapV8<K, V>
4307           * or {@code null} if additions are not supported.
4308           *
4309           * @return the default mapped value for additions, or {@code null}
4310 <         * if not supported.
4310 >         * if not supported
4311           */
4312          public V getMappedValue() { return value; }
4313  
4314 <        // implement Set API
4315 <
4314 >        /**
4315 >         * {@inheritDoc}
4316 >         * @throws NullPointerException if the specified key is null
4317 >         */
4318          public boolean contains(Object o) { return map.containsKey(o); }
4741        public boolean remove(Object o)   { return map.remove(o) != null; }
4319  
4320          /**
4321 <         * Returns a "weakly consistent" iterator that will never
4322 <         * throw {@link ConcurrentModificationException}, and
4323 <         * guarantees to traverse elements as they existed upon
4324 <         * construction of the iterator, and may (but is not
4325 <         * guaranteed to) reflect any modifications subsequent to
4326 <         * construction.
4321 >         * Removes the key from this map view, by removing the key (and its
4322 >         * corresponding value) from the backing map.  This method does
4323 >         * nothing if the key is not in the map.
4324 >         *
4325 >         * @param  o the key to be removed from the backing map
4326 >         * @return {@code true} if the backing map contained the specified key
4327 >         * @throws NullPointerException if the specified key is null
4328 >         */
4329 >        public boolean remove(Object o) { return map.remove(o) != null; }
4330 >
4331 >        /**
4332 >         * @return an iterator over the keys of the backing map
4333 >         */
4334 >        public Iterator<K> iterator() {
4335 >            Node<K,V>[] t;
4336 >            ConcurrentHashMapV8<K,V> m = map;
4337 >            int f = (t = m.table) == null ? 0 : t.length;
4338 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4339 >        }
4340 >
4341 >        /**
4342 >         * Adds the specified key to this set view by mapping the key to
4343 >         * the default mapped value in the backing map, if defined.
4344           *
4345 <         * @return an iterator over the keys of this map
4345 >         * @param e key to be added
4346 >         * @return {@code true} if this set changed as a result of the call
4347 >         * @throws NullPointerException if the specified key is null
4348 >         * @throws UnsupportedOperationException if no default mapped value
4349 >         * for additions was provided
4350           */
4753        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4351          public boolean add(K e) {
4352              V v;
4353              if ((v = value) == null)
4354                  throw new UnsupportedOperationException();
4355 <            if (e == null)
4759 <                throw new NullPointerException();
4760 <            return map.internalPut(e, v, true) == null;
4355 >            return map.putVal(e, v, true) == null;
4356          }
4357 +
4358 +        /**
4359 +         * Adds all of the elements in the specified collection to this set,
4360 +         * as if by calling {@link #add} on each one.
4361 +         *
4362 +         * @param c the elements to be inserted into this set
4363 +         * @return {@code true} if this set changed as a result of the call
4364 +         * @throws NullPointerException if the collection or any of its
4365 +         * elements are {@code null}
4366 +         * @throws UnsupportedOperationException if no default mapped value
4367 +         * for additions was provided
4368 +         */
4369          public boolean addAll(Collection<? extends K> c) {
4370              boolean added = false;
4371              V v;
4372              if ((v = value) == null)
4373                  throw new UnsupportedOperationException();
4374              for (K e : c) {
4375 <                if (e == null)
4769 <                    throw new NullPointerException();
4770 <                if (map.internalPut(e, v, true) == null)
4375 >                if (map.putVal(e, v, true) == null)
4376                      added = true;
4377              }
4378              return added;
4379          }
4380 +
4381 +        public int hashCode() {
4382 +            int h = 0;
4383 +            for (K e : this)
4384 +                h += e.hashCode();
4385 +            return h;
4386 +        }
4387 +
4388          public boolean equals(Object o) {
4389              Set<?> c;
4390              return ((o instanceof Set) &&
4391                      ((c = (Set<?>)o) == this ||
4392                       (containsAll(c) && c.containsAll(this))));
4393          }
4394 +
4395 +        public ConcurrentHashMapSpliterator<K> spliterator() {
4396 +            Node<K,V>[] t;
4397 +            ConcurrentHashMapV8<K,V> m = map;
4398 +            long n = m.sumCount();
4399 +            int f = (t = m.table) == null ? 0 : t.length;
4400 +            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4401 +        }
4402 +
4403 +        public void forEach(Action<? super K> action) {
4404 +            if (action == null) throw new NullPointerException();
4405 +            Node<K,V>[] t;
4406 +            if ((t = map.table) != null) {
4407 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4408 +                for (Node<K,V> p; (p = it.advance()) != null; )
4409 +                    action.apply(p.key);
4410 +            }
4411 +        }
4412      }
4413  
4414      /**
4415       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4416       * values, in which additions are disabled. This class cannot be
4417 <     * directly instantiated. See {@link #values},
4787 <     *
4788 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4789 <     * that will never throw {@link ConcurrentModificationException},
4790 <     * and guarantees to traverse elements as they existed upon
4791 <     * construction of the iterator, and may (but is not guaranteed to)
4792 <     * reflect any modifications subsequent to construction.
4417 >     * directly instantiated. See {@link #values()}.
4418       */
4419 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4420 <        implements Collection<V> {
4421 <        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4422 <        public final boolean contains(Object o) { return map.containsValue(o); }
4419 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4420 >        implements Collection<V>, java.io.Serializable {
4421 >        private static final long serialVersionUID = 2249069246763182397L;
4422 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4423 >        public final boolean contains(Object o) {
4424 >            return map.containsValue(o);
4425 >        }
4426 >
4427          public final boolean remove(Object o) {
4428              if (o != null) {
4429 <                Iterator<V> it = new ValueIterator<K,V>(map);
4801 <                while (it.hasNext()) {
4429 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4430                      if (o.equals(it.next())) {
4431                          it.remove();
4432                          return true;
# Line 4808 | Line 4436 | public class ConcurrentHashMapV8<K, V>
4436              return false;
4437          }
4438  
4811        /**
4812         * Returns a "weakly consistent" iterator that will never
4813         * throw {@link ConcurrentModificationException}, and
4814         * guarantees to traverse elements as they existed upon
4815         * construction of the iterator, and may (but is not
4816         * guaranteed to) reflect any modifications subsequent to
4817         * construction.
4818         *
4819         * @return an iterator over the values of this map
4820         */
4439          public final Iterator<V> iterator() {
4440 <            return new ValueIterator<K,V>(map);
4440 >            ConcurrentHashMapV8<K,V> m = map;
4441 >            Node<K,V>[] t;
4442 >            int f = (t = m.table) == null ? 0 : t.length;
4443 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4444          }
4445 +
4446          public final boolean add(V e) {
4447              throw new UnsupportedOperationException();
4448          }
# Line 4828 | Line 4450 | public class ConcurrentHashMapV8<K, V>
4450              throw new UnsupportedOperationException();
4451          }
4452  
4453 +        public ConcurrentHashMapSpliterator<V> spliterator() {
4454 +            Node<K,V>[] t;
4455 +            ConcurrentHashMapV8<K,V> m = map;
4456 +            long n = m.sumCount();
4457 +            int f = (t = m.table) == null ? 0 : t.length;
4458 +            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4459 +        }
4460 +
4461 +        public void forEach(Action<? super V> action) {
4462 +            if (action == null) throw new NullPointerException();
4463 +            Node<K,V>[] t;
4464 +            if ((t = map.table) != null) {
4465 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4466 +                for (Node<K,V> p; (p = it.advance()) != null; )
4467 +                    action.apply(p.val);
4468 +            }
4469 +        }
4470      }
4471  
4472      /**
4473       * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4474       * entries.  This class cannot be directly instantiated. See
4475 <     * {@link #entrySet}.
4475 >     * {@link #entrySet()}.
4476       */
4477 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4478 <        implements Set<Map.Entry<K,V>> {
4479 <        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4480 <        public final boolean contains(Object o) {
4477 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4478 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4479 >        private static final long serialVersionUID = 2249069246763182397L;
4480 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4481 >
4482 >        public boolean contains(Object o) {
4483              Object k, v, r; Map.Entry<?,?> e;
4484              return ((o instanceof Map.Entry) &&
4485                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4846 | Line 4487 | public class ConcurrentHashMapV8<K, V>
4487                      (v = e.getValue()) != null &&
4488                      (v == r || v.equals(r)));
4489          }
4490 <        public final boolean remove(Object o) {
4490 >
4491 >        public boolean remove(Object o) {
4492              Object k, v; Map.Entry<?,?> e;
4493              return ((o instanceof Map.Entry) &&
4494                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4855 | Line 4497 | public class ConcurrentHashMapV8<K, V>
4497          }
4498  
4499          /**
4500 <         * Returns a "weakly consistent" iterator that will never
4859 <         * throw {@link ConcurrentModificationException}, and
4860 <         * guarantees to traverse elements as they existed upon
4861 <         * construction of the iterator, and may (but is not
4862 <         * guaranteed to) reflect any modifications subsequent to
4863 <         * construction.
4864 <         *
4865 <         * @return an iterator over the entries of this map
4500 >         * @return an iterator over the entries of the backing map
4501           */
4502 <        public final Iterator<Map.Entry<K,V>> iterator() {
4503 <            return new EntryIterator<K,V>(map);
4502 >        public Iterator<Map.Entry<K,V>> iterator() {
4503 >            ConcurrentHashMapV8<K,V> m = map;
4504 >            Node<K,V>[] t;
4505 >            int f = (t = m.table) == null ? 0 : t.length;
4506 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4507          }
4508  
4509 <        public final boolean add(Entry<K,V> e) {
4510 <            K key = e.getKey();
4873 <            V value = e.getValue();
4874 <            if (key == null || value == null)
4875 <                throw new NullPointerException();
4876 <            return map.internalPut(key, value, false) == null;
4509 >        public boolean add(Entry<K,V> e) {
4510 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4511          }
4512 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4512 >
4513 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4514              boolean added = false;
4515              for (Entry<K,V> e : c) {
4516                  if (add(e))
# Line 4883 | Line 4518 | public class ConcurrentHashMapV8<K, V>
4518              }
4519              return added;
4520          }
4521 <        public boolean equals(Object o) {
4521 >
4522 >        public final int hashCode() {
4523 >            int h = 0;
4524 >            Node<K,V>[] t;
4525 >            if ((t = map.table) != null) {
4526 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4527 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4528 >                    h += p.hashCode();
4529 >                }
4530 >            }
4531 >            return h;
4532 >        }
4533 >
4534 >        public final boolean equals(Object o) {
4535              Set<?> c;
4536              return ((o instanceof Set) &&
4537                      ((c = (Set<?>)o) == this ||
4538                       (containsAll(c) && c.containsAll(this))));
4539          }
4892    }
4893
4894    // ---------------------------------------------------------------------
4895
4896    /**
4897     * Predefined tasks for performing bulk parallel operations on
4898     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4899     * for bulk operations. Each method has the same name, but returns
4900     * a task rather than invoking it. These methods may be useful in
4901     * custom applications such as submitting a task without waiting
4902     * for completion, using a custom pool, or combining with other
4903     * tasks.
4904     */
4905    public static class ForkJoinTasks {
4906        private ForkJoinTasks() {}
4907
4908        /**
4909         * Returns a task that when invoked, performs the given
4910         * action for each (key, value)
4911         *
4912         * @param map the map
4913         * @param action the action
4914         * @return the task
4915         */
4916        public static <K,V> ForkJoinTask<Void> forEach
4917            (ConcurrentHashMapV8<K,V> map,
4918             BiAction<K,V> action) {
4919            if (action == null) throw new NullPointerException();
4920            return new ForEachMappingTask<K,V>(map, null, -1, action);
4921        }
4922
4923        /**
4924         * Returns a task that when invoked, performs the given
4925         * action for each non-null transformation of each (key, value)
4926         *
4927         * @param map the map
4928         * @param transformer a function returning the transformation
4929         * for an element, or null if there is no transformation (in
4930         * which case the action is not applied)
4931         * @param action the action
4932         * @return the task
4933         */
4934        public static <K,V,U> ForkJoinTask<Void> forEach
4935            (ConcurrentHashMapV8<K,V> map,
4936             BiFun<? super K, ? super V, ? extends U> transformer,
4937             Action<U> action) {
4938            if (transformer == null || action == null)
4939                throw new NullPointerException();
4940            return new ForEachTransformedMappingTask<K,V,U>
4941                (map, null, -1, transformer, action);
4942        }
4943
4944        /**
4945         * Returns a task that when invoked, returns a non-null result
4946         * from applying the given search function on each (key,
4947         * value), or null if none. Upon success, further element
4948         * processing is suppressed and the results of any other
4949         * parallel invocations of the search function are ignored.
4950         *
4951         * @param map the map
4952         * @param searchFunction a function returning a non-null
4953         * result on success, else null
4954         * @return the task
4955         */
4956        public static <K,V,U> ForkJoinTask<U> search
4957            (ConcurrentHashMapV8<K,V> map,
4958             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4959            if (searchFunction == null) throw new NullPointerException();
4960            return new SearchMappingsTask<K,V,U>
4961                (map, null, -1, searchFunction,
4962                 new AtomicReference<U>());
4963        }
4964
4965        /**
4966         * Returns a task that when invoked, returns the result of
4967         * accumulating the given transformation of all (key, value) pairs
4968         * using the given reducer to combine values, or null if none.
4969         *
4970         * @param map the map
4971         * @param transformer a function returning the transformation
4972         * for an element, or null if there is no transformation (in
4973         * which case it is not combined).
4974         * @param reducer a commutative associative combining function
4975         * @return the task
4976         */
4977        public static <K,V,U> ForkJoinTask<U> reduce
4978            (ConcurrentHashMapV8<K,V> map,
4979             BiFun<? super K, ? super V, ? extends U> transformer,
4980             BiFun<? super U, ? super U, ? extends U> reducer) {
4981            if (transformer == null || reducer == null)
4982                throw new NullPointerException();
4983            return new MapReduceMappingsTask<K,V,U>
4984                (map, null, -1, null, transformer, reducer);
4985        }
4986
4987        /**
4988         * Returns a task that when invoked, returns the result of
4989         * accumulating the given transformation of all (key, value) pairs
4990         * using the given reducer to combine values, and the given
4991         * basis as an identity value.
4992         *
4993         * @param map the map
4994         * @param transformer a function returning the transformation
4995         * for an element
4996         * @param basis the identity (initial default value) for the reduction
4997         * @param reducer a commutative associative combining function
4998         * @return the task
4999         */
5000        public static <K,V> ForkJoinTask<Double> reduceToDouble
5001            (ConcurrentHashMapV8<K,V> map,
5002             ObjectByObjectToDouble<? super K, ? super V> transformer,
5003             double basis,
5004             DoubleByDoubleToDouble reducer) {
5005            if (transformer == null || reducer == null)
5006                throw new NullPointerException();
5007            return new MapReduceMappingsToDoubleTask<K,V>
5008                (map, null, -1, null, transformer, basis, reducer);
5009        }
5010
5011        /**
5012         * Returns a task that when invoked, returns the result of
5013         * accumulating the given transformation of all (key, value) pairs
5014         * using the given reducer to combine values, and the given
5015         * basis as an identity value.
5016         *
5017         * @param map the map
5018         * @param transformer a function returning the transformation
5019         * for an element
5020         * @param basis the identity (initial default value) for the reduction
5021         * @param reducer a commutative associative combining function
5022         * @return the task
5023         */
5024        public static <K,V> ForkJoinTask<Long> reduceToLong
5025            (ConcurrentHashMapV8<K,V> map,
5026             ObjectByObjectToLong<? super K, ? super V> transformer,
5027             long basis,
5028             LongByLongToLong reducer) {
5029            if (transformer == null || reducer == null)
5030                throw new NullPointerException();
5031            return new MapReduceMappingsToLongTask<K,V>
5032                (map, null, -1, null, transformer, basis, reducer);
5033        }
4540  
4541 <        /**
4542 <         * Returns a task that when invoked, returns the result of
4543 <         * accumulating the given transformation of all (key, value) pairs
4544 <         * using the given reducer to combine values, and the given
4545 <         * basis as an identity value.
4546 <         *
5041 <         * @param transformer a function returning the transformation
5042 <         * for an element
5043 <         * @param basis the identity (initial default value) for the reduction
5044 <         * @param reducer a commutative associative combining function
5045 <         * @return the task
5046 <         */
5047 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5048 <            (ConcurrentHashMapV8<K,V> map,
5049 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5050 <             int basis,
5051 <             IntByIntToInt reducer) {
5052 <            if (transformer == null || reducer == null)
5053 <                throw new NullPointerException();
5054 <            return new MapReduceMappingsToIntTask<K,V>
5055 <                (map, null, -1, null, transformer, basis, reducer);
4541 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4542 >            Node<K,V>[] t;
4543 >            ConcurrentHashMapV8<K,V> m = map;
4544 >            long n = m.sumCount();
4545 >            int f = (t = m.table) == null ? 0 : t.length;
4546 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4547          }
4548  
4549 <        /**
5059 <         * Returns a task that when invoked, performs the given action
5060 <         * for each key.
5061 <         *
5062 <         * @param map the map
5063 <         * @param action the action
5064 <         * @return the task
5065 <         */
5066 <        public static <K,V> ForkJoinTask<Void> forEachKey
5067 <            (ConcurrentHashMapV8<K,V> map,
5068 <             Action<K> action) {
4549 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4550              if (action == null) throw new NullPointerException();
4551 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4552 <        }
4553 <
4554 <        /**
4555 <         * Returns a task that when invoked, performs the given action
4556 <         * for each non-null transformation of each key.
5076 <         *
5077 <         * @param map the map
5078 <         * @param transformer a function returning the transformation
5079 <         * for an element, or null if there is no transformation (in
5080 <         * which case the action is not applied)
5081 <         * @param action the action
5082 <         * @return the task
5083 <         */
5084 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5085 <            (ConcurrentHashMapV8<K,V> map,
5086 <             Fun<? super K, ? extends U> transformer,
5087 <             Action<U> action) {
5088 <            if (transformer == null || action == null)
5089 <                throw new NullPointerException();
5090 <            return new ForEachTransformedKeyTask<K,V,U>
5091 <                (map, null, -1, transformer, action);
5092 <        }
5093 <
5094 <        /**
5095 <         * Returns a task that when invoked, returns a non-null result
5096 <         * from applying the given search function on each key, or
5097 <         * null if none.  Upon success, further element processing is
5098 <         * suppressed and the results of any other parallel
5099 <         * invocations of the search function are ignored.
5100 <         *
5101 <         * @param map the map
5102 <         * @param searchFunction a function returning a non-null
5103 <         * result on success, else null
5104 <         * @return the task
5105 <         */
5106 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5107 <            (ConcurrentHashMapV8<K,V> map,
5108 <             Fun<? super K, ? extends U> searchFunction) {
5109 <            if (searchFunction == null) throw new NullPointerException();
5110 <            return new SearchKeysTask<K,V,U>
5111 <                (map, null, -1, searchFunction,
5112 <                 new AtomicReference<U>());
5113 <        }
5114 <
5115 <        /**
5116 <         * Returns a task that when invoked, returns the result of
5117 <         * accumulating all keys using the given reducer to combine
5118 <         * values, or null if none.
5119 <         *
5120 <         * @param map the map
5121 <         * @param reducer a commutative associative combining function
5122 <         * @return the task
5123 <         */
5124 <        public static <K,V> ForkJoinTask<K> reduceKeys
5125 <            (ConcurrentHashMapV8<K,V> map,
5126 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5127 <            if (reducer == null) throw new NullPointerException();
5128 <            return new ReduceKeysTask<K,V>
5129 <                (map, null, -1, null, reducer);
5130 <        }
5131 <
5132 <        /**
5133 <         * Returns a task that when invoked, returns the result of
5134 <         * accumulating the given transformation of all keys using the given
5135 <         * reducer to combine values, or null if none.
5136 <         *
5137 <         * @param map the map
5138 <         * @param transformer a function returning the transformation
5139 <         * for an element, or null if there is no transformation (in
5140 <         * which case it is not combined).
5141 <         * @param reducer a commutative associative combining function
5142 <         * @return the task
5143 <         */
5144 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5145 <            (ConcurrentHashMapV8<K,V> map,
5146 <             Fun<? super K, ? extends U> transformer,
5147 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5148 <            if (transformer == null || reducer == null)
5149 <                throw new NullPointerException();
5150 <            return new MapReduceKeysTask<K,V,U>
5151 <                (map, null, -1, null, transformer, reducer);
5152 <        }
5153 <
5154 <        /**
5155 <         * Returns a task that when invoked, returns the result of
5156 <         * accumulating the given transformation of all keys using the given
5157 <         * reducer to combine values, and the given basis as an
5158 <         * identity value.
5159 <         *
5160 <         * @param map the map
5161 <         * @param transformer a function returning the transformation
5162 <         * for an element
5163 <         * @param basis the identity (initial default value) for the reduction
5164 <         * @param reducer a commutative associative combining function
5165 <         * @return the task
5166 <         */
5167 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5168 <            (ConcurrentHashMapV8<K,V> map,
5169 <             ObjectToDouble<? super K> transformer,
5170 <             double basis,
5171 <             DoubleByDoubleToDouble reducer) {
5172 <            if (transformer == null || reducer == null)
5173 <                throw new NullPointerException();
5174 <            return new MapReduceKeysToDoubleTask<K,V>
5175 <                (map, null, -1, null, transformer, basis, reducer);
5176 <        }
5177 <
5178 <        /**
5179 <         * Returns a task that when invoked, returns the result of
5180 <         * accumulating the given transformation of all keys using the given
5181 <         * reducer to combine values, and the given basis as an
5182 <         * identity value.
5183 <         *
5184 <         * @param map the map
5185 <         * @param transformer a function returning the transformation
5186 <         * for an element
5187 <         * @param basis the identity (initial default value) for the reduction
5188 <         * @param reducer a commutative associative combining function
5189 <         * @return the task
5190 <         */
5191 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5192 <            (ConcurrentHashMapV8<K,V> map,
5193 <             ObjectToLong<? super K> transformer,
5194 <             long basis,
5195 <             LongByLongToLong reducer) {
5196 <            if (transformer == null || reducer == null)
5197 <                throw new NullPointerException();
5198 <            return new MapReduceKeysToLongTask<K,V>
5199 <                (map, null, -1, null, transformer, basis, reducer);
5200 <        }
5201 <
5202 <        /**
5203 <         * Returns a task that when invoked, returns the result of
5204 <         * accumulating the given transformation of all keys using the given
5205 <         * reducer to combine values, and the given basis as an
5206 <         * identity value.
5207 <         *
5208 <         * @param map the map
5209 <         * @param transformer a function returning the transformation
5210 <         * for an element
5211 <         * @param basis the identity (initial default value) for the reduction
5212 <         * @param reducer a commutative associative combining function
5213 <         * @return the task
5214 <         */
5215 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5216 <            (ConcurrentHashMapV8<K,V> map,
5217 <             ObjectToInt<? super K> transformer,
5218 <             int basis,
5219 <             IntByIntToInt reducer) {
5220 <            if (transformer == null || reducer == null)
5221 <                throw new NullPointerException();
5222 <            return new MapReduceKeysToIntTask<K,V>
5223 <                (map, null, -1, null, transformer, basis, reducer);
5224 <        }
5225 <
5226 <        /**
5227 <         * Returns a task that when invoked, performs the given action
5228 <         * for each value.
5229 <         *
5230 <         * @param map the map
5231 <         * @param action the action
5232 <         */
5233 <        public static <K,V> ForkJoinTask<Void> forEachValue
5234 <            (ConcurrentHashMapV8<K,V> map,
5235 <             Action<V> action) {
5236 <            if (action == null) throw new NullPointerException();
5237 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5238 <        }
5239 <
5240 <        /**
5241 <         * Returns a task that when invoked, performs the given action
5242 <         * for each non-null transformation of each value.
5243 <         *
5244 <         * @param map the map
5245 <         * @param transformer a function returning the transformation
5246 <         * for an element, or null if there is no transformation (in
5247 <         * which case the action is not applied)
5248 <         * @param action the action
5249 <         */
5250 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5251 <            (ConcurrentHashMapV8<K,V> map,
5252 <             Fun<? super V, ? extends U> transformer,
5253 <             Action<U> action) {
5254 <            if (transformer == null || action == null)
5255 <                throw new NullPointerException();
5256 <            return new ForEachTransformedValueTask<K,V,U>
5257 <                (map, null, -1, transformer, action);
5258 <        }
5259 <
5260 <        /**
5261 <         * Returns a task that when invoked, returns a non-null result
5262 <         * from applying the given search function on each value, or
5263 <         * null if none.  Upon success, further element processing is
5264 <         * suppressed and the results of any other parallel
5265 <         * invocations of the search function are ignored.
5266 <         *
5267 <         * @param map the map
5268 <         * @param searchFunction a function returning a non-null
5269 <         * result on success, else null
5270 <         * @return the task
5271 <         */
5272 <        public static <K,V,U> ForkJoinTask<U> searchValues
5273 <            (ConcurrentHashMapV8<K,V> map,
5274 <             Fun<? super V, ? extends U> searchFunction) {
5275 <            if (searchFunction == null) throw new NullPointerException();
5276 <            return new SearchValuesTask<K,V,U>
5277 <                (map, null, -1, searchFunction,
5278 <                 new AtomicReference<U>());
5279 <        }
5280 <
5281 <        /**
5282 <         * Returns a task that when invoked, returns the result of
5283 <         * accumulating all values using the given reducer to combine
5284 <         * values, or null if none.
5285 <         *
5286 <         * @param map the map
5287 <         * @param reducer a commutative associative combining function
5288 <         * @return the task
5289 <         */
5290 <        public static <K,V> ForkJoinTask<V> reduceValues
5291 <            (ConcurrentHashMapV8<K,V> map,
5292 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5293 <            if (reducer == null) throw new NullPointerException();
5294 <            return new ReduceValuesTask<K,V>
5295 <                (map, null, -1, null, reducer);
5296 <        }
5297 <
5298 <        /**
5299 <         * Returns a task that when invoked, returns the result of
5300 <         * accumulating the given transformation of all values using the
5301 <         * given reducer to combine values, or null if none.
5302 <         *
5303 <         * @param map the map
5304 <         * @param transformer a function returning the transformation
5305 <         * for an element, or null if there is no transformation (in
5306 <         * which case it is not combined).
5307 <         * @param reducer a commutative associative combining function
5308 <         * @return the task
5309 <         */
5310 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5311 <            (ConcurrentHashMapV8<K,V> map,
5312 <             Fun<? super V, ? extends U> transformer,
5313 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5314 <            if (transformer == null || reducer == null)
5315 <                throw new NullPointerException();
5316 <            return new MapReduceValuesTask<K,V,U>
5317 <                (map, null, -1, null, transformer, reducer);
5318 <        }
5319 <
5320 <        /**
5321 <         * Returns a task that when invoked, returns the result of
5322 <         * accumulating the given transformation of all values using the
5323 <         * given reducer to combine values, and the given basis as an
5324 <         * identity value.
5325 <         *
5326 <         * @param map the map
5327 <         * @param transformer a function returning the transformation
5328 <         * for an element
5329 <         * @param basis the identity (initial default value) for the reduction
5330 <         * @param reducer a commutative associative combining function
5331 <         * @return the task
5332 <         */
5333 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5334 <            (ConcurrentHashMapV8<K,V> map,
5335 <             ObjectToDouble<? super V> transformer,
5336 <             double basis,
5337 <             DoubleByDoubleToDouble reducer) {
5338 <            if (transformer == null || reducer == null)
5339 <                throw new NullPointerException();
5340 <            return new MapReduceValuesToDoubleTask<K,V>
5341 <                (map, null, -1, null, transformer, basis, reducer);
5342 <        }
5343 <
5344 <        /**
5345 <         * Returns a task that when invoked, returns the result of
5346 <         * accumulating the given transformation of all values using the
5347 <         * given reducer to combine values, and the given basis as an
5348 <         * identity value.
5349 <         *
5350 <         * @param map the map
5351 <         * @param transformer a function returning the transformation
5352 <         * for an element
5353 <         * @param basis the identity (initial default value) for the reduction
5354 <         * @param reducer a commutative associative combining function
5355 <         * @return the task
5356 <         */
5357 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5358 <            (ConcurrentHashMapV8<K,V> map,
5359 <             ObjectToLong<? super V> transformer,
5360 <             long basis,
5361 <             LongByLongToLong reducer) {
5362 <            if (transformer == null || reducer == null)
5363 <                throw new NullPointerException();
5364 <            return new MapReduceValuesToLongTask<K,V>
5365 <                (map, null, -1, null, transformer, basis, reducer);
5366 <        }
5367 <
5368 <        /**
5369 <         * Returns a task that when invoked, returns the result of
5370 <         * accumulating the given transformation of all values using the
5371 <         * given reducer to combine values, and the given basis as an
5372 <         * identity value.
5373 <         *
5374 <         * @param map the map
5375 <         * @param transformer a function returning the transformation
5376 <         * for an element
5377 <         * @param basis the identity (initial default value) for the reduction
5378 <         * @param reducer a commutative associative combining function
5379 <         * @return the task
5380 <         */
5381 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5382 <            (ConcurrentHashMapV8<K,V> map,
5383 <             ObjectToInt<? super V> transformer,
5384 <             int basis,
5385 <             IntByIntToInt reducer) {
5386 <            if (transformer == null || reducer == null)
5387 <                throw new NullPointerException();
5388 <            return new MapReduceValuesToIntTask<K,V>
5389 <                (map, null, -1, null, transformer, basis, reducer);
5390 <        }
5391 <
5392 <        /**
5393 <         * Returns a task that when invoked, perform the given action
5394 <         * for each entry.
5395 <         *
5396 <         * @param map the map
5397 <         * @param action the action
5398 <         */
5399 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5400 <            (ConcurrentHashMapV8<K,V> map,
5401 <             Action<Map.Entry<K,V>> action) {
5402 <            if (action == null) throw new NullPointerException();
5403 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5404 <        }
5405 <
5406 <        /**
5407 <         * Returns a task that when invoked, perform the given action
5408 <         * for each non-null transformation of each entry.
5409 <         *
5410 <         * @param map the map
5411 <         * @param transformer a function returning the transformation
5412 <         * for an element, or null if there is no transformation (in
5413 <         * which case the action is not applied)
5414 <         * @param action the action
5415 <         */
5416 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5417 <            (ConcurrentHashMapV8<K,V> map,
5418 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5419 <             Action<U> action) {
5420 <            if (transformer == null || action == null)
5421 <                throw new NullPointerException();
5422 <            return new ForEachTransformedEntryTask<K,V,U>
5423 <                (map, null, -1, transformer, action);
5424 <        }
5425 <
5426 <        /**
5427 <         * Returns a task that when invoked, returns a non-null result
5428 <         * from applying the given search function on each entry, or
5429 <         * null if none.  Upon success, further element processing is
5430 <         * suppressed and the results of any other parallel
5431 <         * invocations of the search function are ignored.
5432 <         *
5433 <         * @param map the map
5434 <         * @param searchFunction a function returning a non-null
5435 <         * result on success, else null
5436 <         * @return the task
5437 <         */
5438 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5439 <            (ConcurrentHashMapV8<K,V> map,
5440 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5441 <            if (searchFunction == null) throw new NullPointerException();
5442 <            return new SearchEntriesTask<K,V,U>
5443 <                (map, null, -1, searchFunction,
5444 <                 new AtomicReference<U>());
5445 <        }
5446 <
5447 <        /**
5448 <         * Returns a task that when invoked, returns the result of
5449 <         * accumulating all entries using the given reducer to combine
5450 <         * values, or null if none.
5451 <         *
5452 <         * @param map the map
5453 <         * @param reducer a commutative associative combining function
5454 <         * @return the task
5455 <         */
5456 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5457 <            (ConcurrentHashMapV8<K,V> map,
5458 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5459 <            if (reducer == null) throw new NullPointerException();
5460 <            return new ReduceEntriesTask<K,V>
5461 <                (map, null, -1, null, reducer);
4551 >            Node<K,V>[] t;
4552 >            if ((t = map.table) != null) {
4553 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4554 >                for (Node<K,V> p; (p = it.advance()) != null; )
4555 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4556 >            }
4557          }
4558  
4559 <        /**
5465 <         * Returns a task that when invoked, returns the result of
5466 <         * accumulating the given transformation of all entries using the
5467 <         * given reducer to combine values, or null if none.
5468 <         *
5469 <         * @param map the map
5470 <         * @param transformer a function returning the transformation
5471 <         * for an element, or null if there is no transformation (in
5472 <         * which case it is not combined).
5473 <         * @param reducer a commutative associative combining function
5474 <         * @return the task
5475 <         */
5476 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5477 <            (ConcurrentHashMapV8<K,V> map,
5478 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5479 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5480 <            if (transformer == null || reducer == null)
5481 <                throw new NullPointerException();
5482 <            return new MapReduceEntriesTask<K,V,U>
5483 <                (map, null, -1, null, transformer, reducer);
5484 <        }
4559 >    }
4560  
4561 <        /**
5487 <         * Returns a task that when invoked, returns the result of
5488 <         * accumulating the given transformation of all entries using the
5489 <         * given reducer to combine values, and the given basis as an
5490 <         * identity value.
5491 <         *
5492 <         * @param map the map
5493 <         * @param transformer a function returning the transformation
5494 <         * for an element
5495 <         * @param basis the identity (initial default value) for the reduction
5496 <         * @param reducer a commutative associative combining function
5497 <         * @return the task
5498 <         */
5499 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5500 <            (ConcurrentHashMapV8<K,V> map,
5501 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5502 <             double basis,
5503 <             DoubleByDoubleToDouble reducer) {
5504 <            if (transformer == null || reducer == null)
5505 <                throw new NullPointerException();
5506 <            return new MapReduceEntriesToDoubleTask<K,V>
5507 <                (map, null, -1, null, transformer, basis, reducer);
5508 <        }
4561 >    // -------------------------------------------------------
4562  
4563 <        /**
4564 <         * Returns a task that when invoked, returns the result of
4565 <         * accumulating the given transformation of all entries using the
4566 <         * given reducer to combine values, and the given basis as an
4567 <         * identity value.
4568 <         *
4569 <         * @param map the map
4570 <         * @param transformer a function returning the transformation
4571 <         * for an element
4572 <         * @param basis the identity (initial default value) for the reduction
4573 <         * @param reducer a commutative associative combining function
4574 <         * @return the task
4575 <         */
4576 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4577 <            (ConcurrentHashMapV8<K,V> map,
4578 <             ObjectToLong<Map.Entry<K,V>> transformer,
4579 <             long basis,
4580 <             LongByLongToLong reducer) {
4581 <            if (transformer == null || reducer == null)
4582 <                throw new NullPointerException();
4583 <            return new MapReduceEntriesToLongTask<K,V>
4584 <                (map, null, -1, null, transformer, basis, reducer);
4563 >    /**
4564 >     * Base class for bulk tasks. Repeats some fields and code from
4565 >     * class Traverser, because we need to subclass CountedCompleter.
4566 >     */
4567 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4568 >        Node<K,V>[] tab;        // same as Traverser
4569 >        Node<K,V> next;
4570 >        int index;
4571 >        int baseIndex;
4572 >        int baseLimit;
4573 >        final int baseSize;
4574 >        int batch;              // split control
4575 >
4576 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4577 >            super(par);
4578 >            this.batch = b;
4579 >            this.index = this.baseIndex = i;
4580 >            if ((this.tab = t) == null)
4581 >                this.baseSize = this.baseLimit = 0;
4582 >            else if (par == null)
4583 >                this.baseSize = this.baseLimit = t.length;
4584 >            else {
4585 >                this.baseLimit = f;
4586 >                this.baseSize = par.baseSize;
4587 >            }
4588          }
4589  
4590          /**
4591 <         * Returns a task that when invoked, returns the result of
5536 <         * accumulating the given transformation of all entries using the
5537 <         * given reducer to combine values, and the given basis as an
5538 <         * identity value.
5539 <         *
5540 <         * @param map the map
5541 <         * @param transformer a function returning the transformation
5542 <         * for an element
5543 <         * @param basis the identity (initial default value) for the reduction
5544 <         * @param reducer a commutative associative combining function
5545 <         * @return the task
4591 >         * Same as Traverser version
4592           */
4593 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4594 <            (ConcurrentHashMapV8<K,V> map,
4595 <             ObjectToInt<Map.Entry<K,V>> transformer,
4596 <             int basis,
4597 <             IntByIntToInt reducer) {
4598 <            if (transformer == null || reducer == null)
4599 <                throw new NullPointerException();
4600 <            return new MapReduceEntriesToIntTask<K,V>
4601 <                (map, null, -1, null, transformer, basis, reducer);
4593 >        final Node<K,V> advance() {
4594 >            Node<K,V> e;
4595 >            if ((e = next) != null)
4596 >                e = e.next;
4597 >            for (;;) {
4598 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4599 >                if (e != null)
4600 >                    return next = e;
4601 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4602 >                    (n = t.length) <= (i = index) || i < 0)
4603 >                    return next = null;
4604 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4605 >                    if (e instanceof ForwardingNode) {
4606 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4607 >                        e = null;
4608 >                        continue;
4609 >                    }
4610 >                    else if (e instanceof TreeBin)
4611 >                        e = ((TreeBin<K,V>)e).first;
4612 >                    else
4613 >                        e = null;
4614 >                }
4615 >                if ((index += baseSize) >= n)
4616 >                    index = ++baseIndex;    // visit upper slots if present
4617 >            }
4618          }
4619      }
4620  
5559    // -------------------------------------------------------
5560
4621      /*
4622       * Task classes. Coded in a regular but ugly format/style to
4623       * simplify checks that each variant differs in the right way from
# Line 5565 | Line 4625 | public class ConcurrentHashMapV8<K, V>
4625       * that we've already null-checked task arguments, so we force
4626       * simplest hoisted bypass to help avoid convoluted traps.
4627       */
4628 <
4629 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4630 <        extends Traverser<K,V,Void> {
4631 <        final Action<K> action;
4628 >    @SuppressWarnings("serial")
4629 >    static final class ForEachKeyTask<K,V>
4630 >        extends BulkTask<K,V,Void> {
4631 >        final Action<? super K> action;
4632          ForEachKeyTask
4633 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4634 <             Action<K> action) {
4635 <            super(m, p, b);
4633 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4634 >             Action<? super K> action) {
4635 >            super(p, b, i, f, t);
4636              this.action = action;
4637          }
4638 <        @SuppressWarnings("unchecked") public final void compute() {
4639 <            final Action<K> action;
4638 >        public final void compute() {
4639 >            final Action<? super K> action;
4640              if ((action = this.action) != null) {
4641 <                for (int b; (b = preSplit()) > 0;)
4642 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4643 <                while (advance() != null)
4644 <                    action.apply((K)nextKey);
4641 >                for (int i = baseIndex, f, h; batch > 0 &&
4642 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4643 >                    addToPendingCount(1);
4644 >                    new ForEachKeyTask<K,V>
4645 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4646 >                         action).fork();
4647 >                }
4648 >                for (Node<K,V> p; (p = advance()) != null;)
4649 >                    action.apply(p.key);
4650                  propagateCompletion();
4651              }
4652          }
4653      }
4654  
4655 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4656 <        extends Traverser<K,V,Void> {
4657 <        final Action<V> action;
4655 >    @SuppressWarnings("serial")
4656 >    static final class ForEachValueTask<K,V>
4657 >        extends BulkTask<K,V,Void> {
4658 >        final Action<? super V> action;
4659          ForEachValueTask
4660 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4661 <             Action<V> action) {
4662 <            super(m, p, b);
4660 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4661 >             Action<? super V> action) {
4662 >            super(p, b, i, f, t);
4663              this.action = action;
4664          }
4665 <        @SuppressWarnings("unchecked") public final void compute() {
4666 <            final Action<V> action;
4665 >        public final void compute() {
4666 >            final Action<? super V> action;
4667              if ((action = this.action) != null) {
4668 <                for (int b; (b = preSplit()) > 0;)
4669 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4670 <                V v;
4671 <                while ((v = advance()) != null)
4672 <                    action.apply(v);
4668 >                for (int i = baseIndex, f, h; batch > 0 &&
4669 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4670 >                    addToPendingCount(1);
4671 >                    new ForEachValueTask<K,V>
4672 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4673 >                         action).fork();
4674 >                }
4675 >                for (Node<K,V> p; (p = advance()) != null;)
4676 >                    action.apply(p.val);
4677                  propagateCompletion();
4678              }
4679          }
4680      }
4681  
4682 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4683 <        extends Traverser<K,V,Void> {
4684 <        final Action<Entry<K,V>> action;
4682 >    @SuppressWarnings("serial")
4683 >    static final class ForEachEntryTask<K,V>
4684 >        extends BulkTask<K,V,Void> {
4685 >        final Action<? super Entry<K,V>> action;
4686          ForEachEntryTask
4687 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4688 <             Action<Entry<K,V>> action) {
4689 <            super(m, p, b);
4687 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4688 >             Action<? super Entry<K,V>> action) {
4689 >            super(p, b, i, f, t);
4690              this.action = action;
4691          }
4692 <        @SuppressWarnings("unchecked") public final void compute() {
4693 <            final Action<Entry<K,V>> action;
4692 >        public final void compute() {
4693 >            final Action<? super Entry<K,V>> action;
4694              if ((action = this.action) != null) {
4695 <                for (int b; (b = preSplit()) > 0;)
4696 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4697 <                V v;
4698 <                while ((v = advance()) != null)
4699 <                    action.apply(entryFor((K)nextKey, v));
4695 >                for (int i = baseIndex, f, h; batch > 0 &&
4696 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4697 >                    addToPendingCount(1);
4698 >                    new ForEachEntryTask<K,V>
4699 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4700 >                         action).fork();
4701 >                }
4702 >                for (Node<K,V> p; (p = advance()) != null; )
4703 >                    action.apply(p);
4704                  propagateCompletion();
4705              }
4706          }
4707      }
4708  
4709 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4710 <        extends Traverser<K,V,Void> {
4711 <        final BiAction<K,V> action;
4709 >    @SuppressWarnings("serial")
4710 >    static final class ForEachMappingTask<K,V>
4711 >        extends BulkTask<K,V,Void> {
4712 >        final BiAction<? super K, ? super V> action;
4713          ForEachMappingTask
4714 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4715 <             BiAction<K,V> action) {
4716 <            super(m, p, b);
4714 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4715 >             BiAction<? super K,? super V> action) {
4716 >            super(p, b, i, f, t);
4717              this.action = action;
4718          }
4719 <        @SuppressWarnings("unchecked") public final void compute() {
4720 <            final BiAction<K,V> action;
4719 >        public final void compute() {
4720 >            final BiAction<? super K, ? super V> action;
4721              if ((action = this.action) != null) {
4722 <                for (int b; (b = preSplit()) > 0;)
4723 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4724 <                V v;
4725 <                while ((v = advance()) != null)
4726 <                    action.apply((K)nextKey, v);
4722 >                for (int i = baseIndex, f, h; batch > 0 &&
4723 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4724 >                    addToPendingCount(1);
4725 >                    new ForEachMappingTask<K,V>
4726 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4727 >                         action).fork();
4728 >                }
4729 >                for (Node<K,V> p; (p = advance()) != null; )
4730 >                    action.apply(p.key, p.val);
4731                  propagateCompletion();
4732              }
4733          }
4734      }
4735  
4736 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4737 <        extends Traverser<K,V,Void> {
4736 >    @SuppressWarnings("serial")
4737 >    static final class ForEachTransformedKeyTask<K,V,U>
4738 >        extends BulkTask<K,V,Void> {
4739          final Fun<? super K, ? extends U> transformer;
4740 <        final Action<U> action;
4740 >        final Action<? super U> action;
4741          ForEachTransformedKeyTask
4742 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4743 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
4744 <            super(m, p, b);
4742 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4743 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4744 >            super(p, b, i, f, t);
4745              this.transformer = transformer; this.action = action;
4746          }
4747 <        @SuppressWarnings("unchecked") public final void compute() {
4747 >        public final void compute() {
4748              final Fun<? super K, ? extends U> transformer;
4749 <            final Action<U> action;
4749 >            final Action<? super U> action;
4750              if ((transformer = this.transformer) != null &&
4751                  (action = this.action) != null) {
4752 <                for (int b; (b = preSplit()) > 0;)
4752 >                for (int i = baseIndex, f, h; batch > 0 &&
4753 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4754 >                    addToPendingCount(1);
4755                      new ForEachTransformedKeyTask<K,V,U>
4756 <                        (map, this, b, transformer, action).fork();
4757 <                U u;
4758 <                while (advance() != null) {
4759 <                    if ((u = transformer.apply((K)nextKey)) != null)
4756 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4757 >                         transformer, action).fork();
4758 >                }
4759 >                for (Node<K,V> p; (p = advance()) != null; ) {
4760 >                    U u;
4761 >                    if ((u = transformer.apply(p.key)) != null)
4762                          action.apply(u);
4763                  }
4764                  propagateCompletion();
# Line 5681 | Line 4766 | public class ConcurrentHashMapV8<K, V>
4766          }
4767      }
4768  
4769 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4770 <        extends Traverser<K,V,Void> {
4769 >    @SuppressWarnings("serial")
4770 >    static final class ForEachTransformedValueTask<K,V,U>
4771 >        extends BulkTask<K,V,Void> {
4772          final Fun<? super V, ? extends U> transformer;
4773 <        final Action<U> action;
4773 >        final Action<? super U> action;
4774          ForEachTransformedValueTask
4775 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4776 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
4777 <            super(m, p, b);
4775 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4776 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4777 >            super(p, b, i, f, t);
4778              this.transformer = transformer; this.action = action;
4779          }
4780 <        @SuppressWarnings("unchecked") public final void compute() {
4780 >        public final void compute() {
4781              final Fun<? super V, ? extends U> transformer;
4782 <            final Action<U> action;
4782 >            final Action<? super U> action;
4783              if ((transformer = this.transformer) != null &&
4784                  (action = this.action) != null) {
4785 <                for (int b; (b = preSplit()) > 0;)
4785 >                for (int i = baseIndex, f, h; batch > 0 &&
4786 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4787 >                    addToPendingCount(1);
4788                      new ForEachTransformedValueTask<K,V,U>
4789 <                        (map, this, b, transformer, action).fork();
4790 <                V v; U u;
4791 <                while ((v = advance()) != null) {
4792 <                    if ((u = transformer.apply(v)) != null)
4789 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4790 >                         transformer, action).fork();
4791 >                }
4792 >                for (Node<K,V> p; (p = advance()) != null; ) {
4793 >                    U u;
4794 >                    if ((u = transformer.apply(p.val)) != null)
4795                          action.apply(u);
4796                  }
4797                  propagateCompletion();
# Line 5709 | Line 4799 | public class ConcurrentHashMapV8<K, V>
4799          }
4800      }
4801  
4802 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4803 <        extends Traverser<K,V,Void> {
4802 >    @SuppressWarnings("serial")
4803 >    static final class ForEachTransformedEntryTask<K,V,U>
4804 >        extends BulkTask<K,V,Void> {
4805          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4806 <        final Action<U> action;
4806 >        final Action<? super U> action;
4807          ForEachTransformedEntryTask
4808 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4809 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
4810 <            super(m, p, b);
4808 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4809 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4810 >            super(p, b, i, f, t);
4811              this.transformer = transformer; this.action = action;
4812          }
4813 <        @SuppressWarnings("unchecked") public final void compute() {
4813 >        public final void compute() {
4814              final Fun<Map.Entry<K,V>, ? extends U> transformer;
4815 <            final Action<U> action;
4815 >            final Action<? super U> action;
4816              if ((transformer = this.transformer) != null &&
4817                  (action = this.action) != null) {
4818 <                for (int b; (b = preSplit()) > 0;)
4818 >                for (int i = baseIndex, f, h; batch > 0 &&
4819 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4820 >                    addToPendingCount(1);
4821                      new ForEachTransformedEntryTask<K,V,U>
4822 <                        (map, this, b, transformer, action).fork();
4823 <                V v; U u;
4824 <                while ((v = advance()) != null) {
4825 <                    if ((u = transformer.apply(entryFor((K)nextKey,
4826 <                                                        v))) != null)
4822 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4823 >                         transformer, action).fork();
4824 >                }
4825 >                for (Node<K,V> p; (p = advance()) != null; ) {
4826 >                    U u;
4827 >                    if ((u = transformer.apply(p)) != null)
4828                          action.apply(u);
4829                  }
4830                  propagateCompletion();
# Line 5738 | Line 4832 | public class ConcurrentHashMapV8<K, V>
4832          }
4833      }
4834  
4835 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4836 <        extends Traverser<K,V,Void> {
4835 >    @SuppressWarnings("serial")
4836 >    static final class ForEachTransformedMappingTask<K,V,U>
4837 >        extends BulkTask<K,V,Void> {
4838          final BiFun<? super K, ? super V, ? extends U> transformer;
4839 <        final Action<U> action;
4839 >        final Action<? super U> action;
4840          ForEachTransformedMappingTask
4841 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4841 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4842               BiFun<? super K, ? super V, ? extends U> transformer,
4843 <             Action<U> action) {
4844 <            super(m, p, b);
4843 >             Action<? super U> action) {
4844 >            super(p, b, i, f, t);
4845              this.transformer = transformer; this.action = action;
4846          }
4847 <        @SuppressWarnings("unchecked") public final void compute() {
4847 >        public final void compute() {
4848              final BiFun<? super K, ? super V, ? extends U> transformer;
4849 <            final Action<U> action;
4849 >            final Action<? super U> action;
4850              if ((transformer = this.transformer) != null &&
4851                  (action = this.action) != null) {
4852 <                for (int b; (b = preSplit()) > 0;)
4852 >                for (int i = baseIndex, f, h; batch > 0 &&
4853 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4854 >                    addToPendingCount(1);
4855                      new ForEachTransformedMappingTask<K,V,U>
4856 <                        (map, this, b, transformer, action).fork();
4857 <                V v; U u;
4858 <                while ((v = advance()) != null) {
4859 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
4856 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4857 >                         transformer, action).fork();
4858 >                }
4859 >                for (Node<K,V> p; (p = advance()) != null; ) {
4860 >                    U u;
4861 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4862                          action.apply(u);
4863                  }
4864                  propagateCompletion();
# Line 5767 | Line 4866 | public class ConcurrentHashMapV8<K, V>
4866          }
4867      }
4868  
4869 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4870 <        extends Traverser<K,V,U> {
4869 >    @SuppressWarnings("serial")
4870 >    static final class SearchKeysTask<K,V,U>
4871 >        extends BulkTask<K,V,U> {
4872          final Fun<? super K, ? extends U> searchFunction;
4873          final AtomicReference<U> result;
4874          SearchKeysTask
4875 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4875 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4876               Fun<? super K, ? extends U> searchFunction,
4877               AtomicReference<U> result) {
4878 <            super(m, p, b);
4878 >            super(p, b, i, f, t);
4879              this.searchFunction = searchFunction; this.result = result;
4880          }
4881          public final U getRawResult() { return result.get(); }
4882 <        @SuppressWarnings("unchecked") public final void compute() {
4882 >        public final void compute() {
4883              final Fun<? super K, ? extends U> searchFunction;
4884              final AtomicReference<U> result;
4885              if ((searchFunction = this.searchFunction) != null &&
4886                  (result = this.result) != null) {
4887 <                for (int b;;) {
4887 >                for (int i = baseIndex, f, h; batch > 0 &&
4888 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4889                      if (result.get() != null)
4890                          return;
4891 <                    if ((b = preSplit()) <= 0)
5791 <                        break;
4891 >                    addToPendingCount(1);
4892                      new SearchKeysTask<K,V,U>
4893 <                        (map, this, b, searchFunction, result).fork();
4893 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4894 >                         searchFunction, result).fork();
4895                  }
4896                  while (result.get() == null) {
4897                      U u;
4898 <                    if (advance() == null) {
4898 >                    Node<K,V> p;
4899 >                    if ((p = advance()) == null) {
4900                          propagateCompletion();
4901                          break;
4902                      }
4903 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4903 >                    if ((u = searchFunction.apply(p.key)) != null) {
4904                          if (result.compareAndSet(null, u))
4905                              quietlyCompleteRoot();
4906                          break;
# Line 5808 | Line 4910 | public class ConcurrentHashMapV8<K, V>
4910          }
4911      }
4912  
4913 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4914 <        extends Traverser<K,V,U> {
4913 >    @SuppressWarnings("serial")
4914 >    static final class SearchValuesTask<K,V,U>
4915 >        extends BulkTask<K,V,U> {
4916          final Fun<? super V, ? extends U> searchFunction;
4917          final AtomicReference<U> result;
4918          SearchValuesTask
4919 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4919 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4920               Fun<? super V, ? extends U> searchFunction,
4921               AtomicReference<U> result) {
4922 <            super(m, p, b);
4922 >            super(p, b, i, f, t);
4923              this.searchFunction = searchFunction; this.result = result;
4924          }
4925          public final U getRawResult() { return result.get(); }
4926 <        @SuppressWarnings("unchecked") public final void compute() {
4926 >        public final void compute() {
4927              final Fun<? super V, ? extends U> searchFunction;
4928              final AtomicReference<U> result;
4929              if ((searchFunction = this.searchFunction) != null &&
4930                  (result = this.result) != null) {
4931 <                for (int b;;) {
4931 >                for (int i = baseIndex, f, h; batch > 0 &&
4932 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4933                      if (result.get() != null)
4934                          return;
4935 <                    if ((b = preSplit()) <= 0)
5832 <                        break;
4935 >                    addToPendingCount(1);
4936                      new SearchValuesTask<K,V,U>
4937 <                        (map, this, b, searchFunction, result).fork();
4937 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4938 >                         searchFunction, result).fork();
4939                  }
4940                  while (result.get() == null) {
4941 <                    V v; U u;
4942 <                    if ((v = advance()) == null) {
4941 >                    U u;
4942 >                    Node<K,V> p;
4943 >                    if ((p = advance()) == null) {
4944                          propagateCompletion();
4945                          break;
4946                      }
4947 <                    if ((u = searchFunction.apply(v)) != null) {
4947 >                    if ((u = searchFunction.apply(p.val)) != null) {
4948                          if (result.compareAndSet(null, u))
4949                              quietlyCompleteRoot();
4950                          break;
# Line 5849 | Line 4954 | public class ConcurrentHashMapV8<K, V>
4954          }
4955      }
4956  
4957 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4958 <        extends Traverser<K,V,U> {
4957 >    @SuppressWarnings("serial")
4958 >    static final class SearchEntriesTask<K,V,U>
4959 >        extends BulkTask<K,V,U> {
4960          final Fun<Entry<K,V>, ? extends U> searchFunction;
4961          final AtomicReference<U> result;
4962          SearchEntriesTask
4963 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4963 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4964               Fun<Entry<K,V>, ? extends U> searchFunction,
4965               AtomicReference<U> result) {
4966 <            super(m, p, b);
4966 >            super(p, b, i, f, t);
4967              this.searchFunction = searchFunction; this.result = result;
4968          }
4969          public final U getRawResult() { return result.get(); }
4970 <        @SuppressWarnings("unchecked") public final void compute() {
4970 >        public final void compute() {
4971              final Fun<Entry<K,V>, ? extends U> searchFunction;
4972              final AtomicReference<U> result;
4973              if ((searchFunction = this.searchFunction) != null &&
4974                  (result = this.result) != null) {
4975 <                for (int b;;) {
4975 >                for (int i = baseIndex, f, h; batch > 0 &&
4976 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4977                      if (result.get() != null)
4978                          return;
4979 <                    if ((b = preSplit()) <= 0)
5873 <                        break;
4979 >                    addToPendingCount(1);
4980                      new SearchEntriesTask<K,V,U>
4981 <                        (map, this, b, searchFunction, result).fork();
4981 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4982 >                         searchFunction, result).fork();
4983                  }
4984                  while (result.get() == null) {
4985 <                    V v; U u;
4986 <                    if ((v = advance()) == null) {
4985 >                    U u;
4986 >                    Node<K,V> p;
4987 >                    if ((p = advance()) == null) {
4988                          propagateCompletion();
4989                          break;
4990                      }
4991 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5884 <                                                           v))) != null) {
4991 >                    if ((u = searchFunction.apply(p)) != null) {
4992                          if (result.compareAndSet(null, u))
4993                              quietlyCompleteRoot();
4994                          return;
# Line 5891 | Line 4998 | public class ConcurrentHashMapV8<K, V>
4998          }
4999      }
5000  
5001 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5002 <        extends Traverser<K,V,U> {
5001 >    @SuppressWarnings("serial")
5002 >    static final class SearchMappingsTask<K,V,U>
5003 >        extends BulkTask<K,V,U> {
5004          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5005          final AtomicReference<U> result;
5006          SearchMappingsTask
5007 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5007 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5008               BiFun<? super K, ? super V, ? extends U> searchFunction,
5009               AtomicReference<U> result) {
5010 <            super(m, p, b);
5010 >            super(p, b, i, f, t);
5011              this.searchFunction = searchFunction; this.result = result;
5012          }
5013          public final U getRawResult() { return result.get(); }
5014 <        @SuppressWarnings("unchecked") public final void compute() {
5014 >        public final void compute() {
5015              final BiFun<? super K, ? super V, ? extends U> searchFunction;
5016              final AtomicReference<U> result;
5017              if ((searchFunction = this.searchFunction) != null &&
5018                  (result = this.result) != null) {
5019 <                for (int b;;) {
5019 >                for (int i = baseIndex, f, h; batch > 0 &&
5020 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5021                      if (result.get() != null)
5022                          return;
5023 <                    if ((b = preSplit()) <= 0)
5915 <                        break;
5023 >                    addToPendingCount(1);
5024                      new SearchMappingsTask<K,V,U>
5025 <                        (map, this, b, searchFunction, result).fork();
5025 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5026 >                         searchFunction, result).fork();
5027                  }
5028                  while (result.get() == null) {
5029 <                    V v; U u;
5030 <                    if ((v = advance()) == null) {
5029 >                    U u;
5030 >                    Node<K,V> p;
5031 >                    if ((p = advance()) == null) {
5032                          propagateCompletion();
5033                          break;
5034                      }
5035 <                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5035 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5036                          if (result.compareAndSet(null, u))
5037                              quietlyCompleteRoot();
5038                          break;
# Line 5932 | Line 5042 | public class ConcurrentHashMapV8<K, V>
5042          }
5043      }
5044  
5045 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5046 <        extends Traverser<K,V,K> {
5045 >    @SuppressWarnings("serial")
5046 >    static final class ReduceKeysTask<K,V>
5047 >        extends BulkTask<K,V,K> {
5048          final BiFun<? super K, ? super K, ? extends K> reducer;
5049          K result;
5050          ReduceKeysTask<K,V> rights, nextRight;
5051          ReduceKeysTask
5052 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5052 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5053               ReduceKeysTask<K,V> nextRight,
5054               BiFun<? super K, ? super K, ? extends K> reducer) {
5055 <            super(m, p, b); this.nextRight = nextRight;
5055 >            super(p, b, i, f, t); this.nextRight = nextRight;
5056              this.reducer = reducer;
5057          }
5058          public final K getRawResult() { return result; }
5059 <        @SuppressWarnings("unchecked") public final void compute() {
5059 >        public final void compute() {
5060              final BiFun<? super K, ? super K, ? extends K> reducer;
5061              if ((reducer = this.reducer) != null) {
5062 <                for (int b; (b = preSplit()) > 0;)
5062 >                for (int i = baseIndex, f, h; batch > 0 &&
5063 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5064 >                    addToPendingCount(1);
5065                      (rights = new ReduceKeysTask<K,V>
5066 <                     (map, this, b, rights, reducer)).fork();
5066 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5067 >                      rights, reducer)).fork();
5068 >                }
5069                  K r = null;
5070 <                while (advance() != null) {
5071 <                    K u = (K)nextKey;
5072 <                    r = (r == null) ? u : reducer.apply(r, u);
5070 >                for (Node<K,V> p; (p = advance()) != null; ) {
5071 >                    K u = p.key;
5072 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5073                  }
5074                  result = r;
5075                  CountedCompleter<?> c;
5076                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5077 <                    ReduceKeysTask<K,V>
5077 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5078                          t = (ReduceKeysTask<K,V>)c,
5079                          s = t.rights;
5080                      while (s != null) {
# Line 5974 | Line 5089 | public class ConcurrentHashMapV8<K, V>
5089          }
5090      }
5091  
5092 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5093 <        extends Traverser<K,V,V> {
5092 >    @SuppressWarnings("serial")
5093 >    static final class ReduceValuesTask<K,V>
5094 >        extends BulkTask<K,V,V> {
5095          final BiFun<? super V, ? super V, ? extends V> reducer;
5096          V result;
5097          ReduceValuesTask<K,V> rights, nextRight;
5098          ReduceValuesTask
5099 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5099 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5100               ReduceValuesTask<K,V> nextRight,
5101               BiFun<? super V, ? super V, ? extends V> reducer) {
5102 <            super(m, p, b); this.nextRight = nextRight;
5102 >            super(p, b, i, f, t); this.nextRight = nextRight;
5103              this.reducer = reducer;
5104          }
5105          public final V getRawResult() { return result; }
5106 <        @SuppressWarnings("unchecked") public final void compute() {
5106 >        public final void compute() {
5107              final BiFun<? super V, ? super V, ? extends V> reducer;
5108              if ((reducer = this.reducer) != null) {
5109 <                for (int b; (b = preSplit()) > 0;)
5109 >                for (int i = baseIndex, f, h; batch > 0 &&
5110 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5111 >                    addToPendingCount(1);
5112                      (rights = new ReduceValuesTask<K,V>
5113 <                     (map, this, b, rights, reducer)).fork();
5113 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5114 >                      rights, reducer)).fork();
5115 >                }
5116                  V r = null;
5117 <                V v;
5118 <                while ((v = advance()) != null) {
5119 <                    V u = v;
6000 <                    r = (r == null) ? u : reducer.apply(r, u);
5117 >                for (Node<K,V> p; (p = advance()) != null; ) {
5118 >                    V v = p.val;
5119 >                    r = (r == null) ? v : reducer.apply(r, v);
5120                  }
5121                  result = r;
5122                  CountedCompleter<?> c;
5123                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5124 <                    ReduceValuesTask<K,V>
5124 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5125                          t = (ReduceValuesTask<K,V>)c,
5126                          s = t.rights;
5127                      while (s != null) {
# Line 6017 | Line 5136 | public class ConcurrentHashMapV8<K, V>
5136          }
5137      }
5138  
5139 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5140 <        extends Traverser<K,V,Map.Entry<K,V>> {
5139 >    @SuppressWarnings("serial")
5140 >    static final class ReduceEntriesTask<K,V>
5141 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5142          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5143          Map.Entry<K,V> result;
5144          ReduceEntriesTask<K,V> rights, nextRight;
5145          ReduceEntriesTask
5146 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5146 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5147               ReduceEntriesTask<K,V> nextRight,
5148               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5149 <            super(m, p, b); this.nextRight = nextRight;
5149 >            super(p, b, i, f, t); this.nextRight = nextRight;
5150              this.reducer = reducer;
5151          }
5152          public final Map.Entry<K,V> getRawResult() { return result; }
5153 <        @SuppressWarnings("unchecked") public final void compute() {
5153 >        public final void compute() {
5154              final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5155              if ((reducer = this.reducer) != null) {
5156 <                for (int b; (b = preSplit()) > 0;)
5156 >                for (int i = baseIndex, f, h; batch > 0 &&
5157 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5158 >                    addToPendingCount(1);
5159                      (rights = new ReduceEntriesTask<K,V>
5160 <                     (map, this, b, rights, reducer)).fork();
5161 <                Map.Entry<K,V> r = null;
6040 <                V v;
6041 <                while ((v = advance()) != null) {
6042 <                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6043 <                    r = (r == null) ? u : reducer.apply(r, u);
5160 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5161 >                      rights, reducer)).fork();
5162                  }
5163 +                Map.Entry<K,V> r = null;
5164 +                for (Node<K,V> p; (p = advance()) != null; )
5165 +                    r = (r == null) ? p : reducer.apply(r, p);
5166                  result = r;
5167                  CountedCompleter<?> c;
5168                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5169 <                    ReduceEntriesTask<K,V>
5169 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5170                          t = (ReduceEntriesTask<K,V>)c,
5171                          s = t.rights;
5172                      while (s != null) {
# Line 6060 | Line 5181 | public class ConcurrentHashMapV8<K, V>
5181          }
5182      }
5183  
5184 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5185 <        extends Traverser<K,V,U> {
5184 >    @SuppressWarnings("serial")
5185 >    static final class MapReduceKeysTask<K,V,U>
5186 >        extends BulkTask<K,V,U> {
5187          final Fun<? super K, ? extends U> transformer;
5188          final BiFun<? super U, ? super U, ? extends U> reducer;
5189          U result;
5190          MapReduceKeysTask<K,V,U> rights, nextRight;
5191          MapReduceKeysTask
5192 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5192 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5193               MapReduceKeysTask<K,V,U> nextRight,
5194               Fun<? super K, ? extends U> transformer,
5195               BiFun<? super U, ? super U, ? extends U> reducer) {
5196 <            super(m, p, b); this.nextRight = nextRight;
5196 >            super(p, b, i, f, t); this.nextRight = nextRight;
5197              this.transformer = transformer;
5198              this.reducer = reducer;
5199          }
5200          public final U getRawResult() { return result; }
5201 <        @SuppressWarnings("unchecked") public final void compute() {
5201 >        public final void compute() {
5202              final Fun<? super K, ? extends U> transformer;
5203              final BiFun<? super U, ? super U, ? extends U> reducer;
5204              if ((transformer = this.transformer) != null &&
5205                  (reducer = this.reducer) != null) {
5206 <                for (int b; (b = preSplit()) > 0;)
5206 >                for (int i = baseIndex, f, h; batch > 0 &&
5207 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5208 >                    addToPendingCount(1);
5209                      (rights = new MapReduceKeysTask<K,V,U>
5210 <                     (map, this, b, rights, transformer, reducer)).fork();
5211 <                U r = null, u;
5212 <                while (advance() != null) {
5213 <                    if ((u = transformer.apply((K)nextKey)) != null)
5210 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5211 >                      rights, transformer, reducer)).fork();
5212 >                }
5213 >                U r = null;
5214 >                for (Node<K,V> p; (p = advance()) != null; ) {
5215 >                    U u;
5216 >                    if ((u = transformer.apply(p.key)) != null)
5217                          r = (r == null) ? u : reducer.apply(r, u);
5218                  }
5219                  result = r;
5220                  CountedCompleter<?> c;
5221                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5222 <                    MapReduceKeysTask<K,V,U>
5222 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5223                          t = (MapReduceKeysTask<K,V,U>)c,
5224                          s = t.rights;
5225                      while (s != null) {
# Line 6107 | Line 5234 | public class ConcurrentHashMapV8<K, V>
5234          }
5235      }
5236  
5237 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5238 <        extends Traverser<K,V,U> {
5237 >    @SuppressWarnings("serial")
5238 >    static final class MapReduceValuesTask<K,V,U>
5239 >        extends BulkTask<K,V,U> {
5240          final Fun<? super V, ? extends U> transformer;
5241          final BiFun<? super U, ? super U, ? extends U> reducer;
5242          U result;
5243          MapReduceValuesTask<K,V,U> rights, nextRight;
5244          MapReduceValuesTask
5245 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5245 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5246               MapReduceValuesTask<K,V,U> nextRight,
5247               Fun<? super V, ? extends U> transformer,
5248               BiFun<? super U, ? super U, ? extends U> reducer) {
5249 <            super(m, p, b); this.nextRight = nextRight;
5249 >            super(p, b, i, f, t); this.nextRight = nextRight;
5250              this.transformer = transformer;
5251              this.reducer = reducer;
5252          }
5253          public final U getRawResult() { return result; }
5254 <        @SuppressWarnings("unchecked") public final void compute() {
5254 >        public final void compute() {
5255              final Fun<? super V, ? extends U> transformer;
5256              final BiFun<? super U, ? super U, ? extends U> reducer;
5257              if ((transformer = this.transformer) != null &&
5258                  (reducer = this.reducer) != null) {
5259 <                for (int b; (b = preSplit()) > 0;)
5259 >                for (int i = baseIndex, f, h; batch > 0 &&
5260 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5261 >                    addToPendingCount(1);
5262                      (rights = new MapReduceValuesTask<K,V,U>
5263 <                     (map, this, b, rights, transformer, reducer)).fork();
5264 <                U r = null, u;
5265 <                V v;
5266 <                while ((v = advance()) != null) {
5267 <                    if ((u = transformer.apply(v)) != null)
5263 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5264 >                      rights, transformer, reducer)).fork();
5265 >                }
5266 >                U r = null;
5267 >                for (Node<K,V> p; (p = advance()) != null; ) {
5268 >                    U u;
5269 >                    if ((u = transformer.apply(p.val)) != null)
5270                          r = (r == null) ? u : reducer.apply(r, u);
5271                  }
5272                  result = r;
5273                  CountedCompleter<?> c;
5274                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5275 <                    MapReduceValuesTask<K,V,U>
5275 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5276                          t = (MapReduceValuesTask<K,V,U>)c,
5277                          s = t.rights;
5278                      while (s != null) {
# Line 6155 | Line 5287 | public class ConcurrentHashMapV8<K, V>
5287          }
5288      }
5289  
5290 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5291 <        extends Traverser<K,V,U> {
5290 >    @SuppressWarnings("serial")
5291 >    static final class MapReduceEntriesTask<K,V,U>
5292 >        extends BulkTask<K,V,U> {
5293          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5294          final BiFun<? super U, ? super U, ? extends U> reducer;
5295          U result;
5296          MapReduceEntriesTask<K,V,U> rights, nextRight;
5297          MapReduceEntriesTask
5298 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5298 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5299               MapReduceEntriesTask<K,V,U> nextRight,
5300               Fun<Map.Entry<K,V>, ? extends U> transformer,
5301               BiFun<? super U, ? super U, ? extends U> reducer) {
5302 <            super(m, p, b); this.nextRight = nextRight;
5302 >            super(p, b, i, f, t); this.nextRight = nextRight;
5303              this.transformer = transformer;
5304              this.reducer = reducer;
5305          }
5306          public final U getRawResult() { return result; }
5307 <        @SuppressWarnings("unchecked") public final void compute() {
5307 >        public final void compute() {
5308              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5309              final BiFun<? super U, ? super U, ? extends U> reducer;
5310              if ((transformer = this.transformer) != null &&
5311                  (reducer = this.reducer) != null) {
5312 <                for (int b; (b = preSplit()) > 0;)
5312 >                for (int i = baseIndex, f, h; batch > 0 &&
5313 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5314 >                    addToPendingCount(1);
5315                      (rights = new MapReduceEntriesTask<K,V,U>
5316 <                     (map, this, b, rights, transformer, reducer)).fork();
5317 <                U r = null, u;
5318 <                V v;
5319 <                while ((v = advance()) != null) {
5320 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5321 <                                                        v))) != null)
5316 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5317 >                      rights, transformer, reducer)).fork();
5318 >                }
5319 >                U r = null;
5320 >                for (Node<K,V> p; (p = advance()) != null; ) {
5321 >                    U u;
5322 >                    if ((u = transformer.apply(p)) != null)
5323                          r = (r == null) ? u : reducer.apply(r, u);
5324                  }
5325                  result = r;
5326                  CountedCompleter<?> c;
5327                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5328 <                    MapReduceEntriesTask<K,V,U>
5328 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5329                          t = (MapReduceEntriesTask<K,V,U>)c,
5330                          s = t.rights;
5331                      while (s != null) {
# Line 6204 | Line 5340 | public class ConcurrentHashMapV8<K, V>
5340          }
5341      }
5342  
5343 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5344 <        extends Traverser<K,V,U> {
5343 >    @SuppressWarnings("serial")
5344 >    static final class MapReduceMappingsTask<K,V,U>
5345 >        extends BulkTask<K,V,U> {
5346          final BiFun<? super K, ? super V, ? extends U> transformer;
5347          final BiFun<? super U, ? super U, ? extends U> reducer;
5348          U result;
5349          MapReduceMappingsTask<K,V,U> rights, nextRight;
5350          MapReduceMappingsTask
5351 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5351 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5352               MapReduceMappingsTask<K,V,U> nextRight,
5353               BiFun<? super K, ? super V, ? extends U> transformer,
5354               BiFun<? super U, ? super U, ? extends U> reducer) {
5355 <            super(m, p, b); this.nextRight = nextRight;
5355 >            super(p, b, i, f, t); this.nextRight = nextRight;
5356              this.transformer = transformer;
5357              this.reducer = reducer;
5358          }
5359          public final U getRawResult() { return result; }
5360 <        @SuppressWarnings("unchecked") public final void compute() {
5360 >        public final void compute() {
5361              final BiFun<? super K, ? super V, ? extends U> transformer;
5362              final BiFun<? super U, ? super U, ? extends U> reducer;
5363              if ((transformer = this.transformer) != null &&
5364                  (reducer = this.reducer) != null) {
5365 <                for (int b; (b = preSplit()) > 0;)
5365 >                for (int i = baseIndex, f, h; batch > 0 &&
5366 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5367 >                    addToPendingCount(1);
5368                      (rights = new MapReduceMappingsTask<K,V,U>
5369 <                     (map, this, b, rights, transformer, reducer)).fork();
5370 <                U r = null, u;
5371 <                V v;
5372 <                while ((v = advance()) != null) {
5373 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5369 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5370 >                      rights, transformer, reducer)).fork();
5371 >                }
5372 >                U r = null;
5373 >                for (Node<K,V> p; (p = advance()) != null; ) {
5374 >                    U u;
5375 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5376                          r = (r == null) ? u : reducer.apply(r, u);
5377                  }
5378                  result = r;
5379                  CountedCompleter<?> c;
5380                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5381 <                    MapReduceMappingsTask<K,V,U>
5381 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5382                          t = (MapReduceMappingsTask<K,V,U>)c,
5383                          s = t.rights;
5384                      while (s != null) {
# Line 6252 | Line 5393 | public class ConcurrentHashMapV8<K, V>
5393          }
5394      }
5395  
5396 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5397 <        extends Traverser<K,V,Double> {
5396 >    @SuppressWarnings("serial")
5397 >    static final class MapReduceKeysToDoubleTask<K,V>
5398 >        extends BulkTask<K,V,Double> {
5399          final ObjectToDouble<? super K> transformer;
5400          final DoubleByDoubleToDouble reducer;
5401          final double basis;
5402          double result;
5403          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5404          MapReduceKeysToDoubleTask
5405 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5405 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5406               MapReduceKeysToDoubleTask<K,V> nextRight,
5407               ObjectToDouble<? super K> transformer,
5408               double basis,
5409               DoubleByDoubleToDouble reducer) {
5410 <            super(m, p, b); this.nextRight = nextRight;
5410 >            super(p, b, i, f, t); this.nextRight = nextRight;
5411              this.transformer = transformer;
5412              this.basis = basis; this.reducer = reducer;
5413          }
5414          public final Double getRawResult() { return result; }
5415 <        @SuppressWarnings("unchecked") public final void compute() {
5415 >        public final void compute() {
5416              final ObjectToDouble<? super K> transformer;
5417              final DoubleByDoubleToDouble reducer;
5418              if ((transformer = this.transformer) != null &&
5419                  (reducer = this.reducer) != null) {
5420                  double r = this.basis;
5421 <                for (int b; (b = preSplit()) > 0;)
5421 >                for (int i = baseIndex, f, h; batch > 0 &&
5422 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5423 >                    addToPendingCount(1);
5424                      (rights = new MapReduceKeysToDoubleTask<K,V>
5425 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5426 <                while (advance() != null)
5427 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5425 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5426 >                      rights, transformer, r, reducer)).fork();
5427 >                }
5428 >                for (Node<K,V> p; (p = advance()) != null; )
5429 >                    r = reducer.apply(r, transformer.apply(p.key));
5430                  result = r;
5431                  CountedCompleter<?> c;
5432                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5433 <                    MapReduceKeysToDoubleTask<K,V>
5433 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5434                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5435                          s = t.rights;
5436                      while (s != null) {
# Line 6296 | Line 5442 | public class ConcurrentHashMapV8<K, V>
5442          }
5443      }
5444  
5445 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5446 <        extends Traverser<K,V,Double> {
5445 >    @SuppressWarnings("serial")
5446 >    static final class MapReduceValuesToDoubleTask<K,V>
5447 >        extends BulkTask<K,V,Double> {
5448          final ObjectToDouble<? super V> transformer;
5449          final DoubleByDoubleToDouble reducer;
5450          final double basis;
5451          double result;
5452          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5453          MapReduceValuesToDoubleTask
5454 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5454 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5455               MapReduceValuesToDoubleTask<K,V> nextRight,
5456               ObjectToDouble<? super V> transformer,
5457               double basis,
5458               DoubleByDoubleToDouble reducer) {
5459 <            super(m, p, b); this.nextRight = nextRight;
5459 >            super(p, b, i, f, t); this.nextRight = nextRight;
5460              this.transformer = transformer;
5461              this.basis = basis; this.reducer = reducer;
5462          }
5463          public final Double getRawResult() { return result; }
5464 <        @SuppressWarnings("unchecked") public final void compute() {
5464 >        public final void compute() {
5465              final ObjectToDouble<? super V> transformer;
5466              final DoubleByDoubleToDouble reducer;
5467              if ((transformer = this.transformer) != null &&
5468                  (reducer = this.reducer) != null) {
5469                  double r = this.basis;
5470 <                for (int b; (b = preSplit()) > 0;)
5470 >                for (int i = baseIndex, f, h; batch > 0 &&
5471 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5472 >                    addToPendingCount(1);
5473                      (rights = new MapReduceValuesToDoubleTask<K,V>
5474 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5475 <                V v;
5476 <                while ((v = advance()) != null)
5477 <                    r = reducer.apply(r, transformer.apply(v));
5474 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5475 >                      rights, transformer, r, reducer)).fork();
5476 >                }
5477 >                for (Node<K,V> p; (p = advance()) != null; )
5478 >                    r = reducer.apply(r, transformer.apply(p.val));
5479                  result = r;
5480                  CountedCompleter<?> c;
5481                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5482 <                    MapReduceValuesToDoubleTask<K,V>
5482 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5483                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5484                          s = t.rights;
5485                      while (s != null) {
# Line 6341 | Line 5491 | public class ConcurrentHashMapV8<K, V>
5491          }
5492      }
5493  
5494 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5495 <        extends Traverser<K,V,Double> {
5494 >    @SuppressWarnings("serial")
5495 >    static final class MapReduceEntriesToDoubleTask<K,V>
5496 >        extends BulkTask<K,V,Double> {
5497          final ObjectToDouble<Map.Entry<K,V>> transformer;
5498          final DoubleByDoubleToDouble reducer;
5499          final double basis;
5500          double result;
5501          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5502          MapReduceEntriesToDoubleTask
5503 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5503 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5504               MapReduceEntriesToDoubleTask<K,V> nextRight,
5505               ObjectToDouble<Map.Entry<K,V>> transformer,
5506               double basis,
5507               DoubleByDoubleToDouble reducer) {
5508 <            super(m, p, b); this.nextRight = nextRight;
5508 >            super(p, b, i, f, t); this.nextRight = nextRight;
5509              this.transformer = transformer;
5510              this.basis = basis; this.reducer = reducer;
5511          }
5512          public final Double getRawResult() { return result; }
5513 <        @SuppressWarnings("unchecked") public final void compute() {
5513 >        public final void compute() {
5514              final ObjectToDouble<Map.Entry<K,V>> transformer;
5515              final DoubleByDoubleToDouble reducer;
5516              if ((transformer = this.transformer) != null &&
5517                  (reducer = this.reducer) != null) {
5518                  double r = this.basis;
5519 <                for (int b; (b = preSplit()) > 0;)
5519 >                for (int i = baseIndex, f, h; batch > 0 &&
5520 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5521 >                    addToPendingCount(1);
5522                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5523 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5524 <                V v;
5525 <                while ((v = advance()) != null)
5526 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5527 <                                                                    v)));
5523 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5524 >                      rights, transformer, r, reducer)).fork();
5525 >                }
5526 >                for (Node<K,V> p; (p = advance()) != null; )
5527 >                    r = reducer.apply(r, transformer.apply(p));
5528                  result = r;
5529                  CountedCompleter<?> c;
5530                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5531 <                    MapReduceEntriesToDoubleTask<K,V>
5531 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5532                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5533                          s = t.rights;
5534                      while (s != null) {
# Line 6387 | Line 5540 | public class ConcurrentHashMapV8<K, V>
5540          }
5541      }
5542  
5543 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5544 <        extends Traverser<K,V,Double> {
5543 >    @SuppressWarnings("serial")
5544 >    static final class MapReduceMappingsToDoubleTask<K,V>
5545 >        extends BulkTask<K,V,Double> {
5546          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5547          final DoubleByDoubleToDouble reducer;
5548          final double basis;
5549          double result;
5550          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5551          MapReduceMappingsToDoubleTask
5552 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5552 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5553               MapReduceMappingsToDoubleTask<K,V> nextRight,
5554               ObjectByObjectToDouble<? super K, ? super V> transformer,
5555               double basis,
5556               DoubleByDoubleToDouble reducer) {
5557 <            super(m, p, b); this.nextRight = nextRight;
5557 >            super(p, b, i, f, t); this.nextRight = nextRight;
5558              this.transformer = transformer;
5559              this.basis = basis; this.reducer = reducer;
5560          }
5561          public final Double getRawResult() { return result; }
5562 <        @SuppressWarnings("unchecked") public final void compute() {
5562 >        public final void compute() {
5563              final ObjectByObjectToDouble<? super K, ? super V> transformer;
5564              final DoubleByDoubleToDouble reducer;
5565              if ((transformer = this.transformer) != null &&
5566                  (reducer = this.reducer) != null) {
5567                  double r = this.basis;
5568 <                for (int b; (b = preSplit()) > 0;)
5568 >                for (int i = baseIndex, f, h; batch > 0 &&
5569 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5570 >                    addToPendingCount(1);
5571                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5572 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5573 <                V v;
5574 <                while ((v = advance()) != null)
5575 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5572 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5573 >                      rights, transformer, r, reducer)).fork();
5574 >                }
5575 >                for (Node<K,V> p; (p = advance()) != null; )
5576 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5577                  result = r;
5578                  CountedCompleter<?> c;
5579                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5580 <                    MapReduceMappingsToDoubleTask<K,V>
5580 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5581                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5582                          s = t.rights;
5583                      while (s != null) {
# Line 6432 | Line 5589 | public class ConcurrentHashMapV8<K, V>
5589          }
5590      }
5591  
5592 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5593 <        extends Traverser<K,V,Long> {
5592 >    @SuppressWarnings("serial")
5593 >    static final class MapReduceKeysToLongTask<K,V>
5594 >        extends BulkTask<K,V,Long> {
5595          final ObjectToLong<? super K> transformer;
5596          final LongByLongToLong reducer;
5597          final long basis;
5598          long result;
5599          MapReduceKeysToLongTask<K,V> rights, nextRight;
5600          MapReduceKeysToLongTask
5601 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5601 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5602               MapReduceKeysToLongTask<K,V> nextRight,
5603               ObjectToLong<? super K> transformer,
5604               long basis,
5605               LongByLongToLong reducer) {
5606 <            super(m, p, b); this.nextRight = nextRight;
5606 >            super(p, b, i, f, t); this.nextRight = nextRight;
5607              this.transformer = transformer;
5608              this.basis = basis; this.reducer = reducer;
5609          }
5610          public final Long getRawResult() { return result; }
5611 <        @SuppressWarnings("unchecked") public final void compute() {
5611 >        public final void compute() {
5612              final ObjectToLong<? super K> transformer;
5613              final LongByLongToLong reducer;
5614              if ((transformer = this.transformer) != null &&
5615                  (reducer = this.reducer) != null) {
5616                  long r = this.basis;
5617 <                for (int b; (b = preSplit()) > 0;)
5617 >                for (int i = baseIndex, f, h; batch > 0 &&
5618 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5619 >                    addToPendingCount(1);
5620                      (rights = new MapReduceKeysToLongTask<K,V>
5621 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5622 <                while (advance() != null)
5623 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5621 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5622 >                      rights, transformer, r, reducer)).fork();
5623 >                }
5624 >                for (Node<K,V> p; (p = advance()) != null; )
5625 >                    r = reducer.apply(r, transformer.apply(p.key));
5626                  result = r;
5627                  CountedCompleter<?> c;
5628                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5629 <                    MapReduceKeysToLongTask<K,V>
5629 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5630                          t = (MapReduceKeysToLongTask<K,V>)c,
5631                          s = t.rights;
5632                      while (s != null) {
# Line 6476 | Line 5638 | public class ConcurrentHashMapV8<K, V>
5638          }
5639      }
5640  
5641 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5642 <        extends Traverser<K,V,Long> {
5641 >    @SuppressWarnings("serial")
5642 >    static final class MapReduceValuesToLongTask<K,V>
5643 >        extends BulkTask<K,V,Long> {
5644          final ObjectToLong<? super V> transformer;
5645          final LongByLongToLong reducer;
5646          final long basis;
5647          long result;
5648          MapReduceValuesToLongTask<K,V> rights, nextRight;
5649          MapReduceValuesToLongTask
5650 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5650 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5651               MapReduceValuesToLongTask<K,V> nextRight,
5652               ObjectToLong<? super V> transformer,
5653               long basis,
5654               LongByLongToLong reducer) {
5655 <            super(m, p, b); this.nextRight = nextRight;
5655 >            super(p, b, i, f, t); this.nextRight = nextRight;
5656              this.transformer = transformer;
5657              this.basis = basis; this.reducer = reducer;
5658          }
5659          public final Long getRawResult() { return result; }
5660 <        @SuppressWarnings("unchecked") public final void compute() {
5660 >        public final void compute() {
5661              final ObjectToLong<? super V> transformer;
5662              final LongByLongToLong reducer;
5663              if ((transformer = this.transformer) != null &&
5664                  (reducer = this.reducer) != null) {
5665                  long r = this.basis;
5666 <                for (int b; (b = preSplit()) > 0;)
5666 >                for (int i = baseIndex, f, h; batch > 0 &&
5667 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5668 >                    addToPendingCount(1);
5669                      (rights = new MapReduceValuesToLongTask<K,V>
5670 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5671 <                V v;
5672 <                while ((v = advance()) != null)
5673 <                    r = reducer.apply(r, transformer.apply(v));
5670 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5671 >                      rights, transformer, r, reducer)).fork();
5672 >                }
5673 >                for (Node<K,V> p; (p = advance()) != null; )
5674 >                    r = reducer.apply(r, transformer.apply(p.val));
5675                  result = r;
5676                  CountedCompleter<?> c;
5677                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5678 <                    MapReduceValuesToLongTask<K,V>
5678 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5679                          t = (MapReduceValuesToLongTask<K,V>)c,
5680                          s = t.rights;
5681                      while (s != null) {
# Line 6521 | Line 5687 | public class ConcurrentHashMapV8<K, V>
5687          }
5688      }
5689  
5690 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5691 <        extends Traverser<K,V,Long> {
5690 >    @SuppressWarnings("serial")
5691 >    static final class MapReduceEntriesToLongTask<K,V>
5692 >        extends BulkTask<K,V,Long> {
5693          final ObjectToLong<Map.Entry<K,V>> transformer;
5694          final LongByLongToLong reducer;
5695          final long basis;
5696          long result;
5697          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5698          MapReduceEntriesToLongTask
5699 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5699 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5700               MapReduceEntriesToLongTask<K,V> nextRight,
5701               ObjectToLong<Map.Entry<K,V>> transformer,
5702               long basis,
5703               LongByLongToLong reducer) {
5704 <            super(m, p, b); this.nextRight = nextRight;
5704 >            super(p, b, i, f, t); this.nextRight = nextRight;
5705              this.transformer = transformer;
5706              this.basis = basis; this.reducer = reducer;
5707          }
5708          public final Long getRawResult() { return result; }
5709 <        @SuppressWarnings("unchecked") public final void compute() {
5709 >        public final void compute() {
5710              final ObjectToLong<Map.Entry<K,V>> transformer;
5711              final LongByLongToLong reducer;
5712              if ((transformer = this.transformer) != null &&
5713                  (reducer = this.reducer) != null) {
5714                  long r = this.basis;
5715 <                for (int b; (b = preSplit()) > 0;)
5715 >                for (int i = baseIndex, f, h; batch > 0 &&
5716 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5717 >                    addToPendingCount(1);
5718                      (rights = new MapReduceEntriesToLongTask<K,V>
5719 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5720 <                V v;
5721 <                while ((v = advance()) != null)
5722 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5723 <                                                                    v)));
5719 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5720 >                      rights, transformer, r, reducer)).fork();
5721 >                }
5722 >                for (Node<K,V> p; (p = advance()) != null; )
5723 >                    r = reducer.apply(r, transformer.apply(p));
5724                  result = r;
5725                  CountedCompleter<?> c;
5726                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5727 <                    MapReduceEntriesToLongTask<K,V>
5727 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5728                          t = (MapReduceEntriesToLongTask<K,V>)c,
5729                          s = t.rights;
5730                      while (s != null) {
# Line 6567 | Line 5736 | public class ConcurrentHashMapV8<K, V>
5736          }
5737      }
5738  
5739 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5740 <        extends Traverser<K,V,Long> {
5739 >    @SuppressWarnings("serial")
5740 >    static final class MapReduceMappingsToLongTask<K,V>
5741 >        extends BulkTask<K,V,Long> {
5742          final ObjectByObjectToLong<? super K, ? super V> transformer;
5743          final LongByLongToLong reducer;
5744          final long basis;
5745          long result;
5746          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5747          MapReduceMappingsToLongTask
5748 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5748 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5749               MapReduceMappingsToLongTask<K,V> nextRight,
5750               ObjectByObjectToLong<? super K, ? super V> transformer,
5751               long basis,
5752               LongByLongToLong reducer) {
5753 <            super(m, p, b); this.nextRight = nextRight;
5753 >            super(p, b, i, f, t); this.nextRight = nextRight;
5754              this.transformer = transformer;
5755              this.basis = basis; this.reducer = reducer;
5756          }
5757          public final Long getRawResult() { return result; }
5758 <        @SuppressWarnings("unchecked") public final void compute() {
5758 >        public final void compute() {
5759              final ObjectByObjectToLong<? super K, ? super V> transformer;
5760              final LongByLongToLong reducer;
5761              if ((transformer = this.transformer) != null &&
5762                  (reducer = this.reducer) != null) {
5763                  long r = this.basis;
5764 <                for (int b; (b = preSplit()) > 0;)
5764 >                for (int i = baseIndex, f, h; batch > 0 &&
5765 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5766 >                    addToPendingCount(1);
5767                      (rights = new MapReduceMappingsToLongTask<K,V>
5768 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5769 <                V v;
5770 <                while ((v = advance()) != null)
5771 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5768 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5769 >                      rights, transformer, r, reducer)).fork();
5770 >                }
5771 >                for (Node<K,V> p; (p = advance()) != null; )
5772 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5773                  result = r;
5774                  CountedCompleter<?> c;
5775                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5776 <                    MapReduceMappingsToLongTask<K,V>
5776 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5777                          t = (MapReduceMappingsToLongTask<K,V>)c,
5778                          s = t.rights;
5779                      while (s != null) {
# Line 6612 | Line 5785 | public class ConcurrentHashMapV8<K, V>
5785          }
5786      }
5787  
5788 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5789 <        extends Traverser<K,V,Integer> {
5788 >    @SuppressWarnings("serial")
5789 >    static final class MapReduceKeysToIntTask<K,V>
5790 >        extends BulkTask<K,V,Integer> {
5791          final ObjectToInt<? super K> transformer;
5792          final IntByIntToInt reducer;
5793          final int basis;
5794          int result;
5795          MapReduceKeysToIntTask<K,V> rights, nextRight;
5796          MapReduceKeysToIntTask
5797 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5797 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5798               MapReduceKeysToIntTask<K,V> nextRight,
5799               ObjectToInt<? super K> transformer,
5800               int basis,
5801               IntByIntToInt reducer) {
5802 <            super(m, p, b); this.nextRight = nextRight;
5802 >            super(p, b, i, f, t); this.nextRight = nextRight;
5803              this.transformer = transformer;
5804              this.basis = basis; this.reducer = reducer;
5805          }
5806          public final Integer getRawResult() { return result; }
5807 <        @SuppressWarnings("unchecked") public final void compute() {
5807 >        public final void compute() {
5808              final ObjectToInt<? super K> transformer;
5809              final IntByIntToInt reducer;
5810              if ((transformer = this.transformer) != null &&
5811                  (reducer = this.reducer) != null) {
5812                  int r = this.basis;
5813 <                for (int b; (b = preSplit()) > 0;)
5813 >                for (int i = baseIndex, f, h; batch > 0 &&
5814 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5815 >                    addToPendingCount(1);
5816                      (rights = new MapReduceKeysToIntTask<K,V>
5817 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5818 <                while (advance() != null)
5819 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5817 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5818 >                      rights, transformer, r, reducer)).fork();
5819 >                }
5820 >                for (Node<K,V> p; (p = advance()) != null; )
5821 >                    r = reducer.apply(r, transformer.apply(p.key));
5822                  result = r;
5823                  CountedCompleter<?> c;
5824                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5825 <                    MapReduceKeysToIntTask<K,V>
5825 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5826                          t = (MapReduceKeysToIntTask<K,V>)c,
5827                          s = t.rights;
5828                      while (s != null) {
# Line 6656 | Line 5834 | public class ConcurrentHashMapV8<K, V>
5834          }
5835      }
5836  
5837 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5838 <        extends Traverser<K,V,Integer> {
5837 >    @SuppressWarnings("serial")
5838 >    static final class MapReduceValuesToIntTask<K,V>
5839 >        extends BulkTask<K,V,Integer> {
5840          final ObjectToInt<? super V> transformer;
5841          final IntByIntToInt reducer;
5842          final int basis;
5843          int result;
5844          MapReduceValuesToIntTask<K,V> rights, nextRight;
5845          MapReduceValuesToIntTask
5846 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5846 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5847               MapReduceValuesToIntTask<K,V> nextRight,
5848               ObjectToInt<? super V> transformer,
5849               int basis,
5850               IntByIntToInt reducer) {
5851 <            super(m, p, b); this.nextRight = nextRight;
5851 >            super(p, b, i, f, t); this.nextRight = nextRight;
5852              this.transformer = transformer;
5853              this.basis = basis; this.reducer = reducer;
5854          }
5855          public final Integer getRawResult() { return result; }
5856 <        @SuppressWarnings("unchecked") public final void compute() {
5856 >        public final void compute() {
5857              final ObjectToInt<? super V> transformer;
5858              final IntByIntToInt reducer;
5859              if ((transformer = this.transformer) != null &&
5860                  (reducer = this.reducer) != null) {
5861                  int r = this.basis;
5862 <                for (int b; (b = preSplit()) > 0;)
5862 >                for (int i = baseIndex, f, h; batch > 0 &&
5863 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5864 >                    addToPendingCount(1);
5865                      (rights = new MapReduceValuesToIntTask<K,V>
5866 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5867 <                V v;
5868 <                while ((v = advance()) != null)
5869 <                    r = reducer.apply(r, transformer.apply(v));
5866 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5867 >                      rights, transformer, r, reducer)).fork();
5868 >                }
5869 >                for (Node<K,V> p; (p = advance()) != null; )
5870 >                    r = reducer.apply(r, transformer.apply(p.val));
5871                  result = r;
5872                  CountedCompleter<?> c;
5873                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5874 <                    MapReduceValuesToIntTask<K,V>
5874 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5875                          t = (MapReduceValuesToIntTask<K,V>)c,
5876                          s = t.rights;
5877                      while (s != null) {
# Line 6701 | Line 5883 | public class ConcurrentHashMapV8<K, V>
5883          }
5884      }
5885  
5886 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5887 <        extends Traverser<K,V,Integer> {
5886 >    @SuppressWarnings("serial")
5887 >    static final class MapReduceEntriesToIntTask<K,V>
5888 >        extends BulkTask<K,V,Integer> {
5889          final ObjectToInt<Map.Entry<K,V>> transformer;
5890          final IntByIntToInt reducer;
5891          final int basis;
5892          int result;
5893          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5894          MapReduceEntriesToIntTask
5895 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5895 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5896               MapReduceEntriesToIntTask<K,V> nextRight,
5897               ObjectToInt<Map.Entry<K,V>> transformer,
5898               int basis,
5899               IntByIntToInt reducer) {
5900 <            super(m, p, b); this.nextRight = nextRight;
5900 >            super(p, b, i, f, t); this.nextRight = nextRight;
5901              this.transformer = transformer;
5902              this.basis = basis; this.reducer = reducer;
5903          }
5904          public final Integer getRawResult() { return result; }
5905 <        @SuppressWarnings("unchecked") public final void compute() {
5905 >        public final void compute() {
5906              final ObjectToInt<Map.Entry<K,V>> transformer;
5907              final IntByIntToInt reducer;
5908              if ((transformer = this.transformer) != null &&
5909                  (reducer = this.reducer) != null) {
5910                  int r = this.basis;
5911 <                for (int b; (b = preSplit()) > 0;)
5911 >                for (int i = baseIndex, f, h; batch > 0 &&
5912 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5913 >                    addToPendingCount(1);
5914                      (rights = new MapReduceEntriesToIntTask<K,V>
5915 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5916 <                V v;
5917 <                while ((v = advance()) != null)
5918 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5919 <                                                                    v)));
5915 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5916 >                      rights, transformer, r, reducer)).fork();
5917 >                }
5918 >                for (Node<K,V> p; (p = advance()) != null; )
5919 >                    r = reducer.apply(r, transformer.apply(p));
5920                  result = r;
5921                  CountedCompleter<?> c;
5922                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5923 <                    MapReduceEntriesToIntTask<K,V>
5923 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5924                          t = (MapReduceEntriesToIntTask<K,V>)c,
5925                          s = t.rights;
5926                      while (s != null) {
# Line 6747 | Line 5932 | public class ConcurrentHashMapV8<K, V>
5932          }
5933      }
5934  
5935 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5936 <        extends Traverser<K,V,Integer> {
5935 >    @SuppressWarnings("serial")
5936 >    static final class MapReduceMappingsToIntTask<K,V>
5937 >        extends BulkTask<K,V,Integer> {
5938          final ObjectByObjectToInt<? super K, ? super V> transformer;
5939          final IntByIntToInt reducer;
5940          final int basis;
5941          int result;
5942          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5943          MapReduceMappingsToIntTask
5944 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5944 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5945               MapReduceMappingsToIntTask<K,V> nextRight,
5946               ObjectByObjectToInt<? super K, ? super V> transformer,
5947               int basis,
5948               IntByIntToInt reducer) {
5949 <            super(m, p, b); this.nextRight = nextRight;
5949 >            super(p, b, i, f, t); this.nextRight = nextRight;
5950              this.transformer = transformer;
5951              this.basis = basis; this.reducer = reducer;
5952          }
5953          public final Integer getRawResult() { return result; }
5954 <        @SuppressWarnings("unchecked") public final void compute() {
5954 >        public final void compute() {
5955              final ObjectByObjectToInt<? super K, ? super V> transformer;
5956              final IntByIntToInt reducer;
5957              if ((transformer = this.transformer) != null &&
5958                  (reducer = this.reducer) != null) {
5959                  int r = this.basis;
5960 <                for (int b; (b = preSplit()) > 0;)
5960 >                for (int i = baseIndex, f, h; batch > 0 &&
5961 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5962 >                    addToPendingCount(1);
5963                      (rights = new MapReduceMappingsToIntTask<K,V>
5964 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5965 <                V v;
5966 <                while ((v = advance()) != null)
5967 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5964 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5965 >                      rights, transformer, r, reducer)).fork();
5966 >                }
5967 >                for (Node<K,V> p; (p = advance()) != null; )
5968 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5969                  result = r;
5970                  CountedCompleter<?> c;
5971                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5972 <                    MapReduceMappingsToIntTask<K,V>
5972 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
5973                          t = (MapReduceMappingsToIntTask<K,V>)c,
5974                          s = t.rights;
5975                      while (s != null) {
# Line 6792 | Line 5981 | public class ConcurrentHashMapV8<K, V>
5981          }
5982      }
5983  
5984 +    /* ---------------- Counters -------------- */
5985 +
5986 +    // Adapted from LongAdder and Striped64.
5987 +    // See their internal docs for explanation.
5988 +
5989 +    // A padded cell for distributing counts
5990 +    static final class CounterCell {
5991 +        volatile long p0, p1, p2, p3, p4, p5, p6;
5992 +        volatile long value;
5993 +        volatile long q0, q1, q2, q3, q4, q5, q6;
5994 +        CounterCell(long x) { value = x; }
5995 +    }
5996 +
5997 +    /**
5998 +     * Holder for the thread-local hash code determining which
5999 +     * CounterCell to use. The code is initialized via the
6000 +     * counterHashCodeGenerator, but may be moved upon collisions.
6001 +     */
6002 +    static final class CounterHashCode {
6003 +        int code;
6004 +    }
6005 +
6006 +    /**
6007 +     * Generates initial value for per-thread CounterHashCodes.
6008 +     */
6009 +    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
6010 +
6011 +    /**
6012 +     * Increment for counterHashCodeGenerator. See class ThreadLocal
6013 +     * for explanation.
6014 +     */
6015 +    static final int SEED_INCREMENT = 0x61c88647;
6016 +
6017 +    /**
6018 +     * Per-thread counter hash codes. Shared across all instances.
6019 +     */
6020 +    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6021 +        new ThreadLocal<CounterHashCode>();
6022 +
6023 +
6024 +    final long sumCount() {
6025 +        CounterCell[] as = counterCells; CounterCell a;
6026 +        long sum = baseCount;
6027 +        if (as != null) {
6028 +            for (int i = 0; i < as.length; ++i) {
6029 +                if ((a = as[i]) != null)
6030 +                    sum += a.value;
6031 +            }
6032 +        }
6033 +        return sum;
6034 +    }
6035 +
6036 +    // See LongAdder version for explanation
6037 +    private final void fullAddCount(long x, CounterHashCode hc,
6038 +                                    boolean wasUncontended) {
6039 +        int h;
6040 +        if (hc == null) {
6041 +            hc = new CounterHashCode();
6042 +            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6043 +            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6044 +            threadCounterHashCode.set(hc);
6045 +        }
6046 +        else
6047 +            h = hc.code;
6048 +        boolean collide = false;                // True if last slot nonempty
6049 +        for (;;) {
6050 +            CounterCell[] as; CounterCell a; int n; long v;
6051 +            if ((as = counterCells) != null && (n = as.length) > 0) {
6052 +                if ((a = as[(n - 1) & h]) == null) {
6053 +                    if (cellsBusy == 0) {            // Try to attach new Cell
6054 +                        CounterCell r = new CounterCell(x); // Optimistic create
6055 +                        if (cellsBusy == 0 &&
6056 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6057 +                            boolean created = false;
6058 +                            try {               // Recheck under lock
6059 +                                CounterCell[] rs; int m, j;
6060 +                                if ((rs = counterCells) != null &&
6061 +                                    (m = rs.length) > 0 &&
6062 +                                    rs[j = (m - 1) & h] == null) {
6063 +                                    rs[j] = r;
6064 +                                    created = true;
6065 +                                }
6066 +                            } finally {
6067 +                                cellsBusy = 0;
6068 +                            }
6069 +                            if (created)
6070 +                                break;
6071 +                            continue;           // Slot is now non-empty
6072 +                        }
6073 +                    }
6074 +                    collide = false;
6075 +                }
6076 +                else if (!wasUncontended)       // CAS already known to fail
6077 +                    wasUncontended = true;      // Continue after rehash
6078 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6079 +                    break;
6080 +                else if (counterCells != as || n >= NCPU)
6081 +                    collide = false;            // At max size or stale
6082 +                else if (!collide)
6083 +                    collide = true;
6084 +                else if (cellsBusy == 0 &&
6085 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6086 +                    try {
6087 +                        if (counterCells == as) {// Expand table unless stale
6088 +                            CounterCell[] rs = new CounterCell[n << 1];
6089 +                            for (int i = 0; i < n; ++i)
6090 +                                rs[i] = as[i];
6091 +                            counterCells = rs;
6092 +                        }
6093 +                    } finally {
6094 +                        cellsBusy = 0;
6095 +                    }
6096 +                    collide = false;
6097 +                    continue;                   // Retry with expanded table
6098 +                }
6099 +                h ^= h << 13;                   // Rehash
6100 +                h ^= h >>> 17;
6101 +                h ^= h << 5;
6102 +            }
6103 +            else if (cellsBusy == 0 && counterCells == as &&
6104 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6105 +                boolean init = false;
6106 +                try {                           // Initialize table
6107 +                    if (counterCells == as) {
6108 +                        CounterCell[] rs = new CounterCell[2];
6109 +                        rs[h & 1] = new CounterCell(x);
6110 +                        counterCells = rs;
6111 +                        init = true;
6112 +                    }
6113 +                } finally {
6114 +                    cellsBusy = 0;
6115 +                }
6116 +                if (init)
6117 +                    break;
6118 +            }
6119 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6120 +                break;                          // Fall back on using base
6121 +        }
6122 +        hc.code = h;                            // Record index for next time
6123 +    }
6124 +
6125      // Unsafe mechanics
6126      private static final sun.misc.Unsafe U;
6127      private static final long SIZECTL;
6128      private static final long TRANSFERINDEX;
6129      private static final long TRANSFERORIGIN;
6130      private static final long BASECOUNT;
6131 <    private static final long COUNTERBUSY;
6131 >    private static final long CELLSBUSY;
6132      private static final long CELLVALUE;
6133      private static final long ABASE;
6134      private static final int ASHIFT;
6135  
6136      static {
6807        int ss;
6137          try {
6138              U = getUnsafe();
6139              Class<?> k = ConcurrentHashMapV8.class;
# Line 6816 | Line 6145 | public class ConcurrentHashMapV8<K, V>
6145                  (k.getDeclaredField("transferOrigin"));
6146              BASECOUNT = U.objectFieldOffset
6147                  (k.getDeclaredField("baseCount"));
6148 <            COUNTERBUSY = U.objectFieldOffset
6149 <                (k.getDeclaredField("counterBusy"));
6148 >            CELLSBUSY = U.objectFieldOffset
6149 >                (k.getDeclaredField("cellsBusy"));
6150              Class<?> ck = CounterCell.class;
6151              CELLVALUE = U.objectFieldOffset
6152                  (ck.getDeclaredField("value"));
6153 <            Class<?> sc = Node[].class;
6154 <            ABASE = U.arrayBaseOffset(sc);
6155 <            ss = U.arrayIndexScale(sc);
6156 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6153 >            Class<?> ak = Node[].class;
6154 >            ABASE = U.arrayBaseOffset(ak);
6155 >            int scale = U.arrayIndexScale(ak);
6156 >            if ((scale & (scale - 1)) != 0)
6157 >                throw new Error("data type scale not a power of two");
6158 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6159          } catch (Exception e) {
6160              throw new Error(e);
6161          }
6831        if ((ss & (ss-1)) != 0)
6832            throw new Error("data type scale not a power of two");
6162      }
6163  
6164      /**
# Line 6842 | Line 6171 | public class ConcurrentHashMapV8<K, V>
6171      private static sun.misc.Unsafe getUnsafe() {
6172          try {
6173              return sun.misc.Unsafe.getUnsafe();
6174 <        } catch (SecurityException se) {
6175 <            try {
6176 <                return java.security.AccessController.doPrivileged
6177 <                    (new java.security
6178 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6179 <                        public sun.misc.Unsafe run() throws Exception {
6180 <                            java.lang.reflect.Field f = sun.misc
6181 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6182 <                            f.setAccessible(true);
6183 <                            return (sun.misc.Unsafe) f.get(null);
6184 <                        }});
6185 <            } catch (java.security.PrivilegedActionException e) {
6186 <                throw new RuntimeException("Could not initialize intrinsics",
6187 <                                           e.getCause());
6188 <            }
6174 >        } catch (SecurityException tryReflectionInstead) {}
6175 >        try {
6176 >            return java.security.AccessController.doPrivileged
6177 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6178 >                public sun.misc.Unsafe run() throws Exception {
6179 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6180 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6181 >                        f.setAccessible(true);
6182 >                        Object x = f.get(null);
6183 >                        if (k.isInstance(x))
6184 >                            return k.cast(x);
6185 >                    }
6186 >                    throw new NoSuchFieldError("the Unsafe");
6187 >                }});
6188 >        } catch (java.security.PrivilegedActionException e) {
6189 >            throw new RuntimeException("Could not initialize intrinsics",
6190 >                                       e.getCause());
6191          }
6192      }
6193   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines