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.98 by jsr166, Mon Feb 11 20:52:00 2013 UTC vs.
Revision 1.107 by dl, Wed Jun 26 10:56:10 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 >     * insignficant.)
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 beause 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     = 0x8fffffff; // (-1) hash for forwarding nodes
572 >    static final int TREEBIN   = 0x80000000; // hash for heads of treea
573 >    static final int RESERVED  = 0x80000001; // 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 negativehash 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 >        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 do not need full volatile semantics, but still require
726 >     * ordering to maintain concurrent readability.
727 >     */
728 >
729 >    @SuppressWarnings("unchecked")
730 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
731 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
732 >    }
733 >
734 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
735 >                                        Node<K,V> c, Node<K,V> v) {
736 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
737 >    }
738 >
739 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
740 >        U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
741 >    }
742  
743      /* ---------------- Fields -------------- */
744  
# Line 578 | Line 746 | public class ConcurrentHashMapV8<K, V>
746       * The array of bins. Lazily initialized upon first insertion.
747       * Size is always a power of two. Accessed directly by iterators.
748       */
749 <    transient volatile Node<V>[] table;
749 >    transient volatile Node<K,V>[] table;
750  
751      /**
752       * The next table to use; non-null only while resizing.
753       */
754 <    private transient volatile Node<V>[] nextTable;
754 >    private transient volatile Node<K,V>[] nextTable;
755  
756      /**
757       * Base counter value, used mainly when there is no contention,
# Line 613 | Line 781 | public class ConcurrentHashMapV8<K, V>
781      private transient volatile int transferOrigin;
782  
783      /**
784 <     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
784 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
785       */
786 <    private transient volatile int counterBusy;
786 >    private transient volatile int cellsBusy;
787  
788      /**
789       * Table of counter cells. When non-null, size is a power of 2.
# Line 627 | Line 795 | public class ConcurrentHashMapV8<K, V>
795      private transient ValuesView<K,V> values;
796      private transient EntrySetView<K,V> entrySet;
797  
630    /** For serialization compatibility. Null unless serialized; see below */
631    private Segment<K,V>[] segments;
798  
799 <    /* ---------------- Table element access -------------- */
799 >    /* ---------------- Public operations -------------- */
800  
801 <    /*
802 <     * Volatile access methods are used for table elements as well as
803 <     * elements of in-progress next table while resizing.  Uses are
804 <     * 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);
801 >    /**
802 >     * Creates a new, empty map with the default initial table size (16).
803 >     */
804 >    public ConcurrentHashMapV8() {
805      }
806  
807 <    private static final <V> boolean casTabAt
808 <        (Node<V>[] tab, int i, Node<V> c, Node<V> v) {
809 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
807 >    /**
808 >     * Creates a new, empty map with an initial table size
809 >     * accommodating the specified number of elements without the need
810 >     * to dynamically resize.
811 >     *
812 >     * @param initialCapacity The implementation performs internal
813 >     * sizing to accommodate this many elements.
814 >     * @throws IllegalArgumentException if the initial capacity of
815 >     * elements is negative
816 >     */
817 >    public ConcurrentHashMapV8(int initialCapacity) {
818 >        if (initialCapacity < 0)
819 >            throw new IllegalArgumentException();
820 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
821 >                   MAXIMUM_CAPACITY :
822 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
823 >        this.sizeCtl = cap;
824      }
825  
826 <    private static final <V> void setTabAt
827 <        (Node<V>[] tab, int i, Node<V> v) {
828 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
826 >    /**
827 >     * Creates a new map with the same mappings as the given map.
828 >     *
829 >     * @param m the map
830 >     */
831 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
832 >        this.sizeCtl = DEFAULT_CAPACITY;
833 >        putAll(m);
834      }
835  
662    /* ---------------- Nodes -------------- */
663
836      /**
837 <     * Key-value entry. Note that this is never exported out as a
838 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
839 <     * field of MOVED are special, and do not contain user keys or
840 <     * values.  Otherwise, keys are never null, and null val fields
841 <     * indicate that a node is in the process of being deleted or
842 <     * created. For purposes of read-only access, a key may be read
843 <     * before a val, but can only be used after checking val to be
844 <     * non-null.
837 >     * Creates a new, empty map with an initial table size based on
838 >     * the given number of elements ({@code initialCapacity}) and
839 >     * initial table density ({@code loadFactor}).
840 >     *
841 >     * @param initialCapacity the initial capacity. The implementation
842 >     * performs internal sizing to accommodate this many elements,
843 >     * given the specified load factor.
844 >     * @param loadFactor the load factor (table density) for
845 >     * establishing the initial table size
846 >     * @throws IllegalArgumentException if the initial capacity of
847 >     * elements is negative or the load factor is nonpositive
848 >     *
849 >     * @since 1.6
850       */
851 <    static class Node<V> {
852 <        final int hash;
853 <        final Object key;
677 <        volatile V val;
678 <        volatile Node<V> next;
851 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
852 >        this(initialCapacity, loadFactor, 1);
853 >    }
854  
855 <        Node(int hash, Object key, V val, Node<V> next) {
856 <            this.hash = hash;
857 <            this.key = key;
858 <            this.val = val;
859 <            this.next = next;
860 <        }
855 >    /**
856 >     * Creates a new, empty map with an initial table size based on
857 >     * the given number of elements ({@code initialCapacity}), table
858 >     * density ({@code loadFactor}), and number of concurrently
859 >     * updating threads ({@code concurrencyLevel}).
860 >     *
861 >     * @param initialCapacity the initial capacity. The implementation
862 >     * performs internal sizing to accommodate this many elements,
863 >     * given the specified load factor.
864 >     * @param loadFactor the load factor (table density) for
865 >     * establishing the initial table size
866 >     * @param concurrencyLevel the estimated number of concurrently
867 >     * updating threads. The implementation may use this value as
868 >     * a sizing hint.
869 >     * @throws IllegalArgumentException if the initial capacity is
870 >     * negative or the load factor or concurrencyLevel are
871 >     * nonpositive
872 >     */
873 >    public ConcurrentHashMapV8(int initialCapacity,
874 >                             float loadFactor, int concurrencyLevel) {
875 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
876 >            throw new IllegalArgumentException();
877 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
878 >            initialCapacity = concurrencyLevel;   // as estimated threads
879 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
880 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
881 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
882 >        this.sizeCtl = cap;
883      }
884  
885 <    /* ---------------- TreeBins -------------- */
885 >    // Original (since JDK1.2) Map methods
886  
887      /**
888 <     * Nodes for use in TreeBins
888 >     * {@inheritDoc}
889       */
890 <    static final class TreeNode<V> extends Node<V> {
891 <        TreeNode<V> parent;  // red-black tree links
892 <        TreeNode<V> left;
893 <        TreeNode<V> right;
894 <        TreeNode<V> prev;    // needed to unlink next upon deletion
895 <        boolean red;
890 >    public int size() {
891 >        long n = sumCount();
892 >        return ((n < 0L) ? 0 :
893 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
894 >                (int)n);
895 >    }
896  
897 <        TreeNode(int hash, Object key, V val, Node<V> next, TreeNode<V> parent) {
898 <            super(hash, key, val, next);
899 <            this.parent = parent;
900 <        }
897 >    /**
898 >     * {@inheritDoc}
899 >     */
900 >    public boolean isEmpty() {
901 >        return sumCount() <= 0L; // ignore transient negative values
902      }
903  
904      /**
905 <     * A specialized form of red-black tree for use in bins
906 <     * whose size exceeds a threshold.
905 >     * Returns the value to which the specified key is mapped,
906 >     * or {@code null} if this map contains no mapping for the key.
907       *
908 <     * TreeBins use a special form of comparison for search and
909 <     * related operations (which is the main reason we cannot use
910 <     * existing collections such as TreeMaps). TreeBins contain
911 <     * 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).
908 >     * <p>More formally, if this map contains a mapping from a key
909 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
910 >     * then this method returns {@code v}; otherwise it returns
911 >     * {@code null}.  (There can be at most one such mapping.)
912       *
913 <     * 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.
913 >     * @throws NullPointerException if the specified key is null
914       */
915 <    static final class TreeBin<V> extends AbstractQueuedSynchronizer {
916 <        private static final long serialVersionUID = 2249069246763182397L;
917 <        transient TreeNode<V> root;  // root of tree
918 <        transient TreeNode<V> first; // head of next-pointer list
919 <
920 <        /* AQS overrides */
921 <        public final boolean isHeldExclusively() { return getState() > 0; }
922 <        public final boolean tryAcquire(int ignore) {
923 <            if (compareAndSetState(0, 1)) {
924 <                setExclusiveOwnerThread(Thread.currentThread());
925 <                return true;
926 <            }
927 <            return false;
928 <        }
929 <        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;
915 >    public V get(Object key) {
916 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
917 >        int h = spread(key.hashCode());
918 >        if ((tab = table) != null && (n = tab.length) > 0 &&
919 >            (e = tabAt(tab, (n - 1) & h)) != null) {
920 >            if ((eh = e.hash) == h) {
921 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
922 >                    return e.val;
923 >            }
924 >            else if (eh < 0)
925 >                return (p = e.find(h, key)) != null ? p.val : null;
926 >            while ((e = e.next) != null) {
927 >                if (e.hash == h &&
928 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
929 >                    return e.val;
930              }
931          }
932 +        return null;
933 +    }
934  
935 <        /**
936 <         * Returns the TreeNode (or null if not found) for the given key
937 <         * starting at given root.
938 <         */
939 <        @SuppressWarnings("unchecked") final TreeNode<V> getTreeNode
940 <            (int h, Object k, TreeNode<V> p) {
941 <            Class<?> c = k.getClass();
942 <            while (p != null) {
943 <                int dir, ph;  Object pk; Class<?> pc;
944 <                if ((ph = p.hash) == h) {
945 <                    if ((pk = p.key) == k || k.equals(pk))
946 <                        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 <        }
935 >    /**
936 >     * Tests if the specified object is a key in this table.
937 >     *
938 >     * @param  key possible key
939 >     * @return {@code true} if and only if the specified object
940 >     *         is a key in this table, as determined by the
941 >     *         {@code equals} method; {@code false} otherwise
942 >     * @throws NullPointerException if the specified key is null
943 >     */
944 >    public boolean containsKey(Object key) {
945 >        return get(key) != null;
946 >    }
947  
948 <        /**
949 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
950 <         * read-lock to call getTreeNode, but during failure to get
951 <         * lock, searches along next links.
952 <         */
953 <        final V getValue(int h, Object k) {
954 <            Node<V> r = null;
955 <            int c = getState(); // Must read lock state first
956 <            for (Node<V> e = first; e != null; e = e.next) {
957 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
958 <                    try {
959 <                        r = getTreeNode(h, k, root);
960 <                    } finally {
961 <                        releaseShared(0);
962 <                    }
963 <                    break;
964 <                }
965 <                else if (e.hash == h && k.equals(e.key)) {
966 <                    r = e;
967 <                    break;
871 <                }
872 <                else
873 <                    c = getState();
948 >    /**
949 >     * Returns {@code true} if this map maps one or more keys to the
950 >     * specified value. Note: This method may require a full traversal
951 >     * of the map, and is much slower than method {@code containsKey}.
952 >     *
953 >     * @param value value whose presence in this map is to be tested
954 >     * @return {@code true} if this map maps one or more keys to the
955 >     *         specified value
956 >     * @throws NullPointerException if the specified value is null
957 >     */
958 >    public boolean containsValue(Object value) {
959 >        if (value == null)
960 >            throw new NullPointerException();
961 >        Node<K,V>[] t;
962 >        if ((t = table) != null) {
963 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
964 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
965 >                V v;
966 >                if ((v = p.val) == value || (v != null && value.equals(v)))
967 >                    return true;
968              }
875            return r == null ? null : r.val;
969          }
970 +        return false;
971 +    }
972  
973 <        /**
974 <         * Finds or adds a node.
975 <         * @return null if added
976 <         */
977 <        @SuppressWarnings("unchecked") final TreeNode<V> putTreeNode
978 <            (int h, Object k, V v) {
979 <            Class<?> c = k.getClass();
980 <            TreeNode<V> pp = root, p = null;
981 <            int dir = 0;
982 <            while (pp != null) { // find existing node or leaf to insert at
983 <                int ph;  Object pk; Class<?> pc;
984 <                p = pp;
985 <                if ((ph = p.hash) == h) {
986 <                    if ((pk = p.key) == k || k.equals(pk))
987 <                        return p;
988 <                    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 <        }
973 >    /**
974 >     * Maps the specified key to the specified value in this table.
975 >     * Neither the key nor the value can be null.
976 >     *
977 >     * <p>The value can be retrieved by calling the {@code get} method
978 >     * with a key that is equal to the original key.
979 >     *
980 >     * @param key key with which the specified value is to be associated
981 >     * @param value value to be associated with the specified key
982 >     * @return the previous value associated with {@code key}, or
983 >     *         {@code null} if there was no mapping for {@code key}
984 >     * @throws NullPointerException if the specified key or value is null
985 >     */
986 >    public V put(K key, V value) {
987 >        return putVal(key, value, false);
988 >    }
989  
990 <        /**
991 <         * Removes the given node, that must be present before this
992 <         * call.  This is messier than typical red-black deletion code
993 <         * because we cannot swap the contents of an interior node
994 <         * with a leaf successor that is pinned by "next" pointers
995 <         * that are accessible independently of lock. So instead we
996 <         * swap the tree linkages.
997 <         */
998 <        final void deleteTreeNode(TreeNode<V> p) {
999 <            TreeNode<V> next = (TreeNode<V>)p.next; // unlink traversal pointers
1000 <            TreeNode<V> pred = p.prev;
1001 <            if (pred == null)
1002 <                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;
990 >    /** Implementation for put and putIfAbsent */
991 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
992 >        if (key == null || value == null) throw new NullPointerException();
993 >        int hash = spread(key.hashCode());
994 >        int binCount = 0;
995 >        for (Node<K,V>[] tab = table;;) {
996 >            Node<K,V> f; int n, i, fh;
997 >            if (tab == null || (n = tab.length) == 0)
998 >                tab = initTable();
999 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1000 >                if (casTabAt(tab, i, null,
1001 >                             new Node<K,V>(hash, key, value, null)))
1002 >                    break;                   // no lock when adding to empty bin
1003              }
1004 +            else if ((fh = f.hash) == MOVED)
1005 +                tab = helpTransfer(tab, f);
1006              else {
1007 <                replacement.parent = pp;
1008 <                if (pp == null)
1009 <                    root = replacement;
1010 <                else if (p == pp.left)
1011 <                    pp.left = replacement;
1012 <                else
1013 <                    pp.right = replacement;
1014 <                p.left = p.right = p.parent = null;
1015 <            }
1016 <            if (!p.red) { // rebalance, from CLR
1017 <                TreeNode<V> x = replacement;
1018 <                while (x != null) {
1019 <                    TreeNode<V> xp, xpl;
1020 <                    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;
1007 >                V oldVal = null;
1008 >                synchronized (f) {
1009 >                    if (tabAt(tab, i) == f) {
1010 >                        if (fh >= 0) {
1011 >                            binCount = 1;
1012 >                            for (Node<K,V> e = f;; ++binCount) {
1013 >                                K ek;
1014 >                                if (e.hash == hash &&
1015 >                                    ((ek = e.key) == key ||
1016 >                                     (ek != null && key.equals(ek)))) {
1017 >                                    oldVal = e.val;
1018 >                                    if (!onlyIfAbsent)
1019 >                                        e.val = value;
1020 >                                    break;
1021                                  }
1022 <                                if (xp != null) {
1023 <                                    xp.red = false;
1024 <                                    rotateLeft(xp);
1022 >                                Node<K,V> pred = e;
1023 >                                if ((e = e.next) == null) {
1024 >                                    pred.next = new Node<K,V>(hash, key,
1025 >                                                              value, null);
1026 >                                    break;
1027                                  }
1102                                x = root;
1028                              }
1029                          }
1030 <                    }
1031 <                    else { // symmetric
1032 <                        TreeNode<V> sib = xpl;
1033 <                        if (sib != null && sib.red) {
1034 <                            sib.red = false;
1035 <                            xp.red = true;
1036 <                            rotateRight(xp);
1037 <                            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;
1030 >                        else if (f instanceof TreeBin) {
1031 >                            Node<K,V> p;
1032 >                            binCount = 2;
1033 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1034 >                                                           value)) != null) {
1035 >                                oldVal = p.val;
1036 >                                if (!onlyIfAbsent)
1037 >                                    p.val = value;
1038                              }
1039                          }
1040                      }
1041                  }
1042 <            }
1043 <            if (p == replacement && (pp = p.parent) != null) {
1044 <                if (p == pp.left) // detach pointers
1045 <                    pp.left = null;
1046 <                else if (p == pp.right)
1047 <                    pp.right = null;
1048 <                p.parent = null;
1042 >                if (binCount != 0) {
1043 >                    if (binCount >= TREEIFY_THRESHOLD)
1044 >                        treeifyBin(tab, i);
1045 >                    if (oldVal != null)
1046 >                        return oldVal;
1047 >                    break;
1048 >                }
1049              }
1050          }
1051 +        addCount(1L, binCount);
1052 +        return null;
1053      }
1054  
1157    /* ---------------- Collision reduction methods -------------- */
1158
1055      /**
1056 <     * Spreads higher bits to lower, and also forces top bit to 0.
1057 <     * Because the table uses power-of-two masking, sets of hashes
1058 <     * that vary only in bits above the current mask will always
1059 <     * collide. (Among known examples are sets of Float keys holding
1060 <     * 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.
1056 >     * Copies all of the mappings from the specified map to this one.
1057 >     * These mappings replace any mappings that this map had for any of the
1058 >     * keys currently in the specified map.
1059 >     *
1060 >     * @param m mappings to be stored in this map
1061       */
1062 <    private static final int spread(int h) {
1063 <        h ^= (h >>> 18) ^ (h >>> 12);
1064 <        return (h ^ (h >>> 10)) & HASH_BITS;
1062 >    public void putAll(Map<? extends K, ? extends V> m) {
1063 >        tryPresize(m.size());
1064 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1065 >            putVal(e.getKey(), e.getValue(), false);
1066      }
1067  
1068      /**
1069 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1070 <     * only when locked.
1069 >     * Removes the key (and its corresponding value) from this map.
1070 >     * This method does nothing if the key is not in the map.
1071 >     *
1072 >     * @param  key the key that needs to be removed
1073 >     * @return the previous value associated with {@code key}, or
1074 >     *         {@code null} if there was no mapping for {@code key}
1075 >     * @throws NullPointerException if the specified key is null
1076       */
1077 <    private final void replaceWithTreeBin(Node<V>[] tab, int index, Object key) {
1078 <        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;
1077 >    public V remove(Object key) {
1078 >        return replaceNode(key, null, null);
1079      }
1080  
1081      /**
# Line 1217 | Line 1083 | public class ConcurrentHashMapV8<K, V>
1083       * Replaces node value with v, conditional upon match of cv if
1084       * non-null.  If resulting value is null, delete.
1085       */
1086 <    @SuppressWarnings("unchecked") private final V internalReplace
1087 <        (Object k, V v, Object cv) {
1088 <        int h = spread(k.hashCode());
1089 <        V oldVal = null;
1090 <        for (Node<V>[] tab = table;;) {
1091 <            Node<V> f; int i, fh; Object fk;
1226 <            if (tab == null ||
1227 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1086 >    final V replaceNode(Object key, V value, Object cv) {
1087 >        int hash = spread(key.hashCode());
1088 >        for (Node<K,V>[] tab = table;;) {
1089 >            Node<K,V> f; int n, i, fh;
1090 >            if (tab == null || (n = tab.length) == 0 ||
1091 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1092                  break;
1093 <            else if ((fh = f.hash) < 0) {
1094 <                if ((fk = f.key) instanceof TreeBin) {
1095 <                    TreeBin<V> t = (TreeBin<V>)fk;
1096 <                    boolean validated = false;
1097 <                    boolean deleted = false;
1098 <                    t.acquire(0);
1099 <                    try {
1100 <                        if (tabAt(tab, i) == f) {
1093 >            else if ((fh = f.hash) == MOVED)
1094 >                tab = helpTransfer(tab, f);
1095 >            else {
1096 >                V oldVal = null;
1097 >                boolean validated = false;
1098 >                synchronized (f) {
1099 >                    if (tabAt(tab, i) == f) {
1100 >                        if (fh >= 0) {
1101 >                            validated = true;
1102 >                            for (Node<K,V> e = f, pred = null;;) {
1103 >                                K ek;
1104 >                                if (e.hash == hash &&
1105 >                                    ((ek = e.key) == key ||
1106 >                                     (ek != null && key.equals(ek)))) {
1107 >                                    V ev = e.val;
1108 >                                    if (cv == null || cv == ev ||
1109 >                                        (ev != null && cv.equals(ev))) {
1110 >                                        oldVal = ev;
1111 >                                        if (value != null)
1112 >                                            e.val = value;
1113 >                                        else if (pred != null)
1114 >                                            pred.next = e.next;
1115 >                                        else
1116 >                                            setTabAt(tab, i, e.next);
1117 >                                    }
1118 >                                    break;
1119 >                                }
1120 >                                pred = e;
1121 >                                if ((e = e.next) == null)
1122 >                                    break;
1123 >                            }
1124 >                        }
1125 >                        else if (f instanceof TreeBin) {
1126                              validated = true;
1127 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1128 <                            if (p != null) {
1127 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1128 >                            TreeNode<K,V> r, p;
1129 >                            if ((r = t.root) != null &&
1130 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1131                                  V pv = p.val;
1132 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1132 >                                if (cv == null || cv == pv ||
1133 >                                    (pv != null && cv.equals(pv))) {
1134                                      oldVal = pv;
1135 <                                    if ((p.val = v) == null) {
1136 <                                        deleted = true;
1137 <                                        t.deleteTreeNode(p);
1138 <                                    }
1135 >                                    if (value != null)
1136 >                                        p.val = value;
1137 >                                    else if (t.removeTreeNode(p))
1138 >                                        setTabAt(tab, i, untreeify(t.first));
1139                                  }
1140                              }
1141                          }
1250                    } finally {
1251                        t.release(0);
1142                      }
1143 <                    if (validated) {
1144 <                        if (deleted)
1143 >                }
1144 >                if (validated) {
1145 >                    if (oldVal != null) {
1146 >                        if (value == null)
1147                              addCount(-1L, -1);
1148 <                        break;
1148 >                        return oldVal;
1149                      }
1150 +                    break;
1151                  }
1259                else
1260                    tab = (Node<V>[])fk;
1152              }
1153 <            else if (fh != h && f.next == null) // precheck
1154 <                break;                          // rules out possible existence
1153 >        }
1154 >        return null;
1155 >    }
1156 >
1157 >    /**
1158 >     * Removes all of the mappings from this map.
1159 >     */
1160 >    public void clear() {
1161 >        long delta = 0L; // negative number of deletions
1162 >        int i = 0;
1163 >        Node<K,V>[] tab = table;
1164 >        while (tab != null && i < tab.length) {
1165 >            int fh;
1166 >            Node<K,V> f = tabAt(tab, i);
1167 >            if (f == null)
1168 >                ++i;
1169 >            else if ((fh = f.hash) == MOVED) {
1170 >                tab = helpTransfer(tab, f);
1171 >                i = 0; // restart
1172 >            }
1173              else {
1265                boolean validated = false;
1266                boolean deleted = false;
1174                  synchronized (f) {
1175                      if (tabAt(tab, i) == f) {
1176 <                        validated = true;
1177 <                        for (Node<V> e = f, pred = null;;) {
1178 <                            Object ek; V ev;
1179 <                            if (e.hash == h &&
1180 <                                ((ev = e.val) != null) &&
1181 <                                ((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;
1176 >                        Node<K,V> p = (fh >= 0 ? f :
1177 >                                       (f instanceof TreeBin) ?
1178 >                                       ((TreeBin<K,V>)f).first : null);
1179 >                        while (p != null) {
1180 >                            --delta;
1181 >                            p = p.next;
1182                          }
1183 +                        setTabAt(tab, i++, null);
1184                      }
1185                  }
1186 <                if (validated) {
1187 <                    if (deleted)
1188 <                        addCount(-1L, -1);
1186 >            }
1187 >        }
1188 >        if (delta != 0L)
1189 >            addCount(delta, -1);
1190 >    }
1191 >
1192 >    /**
1193 >     * Returns a {@link Set} view of the keys contained in this map.
1194 >     * The set is backed by the map, so changes to the map are
1195 >     * reflected in the set, and vice-versa. The set supports element
1196 >     * removal, which removes the corresponding mapping from this map,
1197 >     * via the {@code Iterator.remove}, {@code Set.remove},
1198 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1199 >     * operations.  It does not support the {@code add} or
1200 >     * {@code addAll} operations.
1201 >     *
1202 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1203 >     * that will never throw {@link ConcurrentModificationException},
1204 >     * and guarantees to traverse elements as they existed upon
1205 >     * construction of the iterator, and may (but is not guaranteed to)
1206 >     * reflect any modifications subsequent to construction.
1207 >     *
1208 >     * @return the set view
1209 >     */
1210 >    public KeySetView<K,V> keySet() {
1211 >        KeySetView<K,V> ks;
1212 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1213 >    }
1214 >
1215 >    /**
1216 >     * Returns a {@link Collection} view of the values contained in this map.
1217 >     * The collection is backed by the map, so changes to the map are
1218 >     * reflected in the collection, and vice-versa.  The collection
1219 >     * supports element removal, which removes the corresponding
1220 >     * mapping from this map, via the {@code Iterator.remove},
1221 >     * {@code Collection.remove}, {@code removeAll},
1222 >     * {@code retainAll}, and {@code clear} operations.  It does not
1223 >     * support the {@code add} or {@code addAll} operations.
1224 >     *
1225 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1226 >     * that will never throw {@link ConcurrentModificationException},
1227 >     * and guarantees to traverse elements as they existed upon
1228 >     * construction of the iterator, and may (but is not guaranteed to)
1229 >     * reflect any modifications subsequent to construction.
1230 >     *
1231 >     * @return the collection view
1232 >     */
1233 >    public Collection<V> values() {
1234 >        ValuesView<K,V> vs;
1235 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1236 >    }
1237 >
1238 >    /**
1239 >     * Returns a {@link Set} view of the mappings contained in this map.
1240 >     * The set is backed by the map, so changes to the map are
1241 >     * reflected in the set, and vice-versa.  The set supports element
1242 >     * removal, which removes the corresponding mapping from the map,
1243 >     * via the {@code Iterator.remove}, {@code Set.remove},
1244 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1245 >     * operations.
1246 >     *
1247 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1248 >     * that will never throw {@link ConcurrentModificationException},
1249 >     * and guarantees to traverse elements as they existed upon
1250 >     * construction of the iterator, and may (but is not guaranteed to)
1251 >     * reflect any modifications subsequent to construction.
1252 >     *
1253 >     * @return the set view
1254 >     */
1255 >    public Set<Map.Entry<K,V>> entrySet() {
1256 >        EntrySetView<K,V> es;
1257 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1258 >    }
1259 >
1260 >    /**
1261 >     * Returns the hash code value for this {@link Map}, i.e.,
1262 >     * the sum of, for each key-value pair in the map,
1263 >     * {@code key.hashCode() ^ value.hashCode()}.
1264 >     *
1265 >     * @return the hash code value for this map
1266 >     */
1267 >    public int hashCode() {
1268 >        int h = 0;
1269 >        Node<K,V>[] t;
1270 >        if ((t = table) != null) {
1271 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1272 >            for (Node<K,V> p; (p = it.advance()) != null; )
1273 >                h += p.key.hashCode() ^ p.val.hashCode();
1274 >        }
1275 >        return h;
1276 >    }
1277 >
1278 >    /**
1279 >     * Returns a string representation of this map.  The string
1280 >     * representation consists of a list of key-value mappings (in no
1281 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1282 >     * mappings are separated by the characters {@code ", "} (comma
1283 >     * and space).  Each key-value mapping is rendered as the key
1284 >     * followed by an equals sign ("{@code =}") followed by the
1285 >     * associated value.
1286 >     *
1287 >     * @return a string representation of this map
1288 >     */
1289 >    public String toString() {
1290 >        Node<K,V>[] t;
1291 >        int f = (t = table) == null ? 0 : t.length;
1292 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1293 >        StringBuilder sb = new StringBuilder();
1294 >        sb.append('{');
1295 >        Node<K,V> p;
1296 >        if ((p = it.advance()) != null) {
1297 >            for (;;) {
1298 >                K k = p.key;
1299 >                V v = p.val;
1300 >                sb.append(k == this ? "(this Map)" : k);
1301 >                sb.append('=');
1302 >                sb.append(v == this ? "(this Map)" : v);
1303 >                if ((p = it.advance()) == null)
1304                      break;
1305 <                }
1305 >                sb.append(',').append(' ');
1306              }
1307          }
1308 <        return oldVal;
1308 >        return sb.append('}').toString();
1309      }
1310  
1311 <    /*
1312 <     * Internal versions of insertion methods
1313 <     * All have the same basic structure as the first (internalPut):
1314 <     *  1. If table uninitialized, create
1315 <     *  2. If bin empty, try to CAS new node
1316 <     *  3. If bin stale, use new table
1317 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1318 <     *  5. Lock and validate; if valid, scan and add or update
1319 <     *
1313 <     * The putAll method differs mainly in attempting to pre-allocate
1314 <     * enough table space, and also more lazily performs count updates
1315 <     * and checks.
1316 <     *
1317 <     * Most of the function-accepting methods can't be factored nicely
1318 <     * because they require different functional forms, so instead
1319 <     * sprawl out similar mechanics.
1311 >    /**
1312 >     * Compares the specified object with this map for equality.
1313 >     * Returns {@code true} if the given object is a map with the same
1314 >     * mappings as this map.  This operation may return misleading
1315 >     * results if either map is concurrently modified during execution
1316 >     * of this method.
1317 >     *
1318 >     * @param o object to be compared for equality with this map
1319 >     * @return {@code true} if the specified object is equal to this map
1320       */
1321 +    public boolean equals(Object o) {
1322 +        if (o != this) {
1323 +            if (!(o instanceof Map))
1324 +                return false;
1325 +            Map<?,?> m = (Map<?,?>) o;
1326 +            Node<K,V>[] t;
1327 +            int f = (t = table) == null ? 0 : t.length;
1328 +            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1329 +            for (Node<K,V> p; (p = it.advance()) != null; ) {
1330 +                V val = p.val;
1331 +                Object v = m.get(p.key);
1332 +                if (v == null || (v != val && !v.equals(val)))
1333 +                    return false;
1334 +            }
1335 +            for (Map.Entry<?,?> e : m.entrySet()) {
1336 +                Object mk, mv, v;
1337 +                if ((mk = e.getKey()) == null ||
1338 +                    (mv = e.getValue()) == null ||
1339 +                    (v = get(mk)) == null ||
1340 +                    (mv != v && !mv.equals(v)))
1341 +                    return false;
1342 +            }
1343 +        }
1344 +        return true;
1345 +    }
1346  
1347 <    /** Implementation for put and putIfAbsent */
1348 <    @SuppressWarnings("unchecked") private final V internalPut
1349 <        (K k, V v, boolean onlyIfAbsent) {
1350 <        if (k == null || v == null) throw new NullPointerException();
1351 <        int h = spread(k.hashCode());
1352 <        int len = 0;
1353 <        for (Node<V>[] tab = table;;) {
1354 <            int i, fh; Node<V> f; Object fk; V fv;
1355 <            if (tab == null)
1356 <                tab = initTable();
1357 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1358 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null)))
1359 <                    break;                   // no lock when adding to empty bin
1347 >    /**
1348 >     * Stripped-down version of helper class used in previous version,
1349 >     * declared for the sake of serialization compatibility
1350 >     */
1351 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1352 >        private static final long serialVersionUID = 2249069246763182397L;
1353 >        final float loadFactor;
1354 >        Segment(float lf) { this.loadFactor = lf; }
1355 >    }
1356 >
1357 >    /**
1358 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1359 >     * stream (i.e., serializes it).
1360 >     * @param s the stream
1361 >     * @serialData
1362 >     * the key (Object) and value (Object)
1363 >     * for each key-value mapping, followed by a null pair.
1364 >     * The key-value mappings are emitted in no particular order.
1365 >     */
1366 >    private void writeObject(java.io.ObjectOutputStream s)
1367 >        throws java.io.IOException {
1368 >        // For serialization compatibility
1369 >        // Emulate segment calculation from previous version of this class
1370 >        int sshift = 0;
1371 >        int ssize = 1;
1372 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1373 >            ++sshift;
1374 >            ssize <<= 1;
1375 >        }
1376 >        int segmentShift = 32 - sshift;
1377 >        int segmentMask = ssize - 1;
1378 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1379 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1380 >        for (int i = 0; i < segments.length; ++i)
1381 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1382 >        s.putFields().put("segments", segments);
1383 >        s.putFields().put("segmentShift", segmentShift);
1384 >        s.putFields().put("segmentMask", segmentMask);
1385 >        s.writeFields();
1386 >
1387 >        Node<K,V>[] t;
1388 >        if ((t = table) != null) {
1389 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1390 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1391 >                s.writeObject(p.key);
1392 >                s.writeObject(p.val);
1393              }
1394 <            else if ((fh = f.hash) < 0) {
1395 <                if ((fk = f.key) instanceof TreeBin) {
1396 <                    TreeBin<V> t = (TreeBin<V>)fk;
1397 <                    V oldVal = null;
1398 <                    t.acquire(0);
1399 <                    try {
1400 <                        if (tabAt(tab, i) == f) {
1401 <                            len = 2;
1402 <                            TreeNode<V> p = t.putTreeNode(h, k, v);
1403 <                            if (p != null) {
1404 <                                oldVal = p.val;
1405 <                                if (!onlyIfAbsent)
1406 <                                    p.val = v;
1407 <                            }
1408 <                        }
1409 <                    } finally {
1410 <                        t.release(0);
1411 <                    }
1412 <                    if (len != 0) {
1413 <                        if (oldVal != null)
1414 <                            return oldVal;
1415 <                        break;
1416 <                    }
1417 <                }
1418 <                else
1419 <                    tab = (Node<V>[])fk;
1394 >        }
1395 >        s.writeObject(null);
1396 >        s.writeObject(null);
1397 >        segments = null; // throw away
1398 >    }
1399 >
1400 >    /**
1401 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1402 >     * @param s the stream
1403 >     */
1404 >    private void readObject(java.io.ObjectInputStream s)
1405 >        throws java.io.IOException, ClassNotFoundException {
1406 >        /*
1407 >         * To improve performance in typical cases, we create nodes
1408 >         * while reading, then place in table once size is known.
1409 >         * However, we must also validate uniqueness and deal with
1410 >         * overpopulated bins while doing so, which requires
1411 >         * specialized versions of putVal mechanics.
1412 >         */
1413 >        sizeCtl = -1; // force exclusion for table construction
1414 >        s.defaultReadObject();
1415 >        long size = 0L;
1416 >        Node<K,V> p = null;
1417 >        for (;;) {
1418 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1419 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1420 >            if (k != null && v != null) {
1421 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1422 >                ++size;
1423              }
1424 <            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1425 <                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1426 <                return fv;
1424 >            else
1425 >                break;
1426 >        }
1427 >        if (size == 0L)
1428 >            sizeCtl = 0;
1429 >        else {
1430 >            int n;
1431 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1432 >                n = MAXIMUM_CAPACITY;
1433              else {
1434 <                V oldVal = null;
1435 <                synchronized (f) {
1436 <                    if (tabAt(tab, i) == f) {
1437 <                        len = 1;
1438 <                        for (Node<V> e = f;; ++len) {
1439 <                            Object ek; V ev;
1440 <                            if (e.hash == h &&
1441 <                                (ev = e.val) != null &&
1442 <                                ((ek = e.key) == k || k.equals(ek))) {
1443 <                                oldVal = ev;
1444 <                                if (!onlyIfAbsent)
1445 <                                    e.val = v;
1434 >                int sz = (int)size;
1435 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1436 >            }
1437 >            @SuppressWarnings({"rawtypes","unchecked"})
1438 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1439 >            int mask = n - 1;
1440 >            long added = 0L;
1441 >            while (p != null) {
1442 >                boolean insertAtFront;
1443 >                Node<K,V> next = p.next, first;
1444 >                int h = p.hash, j = h & mask;
1445 >                if ((first = tabAt(tab, j)) == null)
1446 >                    insertAtFront = true;
1447 >                else {
1448 >                    K k = p.key;
1449 >                    if (first.hash < 0) {
1450 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1451 >                        if (t.putTreeVal(h, k, p.val) == null)
1452 >                            ++added;
1453 >                        insertAtFront = false;
1454 >                    }
1455 >                    else {
1456 >                        int binCount = 0;
1457 >                        insertAtFront = true;
1458 >                        Node<K,V> q; K qk;
1459 >                        for (q = first; q != null; q = q.next) {
1460 >                            if (q.hash == h &&
1461 >                                ((qk = q.key) == k ||
1462 >                                 (qk != null && k.equals(qk)))) {
1463 >                                insertAtFront = false;
1464                                  break;
1465                              }
1466 <                            Node<V> last = e;
1467 <                            if ((e = e.next) == null) {
1468 <                                last.next = new Node<V>(h, k, v, null);
1469 <                                if (len >= TREE_THRESHOLD)
1470 <                                    replaceWithTreeBin(tab, i, k);
1471 <                                break;
1466 >                            ++binCount;
1467 >                        }
1468 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1469 >                            insertAtFront = false;
1470 >                            ++added;
1471 >                            p.next = first;
1472 >                            TreeNode<K,V> hd = null, tl = null;
1473 >                            for (q = p; q != null; q = q.next) {
1474 >                                TreeNode<K,V> t = new TreeNode<K,V>
1475 >                                    (q.hash, q.key, q.val, null, null);
1476 >                                if ((t.prev = tl) == null)
1477 >                                    hd = t;
1478 >                                else
1479 >                                    tl.next = t;
1480 >                                tl = t;
1481                              }
1482 +                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1483                          }
1484                      }
1485                  }
1486 <                if (len != 0) {
1487 <                    if (oldVal != null)
1488 <                        return oldVal;
1489 <                    break;
1486 >                if (insertAtFront) {
1487 >                    ++added;
1488 >                    p.next = first;
1489 >                    setTabAt(tab, j, p);
1490                  }
1491 +                p = next;
1492              }
1493 +            table = tab;
1494 +            sizeCtl = n - (n >>> 2);
1495 +            baseCount = added;
1496          }
1398        addCount(1L, len);
1399        return null;
1497      }
1498  
1499 <    /** Implementation for computeIfAbsent */
1500 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1501 <        (K k, Fun<? super K, ? extends V> mf) {
1502 <        if (k == null || mf == null)
1499 >    // ConcurrentMap methods
1500 >
1501 >    /**
1502 >     * {@inheritDoc}
1503 >     *
1504 >     * @return the previous value associated with the specified key,
1505 >     *         or {@code null} if there was no mapping for the key
1506 >     * @throws NullPointerException if the specified key or value is null
1507 >     */
1508 >    public V putIfAbsent(K key, V value) {
1509 >        return putVal(key, value, true);
1510 >    }
1511 >
1512 >    /**
1513 >     * {@inheritDoc}
1514 >     *
1515 >     * @throws NullPointerException if the specified key is null
1516 >     */
1517 >    public boolean remove(Object key, Object value) {
1518 >        if (key == null)
1519              throw new NullPointerException();
1520 <        int h = spread(k.hashCode());
1520 >        return value != null && replaceNode(key, null, value) != null;
1521 >    }
1522 >
1523 >    /**
1524 >     * {@inheritDoc}
1525 >     *
1526 >     * @throws NullPointerException if any of the arguments are null
1527 >     */
1528 >    public boolean replace(K key, V oldValue, V newValue) {
1529 >        if (key == null || oldValue == null || newValue == null)
1530 >            throw new NullPointerException();
1531 >        return replaceNode(key, newValue, oldValue) != null;
1532 >    }
1533 >
1534 >    /**
1535 >     * {@inheritDoc}
1536 >     *
1537 >     * @return the previous value associated with the specified key,
1538 >     *         or {@code null} if there was no mapping for the key
1539 >     * @throws NullPointerException if the specified key or value is null
1540 >     */
1541 >    public V replace(K key, V value) {
1542 >        if (key == null || value == null)
1543 >            throw new NullPointerException();
1544 >        return replaceNode(key, value, null);
1545 >    }
1546 >
1547 >    // Overrides of JDK8+ Map extension method defaults
1548 >
1549 >    /**
1550 >     * Returns the value to which the specified key is mapped, or the
1551 >     * given default value if this map contains no mapping for the
1552 >     * key.
1553 >     *
1554 >     * @param key the key whose associated value is to be returned
1555 >     * @param defaultValue the value to return if this map contains
1556 >     * no mapping for the given key
1557 >     * @return the mapping for the key, if present; else the default value
1558 >     * @throws NullPointerException if the specified key is null
1559 >     */
1560 >    public V getOrDefault(Object key, V defaultValue) {
1561 >        V v;
1562 >        return (v = get(key)) == null ? defaultValue : v;
1563 >    }
1564 >
1565 >    public void forEach(BiAction<? super K, ? super V> action) {
1566 >        if (action == null) throw new NullPointerException();
1567 >        Node<K,V>[] t;
1568 >        if ((t = table) != null) {
1569 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1570 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1571 >                action.apply(p.key, p.val);
1572 >            }
1573 >        }
1574 >    }
1575 >
1576 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1577 >        if (function == null) throw new NullPointerException();
1578 >        Node<K,V>[] t;
1579 >        if ((t = table) != null) {
1580 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1581 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1582 >                V oldValue = p.val;
1583 >                for (K key = p.key;;) {
1584 >                    V newValue = function.apply(key, oldValue);
1585 >                    if (newValue == null)
1586 >                        throw new NullPointerException();
1587 >                    if (replaceNode(key, newValue, oldValue) != null ||
1588 >                        (oldValue = get(key)) == null)
1589 >                        break;
1590 >                }
1591 >            }
1592 >        }
1593 >    }
1594 >
1595 >    /**
1596 >     * If the specified key is not already associated with a value,
1597 >     * attempts to compute its value using the given mapping function
1598 >     * and enters it into this map unless {@code null}.  The entire
1599 >     * method invocation is performed atomically, so the function is
1600 >     * applied at most once per key.  Some attempted update operations
1601 >     * on this map by other threads may be blocked while computation
1602 >     * is in progress, so the computation should be short and simple,
1603 >     * and must not attempt to update any other mappings of this map.
1604 >     *
1605 >     * @param key key with which the specified value is to be associated
1606 >     * @param mappingFunction the function to compute a value
1607 >     * @return the current (existing or computed) value associated with
1608 >     *         the specified key, or null if the computed value is null
1609 >     * @throws NullPointerException if the specified key or mappingFunction
1610 >     *         is null
1611 >     * @throws IllegalStateException if the computation detectably
1612 >     *         attempts a recursive update to this map that would
1613 >     *         otherwise never complete
1614 >     * @throws RuntimeException or Error if the mappingFunction does so,
1615 >     *         in which case the mapping is left unestablished
1616 >     */
1617 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1618 >        if (key == null || mappingFunction == null)
1619 >            throw new NullPointerException();
1620 >        int h = spread(key.hashCode());
1621          V val = null;
1622 <        int len = 0;
1623 <        for (Node<V>[] tab = table;;) {
1624 <            Node<V> f; int i; Object fk;
1625 <            if (tab == null)
1622 >        int binCount = 0;
1623 >        for (Node<K,V>[] tab = table;;) {
1624 >            Node<K,V> f; int n, i, fh;
1625 >            if (tab == null || (n = tab.length) == 0)
1626                  tab = initTable();
1627 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1628 <                Node<V> node = new Node<V>(h, k, null, null);
1629 <                synchronized (node) {
1630 <                    if (casTabAt(tab, i, null, node)) {
1631 <                        len = 1;
1627 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1628 >                Node<K,V> r = new ReservationNode<K,V>();
1629 >                synchronized (r) {
1630 >                    if (casTabAt(tab, i, null, r)) {
1631 >                        binCount = 1;
1632 >                        Node<K,V> node = null;
1633                          try {
1634 <                            if ((val = mf.apply(k)) != null)
1635 <                                node.val = val;
1634 >                            if ((val = mappingFunction.apply(key)) != null)
1635 >                                node = new Node<K,V>(h, key, val, null);
1636                          } finally {
1637 <                            if (val == null)
1424 <                                setTabAt(tab, i, null);
1637 >                            setTabAt(tab, i, node);
1638                          }
1639                      }
1640                  }
1641 <                if (len != 0)
1641 >                if (binCount != 0)
1642                      break;
1643              }
1644 <            else if (f.hash < 0) {
1645 <                if ((fk = f.key) instanceof TreeBin) {
1646 <                    TreeBin<V> t = (TreeBin<V>)fk;
1647 <                    boolean added = false;
1648 <                    t.acquire(0);
1649 <                    try {
1650 <                        if (tabAt(tab, i) == f) {
1651 <                            len = 1;
1652 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1653 <                            if (p != null)
1644 >            else if ((fh = f.hash) == MOVED)
1645 >                tab = helpTransfer(tab, f);
1646 >            else {
1647 >                boolean added = false;
1648 >                synchronized (f) {
1649 >                    if (tabAt(tab, i) == f) {
1650 >                        if (fh >= 0) {
1651 >                            binCount = 1;
1652 >                            for (Node<K,V> e = f;; ++binCount) {
1653 >                                K ek; V ev;
1654 >                                if (e.hash == h &&
1655 >                                    ((ek = e.key) == key ||
1656 >                                     (ek != null && key.equals(ek)))) {
1657 >                                    val = e.val;
1658 >                                    break;
1659 >                                }
1660 >                                Node<K,V> pred = e;
1661 >                                if ((e = e.next) == null) {
1662 >                                    if ((val = mappingFunction.apply(key)) != null) {
1663 >                                        added = true;
1664 >                                        pred.next = new Node<K,V>(h, key, val, null);
1665 >                                    }
1666 >                                    break;
1667 >                                }
1668 >                            }
1669 >                        }
1670 >                        else if (f instanceof TreeBin) {
1671 >                            binCount = 2;
1672 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1673 >                            TreeNode<K,V> r, p;
1674 >                            if ((r = t.root) != null &&
1675 >                                (p = r.findTreeNode(h, key, null)) != null)
1676                                  val = p.val;
1677 <                            else if ((val = mf.apply(k)) != null) {
1677 >                            else if ((val = mappingFunction.apply(key)) != null) {
1678                                  added = true;
1679 <                                len = 2;
1445 <                                t.putTreeNode(h, k, val);
1679 >                                t.putTreeVal(h, key, val);
1680                              }
1681                          }
1448                    } finally {
1449                        t.release(0);
1450                    }
1451                    if (len != 0) {
1452                        if (!added)
1453                            return val;
1454                        break;
1682                      }
1683                  }
1684 <                else
1685 <                    tab = (Node<V>[])fk;
1684 >                if (binCount != 0) {
1685 >                    if (binCount >= TREEIFY_THRESHOLD)
1686 >                        treeifyBin(tab, i);
1687 >                    if (!added)
1688 >                        return val;
1689 >                    break;
1690 >                }
1691              }
1692 +        }
1693 +        if (val != null)
1694 +            addCount(1L, binCount);
1695 +        return val;
1696 +    }
1697 +
1698 +    /**
1699 +     * If the value for the specified key is present, attempts to
1700 +     * compute a new mapping given the key and its current mapped
1701 +     * value.  The entire method invocation is performed atomically.
1702 +     * Some attempted update operations on this map by other threads
1703 +     * may be blocked while computation is in progress, so the
1704 +     * computation should be short and simple, and must not attempt to
1705 +     * update any other mappings of this map.
1706 +     *
1707 +     * @param key key with which a value may be associated
1708 +     * @param remappingFunction the function to compute a value
1709 +     * @return the new value associated with the specified key, or null if none
1710 +     * @throws NullPointerException if the specified key or remappingFunction
1711 +     *         is null
1712 +     * @throws IllegalStateException if the computation detectably
1713 +     *         attempts a recursive update to this map that would
1714 +     *         otherwise never complete
1715 +     * @throws RuntimeException or Error if the remappingFunction does so,
1716 +     *         in which case the mapping is unchanged
1717 +     */
1718 +    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1719 +        if (key == null || remappingFunction == null)
1720 +            throw new NullPointerException();
1721 +        int h = spread(key.hashCode());
1722 +        V val = null;
1723 +        int delta = 0;
1724 +        int binCount = 0;
1725 +        for (Node<K,V>[] tab = table;;) {
1726 +            Node<K,V> f; int n, i, fh;
1727 +            if (tab == null || (n = tab.length) == 0)
1728 +                tab = initTable();
1729 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1730 +                break;
1731 +            else if ((fh = f.hash) == MOVED)
1732 +                tab = helpTransfer(tab, f);
1733              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;
1734                  synchronized (f) {
1735                      if (tabAt(tab, i) == f) {
1736 <                        len = 1;
1737 <                        for (Node<V> e = f;; ++len) {
1738 <                            Object ek; V ev;
1739 <                            if (e.hash == h &&
1740 <                                (ev = e.val) != null &&
1741 <                                ((ek = e.key) == k || k.equals(ek))) {
1742 <                                val = ev;
1743 <                                break;
1736 >                        if (fh >= 0) {
1737 >                            binCount = 1;
1738 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1739 >                                K ek;
1740 >                                if (e.hash == h &&
1741 >                                    ((ek = e.key) == key ||
1742 >                                     (ek != null && key.equals(ek)))) {
1743 >                                    val = remappingFunction.apply(key, e.val);
1744 >                                    if (val != null)
1745 >                                        e.val = val;
1746 >                                    else {
1747 >                                        delta = -1;
1748 >                                        Node<K,V> en = e.next;
1749 >                                        if (pred != null)
1750 >                                            pred.next = en;
1751 >                                        else
1752 >                                            setTabAt(tab, i, en);
1753 >                                    }
1754 >                                    break;
1755 >                                }
1756 >                                pred = e;
1757 >                                if ((e = e.next) == null)
1758 >                                    break;
1759                              }
1760 <                            Node<V> last = e;
1761 <                            if ((e = e.next) == null) {
1762 <                                if ((val = mf.apply(k)) != null) {
1763 <                                    added = true;
1764 <                                    last.next = new Node<V>(h, k, val, null);
1765 <                                    if (len >= TREE_THRESHOLD)
1766 <                                        replaceWithTreeBin(tab, i, k);
1760 >                        }
1761 >                        else if (f instanceof TreeBin) {
1762 >                            binCount = 2;
1763 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1764 >                            TreeNode<K,V> r, p;
1765 >                            if ((r = t.root) != null &&
1766 >                                (p = r.findTreeNode(h, key, null)) != null) {
1767 >                                val = remappingFunction.apply(key, p.val);
1768 >                                if (val != null)
1769 >                                    p.val = val;
1770 >                                else {
1771 >                                    delta = -1;
1772 >                                    if (t.removeTreeNode(p))
1773 >                                        setTabAt(tab, i, untreeify(t.first));
1774                                  }
1487                                break;
1775                              }
1776                          }
1777                      }
1778                  }
1779 <                if (len != 0) {
1493 <                    if (!added)
1494 <                        return val;
1779 >                if (binCount != 0)
1780                      break;
1496                }
1781              }
1782          }
1783 <        if (val != null)
1784 <            addCount(1L, len);
1783 >        if (delta != 0)
1784 >            addCount((long)delta, binCount);
1785          return val;
1786      }
1787  
1788 <    /** Implementation for compute */
1789 <    @SuppressWarnings("unchecked") private final V internalCompute
1790 <        (K k, boolean onlyIfPresent,
1791 <         BiFun<? super K, ? super V, ? extends V> mf) {
1792 <        if (k == null || mf == null)
1788 >    /**
1789 >     * Attempts to compute a mapping for the specified key and its
1790 >     * current mapped value (or {@code null} if there is no current
1791 >     * mapping). The entire method invocation is performed atomically.
1792 >     * Some attempted update operations on this map by other threads
1793 >     * may be blocked while computation is in progress, so the
1794 >     * computation should be short and simple, and must not attempt to
1795 >     * update any other mappings of this Map.
1796 >     *
1797 >     * @param key key with which the specified value is to be associated
1798 >     * @param remappingFunction the function to compute a value
1799 >     * @return the new value associated with the specified key, or null if none
1800 >     * @throws NullPointerException if the specified key or remappingFunction
1801 >     *         is null
1802 >     * @throws IllegalStateException if the computation detectably
1803 >     *         attempts a recursive update to this map that would
1804 >     *         otherwise never complete
1805 >     * @throws RuntimeException or Error if the remappingFunction does so,
1806 >     *         in which case the mapping is unchanged
1807 >     */
1808 >    public V compute(K key,
1809 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1810 >        if (key == null || remappingFunction == null)
1811              throw new NullPointerException();
1812 <        int h = spread(k.hashCode());
1812 >        int h = spread(key.hashCode());
1813          V val = null;
1814          int delta = 0;
1815 <        int len = 0;
1816 <        for (Node<V>[] tab = table;;) {
1817 <            Node<V> f; int i, fh; Object fk;
1818 <            if (tab == null)
1815 >        int binCount = 0;
1816 >        for (Node<K,V>[] tab = table;;) {
1817 >            Node<K,V> f; int n, i, fh;
1818 >            if (tab == null || (n = tab.length) == 0)
1819                  tab = initTable();
1820 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1821 <                if (onlyIfPresent)
1822 <                    break;
1823 <                Node<V> node = new Node<V>(h, k, null, null);
1824 <                synchronized (node) {
1825 <                    if (casTabAt(tab, i, null, node)) {
1820 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1821 >                Node<K,V> r = new ReservationNode<K,V>();
1822 >                synchronized (r) {
1823 >                    if (casTabAt(tab, i, null, r)) {
1824 >                        binCount = 1;
1825 >                        Node<K,V> node = null;
1826                          try {
1827 <                            len = 1;
1526 <                            if ((val = mf.apply(k, null)) != null) {
1527 <                                node.val = val;
1827 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1828                                  delta = 1;
1829 +                                node = new Node<K,V>(h, key, val, null);
1830                              }
1831                          } finally {
1832 <                            if (delta == 0)
1532 <                                setTabAt(tab, i, null);
1832 >                            setTabAt(tab, i, node);
1833                          }
1834                      }
1835                  }
1836 <                if (len != 0)
1836 >                if (binCount != 0)
1837                      break;
1838              }
1839 <            else if ((fh = f.hash) < 0) {
1840 <                if ((fk = f.key) instanceof TreeBin) {
1841 <                    TreeBin<V> t = (TreeBin<V>)fk;
1842 <                    t.acquire(0);
1843 <                    try {
1844 <                        if (tabAt(tab, i) == f) {
1845 <                            len = 1;
1846 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1847 <                            if (p == null && onlyIfPresent)
1848 <                                break;
1839 >            else if ((fh = f.hash) == MOVED)
1840 >                tab = helpTransfer(tab, f);
1841 >            else {
1842 >                synchronized (f) {
1843 >                    if (tabAt(tab, i) == f) {
1844 >                        if (fh >= 0) {
1845 >                            binCount = 1;
1846 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1847 >                                K ek;
1848 >                                if (e.hash == h &&
1849 >                                    ((ek = e.key) == key ||
1850 >                                     (ek != null && key.equals(ek)))) {
1851 >                                    val = remappingFunction.apply(key, e.val);
1852 >                                    if (val != null)
1853 >                                        e.val = val;
1854 >                                    else {
1855 >                                        delta = -1;
1856 >                                        Node<K,V> en = e.next;
1857 >                                        if (pred != null)
1858 >                                            pred.next = en;
1859 >                                        else
1860 >                                            setTabAt(tab, i, en);
1861 >                                    }
1862 >                                    break;
1863 >                                }
1864 >                                pred = e;
1865 >                                if ((e = e.next) == null) {
1866 >                                    val = remappingFunction.apply(key, null);
1867 >                                    if (val != null) {
1868 >                                        delta = 1;
1869 >                                        pred.next =
1870 >                                            new Node<K,V>(h, key, val, null);
1871 >                                    }
1872 >                                    break;
1873 >                                }
1874 >                            }
1875 >                        }
1876 >                        else if (f instanceof TreeBin) {
1877 >                            binCount = 1;
1878 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1879 >                            TreeNode<K,V> r, p;
1880 >                            if ((r = t.root) != null)
1881 >                                p = r.findTreeNode(h, key, null);
1882 >                            else
1883 >                                p = null;
1884                              V pv = (p == null) ? null : p.val;
1885 <                            if ((val = mf.apply(k, pv)) != null) {
1885 >                            val = remappingFunction.apply(key, pv);
1886 >                            if (val != null) {
1887                                  if (p != null)
1888                                      p.val = val;
1889                                  else {
1554                                    len = 2;
1890                                      delta = 1;
1891 <                                    t.putTreeNode(h, k, val);
1891 >                                    t.putTreeVal(h, key, val);
1892                                  }
1893                              }
1894                              else if (p != null) {
1895                                  delta = -1;
1896 <                                t.deleteTreeNode(p);
1896 >                                if (t.removeTreeNode(p))
1897 >                                    setTabAt(tab, i, untreeify(t.first));
1898                              }
1899                          }
1564                    } finally {
1565                        t.release(0);
1900                      }
1567                    if (len != 0)
1568                        break;
1901                  }
1902 <                else
1903 <                    tab = (Node<V>[])fk;
1904 <            }
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)
1902 >                if (binCount != 0) {
1903 >                    if (binCount >= TREEIFY_THRESHOLD)
1904 >                        treeifyBin(tab, i);
1905                      break;
1906 +                }
1907              }
1908          }
1909          if (delta != 0)
1910 <            addCount((long)delta, len);
1910 >            addCount((long)delta, binCount);
1911          return val;
1912      }
1913  
1914 <    /** Implementation for merge */
1915 <    @SuppressWarnings("unchecked") private final V internalMerge
1916 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1917 <        if (k == null || v == null || mf == null)
1914 >    /**
1915 >     * If the specified key is not already associated with a
1916 >     * (non-null) value, associates it with the given value.
1917 >     * Otherwise, replaces the value with the results of the given
1918 >     * remapping function, or removes if {@code null}. The entire
1919 >     * method invocation is performed atomically.  Some attempted
1920 >     * update operations on this map by other threads may be blocked
1921 >     * while computation is in progress, so the computation should be
1922 >     * short and simple, and must not attempt to update any other
1923 >     * mappings of this Map.
1924 >     *
1925 >     * @param key key with which the specified value is to be associated
1926 >     * @param value the value to use if absent
1927 >     * @param remappingFunction the function to recompute a value if present
1928 >     * @return the new value associated with the specified key, or null if none
1929 >     * @throws NullPointerException if the specified key or the
1930 >     *         remappingFunction is null
1931 >     * @throws RuntimeException or Error if the remappingFunction does so,
1932 >     *         in which case the mapping is unchanged
1933 >     */
1934 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1935 >        if (key == null || value == null || remappingFunction == null)
1936              throw new NullPointerException();
1937 <        int h = spread(k.hashCode());
1937 >        int h = spread(key.hashCode());
1938          V val = null;
1939          int delta = 0;
1940 <        int len = 0;
1941 <        for (Node<V>[] tab = table;;) {
1942 <            int i; Node<V> f; Object fk; V fv;
1943 <            if (tab == null)
1940 >        int binCount = 0;
1941 >        for (Node<K,V>[] tab = table;;) {
1942 >            Node<K,V> f; int n, i, fh;
1943 >            if (tab == null || (n = tab.length) == 0)
1944                  tab = initTable();
1945 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1946 <                if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
1945 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1946 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1947                      delta = 1;
1948 <                    val = v;
1948 >                    val = value;
1949                      break;
1950                  }
1951              }
1952 <            else if (f.hash < 0) {
1953 <                if ((fk = f.key) instanceof TreeBin) {
1954 <                    TreeBin<V> t = (TreeBin<V>)fk;
1955 <                    t.acquire(0);
1956 <                    try {
1957 <                        if (tabAt(tab, i) == f) {
1958 <                            len = 1;
1959 <                            TreeNode<V> p = t.getTreeNode(h, k, t.root);
1960 <                            val = (p == null) ? v : mf.apply(p.val, v);
1952 >            else if ((fh = f.hash) == MOVED)
1953 >                tab = helpTransfer(tab, f);
1954 >            else {
1955 >                synchronized (f) {
1956 >                    if (tabAt(tab, i) == f) {
1957 >                        if (fh >= 0) {
1958 >                            binCount = 1;
1959 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1960 >                                K ek;
1961 >                                if (e.hash == h &&
1962 >                                    ((ek = e.key) == key ||
1963 >                                     (ek != null && key.equals(ek)))) {
1964 >                                    val = remappingFunction.apply(e.val, value);
1965 >                                    if (val != null)
1966 >                                        e.val = val;
1967 >                                    else {
1968 >                                        delta = -1;
1969 >                                        Node<K,V> en = e.next;
1970 >                                        if (pred != null)
1971 >                                            pred.next = en;
1972 >                                        else
1973 >                                            setTabAt(tab, i, en);
1974 >                                    }
1975 >                                    break;
1976 >                                }
1977 >                                pred = e;
1978 >                                if ((e = e.next) == null) {
1979 >                                    delta = 1;
1980 >                                    val = value;
1981 >                                    pred.next =
1982 >                                        new Node<K,V>(h, key, val, null);
1983 >                                    break;
1984 >                                }
1985 >                            }
1986 >                        }
1987 >                        else if (f instanceof TreeBin) {
1988 >                            binCount = 2;
1989 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1990 >                            TreeNode<K,V> r = t.root;
1991 >                            TreeNode<K,V> p = (r == null) ? null :
1992 >                                r.findTreeNode(h, key, null);
1993 >                            val = (p == null) ? value :
1994 >                                remappingFunction.apply(p.val, value);
1995                              if (val != null) {
1996                                  if (p != null)
1997                                      p.val = val;
1998                                  else {
1651                                    len = 2;
1999                                      delta = 1;
2000 <                                    t.putTreeNode(h, k, val);
2000 >                                    t.putTreeVal(h, key, val);
2001                                  }
2002                              }
2003                              else if (p != null) {
2004                                  delta = -1;
2005 <                                t.deleteTreeNode(p);
2006 <                            }
1660 <                        }
1661 <                    } finally {
1662 <                        t.release(0);
1663 <                    }
1664 <                    if (len != 0)
1665 <                        break;
1666 <                }
1667 <                else
1668 <                    tab = (Node<V>[])fk;
1669 <            }
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;
2005 >                                if (t.removeTreeNode(p))
2006 >                                    setTabAt(tab, i, untreeify(t.first));
2007                              }
2008                          }
2009                      }
2010                  }
2011 <                if (len != 0)
2011 >                if (binCount != 0) {
2012 >                    if (binCount >= TREEIFY_THRESHOLD)
2013 >                        treeifyBin(tab, i);
2014                      break;
2015 +                }
2016              }
2017          }
2018          if (delta != 0)
2019 <            addCount((long)delta, len);
2019 >            addCount((long)delta, binCount);
2020          return val;
2021      }
2022  
2023 <    /** Implementation for putAll */
2024 <    @SuppressWarnings("unchecked") private final void internalPutAll
2025 <        (Map<? extends K, ? extends V> m) {
2026 <        tryPresize(m.size());
2027 <        long delta = 0L;     // number of uncommitted additions
2028 <        boolean npe = false; // to throw exception on exit for nulls
2029 <        try {                // to clean up counts on other exceptions
2030 <            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
2031 <                Object k; V v;
2032 <                if (entry == null || (k = entry.getKey()) == null ||
2033 <                    (v = entry.getValue()) == null) {
2034 <                    npe = true;
2035 <                    break;
2036 <                }
2037 <                int h = spread(k.hashCode());
2038 <                for (Node<V>[] tab = table;;) {
2039 <                    int i; Node<V> f; int fh; Object fk;
2040 <                    if (tab == null)
2041 <                        tab = initTable();
2042 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2043 <                        if (casTabAt(tab, i, null, new Node<V>(h, k, v, null))) {
2044 <                            ++delta;
2045 <                            break;
2046 <                        }
2047 <                    }
2048 <                    else if ((fh = f.hash) < 0) {
2049 <                        if ((fk = f.key) instanceof TreeBin) {
2050 <                            TreeBin<V> t = (TreeBin<V>)fk;
2051 <                            boolean validated = false;
2052 <                            t.acquire(0);
2053 <                            try {
2054 <                                if (tabAt(tab, i) == f) {
2055 <                                    validated = true;
2056 <                                    TreeNode<V> p = t.getTreeNode(h, k, t.root);
2057 <                                    if (p != null)
2058 <                                        p.val = v;
2059 <                                    else {
2060 <                                        t.putTreeNode(h, k, v);
2061 <                                        ++delta;
2062 <                                    }
2063 <                                }
2064 <                            } finally {
2065 <                                t.release(0);
2066 <                            }
2067 <                            if (validated)
2068 <                                break;
2069 <                        }
2070 <                        else
2071 <                            tab = (Node<V>[])fk;
2072 <                    }
2073 <                    else {
2074 <                        int len = 0;
2075 <                        synchronized (f) {
2076 <                            if (tabAt(tab, i) == f) {
2077 <                                len = 1;
2078 <                                for (Node<V> e = f;; ++len) {
2079 <                                    Object ek; V ev;
2080 <                                    if (e.hash == h &&
2081 <                                        (ev = e.val) != null &&
2082 <                                        ((ek = e.key) == k || k.equals(ek))) {
2083 <                                        e.val = v;
2084 <                                        break;
2085 <                                    }
2086 <                                    Node<V> last = e;
2087 <                                    if ((e = e.next) == null) {
2088 <                                        ++delta;
2089 <                                        last.next = new Node<V>(h, k, v, null);
2090 <                                        if (len >= TREE_THRESHOLD)
2091 <                                            replaceWithTreeBin(tab, i, k);
2092 <                                        break;
2093 <                                    }
2094 <                                }
2095 <                            }
2096 <                        }
2097 <                        if (len != 0) {
2098 <                            if (len > 1) {
2099 <                                addCount(delta, len);
2100 <                                delta = 0L;
2101 <                            }
2102 <                            break;
2103 <                        }
2104 <                    }
2105 <                }
2106 <            }
2107 <        } finally {
2108 <            if (delta != 0L)
2109 <                addCount(delta, 2);
2110 <        }
2111 <        if (npe)
2023 >    // Hashtable legacy methods
2024 >
2025 >    /**
2026 >     * Legacy method testing if some key maps into the specified value
2027 >     * in this table.  This method is identical in functionality to
2028 >     * {@link #containsValue(Object)}, and exists solely to ensure
2029 >     * full compatibility with class {@link java.util.Hashtable},
2030 >     * which supported this method prior to introduction of the
2031 >     * Java Collections framework.
2032 >     *
2033 >     * @param  value a value to search for
2034 >     * @return {@code true} if and only if some key maps to the
2035 >     *         {@code value} argument in this table as
2036 >     *         determined by the {@code equals} method;
2037 >     *         {@code false} otherwise
2038 >     * @throws NullPointerException if the specified value is null
2039 >     */
2040 >    @Deprecated public boolean contains(Object value) {
2041 >        return containsValue(value);
2042 >    }
2043 >
2044 >    /**
2045 >     * Returns an enumeration of the keys in this table.
2046 >     *
2047 >     * @return an enumeration of the keys in this table
2048 >     * @see #keySet()
2049 >     */
2050 >    public Enumeration<K> keys() {
2051 >        Node<K,V>[] t;
2052 >        int f = (t = table) == null ? 0 : t.length;
2053 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2054 >    }
2055 >
2056 >    /**
2057 >     * Returns an enumeration of the values in this table.
2058 >     *
2059 >     * @return an enumeration of the values in this table
2060 >     * @see #values()
2061 >     */
2062 >    public Enumeration<V> elements() {
2063 >        Node<K,V>[] t;
2064 >        int f = (t = table) == null ? 0 : t.length;
2065 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2066 >    }
2067 >
2068 >    // ConcurrentHashMapV8-only methods
2069 >
2070 >    /**
2071 >     * Returns the number of mappings. This method should be used
2072 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2073 >     * contain more mappings than can be represented as an int. The
2074 >     * value returned is an estimate; the actual count may differ if
2075 >     * there are concurrent insertions or removals.
2076 >     *
2077 >     * @return the number of mappings
2078 >     * @since 1.8
2079 >     */
2080 >    public long mappingCount() {
2081 >        long n = sumCount();
2082 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2083 >    }
2084 >
2085 >    /**
2086 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2087 >     * from the given type to {@code Boolean.TRUE}.
2088 >     *
2089 >     * @return the new set
2090 >     * @since 1.8
2091 >     */
2092 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2093 >        return new KeySetView<K,Boolean>
2094 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2095 >    }
2096 >
2097 >    /**
2098 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2099 >     * from the given type to {@code Boolean.TRUE}.
2100 >     *
2101 >     * @param initialCapacity The implementation performs internal
2102 >     * sizing to accommodate this many elements.
2103 >     * @throws IllegalArgumentException if the initial capacity of
2104 >     * elements is negative
2105 >     * @return the new set
2106 >     * @since 1.8
2107 >     */
2108 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2109 >        return new KeySetView<K,Boolean>
2110 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2111 >    }
2112 >
2113 >    /**
2114 >     * Returns a {@link Set} view of the keys in this map, using the
2115 >     * given common mapped value for any additions (i.e., {@link
2116 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2117 >     * This is of course only appropriate if it is acceptable to use
2118 >     * the same value for all additions from this view.
2119 >     *
2120 >     * @param mappedValue the mapped value to use for any additions
2121 >     * @return the set view
2122 >     * @throws NullPointerException if the mappedValue is null
2123 >     */
2124 >    public KeySetView<K,V> keySet(V mappedValue) {
2125 >        if (mappedValue == null)
2126              throw new NullPointerException();
2127 +        return new KeySetView<K,V>(this, mappedValue);
2128      }
2129  
2130 +    /* ---------------- Special Nodes -------------- */
2131 +
2132      /**
2133 <     * Implementation for clear. Steps through each bin, removing all
1807 <     * nodes.
2133 >     * A node inserted at head of bins during transfer operations.
2134       */
2135 <    @SuppressWarnings("unchecked") private final void internalClear() {
2136 <        long delta = 0L; // negative number of deletions
2137 <        int i = 0;
2138 <        Node<V>[] tab = table;
2139 <        while (tab != null && i < tab.length) {
2140 <            Node<V> f = tabAt(tab, i);
2141 <            if (f == null)
2142 <                ++i;
2143 <            else if (f.hash < 0) {
2144 <                Object fk;
2145 <                if ((fk = f.key) instanceof TreeBin) {
2146 <                    TreeBin<V> t = (TreeBin<V>)fk;
2147 <                    t.acquire(0);
2148 <                    try {
2149 <                        if (tabAt(tab, i) == f) {
2150 <                            for (Node<V> p = t.first; p != null; p = p.next) {
2151 <                                if (p.val != null) { // (currently always true)
2152 <                                    p.val = null;
2153 <                                    --delta;
2154 <                                }
1829 <                            }
1830 <                            t.first = null;
1831 <                            t.root = null;
1832 <                            ++i;
1833 <                        }
1834 <                    } finally {
1835 <                        t.release(0);
1836 <                    }
1837 <                }
1838 <                else
1839 <                    tab = (Node<V>[])fk;
1840 <            }
1841 <            else {
1842 <                synchronized (f) {
1843 <                    if (tabAt(tab, i) == f) {
1844 <                        for (Node<V> e = f; e != null; e = e.next) {
1845 <                            if (e.val != null) {  // (currently always true)
1846 <                                e.val = null;
1847 <                                --delta;
1848 <                            }
1849 <                        }
1850 <                        setTabAt(tab, i, null);
1851 <                        ++i;
1852 <                    }
1853 <                }
2135 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2136 >        final Node<K,V>[] nextTable;
2137 >        ForwardingNode(Node<K,V>[] tab) {
2138 >            super(MOVED, null, null, null);
2139 >            this.nextTable = tab;
2140 >        }
2141 >
2142 >        Node<K,V> find(int h, Object k) {
2143 >            Node<K,V> e; int n;
2144 >            Node<K,V>[] tab = nextTable;
2145 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2146 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2147 >                do {
2148 >                    int eh; K ek;
2149 >                    if ((eh = e.hash) == h &&
2150 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2151 >                        return e;
2152 >                    if (eh < 0)
2153 >                        return e.find(h, k);
2154 >                } while ((e = e.next) != null);
2155              }
2156 +            return null;
2157          }
1856        if (delta != 0L)
1857            addCount(delta, -1);
2158      }
2159  
1860    /* ---------------- Table Initialization and Resizing -------------- */
1861
2160      /**
2161 <     * Returns a power of two table size for the given desired capacity.
1864 <     * See Hackers Delight, sec 3.2
2161 >     * A place-holder node used in computeIfAbsent and compute
2162       */
2163 <    private static final int tableSizeFor(int c) {
2164 <        int n = c - 1;
2165 <        n |= n >>> 1;
2166 <        n |= n >>> 2;
2167 <        n |= n >>> 4;
2168 <        n |= n >>> 8;
2169 <        n |= n >>> 16;
2170 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2163 >    static final class ReservationNode<K,V> extends Node<K,V> {
2164 >        ReservationNode() {
2165 >            super(RESERVED, null, null, null);
2166 >        }
2167 >
2168 >        Node<K,V> find(int h, Object k) {
2169 >            return null;
2170 >        }
2171      }
2172  
2173 +    /* ---------------- Table Initialization and Resizing -------------- */
2174 +
2175      /**
2176       * Initializes table, using the size recorded in sizeCtl.
2177       */
2178 <    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
2179 <        Node<V>[] tab; int sc;
2180 <        while ((tab = table) == null) {
2178 >    private final Node<K,V>[] initTable() {
2179 >        Node<K,V>[] tab; int sc;
2180 >        while ((tab = table) == null || tab.length == 0) {
2181              if ((sc = sizeCtl) < 0)
2182                  Thread.yield(); // lost initialization race; just spin
2183              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2184                  try {
2185 <                    if ((tab = table) == null) {
2185 >                    if ((tab = table) == null || tab.length == 0) {
2186                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2187 <                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2188 <                        table = tab = (Node<V>[])tb;
2187 >                        @SuppressWarnings({"rawtypes","unchecked"})
2188 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2189 >                        table = tab = nt;
2190                          sc = n - (n >>> 2);
2191                      }
2192                  } finally {
# Line 1927 | Line 2227 | public class ConcurrentHashMapV8<K, V>
2227              s = sumCount();
2228          }
2229          if (check >= 0) {
2230 <            Node<V>[] tab, nt; int sc;
2230 >            Node<K,V>[] tab, nt; int sc;
2231              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2232                     tab.length < MAXIMUM_CAPACITY) {
2233                  if (sc < 0) {
# Line 1945 | Line 2245 | public class ConcurrentHashMapV8<K, V>
2245      }
2246  
2247      /**
2248 +     * Helps transfer if a resize is in progress.
2249 +     */
2250 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2251 +        Node<K,V>[] nextTab; int sc;
2252 +        if ((f instanceof ForwardingNode) &&
2253 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2254 +            if (nextTab == nextTable && tab == table &&
2255 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2256 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2257 +                transfer(tab, nextTab);
2258 +            return nextTab;
2259 +        }
2260 +        return table;
2261 +    }
2262 +
2263 +    /**
2264       * Tries to presize table to accommodate the given number of elements.
2265       *
2266       * @param size number of elements (doesn't need to be perfectly accurate)
2267       */
2268 <    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
2268 >    private final void tryPresize(int size) {
2269          int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2270              tableSizeFor(size + (size >>> 1) + 1);
2271          int sc;
2272          while ((sc = sizeCtl) >= 0) {
2273 <            Node<V>[] tab = table; int n;
2273 >            Node<K,V>[] tab = table; int n;
2274              if (tab == null || (n = tab.length) == 0) {
2275                  n = (sc > c) ? sc : c;
2276                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2277                      try {
2278                          if (table == tab) {
2279 <                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
2280 <                            table = (Node<V>[])tb;
2279 >                            @SuppressWarnings({"rawtypes","unchecked"})
2280 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2281 >                            table = nt;
2282                              sc = n - (n >>> 2);
2283                          }
2284                      } finally {
# Line 1981 | Line 2298 | public class ConcurrentHashMapV8<K, V>
2298       * Moves and/or copies the nodes in each bin to new table. See
2299       * above for explanation.
2300       */
2301 <    @SuppressWarnings("unchecked") private final void transfer
1985 <        (Node<V>[] tab, Node<V>[] nextTab) {
2301 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2302          int n = tab.length, stride;
2303          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2304              stride = MIN_TRANSFER_STRIDE; // subdivide range
2305          if (nextTab == null) {            // initiating
2306              try {
2307 <                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
2308 <                nextTab = (Node<V>[])tb;
2307 >                @SuppressWarnings({"rawtypes","unchecked"})
2308 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2309 >                nextTab = nt;
2310              } catch (Throwable ex) {      // try to cope with OOME
2311                  sizeCtl = Integer.MAX_VALUE;
2312                  return;
# Line 1997 | Line 2314 | public class ConcurrentHashMapV8<K, V>
2314              nextTable = nextTab;
2315              transferOrigin = n;
2316              transferIndex = n;
2317 <            Node<V> rev = new Node<V>(MOVED, tab, null, null);
2317 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2318              for (int k = n; k > 0;) {    // progressively reveal ready slots
2319                  int nextk = (k > stride) ? k - stride : 0;
2320                  for (int m = nextk; m < k; ++m)
# Line 2008 | Line 2325 | public class ConcurrentHashMapV8<K, V>
2325              }
2326          }
2327          int nextn = nextTab.length;
2328 <        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
2328 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2329          boolean advance = true;
2330          for (int i = 0, bound = 0;;) {
2331 <            int nextIndex, nextBound; Node<V> f; Object fk;
2331 >            int nextIndex, nextBound, fh; Node<K,V> f;
2332              while (advance) {
2333                  if (--i >= bound)
2334                      advance = false;
# Line 2047 | Line 2364 | public class ConcurrentHashMapV8<K, V>
2364                      advance = true;
2365                  }
2366              }
2367 <            else if (f.hash >= 0) {
2367 >            else if ((fh = f.hash) == MOVED)
2368 >                advance = true; // already processed
2369 >            else {
2370                  synchronized (f) {
2371                      if (tabAt(tab, i) == f) {
2372 <                        int runBit = f.hash & n;
2373 <                        Node<V> lastRun = f, lo = null, hi = null;
2374 <                        for (Node<V> p = f.next; p != null; p = p.next) {
2375 <                            int b = p.hash & n;
2376 <                            if (b != runBit) {
2377 <                                runBit = b;
2378 <                                lastRun = p;
2372 >                        Node<K,V> ln, hn;
2373 >                        if (fh >= 0) {
2374 >                            int runBit = fh & n;
2375 >                            Node<K,V> lastRun = f;
2376 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2377 >                                int b = p.hash & n;
2378 >                                if (b != runBit) {
2379 >                                    runBit = b;
2380 >                                    lastRun = p;
2381 >                                }
2382                              }
2383 <                        }
2384 <                        if (runBit == 0)
2385 <                            lo = lastRun;
2064 <                        else
2065 <                            hi = lastRun;
2066 <                        for (Node<V> p = f; p != lastRun; p = p.next) {
2067 <                            int ph = p.hash;
2068 <                            Object pk = p.key; V pv = p.val;
2069 <                            if ((ph & n) == 0)
2070 <                                lo = new Node<V>(ph, pk, pv, lo);
2071 <                            else
2072 <                                hi = new Node<V>(ph, pk, pv, hi);
2073 <                        }
2074 <                        setTabAt(nextTab, i, lo);
2075 <                        setTabAt(nextTab, i + n, hi);
2076 <                        setTabAt(tab, i, fwd);
2077 <                        advance = true;
2078 <                    }
2079 <                }
2080 <            }
2081 <            else if ((fk = f.key) instanceof TreeBin) {
2082 <                TreeBin<V> t = (TreeBin<V>)fk;
2083 <                t.acquire(0);
2084 <                try {
2085 <                    if (tabAt(tab, i) == f) {
2086 <                        TreeBin<V> lt = new TreeBin<V>();
2087 <                        TreeBin<V> ht = new TreeBin<V>();
2088 <                        int lc = 0, hc = 0;
2089 <                        for (Node<V> e = t.first; e != null; e = e.next) {
2090 <                            int h = e.hash;
2091 <                            Object k = e.key; V v = e.val;
2092 <                            if ((h & n) == 0) {
2093 <                                ++lc;
2094 <                                lt.putTreeNode(h, k, v);
2383 >                            if (runBit == 0) {
2384 >                                ln = lastRun;
2385 >                                hn = null;
2386                              }
2387                              else {
2388 <                                ++hc;
2389 <                                ht.putTreeNode(h, k, v);
2388 >                                hn = lastRun;
2389 >                                ln = null;
2390 >                            }
2391 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2392 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2393 >                                if ((ph & n) == 0)
2394 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2395 >                                else
2396 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2397                              }
2398                          }
2399 <                        Node<V> ln, hn; // throw away trees if too small
2400 <                        if (lc < TREE_THRESHOLD) {
2401 <                            ln = null;
2402 <                            for (Node<V> p = lt.first; p != null; p = p.next)
2403 <                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2399 >                        else if (f instanceof TreeBin) {
2400 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2401 >                            TreeNode<K,V> lo = null, loTail = null;
2402 >                            TreeNode<K,V> hi = null, hiTail = null;
2403 >                            int lc = 0, hc = 0;
2404 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2405 >                                int h = e.hash;
2406 >                                TreeNode<K,V> p = new TreeNode<K,V>
2407 >                                    (h, e.key, e.val, null, null);
2408 >                                if ((h & n) == 0) {
2409 >                                    if ((p.prev = loTail) == null)
2410 >                                        lo = p;
2411 >                                    else
2412 >                                        loTail.next = p;
2413 >                                    loTail = p;
2414 >                                    ++lc;
2415 >                                }
2416 >                                else {
2417 >                                    if ((p.prev = hiTail) == null)
2418 >                                        hi = p;
2419 >                                    else
2420 >                                        hiTail.next = p;
2421 >                                    hiTail = p;
2422 >                                    ++hc;
2423 >                                }
2424 >                            }
2425 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2426 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2427 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2428 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2429                          }
2430                          else
2431 <                            ln = new Node<V>(MOVED, lt, null, null);
2431 >                            ln = hn = null;
2432                          setTabAt(nextTab, i, ln);
2110                        if (hc < TREE_THRESHOLD) {
2111                            hn = null;
2112                            for (Node<V> p = ht.first; p != null; p = p.next)
2113                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2114                        }
2115                        else
2116                            hn = new Node<V>(MOVED, ht, null, null);
2433                          setTabAt(nextTab, i + n, hn);
2434                          setTabAt(tab, i, fwd);
2435                          advance = true;
2436                      }
2121                } finally {
2122                    t.release(0);
2437                  }
2438              }
2125            else
2126                advance = true; // already processed
2439          }
2440      }
2441  
2442 <    /* ---------------- Counter support -------------- */
2442 >    /* ---------------- Conversion from/to TreeBins -------------- */
2443  
2444 <    final long sumCount() {
2445 <        CounterCell[] as = counterCells; CounterCell a;
2446 <        long sum = baseCount;
2447 <        if (as != null) {
2448 <            for (int i = 0; i < as.length; ++i) {
2449 <                if ((a = as[i]) != null)
2450 <                    sum += a.value;
2444 >    /**
2445 >     * Replaces all linked nodes in bin at given index unless table is
2446 >     * too small, in which case resizes instead.
2447 >     */
2448 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2449 >        Node<K,V> b; int n, sc;
2450 >        if (tab != null) {
2451 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2452 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2453 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2454 >                    transfer(tab, null);
2455              }
2456 <        }
2457 <        return sum;
2458 <    }
2459 <
2460 <    // See LongAdder version for explanation
2461 <    private final void fullAddCount(long x, CounterHashCode hc,
2462 <                                    boolean wasUncontended) {
2463 <        int h;
2464 <        if (hc == null) {
2465 <            hc = new CounterHashCode();
2466 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2467 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2468 <            threadCounterHashCode.set(hc);
2153 <        }
2154 <        else
2155 <            h = hc.code;
2156 <        boolean collide = false;                // True if last slot nonempty
2157 <        for (;;) {
2158 <            CounterCell[] as; CounterCell a; int n; long v;
2159 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2160 <                if ((a = as[(n - 1) & h]) == null) {
2161 <                    if (counterBusy == 0) {            // Try to attach new Cell
2162 <                        CounterCell r = new CounterCell(x); // Optimistic create
2163 <                        if (counterBusy == 0 &&
2164 <                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2165 <                            boolean created = false;
2166 <                            try {               // Recheck under lock
2167 <                                CounterCell[] rs; int m, j;
2168 <                                if ((rs = counterCells) != null &&
2169 <                                    (m = rs.length) > 0 &&
2170 <                                    rs[j = (m - 1) & h] == null) {
2171 <                                    rs[j] = r;
2172 <                                    created = true;
2173 <                                }
2174 <                            } finally {
2175 <                                counterBusy = 0;
2176 <                            }
2177 <                            if (created)
2178 <                                break;
2179 <                            continue;           // Slot is now non-empty
2180 <                        }
2181 <                    }
2182 <                    collide = false;
2183 <                }
2184 <                else if (!wasUncontended)       // CAS already known to fail
2185 <                    wasUncontended = true;      // Continue after rehash
2186 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2187 <                    break;
2188 <                else if (counterCells != as || n >= NCPU)
2189 <                    collide = false;            // At max size or stale
2190 <                else if (!collide)
2191 <                    collide = true;
2192 <                else if (counterBusy == 0 &&
2193 <                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2194 <                    try {
2195 <                        if (counterCells == as) {// Expand table unless stale
2196 <                            CounterCell[] rs = new CounterCell[n << 1];
2197 <                            for (int i = 0; i < n; ++i)
2198 <                                rs[i] = as[i];
2199 <                            counterCells = rs;
2456 >            else if ((b = tabAt(tab, index)) != null) {
2457 >                synchronized (b) {
2458 >                    if (tabAt(tab, index) == b) {
2459 >                        TreeNode<K,V> hd = null, tl = null;
2460 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2461 >                            TreeNode<K,V> p =
2462 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2463 >                                                  null, null);
2464 >                            if ((p.prev = tl) == null)
2465 >                                hd = p;
2466 >                            else
2467 >                                tl.next = p;
2468 >                            tl = p;
2469                          }
2470 <                    } finally {
2202 <                        counterBusy = 0;
2470 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2471                      }
2204                    collide = false;
2205                    continue;                   // Retry with expanded table
2472                  }
2207                h ^= h << 13;                   // Rehash
2208                h ^= h >>> 17;
2209                h ^= h << 5;
2473              }
2211            else if (counterBusy == 0 && counterCells == as &&
2212                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2213                boolean init = false;
2214                try {                           // Initialize table
2215                    if (counterCells == as) {
2216                        CounterCell[] rs = new CounterCell[2];
2217                        rs[h & 1] = new CounterCell(x);
2218                        counterCells = rs;
2219                        init = true;
2220                    }
2221                } finally {
2222                    counterBusy = 0;
2223                }
2224                if (init)
2225                    break;
2226            }
2227            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2228                break;                          // Fall back on using base
2474          }
2230        hc.code = h;                            // Record index for next time
2475      }
2476  
2477 <    /* ----------------Table Traversal -------------- */
2477 >    /**
2478 >     * Returns a list on non-TreeNodes replacing those in given list.
2479 >     */
2480 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2481 >        Node<K,V> hd = null, tl = null;
2482 >        for (Node<K,V> q = b; q != null; q = q.next) {
2483 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2484 >            if (tl == null)
2485 >                hd = p;
2486 >            else
2487 >                tl.next = p;
2488 >            tl = p;
2489 >        }
2490 >        return hd;
2491 >    }
2492 >
2493 >    /* ---------------- TreeNodes -------------- */
2494  
2495      /**
2496 <     * Encapsulates traversal for methods such as containsValue; also
2497 <     * serves as a base class for other iterators and bulk tasks.
2498 <     *
2499 <     * At each step, the iterator snapshots the key ("nextKey") and
2500 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2501 <     * snapshot, has a non-null user value). Because val fields can
2502 <     * change (including to null, indicating deletion), field nextVal
2503 <     * might not be accurate at point of use, but still maintains the
2244 <     * weak consistency property of holding a value that was once
2245 <     * valid. To support iterator.remove, the nextKey field is not
2246 <     * updated (nulled out) when the iterator cannot advance.
2247 <     *
2248 <     * Internal traversals directly access these fields, as in:
2249 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2250 <     *
2251 <     * Exported iterators must track whether the iterator has advanced
2252 <     * (in hasNext vs next) (by setting/checking/nulling field
2253 <     * nextVal), and then extract key, value, or key-value pairs as
2254 <     * return values of next().
2255 <     *
2256 <     * The iterator visits once each still-valid node that was
2257 <     * reachable upon iterator construction. It might miss some that
2258 <     * were added to a bin after the bin was visited, which is OK wrt
2259 <     * consistency guarantees. Maintaining this property in the face
2260 <     * of possible ongoing resizes requires a fair amount of
2261 <     * bookkeeping state that is difficult to optimize away amidst
2262 <     * volatile accesses.  Even so, traversal maintains reasonable
2263 <     * throughput.
2264 <     *
2265 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2266 <     * However, if the table has been resized, then all future steps
2267 <     * must traverse both the bin at the current index as well as at
2268 <     * (index + baseSize); and so on for further resizings. To
2269 <     * paranoically cope with potential sharing by users of iterators
2270 <     * across threads, iteration terminates if a bounds checks fails
2271 <     * for a table read.
2272 <     *
2273 <     * This class extends CountedCompleter to streamline parallel
2274 <     * iteration in bulk operations. This adds only a few fields of
2275 <     * space overhead, which is small enough in cases where it is not
2276 <     * needed to not worry about it.  Because CountedCompleter is
2277 <     * Serializable, but iterators need not be, we need to add warning
2278 <     * suppressions.
2279 <     */
2280 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2281 <        extends CountedCompleter<R> {
2282 <        final ConcurrentHashMapV8<K, V> map;
2283 <        Node<V> next;        // the next entry to use
2284 <        Object nextKey;      // cached key field of next
2285 <        V nextVal;           // cached val field of next
2286 <        Node<V>[] tab;       // current table; updated if resized
2287 <        int index;           // index of bin to use next
2288 <        int baseIndex;       // current index of initial table
2289 <        int baseLimit;       // index bound for initial table
2290 <        int baseSize;        // initial table size
2291 <        int batch;           // split control
2496 >     * Nodes for use in TreeBins
2497 >     */
2498 >    static final class TreeNode<K,V> extends Node<K,V> {
2499 >        TreeNode<K,V> parent;  // red-black tree links
2500 >        TreeNode<K,V> left;
2501 >        TreeNode<K,V> right;
2502 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2503 >        boolean red;
2504  
2505 <        /** Creates iterator for all entries in the table. */
2506 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2507 <            this.map = map;
2505 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2506 >                 TreeNode<K,V> parent) {
2507 >            super(hash, key, val, next);
2508 >            this.parent = parent;
2509          }
2510  
2511 <        /** Creates iterator for split() methods and task constructors */
2512 <        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2300 <            super(it);
2301 <            this.batch = batch;
2302 <            if ((this.map = map) != null && it != null) { // split parent
2303 <                Node<V>[] t;
2304 <                if ((t = it.tab) == null &&
2305 <                    (t = it.tab = map.table) != null)
2306 <                    it.baseLimit = it.baseSize = t.length;
2307 <                this.tab = t;
2308 <                this.baseSize = it.baseSize;
2309 <                int hi = this.baseLimit = it.baseLimit;
2310 <                it.baseLimit = this.index = this.baseIndex =
2311 <                    (hi + it.baseIndex + 1) >>> 1;
2312 <            }
2511 >        Node<K,V> find(int h, Object k) {
2512 >            return findTreeNode(h, k, null);
2513          }
2514  
2515          /**
2516 <         * Advances next; returns nextVal or null if terminated.
2517 <         * See above for explanation.
2516 >         * Returns the TreeNode (or null if not found) for the given key
2517 >         * starting at given root.
2518           */
2519 <        @SuppressWarnings("unchecked") final V advance() {
2520 <            Node<V> e = next;
2521 <            V ev = null;
2522 <            outer: do {
2523 <                if (e != null)                  // advance past used/skipped node
2524 <                    e = e.next;
2525 <                while (e == null) {             // get to next non-null bin
2526 <                    ConcurrentHashMapV8<K, V> m;
2527 <                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2528 <                    if ((t = tab) != null)
2529 <                        n = t.length;
2530 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2531 <                        n = baseLimit = baseSize = t.length;
2519 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2520 >            if (k != null) {
2521 >                TreeNode<K,V> p = this;
2522 >                do  {
2523 >                    int ph, dir; K pk; TreeNode<K,V> q;
2524 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2525 >                    if ((ph = p.hash) > h)
2526 >                        p = pl;
2527 >                    else if (ph < h)
2528 >                        p = pr;
2529 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2530 >                        return p;
2531 >                    else if (pl == null && pr == null)
2532 >                        break;
2533 >                    else if ((kc != null ||
2534 >                              (kc = comparableClassFor(k)) != null) &&
2535 >                             (dir = compareComparables(kc, k, pk)) != 0)
2536 >                        p = (dir < 0) ? pl : pr;
2537 >                    else if (pl == null)
2538 >                        p = pr;
2539 >                    else if (pr == null ||
2540 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2541 >                        p = pl;
2542                      else
2543 <                        break outer;
2544 <                    if ((b = baseIndex) >= baseLimit ||
2545 <                        (i = index) < 0 || i >= n)
2546 <                        break outer;
2547 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2548 <                        if ((ek = e.key) instanceof TreeBin)
2549 <                            e = ((TreeBin<V>)ek).first;
2550 <                        else {
2551 <                            tab = (Node<V>[])ek;
2552 <                            continue;           // restarts due to null val
2543 >                        return q;
2544 >                } while (p != null);
2545 >            }
2546 >            return null;
2547 >        }
2548 >    }
2549 >
2550 >    /* ---------------- TreeBins -------------- */
2551 >
2552 >    /**
2553 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2554 >     * keys or values, but instead point to list of TreeNodes and
2555 >     * their root. They also maintain a parasitic read-write lock
2556 >     * forcing writers (who hold bin lock) to wait for readers (who do
2557 >     * not) to complete before tree restructuring operations.
2558 >     */
2559 >    static final class TreeBin<K,V> extends Node<K,V> {
2560 >        TreeNode<K,V> root;
2561 >        volatile TreeNode<K,V> first;
2562 >        volatile Thread waiter;
2563 >        volatile int lockState;
2564 >        // values for lockState
2565 >        static final int WRITER = 1; // set while holding write lock
2566 >        static final int WAITER = 2; // set when waiting for write lock
2567 >        static final int READER = 4; // increment value for setting read lock
2568 >
2569 >        /**
2570 >         * Creates bin with initial set of nodes headed by b.
2571 >         */
2572 >        TreeBin(TreeNode<K,V> b) {
2573 >            super(TREEBIN, null, null, null);
2574 >            this.first = b;
2575 >            TreeNode<K,V> r = null;
2576 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2577 >                next = (TreeNode<K,V>)x.next;
2578 >                x.left = x.right = null;
2579 >                if (r == null) {
2580 >                    x.parent = null;
2581 >                    x.red = false;
2582 >                    r = x;
2583 >                }
2584 >                else {
2585 >                    Object key = x.key;
2586 >                    int hash = x.hash;
2587 >                    Class<?> kc = null;
2588 >                    for (TreeNode<K,V> p = r;;) {
2589 >                        int dir, ph;
2590 >                        if ((ph = p.hash) > hash)
2591 >                            dir = -1;
2592 >                        else if (ph < hash)
2593 >                            dir = 1;
2594 >                        else if ((kc != null ||
2595 >                                  (kc = comparableClassFor(key)) != null))
2596 >                            dir = compareComparables(kc, key, p.key);
2597 >                        else
2598 >                            dir = 0;
2599 >                        TreeNode<K,V> xp = p;
2600 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2601 >                            x.parent = xp;
2602 >                            if (dir <= 0)
2603 >                                xp.left = x;
2604 >                            else
2605 >                                xp.right = x;
2606 >                            r = balanceInsertion(r, x);
2607 >                            break;
2608                          }
2609 <                    }                           // visit upper slots if present
2345 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2609 >                    }
2610                  }
2611 <                nextKey = e.key;
2612 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2349 <            next = e;
2350 <            return nextVal = ev;
2611 >            }
2612 >            this.root = r;
2613          }
2614  
2615 <        public final void remove() {
2616 <            Object k = nextKey;
2617 <            if (k == null && (advance() == null || (k = nextKey) == null))
2618 <                throw new IllegalStateException();
2619 <            map.internalReplace(k, null, null);
2615 >        /**
2616 >         * Acquires write lock for tree restructuring.
2617 >         */
2618 >        private final void lockRoot() {
2619 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2620 >                contendedLock(); // offload to separate method
2621          }
2622  
2623 <        public final boolean hasNext() {
2624 <            return nextVal != null || advance() != null;
2623 >        /**
2624 >         * Releases write lock for tree restructuring.
2625 >         */
2626 >        private final void unlockRoot() {
2627 >            lockState = 0;
2628          }
2629  
2364        public final boolean hasMoreElements() { return hasNext(); }
2365
2366        public void compute() { } // default no-op CountedCompleter body
2367
2630          /**
2631 <         * Returns a batch value > 0 if this task should (and must) be
2370 <         * split, if so, adding to pending count, and in any case
2371 <         * updating batch value. The initial batch value is approx
2372 <         * exp2 of the number of times (minus one) to split task by
2373 <         * two before executing leaf action. This value is faster to
2374 <         * compute and more convenient to use as a guide to splitting
2375 <         * than is the depth, since it is used while dividing by two
2376 <         * anyway.
2631 >         * Possibly blocks awaiting root lock.
2632           */
2633 <        final int preSplit() {
2634 <            ConcurrentHashMapV8<K, V> m; int b; Node<V>[] t;  ForkJoinPool pool;
2635 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2636 <                if ((t = tab) == null && (t = tab = m.table) != null)
2637 <                    baseLimit = baseSize = t.length;
2638 <                if (t != null) {
2639 <                    long n = m.sumCount();
2640 <                    int par = ((pool = getPool()) == null) ?
2641 <                        ForkJoinPool.getCommonPoolParallelism() :
2642 <                        pool.getParallelism();
2643 <                    int sp = par << 3; // slack of 8
2644 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2645 <                }
2646 <            }
2647 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2648 <            if ((batch = b) > 0)
2649 <                addToPendingCount(1);
2650 <            return b;
2633 >        private final void contendedLock() {
2634 >            boolean waiting = false;
2635 >            for (int s;;) {
2636 >                if (((s = lockState) & WRITER) == 0) {
2637 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2638 >                        if (waiting)
2639 >                            waiter = null;
2640 >                        return;
2641 >                    }
2642 >                }
2643 >                else if ((s | WAITER) == 0) {
2644 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2645 >                        waiting = true;
2646 >                        waiter = Thread.currentThread();
2647 >                    }
2648 >                }
2649 >                else if (waiting)
2650 >                    LockSupport.park(this);
2651 >            }
2652          }
2653  
2654 <    }
2655 <
2656 <    /* ---------------- Public operations -------------- */
2657 <
2658 <    /**
2659 <     * Creates a new, empty map with the default initial table size (16).
2660 <     */
2661 <    public ConcurrentHashMapV8() {
2662 <    }
2663 <
2664 <    /**
2665 <     * Creates a new, empty map with an initial table size
2666 <     * accommodating the specified number of elements without the need
2667 <     * to dynamically resize.
2668 <     *
2669 <     * @param initialCapacity The implementation performs internal
2670 <     * sizing to accommodate this many elements.
2671 <     * @throws IllegalArgumentException if the initial capacity of
2672 <     * elements is negative
2673 <     */
2674 <    public ConcurrentHashMapV8(int initialCapacity) {
2675 <        if (initialCapacity < 0)
2676 <            throw new IllegalArgumentException();
2677 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2678 <                   MAXIMUM_CAPACITY :
2679 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2680 <        this.sizeCtl = cap;
2681 <    }
2682 <
2683 <    /**
2684 <     * Creates a new map with the same mappings as the given map.
2685 <     *
2686 <     * @param m the map
2687 <     */
2432 <    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2433 <        this.sizeCtl = DEFAULT_CAPACITY;
2434 <        internalPutAll(m);
2435 <    }
2436 <
2437 <    /**
2438 <     * Creates a new, empty map with an initial table size based on
2439 <     * the given number of elements ({@code initialCapacity}) and
2440 <     * initial table density ({@code loadFactor}).
2441 <     *
2442 <     * @param initialCapacity the initial capacity. The implementation
2443 <     * performs internal sizing to accommodate this many elements,
2444 <     * given the specified load factor.
2445 <     * @param loadFactor the load factor (table density) for
2446 <     * establishing the initial table size
2447 <     * @throws IllegalArgumentException if the initial capacity of
2448 <     * elements is negative or the load factor is nonpositive
2449 <     *
2450 <     * @since 1.6
2451 <     */
2452 <    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
2453 <        this(initialCapacity, loadFactor, 1);
2454 <    }
2455 <
2456 <    /**
2457 <     * Creates a new, empty map with an initial table size based on
2458 <     * the given number of elements ({@code initialCapacity}), table
2459 <     * density ({@code loadFactor}), and number of concurrently
2460 <     * updating threads ({@code concurrencyLevel}).
2461 <     *
2462 <     * @param initialCapacity the initial capacity. The implementation
2463 <     * performs internal sizing to accommodate this many elements,
2464 <     * given the specified load factor.
2465 <     * @param loadFactor the load factor (table density) for
2466 <     * establishing the initial table size
2467 <     * @param concurrencyLevel the estimated number of concurrently
2468 <     * updating threads. The implementation may use this value as
2469 <     * a sizing hint.
2470 <     * @throws IllegalArgumentException if the initial capacity is
2471 <     * negative or the load factor or concurrencyLevel are
2472 <     * nonpositive
2473 <     */
2474 <    public ConcurrentHashMapV8(int initialCapacity,
2475 <                               float loadFactor, int concurrencyLevel) {
2476 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2477 <            throw new IllegalArgumentException();
2478 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2479 <            initialCapacity = concurrencyLevel;   // as estimated threads
2480 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2481 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2482 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2483 <        this.sizeCtl = cap;
2484 <    }
2485 <
2486 <    /**
2487 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2488 <     * from the given type to {@code Boolean.TRUE}.
2489 <     *
2490 <     * @return the new set
2491 <     */
2492 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2493 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(),
2494 <                                      Boolean.TRUE);
2495 <    }
2496 <
2497 <    /**
2498 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2499 <     * from the given type to {@code Boolean.TRUE}.
2500 <     *
2501 <     * @param initialCapacity The implementation performs internal
2502 <     * sizing to accommodate this many elements.
2503 <     * @throws IllegalArgumentException if the initial capacity of
2504 <     * elements is negative
2505 <     * @return the new set
2506 <     */
2507 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2508 <        return new KeySetView<K,Boolean>
2509 <            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2510 <    }
2511 <
2512 <    /**
2513 <     * {@inheritDoc}
2514 <     */
2515 <    public boolean isEmpty() {
2516 <        return sumCount() <= 0L; // ignore transient negative values
2517 <    }
2518 <
2519 <    /**
2520 <     * {@inheritDoc}
2521 <     */
2522 <    public int size() {
2523 <        long n = sumCount();
2524 <        return ((n < 0L) ? 0 :
2525 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2526 <                (int)n);
2527 <    }
2528 <
2529 <    /**
2530 <     * Returns the number of mappings. This method should be used
2531 <     * instead of {@link #size} because a ConcurrentHashMapV8 may
2532 <     * contain more mappings than can be represented as an int. The
2533 <     * value returned is an estimate; the actual count may differ if
2534 <     * there are concurrent insertions or removals.
2535 <     *
2536 <     * @return the number of mappings
2537 <     */
2538 <    public long mappingCount() {
2539 <        long n = sumCount();
2540 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2541 <    }
2542 <
2543 <    /**
2544 <     * Returns the value to which the specified key is mapped,
2545 <     * or {@code null} if this map contains no mapping for the key.
2546 <     *
2547 <     * <p>More formally, if this map contains a mapping from a key
2548 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2549 <     * then this method returns {@code v}; otherwise it returns
2550 <     * {@code null}.  (There can be at most one such mapping.)
2551 <     *
2552 <     * @throws NullPointerException if the specified key is null
2553 <     */
2554 <    public V get(Object key) {
2555 <        return internalGet(key);
2556 <    }
2557 <
2558 <    /**
2559 <     * Returns the value to which the specified key is mapped,
2560 <     * or the given defaultValue if this map contains no mapping for the key.
2561 <     *
2562 <     * @param key the key
2563 <     * @param defaultValue the value to return if this map contains
2564 <     * no mapping for the given key
2565 <     * @return the mapping for the key, if present; else the defaultValue
2566 <     * @throws NullPointerException if the specified key is null
2567 <     */
2568 <    public V getValueOrDefault(Object key, V defaultValue) {
2569 <        V v;
2570 <        return (v = internalGet(key)) == null ? defaultValue : v;
2571 <    }
2572 <
2573 <    /**
2574 <     * Tests if the specified object is a key in this table.
2575 <     *
2576 <     * @param  key   possible key
2577 <     * @return {@code true} if and only if the specified object
2578 <     *         is a key in this table, as determined by the
2579 <     *         {@code equals} method; {@code false} otherwise
2580 <     * @throws NullPointerException if the specified key is null
2581 <     */
2582 <    public boolean containsKey(Object key) {
2583 <        return internalGet(key) != null;
2584 <    }
2585 <
2586 <    /**
2587 <     * Returns {@code true} if this map maps one or more keys to the
2588 <     * specified value. Note: This method may require a full traversal
2589 <     * of the map, and is much slower than method {@code containsKey}.
2590 <     *
2591 <     * @param value value whose presence in this map is to be tested
2592 <     * @return {@code true} if this map maps one or more keys to the
2593 <     *         specified value
2594 <     * @throws NullPointerException if the specified value is null
2595 <     */
2596 <    public boolean containsValue(Object value) {
2597 <        if (value == null)
2598 <            throw new NullPointerException();
2599 <        V v;
2600 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2601 <        while ((v = it.advance()) != null) {
2602 <            if (v == value || value.equals(v))
2603 <                return true;
2654 >        /**
2655 >         * Returns matching node or null if none. Tries to search
2656 >         * using tree compareisons from root, but continues linear
2657 >         * search when lock not available.
2658 >         */
2659 >        final Node<K,V> find(int h, Object k) {
2660 >            if (k != null) {
2661 >                for (Node<K,V> e = first; e != null; e = e.next) {
2662 >                    int s; K ek;
2663 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2664 >                        if (e.hash == h &&
2665 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2666 >                            return e;
2667 >                    }
2668 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2669 >                                                 s + READER)) {
2670 >                        TreeNode<K,V> r, p;
2671 >                        try {
2672 >                            p = ((r = root) == null ? null :
2673 >                                 r.findTreeNode(h, k, null));
2674 >                        } finally {
2675 >                            Thread w;
2676 >                            int ls;
2677 >                            do {} while (!U.compareAndSwapInt
2678 >                                         (this, LOCKSTATE,
2679 >                                          ls = lockState, ls - READER));
2680 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2681 >                                LockSupport.unpark(w);
2682 >                        }
2683 >                        return p;
2684 >                    }
2685 >                }
2686 >            }
2687 >            return null;
2688          }
2605        return false;
2606    }
2607
2608    /**
2609     * Legacy method testing if some key maps into the specified value
2610     * in this table.  This method is identical in functionality to
2611     * {@link #containsValue}, and exists solely to ensure
2612     * full compatibility with class {@link java.util.Hashtable},
2613     * which supported this method prior to introduction of the
2614     * Java Collections framework.
2615     *
2616     * @param  value a value to search for
2617     * @return {@code true} if and only if some key maps to the
2618     *         {@code value} argument in this table as
2619     *         determined by the {@code equals} method;
2620     *         {@code false} otherwise
2621     * @throws NullPointerException if the specified value is null
2622     */
2623    @Deprecated public boolean contains(Object value) {
2624        return containsValue(value);
2625    }
2626
2627    /**
2628     * Maps the specified key to the specified value in this table.
2629     * Neither the key nor the value can be null.
2630     *
2631     * <p>The value can be retrieved by calling the {@code get} method
2632     * with a key that is equal to the original key.
2633     *
2634     * @param key key with which the specified value is to be associated
2635     * @param value value to be associated with the specified key
2636     * @return the previous value associated with {@code key}, or
2637     *         {@code null} if there was no mapping for {@code key}
2638     * @throws NullPointerException if the specified key or value is null
2639     */
2640    public V put(K key, V value) {
2641        return internalPut(key, value, false);
2642    }
2643
2644    /**
2645     * {@inheritDoc}
2646     *
2647     * @return the previous value associated with the specified key,
2648     *         or {@code null} if there was no mapping for the key
2649     * @throws NullPointerException if the specified key or value is null
2650     */
2651    public V putIfAbsent(K key, V value) {
2652        return internalPut(key, value, true);
2653    }
2654
2655    /**
2656     * Copies all of the mappings from the specified map to this one.
2657     * These mappings replace any mappings that this map had for any of the
2658     * keys currently in the specified map.
2659     *
2660     * @param m mappings to be stored in this map
2661     */
2662    public void putAll(Map<? extends K, ? extends V> m) {
2663        internalPutAll(m);
2664    }
2665
2666    /**
2667     * If the specified key is not already associated with a value,
2668     * computes its value using the given mappingFunction and enters
2669     * it into the map unless null.  This is equivalent to
2670     * <pre> {@code
2671     * if (map.containsKey(key))
2672     *   return map.get(key);
2673     * value = mappingFunction.apply(key);
2674     * if (value != null)
2675     *   map.put(key, value);
2676     * return value;}</pre>
2677     *
2678     * except that the action is performed atomically.  If the
2679     * function returns {@code null} no mapping is recorded. If the
2680     * function itself throws an (unchecked) exception, the exception
2681     * is rethrown to its caller, and no mapping is recorded.  Some
2682     * attempted update operations on this map by other threads may be
2683     * blocked while computation is in progress, so the computation
2684     * should be short and simple, and must not attempt to update any
2685     * other mappings of this Map. The most appropriate usage is to
2686     * construct a new object serving as an initial mapped value, or
2687     * memoized result, as in:
2688     *
2689     *  <pre> {@code
2690     * map.computeIfAbsent(key, new Fun<K, V>() {
2691     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2692     *
2693     * @param key key with which the specified value is to be associated
2694     * @param mappingFunction the function to compute a value
2695     * @return the current (existing or computed) value associated with
2696     *         the specified key, or null if the computed value is null
2697     * @throws NullPointerException if the specified key or mappingFunction
2698     *         is null
2699     * @throws IllegalStateException if the computation detectably
2700     *         attempts a recursive update to this map that would
2701     *         otherwise never complete
2702     * @throws RuntimeException or Error if the mappingFunction does so,
2703     *         in which case the mapping is left unestablished
2704     */
2705    public V computeIfAbsent
2706        (K key, Fun<? super K, ? extends V> mappingFunction) {
2707        return internalComputeIfAbsent(key, mappingFunction);
2708    }
2709
2710    /**
2711     * If the given key is present, computes a new mapping value given a key and
2712     * its current mapped value. This is equivalent to
2713     *  <pre> {@code
2714     *   if (map.containsKey(key)) {
2715     *     value = remappingFunction.apply(key, map.get(key));
2716     *     if (value != null)
2717     *       map.put(key, value);
2718     *     else
2719     *       map.remove(key);
2720     *   }
2721     * }</pre>
2722     *
2723     * except that the action is performed atomically.  If the
2724     * function returns {@code null}, the mapping is removed.  If the
2725     * function itself throws an (unchecked) exception, the exception
2726     * is rethrown to its caller, and the current mapping is left
2727     * unchanged.  Some attempted update operations on this map by
2728     * other threads may be blocked while computation is in progress,
2729     * so the computation should be short and simple, and must not
2730     * attempt to update any other mappings of this Map. For example,
2731     * to either create or append new messages to a value mapping:
2732     *
2733     * @param key key with which the specified value is to be associated
2734     * @param remappingFunction the function to compute a value
2735     * @return the new value associated with the specified key, or null if none
2736     * @throws NullPointerException if the specified key or remappingFunction
2737     *         is null
2738     * @throws IllegalStateException if the computation detectably
2739     *         attempts a recursive update to this map that would
2740     *         otherwise never complete
2741     * @throws RuntimeException or Error if the remappingFunction does so,
2742     *         in which case the mapping is unchanged
2743     */
2744    public V computeIfPresent
2745        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2746        return internalCompute(key, true, remappingFunction);
2747    }
2748
2749    /**
2750     * Computes a new mapping value given a key and
2751     * its current mapped value (or {@code null} if there is no current
2752     * mapping). This is equivalent to
2753     *  <pre> {@code
2754     *   value = remappingFunction.apply(key, map.get(key));
2755     *   if (value != null)
2756     *     map.put(key, value);
2757     *   else
2758     *     map.remove(key);
2759     * }</pre>
2760     *
2761     * except that the action is performed atomically.  If the
2762     * function returns {@code null}, the mapping is removed.  If the
2763     * function itself throws an (unchecked) exception, the exception
2764     * is rethrown to its caller, and the current mapping is left
2765     * unchanged.  Some attempted update operations on this map by
2766     * other threads may be blocked while computation is in progress,
2767     * so the computation should be short and simple, and must not
2768     * attempt to update any other mappings of this Map. For example,
2769     * to either create or append new messages to a value mapping:
2770     *
2771     * <pre> {@code
2772     * Map<Key, String> map = ...;
2773     * final String msg = ...;
2774     * map.compute(key, new BiFun<Key, String, String>() {
2775     *   public String apply(Key k, String v) {
2776     *    return (v == null) ? msg : v + msg;});}}</pre>
2777     *
2778     * @param key key with which the specified value is to be associated
2779     * @param remappingFunction the function to compute a value
2780     * @return the new value associated with the specified key, or null if none
2781     * @throws NullPointerException if the specified key or remappingFunction
2782     *         is null
2783     * @throws IllegalStateException if the computation detectably
2784     *         attempts a recursive update to this map that would
2785     *         otherwise never complete
2786     * @throws RuntimeException or Error if the remappingFunction does so,
2787     *         in which case the mapping is unchanged
2788     */
2789    public V compute
2790        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2791        return internalCompute(key, false, remappingFunction);
2792    }
2793
2794    /**
2795     * If the specified key is not already associated
2796     * with a value, associate it with the given value.
2797     * Otherwise, replace the value with the results of
2798     * the given remapping function. This is equivalent to:
2799     *  <pre> {@code
2800     *   if (!map.containsKey(key))
2801     *     map.put(value);
2802     *   else {
2803     *     newValue = remappingFunction.apply(map.get(key), value);
2804     *     if (value != null)
2805     *       map.put(key, value);
2806     *     else
2807     *       map.remove(key);
2808     *   }
2809     * }</pre>
2810     * except that the action is performed atomically.  If the
2811     * function returns {@code null}, the mapping is removed.  If the
2812     * function itself throws an (unchecked) exception, the exception
2813     * is rethrown to its caller, and the current mapping is left
2814     * unchanged.  Some attempted update operations on this map by
2815     * other threads may be blocked while computation is in progress,
2816     * so the computation should be short and simple, and must not
2817     * attempt to update any other mappings of this Map.
2818     */
2819    public V merge
2820        (K key, V value,
2821         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2822        return internalMerge(key, value, remappingFunction);
2823    }
2689  
2690 <    /**
2691 <     * Removes the key (and its corresponding value) from this map.
2692 <     * This method does nothing if the key is not in the map.
2693 <     *
2694 <     * @param  key the key that needs to be removed
2695 <     * @return the previous value associated with {@code key}, or
2696 <     *         {@code null} if there was no mapping for {@code key}
2697 <     * @throws NullPointerException if the specified key is null
2698 <     */
2699 <    public V remove(Object key) {
2700 <        return internalReplace(key, null, null);
2701 <    }
2690 >        /**
2691 >         * Finds or adds a node.
2692 >         * @return null if added
2693 >         */
2694 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2695 >            Class<?> kc = null;
2696 >            for (TreeNode<K,V> p = root;;) {
2697 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2698 >                if (p == null) {
2699 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2700 >                    break;
2701 >                }
2702 >                else if ((ph = p.hash) > h)
2703 >                    dir = -1;
2704 >                else if (ph < h)
2705 >                    dir = 1;
2706 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2707 >                    return p;
2708 >                else if ((kc == null &&
2709 >                          (kc = comparableClassFor(k)) == null) ||
2710 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2711 >                    if (p.left == null)
2712 >                        dir = 1;
2713 >                    else if ((pr = p.right) == null ||
2714 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2715 >                        dir = -1;
2716 >                    else
2717 >                        return q;
2718 >                }
2719 >                TreeNode<K,V> xp = p;
2720 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2721 >                    TreeNode<K,V> x, f = first;
2722 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2723 >                    if (f != null)
2724 >                        f.prev = x;
2725 >                    if (dir < 0)
2726 >                        xp.left = x;
2727 >                    else
2728 >                        xp.right = x;
2729 >                    if (!xp.red)
2730 >                        x.red = true;
2731 >                    else {
2732 >                        lockRoot();
2733 >                        try {
2734 >                            root = balanceInsertion(root, x);
2735 >                        } finally {
2736 >                            unlockRoot();
2737 >                        }
2738 >                    }
2739 >                    break;
2740 >                }
2741 >            }
2742 >            assert checkInvariants(root);
2743 >            return null;
2744 >        }
2745  
2746 <    /**
2747 <     * {@inheritDoc}
2748 <     *
2749 <     * @throws NullPointerException if the specified key is null
2750 <     */
2751 <    public boolean remove(Object key, Object value) {
2752 <        return value != null && internalReplace(key, null, value) != null;
2753 <    }
2746 >        /**
2747 >         * Removes the given node, that must be present before this
2748 >         * call.  This is messier than typical red-black deletion code
2749 >         * because we cannot swap the contents of an interior node
2750 >         * with a leaf successor that is pinned by "next" pointers
2751 >         * that are accessible independently of lock. So instead we
2752 >         * swap the tree linkages.
2753 >         *
2754 >         * @return true if now too small, so should be untreeified
2755 >         */
2756 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2757 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2758 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2759 >            TreeNode<K,V> r, rl;
2760 >            if (pred == null)
2761 >                first = next;
2762 >            else
2763 >                pred.next = next;
2764 >            if (next != null)
2765 >                next.prev = pred;
2766 >            if (first == null) {
2767 >                root = null;
2768 >                return true;
2769 >            }
2770 >            if ((r = root) == null || r.right == null || // too small
2771 >                (rl = r.left) == null || rl.left == null)
2772 >                return true;
2773 >            lockRoot();
2774 >            try {
2775 >                TreeNode<K,V> replacement;
2776 >                TreeNode<K,V> pl = p.left;
2777 >                TreeNode<K,V> pr = p.right;
2778 >                if (pl != null && pr != null) {
2779 >                    TreeNode<K,V> s = pr, sl;
2780 >                    while ((sl = s.left) != null) // find successor
2781 >                        s = sl;
2782 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2783 >                    TreeNode<K,V> sr = s.right;
2784 >                    TreeNode<K,V> pp = p.parent;
2785 >                    if (s == pr) { // p was s's direct parent
2786 >                        p.parent = s;
2787 >                        s.right = p;
2788 >                    }
2789 >                    else {
2790 >                        TreeNode<K,V> sp = s.parent;
2791 >                        if ((p.parent = sp) != null) {
2792 >                            if (s == sp.left)
2793 >                                sp.left = p;
2794 >                            else
2795 >                                sp.right = p;
2796 >                        }
2797 >                        if ((s.right = pr) != null)
2798 >                            pr.parent = s;
2799 >                    }
2800 >                    p.left = null;
2801 >                    if ((p.right = sr) != null)
2802 >                        sr.parent = p;
2803 >                    if ((s.left = pl) != null)
2804 >                        pl.parent = s;
2805 >                    if ((s.parent = pp) == null)
2806 >                        r = s;
2807 >                    else if (p == pp.left)
2808 >                        pp.left = s;
2809 >                    else
2810 >                        pp.right = s;
2811 >                    if (sr != null)
2812 >                        replacement = sr;
2813 >                    else
2814 >                        replacement = p;
2815 >                }
2816 >                else if (pl != null)
2817 >                    replacement = pl;
2818 >                else if (pr != null)
2819 >                    replacement = pr;
2820 >                else
2821 >                    replacement = p;
2822 >                if (replacement != p) {
2823 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2824 >                    if (pp == null)
2825 >                        r = replacement;
2826 >                    else if (p == pp.left)
2827 >                        pp.left = replacement;
2828 >                    else
2829 >                        pp.right = replacement;
2830 >                    p.left = p.right = p.parent = null;
2831 >                }
2832  
2833 <    /**
2848 <     * {@inheritDoc}
2849 <     *
2850 <     * @throws NullPointerException if any of the arguments are null
2851 <     */
2852 <    public boolean replace(K key, V oldValue, V newValue) {
2853 <        if (key == null || oldValue == null || newValue == null)
2854 <            throw new NullPointerException();
2855 <        return internalReplace(key, newValue, oldValue) != null;
2856 <    }
2833 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2834  
2835 <    /**
2836 <     * {@inheritDoc}
2837 <     *
2838 <     * @return the previous value associated with the specified key,
2839 <     *         or {@code null} if there was no mapping for the key
2840 <     * @throws NullPointerException if the specified key or value is null
2841 <     */
2842 <    public V replace(K key, V value) {
2843 <        if (key == null || value == null)
2844 <            throw new NullPointerException();
2845 <        return internalReplace(key, value, null);
2846 <    }
2847 <
2848 <    /**
2849 <     * Removes all of the mappings from this map.
2850 <     */
2874 <    public void clear() {
2875 <        internalClear();
2876 <    }
2835 >                if (p == replacement) {  // detach pointers
2836 >                    TreeNode<K,V> pp;
2837 >                    if ((pp = p.parent) != null) {
2838 >                        if (p == pp.left)
2839 >                            pp.left = null;
2840 >                        else if (p == pp.right)
2841 >                            pp.right = null;
2842 >                        p.parent = null;
2843 >                    }
2844 >                }
2845 >            } finally {
2846 >                unlockRoot();
2847 >            }
2848 >            assert checkInvariants(root);
2849 >            return false;
2850 >        }
2851  
2852 <    /**
2853 <     * Returns a {@link Set} view of the keys contained in this map.
2880 <     * The set is backed by the map, so changes to the map are
2881 <     * reflected in the set, and vice-versa.
2882 <     *
2883 <     * @return the set view
2884 <     */
2885 <    public KeySetView<K,V> keySet() {
2886 <        KeySetView<K,V> ks = keySet;
2887 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2888 <    }
2852 >        /* ------------------------------------------------------------ */
2853 >        // Red-black tree methods, all adapted from CLR
2854  
2855 <    /**
2856 <     * Returns a {@link Set} view of the keys in this map, using the
2857 <     * given common mapped value for any additions (i.e., {@link
2858 <     * Collection#add} and {@link Collection#addAll}). This is of
2859 <     * course only appropriate if it is acceptable to use the same
2860 <     * value for all additions from this view.
2861 <     *
2862 <     * @param mappedValue the mapped value to use for any additions
2863 <     * @return the set view
2864 <     * @throws NullPointerException if the mappedValue is null
2865 <     */
2866 <    public KeySetView<K,V> keySet(V mappedValue) {
2867 <        if (mappedValue == null)
2868 <            throw new NullPointerException();
2869 <        return new KeySetView<K,V>(this, mappedValue);
2870 <    }
2855 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2856 >                                              TreeNode<K,V> p) {
2857 >            TreeNode<K,V> r, pp, rl;
2858 >            if (p != null && (r = p.right) != null) {
2859 >                if ((rl = p.right = r.left) != null)
2860 >                    rl.parent = p;
2861 >                if ((pp = r.parent = p.parent) == null)
2862 >                    (root = r).red = false;
2863 >                else if (pp.left == p)
2864 >                    pp.left = r;
2865 >                else
2866 >                    pp.right = r;
2867 >                r.left = p;
2868 >                p.parent = r;
2869 >            }
2870 >            return root;
2871 >        }
2872  
2873 <    /**
2874 <     * Returns a {@link Collection} view of the values contained in this map.
2875 <     * The collection is backed by the map, so changes to the map are
2876 <     * reflected in the collection, and vice-versa.
2877 <     */
2878 <    public ValuesView<K,V> values() {
2879 <        ValuesView<K,V> vs = values;
2880 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2881 <    }
2873 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2874 >                                               TreeNode<K,V> p) {
2875 >            TreeNode<K,V> l, pp, lr;
2876 >            if (p != null && (l = p.left) != null) {
2877 >                if ((lr = p.left = l.right) != null)
2878 >                    lr.parent = p;
2879 >                if ((pp = l.parent = p.parent) == null)
2880 >                    (root = l).red = false;
2881 >                else if (pp.right == p)
2882 >                    pp.right = l;
2883 >                else
2884 >                    pp.left = l;
2885 >                l.right = p;
2886 >                p.parent = l;
2887 >            }
2888 >            return root;
2889 >        }
2890  
2891 <    /**
2892 <     * Returns a {@link Set} view of the mappings contained in this map.
2893 <     * The set is backed by the map, so changes to the map are
2894 <     * reflected in the set, and vice-versa.  The set supports element
2895 <     * removal, which removes the corresponding mapping from the map,
2896 <     * via the {@code Iterator.remove}, {@code Set.remove},
2897 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
2898 <     * operations.  It does not support the {@code add} or
2899 <     * {@code addAll} operations.
2900 <     *
2901 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2902 <     * that will never throw {@link ConcurrentModificationException},
2903 <     * and guarantees to traverse elements as they existed upon
2904 <     * construction of the iterator, and may (but is not guaranteed to)
2905 <     * reflect any modifications subsequent to construction.
2906 <     */
2907 <    public Set<Map.Entry<K,V>> entrySet() {
2908 <        EntrySetView<K,V> es = entrySet;
2909 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2910 <    }
2891 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2892 >                                                    TreeNode<K,V> x) {
2893 >            x.red = true;
2894 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2895 >                if ((xp = x.parent) == null) {
2896 >                    x.red = false;
2897 >                    return x;
2898 >                }
2899 >                else if (!xp.red || (xpp = xp.parent) == null)
2900 >                    return root;
2901 >                if (xp == (xppl = xpp.left)) {
2902 >                    if ((xppr = xpp.right) != null && xppr.red) {
2903 >                        xppr.red = false;
2904 >                        xp.red = false;
2905 >                        xpp.red = true;
2906 >                        x = xpp;
2907 >                    }
2908 >                    else {
2909 >                        if (x == xp.right) {
2910 >                            root = rotateLeft(root, x = xp);
2911 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2912 >                        }
2913 >                        if (xp != null) {
2914 >                            xp.red = false;
2915 >                            if (xpp != null) {
2916 >                                xpp.red = true;
2917 >                                root = rotateRight(root, xpp);
2918 >                            }
2919 >                        }
2920 >                    }
2921 >                }
2922 >                else {
2923 >                    if (xppl != null && xppl.red) {
2924 >                        xppl.red = false;
2925 >                        xp.red = false;
2926 >                        xpp.red = true;
2927 >                        x = xpp;
2928 >                    }
2929 >                    else {
2930 >                        if (x == xp.left) {
2931 >                            root = rotateRight(root, x = xp);
2932 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2933 >                        }
2934 >                        if (xp != null) {
2935 >                            xp.red = false;
2936 >                            if (xpp != null) {
2937 >                                xpp.red = true;
2938 >                                root = rotateLeft(root, xpp);
2939 >                            }
2940 >                        }
2941 >                    }
2942 >                }
2943 >            }
2944 >        }
2945  
2946 <    /**
2947 <     * Returns an enumeration of the keys in this table.
2948 <     *
2949 <     * @return an enumeration of the keys in this table
2950 <     * @see #keySet()
2951 <     */
2952 <    public Enumeration<K> keys() {
2953 <        return new KeyIterator<K,V>(this);
2954 <    }
2946 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2947 >                                                   TreeNode<K,V> x) {
2948 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2949 >                if (x == null || x == root)
2950 >                    return root;
2951 >                else if ((xp = x.parent) == null) {
2952 >                    x.red = false;
2953 >                    return x;
2954 >                }
2955 >                else if (x.red) {
2956 >                    x.red = false;
2957 >                    return root;
2958 >                }
2959 >                else if ((xpl = xp.left) == x) {
2960 >                    if ((xpr = xp.right) != null && xpr.red) {
2961 >                        xpr.red = false;
2962 >                        xp.red = true;
2963 >                        root = rotateLeft(root, xp);
2964 >                        xpr = (xp = x.parent) == null ? null : xp.right;
2965 >                    }
2966 >                    if (xpr == null)
2967 >                        x = xp;
2968 >                    else {
2969 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2970 >                        if ((sr == null || !sr.red) &&
2971 >                            (sl == null || !sl.red)) {
2972 >                            xpr.red = true;
2973 >                            x = xp;
2974 >                        }
2975 >                        else {
2976 >                            if (sr == null || !sr.red) {
2977 >                                if (sl != null)
2978 >                                    sl.red = false;
2979 >                                xpr.red = true;
2980 >                                root = rotateRight(root, xpr);
2981 >                                xpr = (xp = x.parent) == null ?
2982 >                                    null : xp.right;
2983 >                            }
2984 >                            if (xpr != null) {
2985 >                                xpr.red = (xp == null) ? false : xp.red;
2986 >                                if ((sr = xpr.right) != null)
2987 >                                    sr.red = false;
2988 >                            }
2989 >                            if (xp != null) {
2990 >                                xp.red = false;
2991 >                                root = rotateLeft(root, xp);
2992 >                            }
2993 >                            x = root;
2994 >                        }
2995 >                    }
2996 >                }
2997 >                else { // symmetric
2998 >                    if (xpl != null && xpl.red) {
2999 >                        xpl.red = false;
3000 >                        xp.red = true;
3001 >                        root = rotateRight(root, xp);
3002 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3003 >                    }
3004 >                    if (xpl == null)
3005 >                        x = xp;
3006 >                    else {
3007 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3008 >                        if ((sl == null || !sl.red) &&
3009 >                            (sr == null || !sr.red)) {
3010 >                            xpl.red = true;
3011 >                            x = xp;
3012 >                        }
3013 >                        else {
3014 >                            if (sl == null || !sl.red) {
3015 >                                if (sr != null)
3016 >                                    sr.red = false;
3017 >                                xpl.red = true;
3018 >                                root = rotateLeft(root, xpl);
3019 >                                xpl = (xp = x.parent) == null ?
3020 >                                    null : xp.left;
3021 >                            }
3022 >                            if (xpl != null) {
3023 >                                xpl.red = (xp == null) ? false : xp.red;
3024 >                                if ((sl = xpl.left) != null)
3025 >                                    sl.red = false;
3026 >                            }
3027 >                            if (xp != null) {
3028 >                                xp.red = false;
3029 >                                root = rotateRight(root, xp);
3030 >                            }
3031 >                            x = root;
3032 >                        }
3033 >                    }
3034 >                }
3035 >            }
3036 >        }
3037  
3038 <    /**
3039 <     * Returns an enumeration of the values in this table.
3040 <     *
3041 <     * @return an enumeration of the values in this table
3042 <     * @see #values()
3043 <     */
3044 <    public Enumeration<V> elements() {
3045 <        return new ValueIterator<K,V>(this);
3046 <    }
3038 >        /**
3039 >         * Recursive invariant check
3040 >         */
3041 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3042 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3043 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3044 >            if (tb != null && tb.next != t)
3045 >                return false;
3046 >            if (tn != null && tn.prev != t)
3047 >                return false;
3048 >            if (tp != null && t != tp.left && t != tp.right)
3049 >                return false;
3050 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3051 >                return false;
3052 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3053 >                return false;
3054 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3055 >                return false;
3056 >            if (tl != null && !checkInvariants(tl))
3057 >                return false;
3058 >            if (tr != null && !checkInvariants(tr))
3059 >                return false;
3060 >            return true;
3061 >        }
3062  
3063 <    /**
3064 <     * Returns a partitionable iterator of the keys in this map.
3065 <     *
3066 <     * @return a partitionable iterator of the keys in this map
3067 <     */
3068 <    public Spliterator<K> keySpliterator() {
3069 <        return new KeyIterator<K,V>(this);
3063 >        private static final sun.misc.Unsafe U;
3064 >        private static final long LOCKSTATE;
3065 >        static {
3066 >            try {
3067 >                U = getUnsafe();
3068 >                Class<?> k = TreeBin.class;
3069 >                LOCKSTATE = U.objectFieldOffset
3070 >                    (k.getDeclaredField("lockState"));
3071 >            } catch (Exception e) {
3072 >                throw new Error(e);
3073 >            }
3074 >        }
3075      }
3076  
3077 <    /**
2968 <     * Returns a partitionable iterator of the values in this map.
2969 <     *
2970 <     * @return a partitionable iterator of the values in this map
2971 <     */
2972 <    public Spliterator<V> valueSpliterator() {
2973 <        return new ValueIterator<K,V>(this);
2974 <    }
3077 >    /* ----------------Table Traversal -------------- */
3078  
3079      /**
3080 <     * Returns a partitionable iterator of the entries in this map.
3080 >     * Encapsulates traversal for methods such as containsValue; also
3081 >     * serves as a base class for other iterators and spliterators.
3082       *
3083 <     * @return a partitionable iterator of the entries in this map
3084 <     */
3085 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3086 <        return new EntryIterator<K,V>(this);
3087 <    }
3088 <
3089 <    /**
3090 <     * Returns the hash code value for this {@link Map}, i.e.,
2987 <     * the sum of, for each key-value pair in the map,
2988 <     * {@code key.hashCode() ^ value.hashCode()}.
3083 >     * Method advance visits once each still-valid node that was
3084 >     * reachable upon iterator construction. It might miss some that
3085 >     * were added to a bin after the bin was visited, which is OK wrt
3086 >     * consistency guarantees. Maintaining this property in the face
3087 >     * of possible ongoing resizes requires a fair amount of
3088 >     * bookkeeping state that is difficult to optimize away amidst
3089 >     * volatile accesses.  Even so, traversal maintains reasonable
3090 >     * throughput.
3091       *
3092 <     * @return the hash code value for this map
3092 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3093 >     * However, if the table has been resized, then all future steps
3094 >     * must traverse both the bin at the current index as well as at
3095 >     * (index + baseSize); and so on for further resizings. To
3096 >     * paranoically cope with potential sharing by users of iterators
3097 >     * across threads, iteration terminates if a bounds checks fails
3098 >     * for a table read.
3099       */
3100 <    public int hashCode() {
3101 <        int h = 0;
3102 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3103 <        V v;
3104 <        while ((v = it.advance()) != null) {
3105 <            h += it.nextKey.hashCode() ^ v.hashCode();
3100 >    static class Traverser<K,V> {
3101 >        Node<K,V>[] tab;        // current table; updated if resized
3102 >        Node<K,V> next;         // the next entry to use
3103 >        int index;              // index of bin to use next
3104 >        int baseIndex;          // current index of initial table
3105 >        int baseLimit;          // index bound for initial table
3106 >        final int baseSize;     // initial table size
3107 >
3108 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3109 >            this.tab = tab;
3110 >            this.baseSize = size;
3111 >            this.baseIndex = this.index = index;
3112 >            this.baseLimit = limit;
3113 >            this.next = null;
3114          }
2999        return h;
3000    }
3115  
3116 <    /**
3117 <     * Returns a string representation of this map.  The string
3118 <     * representation consists of a list of key-value mappings (in no
3119 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3120 <     * mappings are separated by the characters {@code ", "} (comma
3121 <     * and space).  Each key-value mapping is rendered as the key
3122 <     * followed by an equals sign ("{@code =}") followed by the
3009 <     * associated value.
3010 <     *
3011 <     * @return a string representation of this map
3012 <     */
3013 <    public String toString() {
3014 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3015 <        StringBuilder sb = new StringBuilder();
3016 <        sb.append('{');
3017 <        V v;
3018 <        if ((v = it.advance()) != null) {
3116 >        /**
3117 >         * Advances if possible, returning next valid node, or null if none.
3118 >         */
3119 >        final Node<K,V> advance() {
3120 >            Node<K,V> e;
3121 >            if ((e = next) != null)
3122 >                e = e.next;
3123              for (;;) {
3124 <                Object k = it.nextKey;
3125 <                sb.append(k == this ? "(this Map)" : k);
3126 <                sb.append('=');
3127 <                sb.append(v == this ? "(this Map)" : v);
3128 <                if ((v = it.advance()) == null)
3129 <                    break;
3130 <                sb.append(',').append(' ');
3124 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3125 >                if (e != null)
3126 >                    return next = e;
3127 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3128 >                    (n = t.length) <= (i = index) || i < 0)
3129 >                    return next = null;
3130 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3131 >                    if (e instanceof ForwardingNode) {
3132 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3133 >                        e = null;
3134 >                        continue;
3135 >                    }
3136 >                    else if (e instanceof TreeBin)
3137 >                        e = ((TreeBin<K,V>)e).first;
3138 >                    else
3139 >                        e = null;
3140 >                }
3141 >                if ((index += baseSize) >= n)
3142 >                    index = ++baseIndex;    // visit upper slots if present
3143              }
3144          }
3029        return sb.append('}').toString();
3145      }
3146  
3147      /**
3148 <     * Compares the specified object with this map for equality.
3149 <     * Returns {@code true} if the given object is a map with the same
3035 <     * mappings as this map.  This operation may return misleading
3036 <     * results if either map is concurrently modified during execution
3037 <     * of this method.
3038 <     *
3039 <     * @param o object to be compared for equality with this map
3040 <     * @return {@code true} if the specified object is equal to this map
3148 >     * Base of key, value, and entry Iterators. Adds fields to
3149 >     * Traverser to support iterator.remove.
3150       */
3151 <    public boolean equals(Object o) {
3152 <        if (o != this) {
3153 <            if (!(o instanceof Map))
3154 <                return false;
3155 <            Map<?,?> m = (Map<?,?>) o;
3156 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3157 <            V val;
3158 <            while ((val = it.advance()) != null) {
3050 <                Object v = m.get(it.nextKey);
3051 <                if (v == null || (v != val && !v.equals(val)))
3052 <                    return false;
3053 <            }
3054 <            for (Map.Entry<?,?> e : m.entrySet()) {
3055 <                Object mk, mv, v;
3056 <                if ((mk = e.getKey()) == null ||
3057 <                    (mv = e.getValue()) == null ||
3058 <                    (v = internalGet(mk)) == null ||
3059 <                    (mv != v && !mv.equals(v)))
3060 <                    return false;
3061 <            }
3151 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3152 >        final ConcurrentHashMapV8<K,V> map;
3153 >        Node<K,V> lastReturned;
3154 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3155 >                    ConcurrentHashMapV8<K,V> map) {
3156 >            super(tab, size, index, limit);
3157 >            this.map = map;
3158 >            advance();
3159          }
3063        return true;
3064    }
3160  
3161 <    /* ----------------Iterators -------------- */
3161 >        public final boolean hasNext() { return next != null; }
3162 >        public final boolean hasMoreElements() { return next != null; }
3163  
3164 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3165 <        extends Traverser<K,V,Object>
3166 <        implements Spliterator<K>, Enumeration<K> {
3071 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3072 <        KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3073 <            super(map, it, -1);
3074 <        }
3075 <        public KeyIterator<K,V> split() {
3076 <            if (nextKey != null)
3164 >        public final void remove() {
3165 >            Node<K,V> p;
3166 >            if ((p = lastReturned) == null)
3167                  throw new IllegalStateException();
3168 <            return new KeyIterator<K,V>(map, this);
3168 >            lastReturned = null;
3169 >            map.replaceNode(p.key, null, null);
3170 >        }
3171 >    }
3172 >
3173 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3174 >        implements Iterator<K>, Enumeration<K> {
3175 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3176 >                    ConcurrentHashMapV8<K,V> map) {
3177 >            super(tab, index, size, limit, map);
3178          }
3179 <        @SuppressWarnings("unchecked") public final K next() {
3180 <            if (nextVal == null && advance() == null)
3179 >
3180 >        public final K next() {
3181 >            Node<K,V> p;
3182 >            if ((p = next) == null)
3183                  throw new NoSuchElementException();
3184 <            Object k = nextKey;
3185 <            nextVal = null;
3186 <            return (K) k;
3184 >            K k = p.key;
3185 >            lastReturned = p;
3186 >            advance();
3187 >            return k;
3188          }
3189  
3190          public final K nextElement() { return next(); }
3191      }
3192  
3193 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3194 <        extends Traverser<K,V,Object>
3195 <        implements Spliterator<V>, Enumeration<V> {
3196 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3197 <        ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3096 <            super(map, it, -1);
3097 <        }
3098 <        public ValueIterator<K,V> split() {
3099 <            if (nextKey != null)
3100 <                throw new IllegalStateException();
3101 <            return new ValueIterator<K,V>(map, this);
3193 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3194 >        implements Iterator<V>, Enumeration<V> {
3195 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3196 >                      ConcurrentHashMapV8<K,V> map) {
3197 >            super(tab, index, size, limit, map);
3198          }
3199  
3200          public final V next() {
3201 <            V v;
3202 <            if ((v = nextVal) == null && (v = advance()) == null)
3201 >            Node<K,V> p;
3202 >            if ((p = next) == null)
3203                  throw new NoSuchElementException();
3204 <            nextVal = null;
3204 >            V v = p.val;
3205 >            lastReturned = p;
3206 >            advance();
3207              return v;
3208          }
3209  
3210          public final V nextElement() { return next(); }
3211      }
3212  
3213 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3214 <        extends Traverser<K,V,Object>
3215 <        implements Spliterator<Map.Entry<K,V>> {
3216 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3217 <        EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3120 <            super(map, it, -1);
3121 <        }
3122 <        public EntryIterator<K,V> split() {
3123 <            if (nextKey != null)
3124 <                throw new IllegalStateException();
3125 <            return new EntryIterator<K,V>(map, this);
3213 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3214 >        implements Iterator<Map.Entry<K,V>> {
3215 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3216 >                      ConcurrentHashMapV8<K,V> map) {
3217 >            super(tab, index, size, limit, map);
3218          }
3219  
3220 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3221 <            V v;
3222 <            if ((v = nextVal) == null && (v = advance()) == null)
3220 >        public final Map.Entry<K,V> next() {
3221 >            Node<K,V> p;
3222 >            if ((p = next) == null)
3223                  throw new NoSuchElementException();
3224 <            Object k = nextKey;
3225 <            nextVal = null;
3226 <            return new MapEntry<K,V>((K)k, v, map);
3224 >            K k = p.key;
3225 >            V v = p.val;
3226 >            lastReturned = p;
3227 >            advance();
3228 >            return new MapEntry<K,V>(k, v, map);
3229          }
3230      }
3231  
3232      /**
3233 <     * Exported Entry for iterators
3233 >     * Exported Entry for EntryIterator
3234       */
3235 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3235 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3236          final K key; // non-null
3237          V val;       // non-null
3238 <        final ConcurrentHashMapV8<K, V> map;
3239 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3238 >        final ConcurrentHashMapV8<K,V> map;
3239 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3240              this.key = key;
3241              this.val = val;
3242              this.map = map;
3243          }
3244 <        public final K getKey()       { return key; }
3245 <        public final V getValue()     { return val; }
3246 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3247 <        public final String toString(){ return key + "=" + val; }
3244 >        public K getKey()        { return key; }
3245 >        public V getValue()      { return val; }
3246 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3247 >        public String toString() { return key + "=" + val; }
3248  
3249 <        public final boolean equals(Object o) {
3249 >        public boolean equals(Object o) {
3250              Object k, v; Map.Entry<?,?> e;
3251              return ((o instanceof Map.Entry) &&
3252                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3166 | Line 3260 | public class ConcurrentHashMapV8<K, V>
3260           * value to return is somewhat arbitrary here. Since we do not
3261           * necessarily track asynchronous changes, the most recent
3262           * "previous" value could be different from what we return (or
3263 <         * could even have been removed in which case the put will
3263 >         * could even have been removed, in which case the put will
3264           * re-establish). We do not and cannot guarantee more.
3265           */
3266 <        public final V setValue(V value) {
3266 >        public V setValue(V value) {
3267              if (value == null) throw new NullPointerException();
3268              V v = val;
3269              val = value;
# Line 3178 | Line 3272 | public class ConcurrentHashMapV8<K, V>
3272          }
3273      }
3274  
3275 <    /**
3276 <     * Returns exportable snapshot entry for the given key and value
3277 <     * when write-through can't or shouldn't be used.
3278 <     */
3279 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3280 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3281 <    }
3275 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3276 >        implements ConcurrentHashMapSpliterator<K> {
3277 >        long est;               // size estimate
3278 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3279 >                       long est) {
3280 >            super(tab, size, index, limit);
3281 >            this.est = est;
3282 >        }
3283 >
3284 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3285 >            int i, f, h;
3286 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3287 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3288 >                                        f, est >>>= 1);
3289 >        }
3290  
3291 <    /* ---------------- Serialization Support -------------- */
3291 >        public void forEachRemaining(Action<? super K> action) {
3292 >            if (action == null) throw new NullPointerException();
3293 >            for (Node<K,V> p; (p = advance()) != null;)
3294 >                action.apply(p.key);
3295 >        }
3296 >
3297 >        public boolean tryAdvance(Action<? super K> action) {
3298 >            if (action == null) throw new NullPointerException();
3299 >            Node<K,V> p;
3300 >            if ((p = advance()) == null)
3301 >                return false;
3302 >            action.apply(p.key);
3303 >            return true;
3304 >        }
3305 >
3306 >        public long estimateSize() { return est; }
3307  
3191    /**
3192     * Stripped-down version of helper class used in previous version,
3193     * declared for the sake of serialization compatibility
3194     */
3195    static class Segment<K,V> implements Serializable {
3196        private static final long serialVersionUID = 2249069246763182397L;
3197        final float loadFactor;
3198        Segment(float lf) { this.loadFactor = lf; }
3308      }
3309  
3310 <    /**
3311 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3312 <     * stream (i.e., serializes it).
3313 <     * @param s the stream
3314 <     * @serialData
3315 <     * the key (Object) and value (Object)
3316 <     * for each key-value mapping, followed by a null pair.
3208 <     * The key-value mappings are emitted in no particular order.
3209 <     */
3210 <    @SuppressWarnings("unchecked") private void writeObject
3211 <        (java.io.ObjectOutputStream s)
3212 <        throws java.io.IOException {
3213 <        if (segments == null) { // for serialization compatibility
3214 <            segments = (Segment<K,V>[])
3215 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3216 <            for (int i = 0; i < segments.length; ++i)
3217 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3310 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3311 >        implements ConcurrentHashMapSpliterator<V> {
3312 >        long est;               // size estimate
3313 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3314 >                         long est) {
3315 >            super(tab, size, index, limit);
3316 >            this.est = est;
3317          }
3318 <        s.defaultWriteObject();
3319 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3320 <        V v;
3321 <        while ((v = it.advance()) != null) {
3322 <            s.writeObject(it.nextKey);
3323 <            s.writeObject(v);
3318 >
3319 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3320 >            int i, f, h;
3321 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3322 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3323 >                                          f, est >>>= 1);
3324          }
3325 <        s.writeObject(null);
3326 <        s.writeObject(null);
3327 <        segments = null; // throw away
3325 >
3326 >        public void forEachRemaining(Action<? super V> action) {
3327 >            if (action == null) throw new NullPointerException();
3328 >            for (Node<K,V> p; (p = advance()) != null;)
3329 >                action.apply(p.val);
3330 >        }
3331 >
3332 >        public boolean tryAdvance(Action<? super V> action) {
3333 >            if (action == null) throw new NullPointerException();
3334 >            Node<K,V> p;
3335 >            if ((p = advance()) == null)
3336 >                return false;
3337 >            action.apply(p.val);
3338 >            return true;
3339 >        }
3340 >
3341 >        public long estimateSize() { return est; }
3342 >
3343      }
3344  
3345 <    /**
3346 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3347 <     * @param s the stream
3348 <     */
3349 <    @SuppressWarnings("unchecked") private void readObject
3350 <        (java.io.ObjectInputStream s)
3351 <        throws java.io.IOException, ClassNotFoundException {
3352 <        s.defaultReadObject();
3353 <        this.segments = null; // unneeded
3345 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3346 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3347 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3348 >        long est;               // size estimate
3349 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3350 >                         long est, ConcurrentHashMapV8<K,V> map) {
3351 >            super(tab, size, index, limit);
3352 >            this.map = map;
3353 >            this.est = est;
3354 >        }
3355  
3356 <        // Create all nodes, then place in table once size is known
3357 <        long size = 0L;
3358 <        Node<V> p = null;
3359 <        for (;;) {
3360 <            K k = (K) s.readObject();
3246 <            V v = (V) s.readObject();
3247 <            if (k != null && v != null) {
3248 <                int h = spread(k.hashCode());
3249 <                p = new Node<V>(h, k, v, p);
3250 <                ++size;
3251 <            }
3252 <            else
3253 <                break;
3356 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3357 >            int i, f, h;
3358 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3359 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3360 >                                          f, est >>>= 1, map);
3361          }
3362 <        if (p != null) {
3363 <            boolean init = false;
3364 <            int n;
3365 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3366 <                n = MAXIMUM_CAPACITY;
3260 <            else {
3261 <                int sz = (int)size;
3262 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3263 <            }
3264 <            int sc = sizeCtl;
3265 <            boolean collide = false;
3266 <            if (n > sc &&
3267 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3268 <                try {
3269 <                    if (table == null) {
3270 <                        init = true;
3271 <                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3272 <                        Node<V>[] tab = (Node<V>[])rt;
3273 <                        int mask = n - 1;
3274 <                        while (p != null) {
3275 <                            int j = p.hash & mask;
3276 <                            Node<V> next = p.next;
3277 <                            Node<V> q = p.next = tabAt(tab, j);
3278 <                            setTabAt(tab, j, p);
3279 <                            if (!collide && q != null && q.hash == p.hash)
3280 <                                collide = true;
3281 <                            p = next;
3282 <                        }
3283 <                        table = tab;
3284 <                        addCount(size, -1);
3285 <                        sc = n - (n >>> 2);
3286 <                    }
3287 <                } finally {
3288 <                    sizeCtl = sc;
3289 <                }
3290 <                if (collide) { // rescan and convert to TreeBins
3291 <                    Node<V>[] tab = table;
3292 <                    for (int i = 0; i < tab.length; ++i) {
3293 <                        int c = 0;
3294 <                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3295 <                            if (++c > TREE_THRESHOLD &&
3296 <                                (e.key instanceof Comparable)) {
3297 <                                replaceWithTreeBin(tab, i, e.key);
3298 <                                break;
3299 <                            }
3300 <                        }
3301 <                    }
3302 <                }
3303 <            }
3304 <            if (!init) { // Can only happen if unsafely published.
3305 <                while (p != null) {
3306 <                    internalPut((K)p.key, p.val, false);
3307 <                    p = p.next;
3308 <                }
3309 <            }
3362 >
3363 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3364 >            if (action == null) throw new NullPointerException();
3365 >            for (Node<K,V> p; (p = advance()) != null; )
3366 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3367          }
3311    }
3368  
3369 <    // -------------------------------------------------------
3369 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3370 >            if (action == null) throw new NullPointerException();
3371 >            Node<K,V> p;
3372 >            if ((p = advance()) == null)
3373 >                return false;
3374 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3375 >            return true;
3376 >        }
3377  
3378 <    // Sams
3316 <    /** Interface describing a void action of one argument */
3317 <    public interface Action<A> { void apply(A a); }
3318 <    /** Interface describing a void action of two arguments */
3319 <    public interface BiAction<A,B> { void apply(A a, B b); }
3320 <    /** Interface describing a function of one argument */
3321 <    public interface Fun<A,T> { T apply(A a); }
3322 <    /** Interface describing a function of two arguments */
3323 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3324 <    /** Interface describing a function of no arguments */
3325 <    public interface Generator<T> { T apply(); }
3326 <    /** Interface describing a function mapping its argument to a double */
3327 <    public interface ObjectToDouble<A> { double apply(A a); }
3328 <    /** Interface describing a function mapping its argument to a long */
3329 <    public interface ObjectToLong<A> { long apply(A a); }
3330 <    /** Interface describing a function mapping its argument to an int */
3331 <    public interface ObjectToInt<A> {int apply(A a); }
3332 <    /** Interface describing a function mapping two arguments to a double */
3333 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3334 <    /** Interface describing a function mapping two arguments to a long */
3335 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3336 <    /** Interface describing a function mapping two arguments to an int */
3337 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3338 <    /** Interface describing a function mapping a double to a double */
3339 <    public interface DoubleToDouble { double apply(double a); }
3340 <    /** Interface describing a function mapping a long to a long */
3341 <    public interface LongToLong { long apply(long a); }
3342 <    /** Interface describing a function mapping an int to an int */
3343 <    public interface IntToInt { int apply(int a); }
3344 <    /** Interface describing a function mapping two doubles to a double */
3345 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3346 <    /** Interface describing a function mapping two longs to a long */
3347 <    public interface LongByLongToLong { long apply(long a, long b); }
3348 <    /** Interface describing a function mapping two ints to an int */
3349 <    public interface IntByIntToInt { int apply(int a, int b); }
3378 >        public long estimateSize() { return est; }
3379  
3380 +    }
3381  
3382 <    // -------------------------------------------------------
3382 >    // Parallel bulk operations
3383  
3384 <    // Sequential bulk operations
3384 >    /**
3385 >     * Computes initial batch value for bulk tasks. The returned value
3386 >     * is approximately exp2 of the number of times (minus one) to
3387 >     * split task by two before executing leaf action. This value is
3388 >     * faster to compute and more convenient to use as a guide to
3389 >     * splitting than is the depth, since it is used while dividing by
3390 >     * two anyway.
3391 >     */
3392 >    final int batchFor(long b) {
3393 >        long n;
3394 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3395 >            return 0;
3396 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3397 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3398 >    }
3399  
3400      /**
3401       * Performs the given action for each (key, value).
3402       *
3403 +     * @param parallelismThreshold the (estimated) number of elements
3404 +     * needed for this operation to be executed in parallel
3405       * @param action the action
3406 +     * @since 1.8
3407       */
3408 <    @SuppressWarnings("unchecked") public void forEachSequentially
3409 <        (BiAction<K,V> action) {
3408 >    public void forEach(long parallelismThreshold,
3409 >                        BiAction<? super K,? super V> action) {
3410          if (action == null) throw new NullPointerException();
3411 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3412 <        V v;
3413 <        while ((v = it.advance()) != null)
3367 <            action.apply((K)it.nextKey, v);
3411 >        new ForEachMappingTask<K,V>
3412 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3413 >             action).invoke();
3414      }
3415  
3416      /**
3417       * Performs the given action for each non-null transformation
3418       * of each (key, value).
3419       *
3420 +     * @param parallelismThreshold the (estimated) number of elements
3421 +     * needed for this operation to be executed in parallel
3422       * @param transformer a function returning the transformation
3423       * for an element, or null if there is no transformation (in
3424       * which case the action is not applied)
3425       * @param action the action
3426 +     * @since 1.8
3427       */
3428 <    @SuppressWarnings("unchecked") public <U> void forEachSequentially
3429 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3430 <         Action<U> action) {
3428 >    public <U> void forEach(long parallelismThreshold,
3429 >                            BiFun<? super K, ? super V, ? extends U> transformer,
3430 >                            Action<? super U> action) {
3431          if (transformer == null || action == null)
3432              throw new NullPointerException();
3433 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3434 <        V v; U u;
3435 <        while ((v = it.advance()) != null) {
3387 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3388 <                action.apply(u);
3389 <        }
3433 >        new ForEachTransformedMappingTask<K,V,U>
3434 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3435 >             transformer, action).invoke();
3436      }
3437  
3438      /**
3439       * Returns a non-null result from applying the given search
3440 <     * function on each (key, value), or null if none.
3440 >     * function on each (key, value), or null if none.  Upon
3441 >     * success, further element processing is suppressed and the
3442 >     * results of any other parallel invocations of the search
3443 >     * function are ignored.
3444       *
3445 +     * @param parallelismThreshold the (estimated) number of elements
3446 +     * needed for this operation to be executed in parallel
3447       * @param searchFunction a function returning a non-null
3448       * result on success, else null
3449       * @return a non-null result from applying the given search
3450       * function on each (key, value), or null if none
3451 +     * @since 1.8
3452       */
3453 <    @SuppressWarnings("unchecked") public <U> U searchSequentially
3454 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3453 >    public <U> U search(long parallelismThreshold,
3454 >                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3455          if (searchFunction == null) throw new NullPointerException();
3456 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3457 <        V v; U u;
3458 <        while ((v = it.advance()) != null) {
3407 <            if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3408 <                return u;
3409 <        }
3410 <        return null;
3456 >        return new SearchMappingsTask<K,V,U>
3457 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3458 >             searchFunction, new AtomicReference<U>()).invoke();
3459      }
3460  
3461      /**
# Line 3415 | Line 3463 | public class ConcurrentHashMapV8<K, V>
3463       * of all (key, value) pairs using the given reducer to
3464       * combine values, or null if none.
3465       *
3466 +     * @param parallelismThreshold the (estimated) number of elements
3467 +     * needed for this operation to be executed in parallel
3468       * @param transformer a function returning the transformation
3469       * for an element, or null if there is no transformation (in
3470       * which case it is not combined)
3471       * @param reducer a commutative associative combining function
3472       * @return the result of accumulating the given transformation
3473       * of all (key, value) pairs
3474 +     * @since 1.8
3475       */
3476 <    @SuppressWarnings("unchecked") public <U> U reduceSequentially
3477 <        (BiFun<? super K, ? super V, ? extends U> transformer,
3478 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3476 >    public <U> U reduce(long parallelismThreshold,
3477 >                        BiFun<? super K, ? super V, ? extends U> transformer,
3478 >                        BiFun<? super U, ? super U, ? extends U> reducer) {
3479          if (transformer == null || reducer == null)
3480              throw new NullPointerException();
3481 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3482 <        U r = null, u; V v;
3483 <        while ((v = it.advance()) != null) {
3433 <            if ((u = transformer.apply((K)it.nextKey, v)) != null)
3434 <                r = (r == null) ? u : reducer.apply(r, u);
3435 <        }
3436 <        return r;
3481 >        return new MapReduceMappingsTask<K,V,U>
3482 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3483 >             null, transformer, reducer).invoke();
3484      }
3485  
3486      /**
# Line 3441 | Line 3488 | public class ConcurrentHashMapV8<K, V>
3488       * of all (key, value) pairs using the given reducer to
3489       * combine values, and the given basis as an identity value.
3490       *
3491 +     * @param parallelismThreshold the (estimated) number of elements
3492 +     * needed for this operation to be executed in parallel
3493       * @param transformer a function returning the transformation
3494       * for an element
3495       * @param basis the identity (initial default value) for the reduction
3496       * @param reducer a commutative associative combining function
3497       * @return the result of accumulating the given transformation
3498       * of all (key, value) pairs
3499 +     * @since 1.8
3500       */
3501 <    @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3502 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
3503 <         double basis,
3504 <         DoubleByDoubleToDouble reducer) {
3501 >    public double reduceToDouble(long parallelismThreshold,
3502 >                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3503 >                                 double basis,
3504 >                                 DoubleByDoubleToDouble reducer) {
3505          if (transformer == null || reducer == null)
3506              throw new NullPointerException();
3507 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3508 <        double r = basis; V v;
3509 <        while ((v = it.advance()) != null)
3460 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3461 <        return r;
3507 >        return new MapReduceMappingsToDoubleTask<K,V>
3508 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3509 >             null, transformer, basis, reducer).invoke();
3510      }
3511  
3512      /**
# Line 3466 | Line 3514 | public class ConcurrentHashMapV8<K, V>
3514       * of all (key, value) pairs using the given reducer to
3515       * combine values, and the given basis as an identity value.
3516       *
3517 +     * @param parallelismThreshold the (estimated) number of elements
3518 +     * needed for this operation to be executed in parallel
3519       * @param transformer a function returning the transformation
3520       * for an element
3521       * @param basis the identity (initial default value) for the reduction
3522       * @param reducer a commutative associative combining function
3523       * @return the result of accumulating the given transformation
3524       * of all (key, value) pairs
3525 +     * @since 1.8
3526       */
3527 <    @SuppressWarnings("unchecked") public long reduceToLongSequentially
3528 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
3529 <         long basis,
3530 <         LongByLongToLong reducer) {
3527 >    public long reduceToLong(long parallelismThreshold,
3528 >                             ObjectByObjectToLong<? super K, ? super V> transformer,
3529 >                             long basis,
3530 >                             LongByLongToLong reducer) {
3531          if (transformer == null || reducer == null)
3532              throw new NullPointerException();
3533 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3534 <        long r = basis; V v;
3535 <        while ((v = it.advance()) != null)
3485 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3486 <        return r;
3533 >        return new MapReduceMappingsToLongTask<K,V>
3534 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3535 >             null, transformer, basis, reducer).invoke();
3536      }
3537  
3538      /**
# Line 3491 | Line 3540 | public class ConcurrentHashMapV8<K, V>
3540       * of all (key, value) pairs using the given reducer to
3541       * combine values, and the given basis as an identity value.
3542       *
3543 +     * @param parallelismThreshold the (estimated) number of elements
3544 +     * needed for this operation to be executed in parallel
3545       * @param transformer a function returning the transformation
3546       * for an element
3547       * @param basis the identity (initial default value) for the reduction
3548       * @param reducer a commutative associative combining function
3549       * @return the result of accumulating the given transformation
3550       * of all (key, value) pairs
3551 +     * @since 1.8
3552       */
3553 <    @SuppressWarnings("unchecked") public int reduceToIntSequentially
3554 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
3555 <         int basis,
3556 <         IntByIntToInt reducer) {
3553 >    public int reduceToInt(long parallelismThreshold,
3554 >                           ObjectByObjectToInt<? super K, ? super V> transformer,
3555 >                           int basis,
3556 >                           IntByIntToInt reducer) {
3557          if (transformer == null || reducer == null)
3558              throw new NullPointerException();
3559 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3560 <        int r = basis; V v;
3561 <        while ((v = it.advance()) != null)
3510 <            r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3511 <        return r;
3559 >        return new MapReduceMappingsToIntTask<K,V>
3560 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3561 >             null, transformer, basis, reducer).invoke();
3562      }
3563  
3564      /**
3565       * Performs the given action for each key.
3566       *
3567 +     * @param parallelismThreshold the (estimated) number of elements
3568 +     * needed for this operation to be executed in parallel
3569       * @param action the action
3570 +     * @since 1.8
3571       */
3572 <    @SuppressWarnings("unchecked") public void forEachKeySequentially
3573 <        (Action<K> action) {
3572 >    public void forEachKey(long parallelismThreshold,
3573 >                           Action<? super K> action) {
3574          if (action == null) throw new NullPointerException();
3575 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3576 <        while (it.advance() != null)
3577 <            action.apply((K)it.nextKey);
3575 >        new ForEachKeyTask<K,V>
3576 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3577 >             action).invoke();
3578      }
3579  
3580      /**
3581       * Performs the given action for each non-null transformation
3582       * of each key.
3583       *
3584 +     * @param parallelismThreshold the (estimated) number of elements
3585 +     * needed for this operation to be executed in parallel
3586       * @param transformer a function returning the transformation
3587       * for an element, or null if there is no transformation (in
3588       * which case the action is not applied)
3589       * @param action the action
3590 +     * @since 1.8
3591       */
3592 <    @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3593 <        (Fun<? super K, ? extends U> transformer,
3594 <         Action<U> action) {
3592 >    public <U> void forEachKey(long parallelismThreshold,
3593 >                               Fun<? super K, ? extends U> transformer,
3594 >                               Action<? super U> action) {
3595          if (transformer == null || action == null)
3596              throw new NullPointerException();
3597 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3598 <        U u;
3599 <        while (it.advance() != null) {
3544 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3545 <                action.apply(u);
3546 <        }
3547 <        ForkJoinTasks.forEachKey
3548 <            (this, transformer, action).invoke();
3597 >        new ForEachTransformedKeyTask<K,V,U>
3598 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3599 >             transformer, action).invoke();
3600      }
3601  
3602      /**
3603       * Returns a non-null result from applying the given search
3604 <     * function on each key, or null if none.
3604 >     * function on each key, or null if none. Upon success,
3605 >     * further element processing is suppressed and the results of
3606 >     * any other parallel invocations of the search function are
3607 >     * ignored.
3608       *
3609 +     * @param parallelismThreshold the (estimated) number of elements
3610 +     * needed for this operation to be executed in parallel
3611       * @param searchFunction a function returning a non-null
3612       * result on success, else null
3613       * @return a non-null result from applying the given search
3614       * function on each key, or null if none
3615 +     * @since 1.8
3616       */
3617 <    @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3618 <        (Fun<? super K, ? extends U> searchFunction) {
3619 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3620 <        U u;
3621 <        while (it.advance() != null) {
3622 <            if ((u = searchFunction.apply((K)it.nextKey)) != null)
3566 <                return u;
3567 <        }
3568 <        return null;
3617 >    public <U> U searchKeys(long parallelismThreshold,
3618 >                            Fun<? super K, ? extends U> searchFunction) {
3619 >        if (searchFunction == null) throw new NullPointerException();
3620 >        return new SearchKeysTask<K,V,U>
3621 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3622 >             searchFunction, new AtomicReference<U>()).invoke();
3623      }
3624  
3625      /**
3626       * Returns the result of accumulating all keys using the given
3627       * reducer to combine values, or null if none.
3628       *
3629 +     * @param parallelismThreshold the (estimated) number of elements
3630 +     * needed for this operation to be executed in parallel
3631       * @param reducer a commutative associative combining function
3632       * @return the result of accumulating all keys using the given
3633       * reducer to combine values, or null if none
3634 +     * @since 1.8
3635       */
3636 <    @SuppressWarnings("unchecked") public K reduceKeysSequentially
3637 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
3636 >    public K reduceKeys(long parallelismThreshold,
3637 >                        BiFun<? super K, ? super K, ? extends K> reducer) {
3638          if (reducer == null) throw new NullPointerException();
3639 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3640 <        K r = null;
3641 <        while (it.advance() != null) {
3585 <            K u = (K)it.nextKey;
3586 <            r = (r == null) ? u : reducer.apply(r, u);
3587 <        }
3588 <        return r;
3639 >        return new ReduceKeysTask<K,V>
3640 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3641 >             null, reducer).invoke();
3642      }
3643  
3644      /**
# Line 3593 | Line 3646 | public class ConcurrentHashMapV8<K, V>
3646       * of all keys using the given reducer to combine values, or
3647       * null if none.
3648       *
3649 +     * @param parallelismThreshold the (estimated) number of elements
3650 +     * needed for this operation to be executed in parallel
3651       * @param transformer a function returning the transformation
3652       * for an element, or null if there is no transformation (in
3653       * which case it is not combined)
3654       * @param reducer a commutative associative combining function
3655       * @return the result of accumulating the given transformation
3656       * of all keys
3657 +     * @since 1.8
3658       */
3659 <    @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3660 <        (Fun<? super K, ? extends U> transformer,
3659 >    public <U> U reduceKeys(long parallelismThreshold,
3660 >                            Fun<? super K, ? extends U> transformer,
3661           BiFun<? super U, ? super U, ? extends U> reducer) {
3662          if (transformer == null || reducer == null)
3663              throw new NullPointerException();
3664 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3665 <        U r = null, u;
3666 <        while (it.advance() != null) {
3611 <            if ((u = transformer.apply((K)it.nextKey)) != null)
3612 <                r = (r == null) ? u : reducer.apply(r, u);
3613 <        }
3614 <        return r;
3664 >        return new MapReduceKeysTask<K,V,U>
3665 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3666 >             null, transformer, reducer).invoke();
3667      }
3668  
3669      /**
# Line 3619 | Line 3671 | public class ConcurrentHashMapV8<K, V>
3671       * of all keys using the given reducer to combine values, and
3672       * the given basis as an identity value.
3673       *
3674 +     * @param parallelismThreshold the (estimated) number of elements
3675 +     * needed for this operation to be executed in parallel
3676       * @param transformer a function returning the transformation
3677       * for an element
3678       * @param basis the identity (initial default value) for the reduction
3679       * @param reducer a commutative associative combining function
3680 <     * @return  the result of accumulating the given transformation
3680 >     * @return the result of accumulating the given transformation
3681       * of all keys
3682 +     * @since 1.8
3683       */
3684 <    @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3685 <        (ObjectToDouble<? super K> transformer,
3686 <         double basis,
3687 <         DoubleByDoubleToDouble reducer) {
3684 >    public double reduceKeysToDouble(long parallelismThreshold,
3685 >                                     ObjectToDouble<? super K> transformer,
3686 >                                     double basis,
3687 >                                     DoubleByDoubleToDouble reducer) {
3688          if (transformer == null || reducer == null)
3689              throw new NullPointerException();
3690 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3691 <        double r = basis;
3692 <        while (it.advance() != null)
3638 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3639 <        return r;
3690 >        return new MapReduceKeysToDoubleTask<K,V>
3691 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3692 >             null, transformer, basis, reducer).invoke();
3693      }
3694  
3695      /**
# Line 3644 | Line 3697 | public class ConcurrentHashMapV8<K, V>
3697       * of all keys using the given reducer to combine values, and
3698       * the given basis as an identity value.
3699       *
3700 +     * @param parallelismThreshold the (estimated) number of elements
3701 +     * needed for this operation to be executed in parallel
3702       * @param transformer a function returning the transformation
3703       * for an element
3704       * @param basis the identity (initial default value) for the reduction
3705       * @param reducer a commutative associative combining function
3706       * @return the result of accumulating the given transformation
3707       * of all keys
3708 +     * @since 1.8
3709       */
3710 <    @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3711 <        (ObjectToLong<? super K> transformer,
3712 <         long basis,
3713 <         LongByLongToLong reducer) {
3710 >    public long reduceKeysToLong(long parallelismThreshold,
3711 >                                 ObjectToLong<? super K> transformer,
3712 >                                 long basis,
3713 >                                 LongByLongToLong reducer) {
3714          if (transformer == null || reducer == null)
3715              throw new NullPointerException();
3716 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3717 <        long r = basis;
3718 <        while (it.advance() != null)
3663 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3664 <        return r;
3716 >        return new MapReduceKeysToLongTask<K,V>
3717 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3718 >             null, transformer, basis, reducer).invoke();
3719      }
3720  
3721      /**
# Line 3669 | Line 3723 | public class ConcurrentHashMapV8<K, V>
3723       * of all keys using the given reducer to combine values, and
3724       * the given basis as an identity value.
3725       *
3726 +     * @param parallelismThreshold the (estimated) number of elements
3727 +     * needed for this operation to be executed in parallel
3728       * @param transformer a function returning the transformation
3729       * for an element
3730       * @param basis the identity (initial default value) for the reduction
3731       * @param reducer a commutative associative combining function
3732       * @return the result of accumulating the given transformation
3733       * of all keys
3734 +     * @since 1.8
3735       */
3736 <    @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3737 <        (ObjectToInt<? super K> transformer,
3738 <         int basis,
3739 <         IntByIntToInt reducer) {
3736 >    public int reduceKeysToInt(long parallelismThreshold,
3737 >                               ObjectToInt<? super K> transformer,
3738 >                               int basis,
3739 >                               IntByIntToInt reducer) {
3740          if (transformer == null || reducer == null)
3741              throw new NullPointerException();
3742 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3743 <        int r = basis;
3744 <        while (it.advance() != null)
3688 <            r = reducer.apply(r, transformer.apply((K)it.nextKey));
3689 <        return r;
3742 >        return new MapReduceKeysToIntTask<K,V>
3743 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3744 >             null, transformer, basis, reducer).invoke();
3745      }
3746  
3747      /**
3748       * Performs the given action for each value.
3749       *
3750 +     * @param parallelismThreshold the (estimated) number of elements
3751 +     * needed for this operation to be executed in parallel
3752       * @param action the action
3753 +     * @since 1.8
3754       */
3755 <    public void forEachValueSequentially(Action<V> action) {
3756 <        if (action == null) throw new NullPointerException();
3757 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3758 <        V v;
3759 <        while ((v = it.advance()) != null)
3760 <            action.apply(v);
3755 >    public void forEachValue(long parallelismThreshold,
3756 >                             Action<? super V> action) {
3757 >        if (action == null)
3758 >            throw new NullPointerException();
3759 >        new ForEachValueTask<K,V>
3760 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3761 >             action).invoke();
3762      }
3763  
3764      /**
3765       * Performs the given action for each non-null transformation
3766       * of each value.
3767       *
3768 +     * @param parallelismThreshold the (estimated) number of elements
3769 +     * needed for this operation to be executed in parallel
3770       * @param transformer a function returning the transformation
3771       * for an element, or null if there is no transformation (in
3772       * which case the action is not applied)
3773 +     * @param action the action
3774 +     * @since 1.8
3775       */
3776 <    public <U> void forEachValueSequentially
3777 <        (Fun<? super V, ? extends U> transformer,
3778 <         Action<U> action) {
3776 >    public <U> void forEachValue(long parallelismThreshold,
3777 >                                 Fun<? super V, ? extends U> transformer,
3778 >                                 Action<? super U> action) {
3779          if (transformer == null || action == null)
3780              throw new NullPointerException();
3781 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3782 <        V v; U u;
3783 <        while ((v = it.advance()) != null) {
3721 <            if ((u = transformer.apply(v)) != null)
3722 <                action.apply(u);
3723 <        }
3781 >        new ForEachTransformedValueTask<K,V,U>
3782 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3783 >             transformer, action).invoke();
3784      }
3785  
3786      /**
3787       * Returns a non-null result from applying the given search
3788 <     * function on each value, or null if none.
3788 >     * function on each value, or null if none.  Upon success,
3789 >     * further element processing is suppressed and the results of
3790 >     * any other parallel invocations of the search function are
3791 >     * ignored.
3792       *
3793 +     * @param parallelismThreshold the (estimated) number of elements
3794 +     * needed for this operation to be executed in parallel
3795       * @param searchFunction a function returning a non-null
3796       * result on success, else null
3797       * @return a non-null result from applying the given search
3798       * function on each value, or null if none
3799 +     * @since 1.8
3800       */
3801 <    public <U> U searchValuesSequentially
3802 <        (Fun<? super V, ? extends U> searchFunction) {
3801 >    public <U> U searchValues(long parallelismThreshold,
3802 >                              Fun<? super V, ? extends U> searchFunction) {
3803          if (searchFunction == null) throw new NullPointerException();
3804 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3805 <        V v; U u;
3806 <        while ((v = it.advance()) != null) {
3741 <            if ((u = searchFunction.apply(v)) != null)
3742 <                return u;
3743 <        }
3744 <        return null;
3804 >        return new SearchValuesTask<K,V,U>
3805 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3806 >             searchFunction, new AtomicReference<U>()).invoke();
3807      }
3808  
3809      /**
3810       * Returns the result of accumulating all values using the
3811       * given reducer to combine values, or null if none.
3812       *
3813 +     * @param parallelismThreshold the (estimated) number of elements
3814 +     * needed for this operation to be executed in parallel
3815       * @param reducer a commutative associative combining function
3816 <     * @return  the result of accumulating all values
3816 >     * @return the result of accumulating all values
3817 >     * @since 1.8
3818       */
3819 <    public V reduceValuesSequentially
3820 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
3819 >    public V reduceValues(long parallelismThreshold,
3820 >                          BiFun<? super V, ? super V, ? extends V> reducer) {
3821          if (reducer == null) throw new NullPointerException();
3822 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3823 <        V r = null; V v;
3824 <        while ((v = it.advance()) != null)
3760 <            r = (r == null) ? v : reducer.apply(r, v);
3761 <        return r;
3822 >        return new ReduceValuesTask<K,V>
3823 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3824 >             null, reducer).invoke();
3825      }
3826  
3827      /**
# Line 3766 | Line 3829 | public class ConcurrentHashMapV8<K, V>
3829       * of all values using the given reducer to combine values, or
3830       * null if none.
3831       *
3832 +     * @param parallelismThreshold the (estimated) number of elements
3833 +     * needed for this operation to be executed in parallel
3834       * @param transformer a function returning the transformation
3835       * for an element, or null if there is no transformation (in
3836       * which case it is not combined)
3837       * @param reducer a commutative associative combining function
3838       * @return the result of accumulating the given transformation
3839       * of all values
3840 +     * @since 1.8
3841       */
3842 <    public <U> U reduceValuesSequentially
3843 <        (Fun<? super V, ? extends U> transformer,
3844 <         BiFun<? super U, ? super U, ? extends U> reducer) {
3842 >    public <U> U reduceValues(long parallelismThreshold,
3843 >                              Fun<? super V, ? extends U> transformer,
3844 >                              BiFun<? super U, ? super U, ? extends U> reducer) {
3845          if (transformer == null || reducer == null)
3846              throw new NullPointerException();
3847 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3848 <        U r = null, u; V v;
3849 <        while ((v = it.advance()) != null) {
3784 <            if ((u = transformer.apply(v)) != null)
3785 <                r = (r == null) ? u : reducer.apply(r, u);
3786 <        }
3787 <        return r;
3847 >        return new MapReduceValuesTask<K,V,U>
3848 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3849 >             null, transformer, reducer).invoke();
3850      }
3851  
3852      /**
# Line 3792 | Line 3854 | public class ConcurrentHashMapV8<K, V>
3854       * of all values using the given reducer to combine values,
3855       * and the given basis as an identity value.
3856       *
3857 +     * @param parallelismThreshold the (estimated) number of elements
3858 +     * needed for this operation to be executed in parallel
3859       * @param transformer a function returning the transformation
3860       * for an element
3861       * @param basis the identity (initial default value) for the reduction
3862       * @param reducer a commutative associative combining function
3863       * @return the result of accumulating the given transformation
3864       * of all values
3865 +     * @since 1.8
3866       */
3867 <    public double reduceValuesToDoubleSequentially
3868 <        (ObjectToDouble<? super V> transformer,
3869 <         double basis,
3870 <         DoubleByDoubleToDouble reducer) {
3867 >    public double reduceValuesToDouble(long parallelismThreshold,
3868 >                                       ObjectToDouble<? super V> transformer,
3869 >                                       double basis,
3870 >                                       DoubleByDoubleToDouble reducer) {
3871          if (transformer == null || reducer == null)
3872              throw new NullPointerException();
3873 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874 <        double r = basis; V v;
3875 <        while ((v = it.advance()) != null)
3811 <            r = reducer.apply(r, transformer.apply(v));
3812 <        return r;
3873 >        return new MapReduceValuesToDoubleTask<K,V>
3874 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3875 >             null, transformer, basis, reducer).invoke();
3876      }
3877  
3878      /**
# Line 3817 | Line 3880 | public class ConcurrentHashMapV8<K, V>
3880       * of all values using the given reducer to combine values,
3881       * and the given basis as an identity value.
3882       *
3883 +     * @param parallelismThreshold the (estimated) number of elements
3884 +     * needed for this operation to be executed in parallel
3885       * @param transformer a function returning the transformation
3886       * for an element
3887       * @param basis the identity (initial default value) for the reduction
3888       * @param reducer a commutative associative combining function
3889       * @return the result of accumulating the given transformation
3890       * of all values
3891 +     * @since 1.8
3892       */
3893 <    public long reduceValuesToLongSequentially
3894 <        (ObjectToLong<? super V> transformer,
3895 <         long basis,
3896 <         LongByLongToLong reducer) {
3893 >    public long reduceValuesToLong(long parallelismThreshold,
3894 >                                   ObjectToLong<? super V> transformer,
3895 >                                   long basis,
3896 >                                   LongByLongToLong reducer) {
3897          if (transformer == null || reducer == null)
3898              throw new NullPointerException();
3899 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3900 <        long r = basis; V v;
3901 <        while ((v = it.advance()) != null)
3836 <            r = reducer.apply(r, transformer.apply(v));
3837 <        return r;
3899 >        return new MapReduceValuesToLongTask<K,V>
3900 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3901 >             null, transformer, basis, reducer).invoke();
3902      }
3903  
3904      /**
# Line 3842 | Line 3906 | public class ConcurrentHashMapV8<K, V>
3906       * of all values using the given reducer to combine values,
3907       * and the given basis as an identity value.
3908       *
3909 +     * @param parallelismThreshold the (estimated) number of elements
3910 +     * needed for this operation to be executed in parallel
3911       * @param transformer a function returning the transformation
3912       * for an element
3913       * @param basis the identity (initial default value) for the reduction
3914       * @param reducer a commutative associative combining function
3915       * @return the result of accumulating the given transformation
3916       * of all values
3917 +     * @since 1.8
3918       */
3919 <    public int reduceValuesToIntSequentially
3920 <        (ObjectToInt<? super V> transformer,
3921 <         int basis,
3922 <         IntByIntToInt reducer) {
3919 >    public int reduceValuesToInt(long parallelismThreshold,
3920 >                                 ObjectToInt<? super V> transformer,
3921 >                                 int basis,
3922 >                                 IntByIntToInt reducer) {
3923          if (transformer == null || reducer == null)
3924              throw new NullPointerException();
3925 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3926 <        int r = basis; V v;
3927 <        while ((v = it.advance()) != null)
3861 <            r = reducer.apply(r, transformer.apply(v));
3862 <        return r;
3925 >        return new MapReduceValuesToIntTask<K,V>
3926 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3927 >             null, transformer, basis, reducer).invoke();
3928      }
3929  
3930      /**
3931       * Performs the given action for each entry.
3932       *
3933 +     * @param parallelismThreshold the (estimated) number of elements
3934 +     * needed for this operation to be executed in parallel
3935       * @param action the action
3936 +     * @since 1.8
3937       */
3938 <    @SuppressWarnings("unchecked") public void forEachEntrySequentially
3939 <        (Action<Map.Entry<K,V>> action) {
3938 >    public void forEachEntry(long parallelismThreshold,
3939 >                             Action<? super Map.Entry<K,V>> action) {
3940          if (action == null) throw new NullPointerException();
3941 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3942 <        V v;
3875 <        while ((v = it.advance()) != null)
3876 <            action.apply(entryFor((K)it.nextKey, v));
3941 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3942 >                                  action).invoke();
3943      }
3944  
3945      /**
3946       * Performs the given action for each non-null transformation
3947       * of each entry.
3948       *
3949 +     * @param parallelismThreshold the (estimated) number of elements
3950 +     * needed for this operation to be executed in parallel
3951       * @param transformer a function returning the transformation
3952       * for an element, or null if there is no transformation (in
3953       * which case the action is not applied)
3954       * @param action the action
3955 +     * @since 1.8
3956       */
3957 <    @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3958 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
3959 <         Action<U> action) {
3957 >    public <U> void forEachEntry(long parallelismThreshold,
3958 >                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
3959 >                                 Action<? super U> action) {
3960          if (transformer == null || action == null)
3961              throw new NullPointerException();
3962 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3963 <        V v; U u;
3964 <        while ((v = it.advance()) != null) {
3896 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3897 <                action.apply(u);
3898 <        }
3962 >        new ForEachTransformedEntryTask<K,V,U>
3963 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3964 >             transformer, action).invoke();
3965      }
3966  
3967      /**
3968       * Returns a non-null result from applying the given search
3969 <     * function on each entry, or null if none.
3969 >     * function on each entry, or null if none.  Upon success,
3970 >     * further element processing is suppressed and the results of
3971 >     * any other parallel invocations of the search function are
3972 >     * ignored.
3973       *
3974 +     * @param parallelismThreshold the (estimated) number of elements
3975 +     * needed for this operation to be executed in parallel
3976       * @param searchFunction a function returning a non-null
3977       * result on success, else null
3978       * @return a non-null result from applying the given search
3979       * function on each entry, or null if none
3980 +     * @since 1.8
3981       */
3982 <    @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
3983 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3982 >    public <U> U searchEntries(long parallelismThreshold,
3983 >                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3984          if (searchFunction == null) throw new NullPointerException();
3985 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3986 <        V v; U u;
3987 <        while ((v = it.advance()) != null) {
3916 <            if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3917 <                return u;
3918 <        }
3919 <        return null;
3985 >        return new SearchEntriesTask<K,V,U>
3986 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3987 >             searchFunction, new AtomicReference<U>()).invoke();
3988      }
3989  
3990      /**
3991       * Returns the result of accumulating all entries using the
3992       * given reducer to combine values, or null if none.
3993       *
3994 +     * @param parallelismThreshold the (estimated) number of elements
3995 +     * needed for this operation to be executed in parallel
3996       * @param reducer a commutative associative combining function
3997       * @return the result of accumulating all entries
3998 +     * @since 1.8
3999       */
4000 <    @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
4001 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4000 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4001 >                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4002          if (reducer == null) throw new NullPointerException();
4003 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4004 <        Map.Entry<K,V> r = null; V v;
4005 <        while ((v = it.advance()) != null) {
3935 <            Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3936 <            r = (r == null) ? u : reducer.apply(r, u);
3937 <        }
3938 <        return r;
4003 >        return new ReduceEntriesTask<K,V>
4004 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4005 >             null, reducer).invoke();
4006      }
4007  
4008      /**
# Line 3943 | Line 4010 | public class ConcurrentHashMapV8<K, V>
4010       * of all entries using the given reducer to combine values,
4011       * or null if none.
4012       *
4013 +     * @param parallelismThreshold the (estimated) number of elements
4014 +     * needed for this operation to be executed in parallel
4015       * @param transformer a function returning the transformation
4016       * for an element, or null if there is no transformation (in
4017       * which case it is not combined)
4018       * @param reducer a commutative associative combining function
4019       * @return the result of accumulating the given transformation
4020       * of all entries
4021 +     * @since 1.8
4022       */
4023 <    @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
4024 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4025 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4023 >    public <U> U reduceEntries(long parallelismThreshold,
4024 >                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4025 >                               BiFun<? super U, ? super U, ? extends U> reducer) {
4026          if (transformer == null || reducer == null)
4027              throw new NullPointerException();
4028 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4029 <        U r = null, u; V v;
4030 <        while ((v = it.advance()) != null) {
3961 <            if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3962 <                r = (r == null) ? u : reducer.apply(r, u);
3963 <        }
3964 <        return r;
4028 >        return new MapReduceEntriesTask<K,V,U>
4029 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4030 >             null, transformer, reducer).invoke();
4031      }
4032  
4033      /**
# Line 3969 | Line 4035 | public class ConcurrentHashMapV8<K, V>
4035       * of all entries using the given reducer to combine values,
4036       * and the given basis as an identity value.
4037       *
4038 +     * @param parallelismThreshold the (estimated) number of elements
4039 +     * needed for this operation to be executed in parallel
4040       * @param transformer a function returning the transformation
4041       * for an element
4042       * @param basis the identity (initial default value) for the reduction
4043       * @param reducer a commutative associative combining function
4044       * @return the result of accumulating the given transformation
4045       * of all entries
4046 +     * @since 1.8
4047       */
4048 <    @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
4049 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4050 <         double basis,
4051 <         DoubleByDoubleToDouble reducer) {
4048 >    public double reduceEntriesToDouble(long parallelismThreshold,
4049 >                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4050 >                                        double basis,
4051 >                                        DoubleByDoubleToDouble reducer) {
4052          if (transformer == null || reducer == null)
4053              throw new NullPointerException();
4054 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4055 <        double r = basis; V v;
4056 <        while ((v = it.advance()) != null)
3988 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3989 <        return r;
4054 >        return new MapReduceEntriesToDoubleTask<K,V>
4055 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4056 >             null, transformer, basis, reducer).invoke();
4057      }
4058  
4059      /**
# Line 3994 | Line 4061 | public class ConcurrentHashMapV8<K, V>
4061       * of all entries using the given reducer to combine values,
4062       * and the given basis as an identity value.
4063       *
4064 +     * @param parallelismThreshold the (estimated) number of elements
4065 +     * needed for this operation to be executed in parallel
4066       * @param transformer a function returning the transformation
4067       * for an element
4068       * @param basis the identity (initial default value) for the reduction
4069       * @param reducer a commutative associative combining function
4070 <     * @return  the result of accumulating the given transformation
4070 >     * @return the result of accumulating the given transformation
4071       * of all entries
4072 +     * @since 1.8
4073       */
4074 <    @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4075 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4076 <         long basis,
4077 <         LongByLongToLong reducer) {
4074 >    public long reduceEntriesToLong(long parallelismThreshold,
4075 >                                    ObjectToLong<Map.Entry<K,V>> transformer,
4076 >                                    long basis,
4077 >                                    LongByLongToLong reducer) {
4078          if (transformer == null || reducer == null)
4079              throw new NullPointerException();
4080 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4081 <        long r = basis; V v;
4082 <        while ((v = it.advance()) != null)
4013 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4014 <        return r;
4080 >        return new MapReduceEntriesToLongTask<K,V>
4081 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4082 >             null, transformer, basis, reducer).invoke();
4083      }
4084  
4085      /**
# Line 4019 | Line 4087 | public class ConcurrentHashMapV8<K, V>
4087       * of all entries using the given reducer to combine values,
4088       * and the given basis as an identity value.
4089       *
4090 +     * @param parallelismThreshold the (estimated) number of elements
4091 +     * needed for this operation to be executed in parallel
4092       * @param transformer a function returning the transformation
4093       * for an element
4094       * @param basis the identity (initial default value) for the reduction
4095       * @param reducer a commutative associative combining function
4096       * @return the result of accumulating the given transformation
4097       * of all entries
4098 +     * @since 1.8
4099       */
4100 <    @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4101 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4102 <         int basis,
4103 <         IntByIntToInt reducer) {
4100 >    public int reduceEntriesToInt(long parallelismThreshold,
4101 >                                  ObjectToInt<Map.Entry<K,V>> transformer,
4102 >                                  int basis,
4103 >                                  IntByIntToInt reducer) {
4104          if (transformer == null || reducer == null)
4105              throw new NullPointerException();
4106 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4107 <        int r = basis; V v;
4108 <        while ((v = it.advance()) != null)
4038 <            r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4039 <        return r;
4040 <    }
4041 <
4042 <    // Parallel bulk operations
4043 <
4044 <    /**
4045 <     * Performs the given action for each (key, value).
4046 <     *
4047 <     * @param action the action
4048 <     */
4049 <    public void forEachInParallel(BiAction<K,V> action) {
4050 <        ForkJoinTasks.forEach
4051 <            (this, action).invoke();
4052 <    }
4053 <
4054 <    /**
4055 <     * Performs the given action for each non-null transformation
4056 <     * of each (key, value).
4057 <     *
4058 <     * @param transformer a function returning the transformation
4059 <     * for an element, or null if there is no transformation (in
4060 <     * which case the action is not applied)
4061 <     * @param action the action
4062 <     */
4063 <    public <U> void forEachInParallel
4064 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4065 <                            Action<U> action) {
4066 <        ForkJoinTasks.forEach
4067 <            (this, transformer, action).invoke();
4068 <    }
4069 <
4070 <    /**
4071 <     * Returns a non-null result from applying the given search
4072 <     * function on each (key, value), or null if none.  Upon
4073 <     * success, further element processing is suppressed and the
4074 <     * results of any other parallel invocations of the search
4075 <     * function are ignored.
4076 <     *
4077 <     * @param searchFunction a function returning a non-null
4078 <     * result on success, else null
4079 <     * @return a non-null result from applying the given search
4080 <     * function on each (key, value), or null if none
4081 <     */
4082 <    public <U> U searchInParallel
4083 <        (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4084 <        return ForkJoinTasks.search
4085 <            (this, searchFunction).invoke();
4086 <    }
4087 <
4088 <    /**
4089 <     * Returns the result of accumulating the given transformation
4090 <     * of all (key, value) pairs using the given reducer to
4091 <     * combine values, or null if none.
4092 <     *
4093 <     * @param transformer a function returning the transformation
4094 <     * for an element, or null if there is no transformation (in
4095 <     * which case it is not combined)
4096 <     * @param reducer a commutative associative combining function
4097 <     * @return the result of accumulating the given transformation
4098 <     * of all (key, value) pairs
4099 <     */
4100 <    public <U> U reduceInParallel
4101 <        (BiFun<? super K, ? super V, ? extends U> transformer,
4102 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4103 <        return ForkJoinTasks.reduce
4104 <            (this, transformer, reducer).invoke();
4105 <    }
4106 <
4107 <    /**
4108 <     * Returns the result of accumulating the given transformation
4109 <     * of all (key, value) pairs using the given reducer to
4110 <     * combine values, and the given basis as an identity value.
4111 <     *
4112 <     * @param transformer a function returning the transformation
4113 <     * for an element
4114 <     * @param basis the identity (initial default value) for the reduction
4115 <     * @param reducer a commutative associative combining function
4116 <     * @return the result of accumulating the given transformation
4117 <     * of all (key, value) pairs
4118 <     */
4119 <    public double reduceToDoubleInParallel
4120 <        (ObjectByObjectToDouble<? super K, ? super V> transformer,
4121 <         double basis,
4122 <         DoubleByDoubleToDouble reducer) {
4123 <        return ForkJoinTasks.reduceToDouble
4124 <            (this, transformer, basis, reducer).invoke();
4125 <    }
4126 <
4127 <    /**
4128 <     * Returns the result of accumulating the given transformation
4129 <     * of all (key, value) pairs using the given reducer to
4130 <     * combine values, and the given basis as an identity value.
4131 <     *
4132 <     * @param transformer a function returning the transformation
4133 <     * for an element
4134 <     * @param basis the identity (initial default value) for the reduction
4135 <     * @param reducer a commutative associative combining function
4136 <     * @return the result of accumulating the given transformation
4137 <     * of all (key, value) pairs
4138 <     */
4139 <    public long reduceToLongInParallel
4140 <        (ObjectByObjectToLong<? super K, ? super V> transformer,
4141 <         long basis,
4142 <         LongByLongToLong reducer) {
4143 <        return ForkJoinTasks.reduceToLong
4144 <            (this, transformer, basis, reducer).invoke();
4145 <    }
4146 <
4147 <    /**
4148 <     * Returns the result of accumulating the given transformation
4149 <     * of all (key, value) pairs using the given reducer to
4150 <     * combine values, and the given basis as an identity value.
4151 <     *
4152 <     * @param transformer a function returning the transformation
4153 <     * for an element
4154 <     * @param basis the identity (initial default value) for the reduction
4155 <     * @param reducer a commutative associative combining function
4156 <     * @return the result of accumulating the given transformation
4157 <     * of all (key, value) pairs
4158 <     */
4159 <    public int reduceToIntInParallel
4160 <        (ObjectByObjectToInt<? super K, ? super V> transformer,
4161 <         int basis,
4162 <         IntByIntToInt reducer) {
4163 <        return ForkJoinTasks.reduceToInt
4164 <            (this, transformer, basis, reducer).invoke();
4165 <    }
4166 <
4167 <    /**
4168 <     * Performs the given action for each key.
4169 <     *
4170 <     * @param action the action
4171 <     */
4172 <    public void forEachKeyInParallel(Action<K> action) {
4173 <        ForkJoinTasks.forEachKey
4174 <            (this, action).invoke();
4175 <    }
4176 <
4177 <    /**
4178 <     * Performs the given action for each non-null transformation
4179 <     * of each key.
4180 <     *
4181 <     * @param transformer a function returning the transformation
4182 <     * for an element, or null if there is no transformation (in
4183 <     * which case the action is not applied)
4184 <     * @param action the action
4185 <     */
4186 <    public <U> void forEachKeyInParallel
4187 <        (Fun<? super K, ? extends U> transformer,
4188 <         Action<U> action) {
4189 <        ForkJoinTasks.forEachKey
4190 <            (this, transformer, action).invoke();
4191 <    }
4192 <
4193 <    /**
4194 <     * Returns a non-null result from applying the given search
4195 <     * function on each key, or null if none. Upon success,
4196 <     * further element processing is suppressed and the results of
4197 <     * any other parallel invocations of the search function are
4198 <     * ignored.
4199 <     *
4200 <     * @param searchFunction a function returning a non-null
4201 <     * result on success, else null
4202 <     * @return a non-null result from applying the given search
4203 <     * function on each key, or null if none
4204 <     */
4205 <    public <U> U searchKeysInParallel
4206 <        (Fun<? super K, ? extends U> searchFunction) {
4207 <        return ForkJoinTasks.searchKeys
4208 <            (this, searchFunction).invoke();
4209 <    }
4210 <
4211 <    /**
4212 <     * Returns the result of accumulating all keys using the given
4213 <     * reducer to combine values, or null if none.
4214 <     *
4215 <     * @param reducer a commutative associative combining function
4216 <     * @return the result of accumulating all keys using the given
4217 <     * reducer to combine values, or null if none
4218 <     */
4219 <    public K reduceKeysInParallel
4220 <        (BiFun<? super K, ? super K, ? extends K> reducer) {
4221 <        return ForkJoinTasks.reduceKeys
4222 <            (this, reducer).invoke();
4223 <    }
4224 <
4225 <    /**
4226 <     * Returns the result of accumulating the given transformation
4227 <     * of all keys using the given reducer to combine values, or
4228 <     * null if none.
4229 <     *
4230 <     * @param transformer a function returning the transformation
4231 <     * for an element, or null if there is no transformation (in
4232 <     * which case it is not combined)
4233 <     * @param reducer a commutative associative combining function
4234 <     * @return the result of accumulating the given transformation
4235 <     * of all keys
4236 <     */
4237 <    public <U> U reduceKeysInParallel
4238 <        (Fun<? super K, ? extends U> transformer,
4239 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4240 <        return ForkJoinTasks.reduceKeys
4241 <            (this, transformer, reducer).invoke();
4242 <    }
4243 <
4244 <    /**
4245 <     * Returns the result of accumulating the given transformation
4246 <     * of all keys using the given reducer to combine values, and
4247 <     * the given basis as an identity value.
4248 <     *
4249 <     * @param transformer a function returning the transformation
4250 <     * for an element
4251 <     * @param basis the identity (initial default value) for the reduction
4252 <     * @param reducer a commutative associative combining function
4253 <     * @return  the result of accumulating the given transformation
4254 <     * of all keys
4255 <     */
4256 <    public double reduceKeysToDoubleInParallel
4257 <        (ObjectToDouble<? super K> transformer,
4258 <         double basis,
4259 <         DoubleByDoubleToDouble reducer) {
4260 <        return ForkJoinTasks.reduceKeysToDouble
4261 <            (this, transformer, basis, reducer).invoke();
4262 <    }
4263 <
4264 <    /**
4265 <     * Returns the result of accumulating the given transformation
4266 <     * of all keys using the given reducer to combine values, and
4267 <     * the given basis as an identity value.
4268 <     *
4269 <     * @param transformer a function returning the transformation
4270 <     * for an element
4271 <     * @param basis the identity (initial default value) for the reduction
4272 <     * @param reducer a commutative associative combining function
4273 <     * @return the result of accumulating the given transformation
4274 <     * of all keys
4275 <     */
4276 <    public long reduceKeysToLongInParallel
4277 <        (ObjectToLong<? super K> transformer,
4278 <         long basis,
4279 <         LongByLongToLong reducer) {
4280 <        return ForkJoinTasks.reduceKeysToLong
4281 <            (this, transformer, basis, reducer).invoke();
4282 <    }
4283 <
4284 <    /**
4285 <     * Returns the result of accumulating the given transformation
4286 <     * of all keys using the given reducer to combine values, and
4287 <     * the given basis as an identity value.
4288 <     *
4289 <     * @param transformer a function returning the transformation
4290 <     * for an element
4291 <     * @param basis the identity (initial default value) for the reduction
4292 <     * @param reducer a commutative associative combining function
4293 <     * @return the result of accumulating the given transformation
4294 <     * of all keys
4295 <     */
4296 <    public int reduceKeysToIntInParallel
4297 <        (ObjectToInt<? super K> transformer,
4298 <         int basis,
4299 <         IntByIntToInt reducer) {
4300 <        return ForkJoinTasks.reduceKeysToInt
4301 <            (this, transformer, basis, reducer).invoke();
4302 <    }
4303 <
4304 <    /**
4305 <     * Performs the given action for each value.
4306 <     *
4307 <     * @param action the action
4308 <     */
4309 <    public void forEachValueInParallel(Action<V> action) {
4310 <        ForkJoinTasks.forEachValue
4311 <            (this, action).invoke();
4312 <    }
4313 <
4314 <    /**
4315 <     * Performs the given action for each non-null transformation
4316 <     * of each value.
4317 <     *
4318 <     * @param transformer a function returning the transformation
4319 <     * for an element, or null if there is no transformation (in
4320 <     * which case the action is not applied)
4321 <     */
4322 <    public <U> void forEachValueInParallel
4323 <        (Fun<? super V, ? extends U> transformer,
4324 <         Action<U> action) {
4325 <        ForkJoinTasks.forEachValue
4326 <            (this, transformer, action).invoke();
4327 <    }
4328 <
4329 <    /**
4330 <     * Returns a non-null result from applying the given search
4331 <     * function on each value, or null if none.  Upon success,
4332 <     * further element processing is suppressed and the results of
4333 <     * any other parallel invocations of the search function are
4334 <     * ignored.
4335 <     *
4336 <     * @param searchFunction a function returning a non-null
4337 <     * result on success, else null
4338 <     * @return a non-null result from applying the given search
4339 <     * function on each value, or null if none
4340 <     */
4341 <    public <U> U searchValuesInParallel
4342 <        (Fun<? super V, ? extends U> searchFunction) {
4343 <        return ForkJoinTasks.searchValues
4344 <            (this, searchFunction).invoke();
4345 <    }
4346 <
4347 <    /**
4348 <     * Returns the result of accumulating all values using the
4349 <     * given reducer to combine values, or null if none.
4350 <     *
4351 <     * @param reducer a commutative associative combining function
4352 <     * @return  the result of accumulating all values
4353 <     */
4354 <    public V reduceValuesInParallel
4355 <        (BiFun<? super V, ? super V, ? extends V> reducer) {
4356 <        return ForkJoinTasks.reduceValues
4357 <            (this, reducer).invoke();
4358 <    }
4359 <
4360 <    /**
4361 <     * Returns the result of accumulating the given transformation
4362 <     * of all values using the given reducer to combine values, or
4363 <     * null if none.
4364 <     *
4365 <     * @param transformer a function returning the transformation
4366 <     * for an element, or null if there is no transformation (in
4367 <     * which case it is not combined)
4368 <     * @param reducer a commutative associative combining function
4369 <     * @return the result of accumulating the given transformation
4370 <     * of all values
4371 <     */
4372 <    public <U> U reduceValuesInParallel
4373 <        (Fun<? super V, ? extends U> transformer,
4374 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4375 <        return ForkJoinTasks.reduceValues
4376 <            (this, transformer, reducer).invoke();
4377 <    }
4378 <
4379 <    /**
4380 <     * Returns the result of accumulating the given transformation
4381 <     * of all values using the given reducer to combine values,
4382 <     * and the given basis as an identity value.
4383 <     *
4384 <     * @param transformer a function returning the transformation
4385 <     * for an element
4386 <     * @param basis the identity (initial default value) for the reduction
4387 <     * @param reducer a commutative associative combining function
4388 <     * @return the result of accumulating the given transformation
4389 <     * of all values
4390 <     */
4391 <    public double reduceValuesToDoubleInParallel
4392 <        (ObjectToDouble<? super V> transformer,
4393 <         double basis,
4394 <         DoubleByDoubleToDouble reducer) {
4395 <        return ForkJoinTasks.reduceValuesToDouble
4396 <            (this, transformer, basis, reducer).invoke();
4397 <    }
4398 <
4399 <    /**
4400 <     * Returns the result of accumulating the given transformation
4401 <     * of all values using the given reducer to combine values,
4402 <     * and the given basis as an identity value.
4403 <     *
4404 <     * @param transformer a function returning the transformation
4405 <     * for an element
4406 <     * @param basis the identity (initial default value) for the reduction
4407 <     * @param reducer a commutative associative combining function
4408 <     * @return the result of accumulating the given transformation
4409 <     * of all values
4410 <     */
4411 <    public long reduceValuesToLongInParallel
4412 <        (ObjectToLong<? super V> transformer,
4413 <         long basis,
4414 <         LongByLongToLong reducer) {
4415 <        return ForkJoinTasks.reduceValuesToLong
4416 <            (this, transformer, basis, reducer).invoke();
4417 <    }
4418 <
4419 <    /**
4420 <     * Returns the result of accumulating the given transformation
4421 <     * of all values using the given reducer to combine values,
4422 <     * and the given basis as an identity value.
4423 <     *
4424 <     * @param transformer a function returning the transformation
4425 <     * for an element
4426 <     * @param basis the identity (initial default value) for the reduction
4427 <     * @param reducer a commutative associative combining function
4428 <     * @return the result of accumulating the given transformation
4429 <     * of all values
4430 <     */
4431 <    public int reduceValuesToIntInParallel
4432 <        (ObjectToInt<? super V> transformer,
4433 <         int basis,
4434 <         IntByIntToInt reducer) {
4435 <        return ForkJoinTasks.reduceValuesToInt
4436 <            (this, transformer, basis, reducer).invoke();
4437 <    }
4438 <
4439 <    /**
4440 <     * Performs the given action for each entry.
4441 <     *
4442 <     * @param action the action
4443 <     */
4444 <    public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4445 <        ForkJoinTasks.forEachEntry
4446 <            (this, action).invoke();
4447 <    }
4448 <
4449 <    /**
4450 <     * Performs the given action for each non-null transformation
4451 <     * of each entry.
4452 <     *
4453 <     * @param transformer a function returning the transformation
4454 <     * for an element, or null if there is no transformation (in
4455 <     * which case the action is not applied)
4456 <     * @param action the action
4457 <     */
4458 <    public <U> void forEachEntryInParallel
4459 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4460 <         Action<U> action) {
4461 <        ForkJoinTasks.forEachEntry
4462 <            (this, transformer, action).invoke();
4463 <    }
4464 <
4465 <    /**
4466 <     * Returns a non-null result from applying the given search
4467 <     * function on each entry, or null if none.  Upon success,
4468 <     * further element processing is suppressed and the results of
4469 <     * any other parallel invocations of the search function are
4470 <     * ignored.
4471 <     *
4472 <     * @param searchFunction a function returning a non-null
4473 <     * result on success, else null
4474 <     * @return a non-null result from applying the given search
4475 <     * function on each entry, or null if none
4476 <     */
4477 <    public <U> U searchEntriesInParallel
4478 <        (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4479 <        return ForkJoinTasks.searchEntries
4480 <            (this, searchFunction).invoke();
4481 <    }
4482 <
4483 <    /**
4484 <     * Returns the result of accumulating all entries using the
4485 <     * given reducer to combine values, or null if none.
4486 <     *
4487 <     * @param reducer a commutative associative combining function
4488 <     * @return the result of accumulating all entries
4489 <     */
4490 <    public Map.Entry<K,V> reduceEntriesInParallel
4491 <        (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4492 <        return ForkJoinTasks.reduceEntries
4493 <            (this, reducer).invoke();
4494 <    }
4495 <
4496 <    /**
4497 <     * Returns the result of accumulating the given transformation
4498 <     * of all entries using the given reducer to combine values,
4499 <     * or null if none.
4500 <     *
4501 <     * @param transformer a function returning the transformation
4502 <     * for an element, or null if there is no transformation (in
4503 <     * which case it is not combined)
4504 <     * @param reducer a commutative associative combining function
4505 <     * @return the result of accumulating the given transformation
4506 <     * of all entries
4507 <     */
4508 <    public <U> U reduceEntriesInParallel
4509 <        (Fun<Map.Entry<K,V>, ? extends U> transformer,
4510 <         BiFun<? super U, ? super U, ? extends U> reducer) {
4511 <        return ForkJoinTasks.reduceEntries
4512 <            (this, transformer, reducer).invoke();
4513 <    }
4514 <
4515 <    /**
4516 <     * Returns the result of accumulating the given transformation
4517 <     * of all entries using the given reducer to combine values,
4518 <     * and the given basis as an identity value.
4519 <     *
4520 <     * @param transformer a function returning the transformation
4521 <     * for an element
4522 <     * @param basis the identity (initial default value) for the reduction
4523 <     * @param reducer a commutative associative combining function
4524 <     * @return the result of accumulating the given transformation
4525 <     * of all entries
4526 <     */
4527 <    public double reduceEntriesToDoubleInParallel
4528 <        (ObjectToDouble<Map.Entry<K,V>> transformer,
4529 <         double basis,
4530 <         DoubleByDoubleToDouble reducer) {
4531 <        return ForkJoinTasks.reduceEntriesToDouble
4532 <            (this, transformer, basis, reducer).invoke();
4533 <    }
4534 <
4535 <    /**
4536 <     * Returns the result of accumulating the given transformation
4537 <     * of all entries using the given reducer to combine values,
4538 <     * and the given basis as an identity value.
4539 <     *
4540 <     * @param transformer a function returning the transformation
4541 <     * for an element
4542 <     * @param basis the identity (initial default value) for the reduction
4543 <     * @param reducer a commutative associative combining function
4544 <     * @return  the result of accumulating the given transformation
4545 <     * of all entries
4546 <     */
4547 <    public long reduceEntriesToLongInParallel
4548 <        (ObjectToLong<Map.Entry<K,V>> transformer,
4549 <         long basis,
4550 <         LongByLongToLong reducer) {
4551 <        return ForkJoinTasks.reduceEntriesToLong
4552 <            (this, transformer, basis, reducer).invoke();
4553 <    }
4554 <
4555 <    /**
4556 <     * Returns the result of accumulating the given transformation
4557 <     * of all entries using the given reducer to combine values,
4558 <     * and the given basis as an identity value.
4559 <     *
4560 <     * @param transformer a function returning the transformation
4561 <     * for an element
4562 <     * @param basis the identity (initial default value) for the reduction
4563 <     * @param reducer a commutative associative combining function
4564 <     * @return the result of accumulating the given transformation
4565 <     * of all entries
4566 <     */
4567 <    public int reduceEntriesToIntInParallel
4568 <        (ObjectToInt<Map.Entry<K,V>> transformer,
4569 <         int basis,
4570 <         IntByIntToInt reducer) {
4571 <        return ForkJoinTasks.reduceEntriesToInt
4572 <            (this, transformer, basis, reducer).invoke();
4106 >        return new MapReduceEntriesToIntTask<K,V>
4107 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4108 >             null, transformer, basis, reducer).invoke();
4109      }
4110  
4111  
# Line 4578 | Line 4114 | public class ConcurrentHashMapV8<K, V>
4114      /**
4115       * Base class for views.
4116       */
4117 <    abstract static class CHMView<K, V> {
4118 <        final ConcurrentHashMapV8<K, V> map;
4119 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4117 >    abstract static class CollectionView<K,V,E>
4118 >        implements Collection<E>, java.io.Serializable {
4119 >        private static final long serialVersionUID = 7249069246763182397L;
4120 >        final ConcurrentHashMapV8<K,V> map;
4121 >        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4122  
4123          /**
4124           * Returns the map backing this view.
# Line 4589 | Line 4127 | public class ConcurrentHashMapV8<K, V>
4127           */
4128          public ConcurrentHashMapV8<K,V> getMap() { return map; }
4129  
4130 <        public final int size()                 { return map.size(); }
4131 <        public final boolean isEmpty()          { return map.isEmpty(); }
4132 <        public final void clear()               { map.clear(); }
4130 >        /**
4131 >         * Removes all of the elements from this view, by removing all
4132 >         * the mappings from the map backing this view.
4133 >         */
4134 >        public final void clear()      { map.clear(); }
4135 >        public final int size()        { return map.size(); }
4136 >        public final boolean isEmpty() { return map.isEmpty(); }
4137  
4138          // implementations below rely on concrete classes supplying these
4139 <        public abstract Iterator<?> iterator();
4139 >        // abstract methods
4140 >        /**
4141 >         * Returns a "weakly consistent" iterator that will never
4142 >         * throw {@link ConcurrentModificationException}, and
4143 >         * guarantees to traverse elements as they existed upon
4144 >         * construction of the iterator, and may (but is not
4145 >         * guaranteed to) reflect any modifications subsequent to
4146 >         * construction.
4147 >         */
4148 >        public abstract Iterator<E> iterator();
4149          public abstract boolean contains(Object o);
4150          public abstract boolean remove(Object o);
4151  
# Line 4602 | Line 4153 | public class ConcurrentHashMapV8<K, V>
4153  
4154          public final Object[] toArray() {
4155              long sz = map.mappingCount();
4156 <            if (sz > (long)(MAX_ARRAY_SIZE))
4156 >            if (sz > MAX_ARRAY_SIZE)
4157                  throw new OutOfMemoryError(oomeMsg);
4158              int n = (int)sz;
4159              Object[] r = new Object[n];
4160              int i = 0;
4161 <            Iterator<?> it = iterator();
4611 <            while (it.hasNext()) {
4161 >            for (E e : this) {
4162                  if (i == n) {
4163                      if (n >= MAX_ARRAY_SIZE)
4164                          throw new OutOfMemoryError(oomeMsg);
# Line 4618 | Line 4168 | public class ConcurrentHashMapV8<K, V>
4168                          n += (n >>> 1) + 1;
4169                      r = Arrays.copyOf(r, n);
4170                  }
4171 <                r[i++] = it.next();
4171 >                r[i++] = e;
4172              }
4173              return (i == n) ? r : Arrays.copyOf(r, i);
4174          }
4175  
4176 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4176 >        @SuppressWarnings("unchecked")
4177 >        public final <T> T[] toArray(T[] a) {
4178              long sz = map.mappingCount();
4179 <            if (sz > (long)(MAX_ARRAY_SIZE))
4179 >            if (sz > MAX_ARRAY_SIZE)
4180                  throw new OutOfMemoryError(oomeMsg);
4181              int m = (int)sz;
4182              T[] r = (a.length >= m) ? a :
# Line 4633 | Line 4184 | public class ConcurrentHashMapV8<K, V>
4184                  .newInstance(a.getClass().getComponentType(), m);
4185              int n = r.length;
4186              int i = 0;
4187 <            Iterator<?> it = iterator();
4637 <            while (it.hasNext()) {
4187 >            for (E e : this) {
4188                  if (i == n) {
4189                      if (n >= MAX_ARRAY_SIZE)
4190                          throw new OutOfMemoryError(oomeMsg);
# Line 4644 | Line 4194 | public class ConcurrentHashMapV8<K, V>
4194                          n += (n >>> 1) + 1;
4195                      r = Arrays.copyOf(r, n);
4196                  }
4197 <                r[i++] = (T)it.next();
4197 >                r[i++] = (T)e;
4198              }
4199              if (a == r && i < n) {
4200                  r[i] = null; // null-terminate
# Line 4653 | Line 4203 | public class ConcurrentHashMapV8<K, V>
4203              return (i == n) ? r : Arrays.copyOf(r, i);
4204          }
4205  
4206 <        public final int hashCode() {
4207 <            int h = 0;
4208 <            for (Iterator<?> it = iterator(); it.hasNext();)
4209 <                h += it.next().hashCode();
4210 <            return h;
4211 <        }
4212 <
4206 >        /**
4207 >         * Returns a string representation of this collection.
4208 >         * The string representation consists of the string representations
4209 >         * of the collection's elements in the order they are returned by
4210 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4211 >         * Adjacent elements are separated by the characters {@code ", "}
4212 >         * (comma and space).  Elements are converted to strings as by
4213 >         * {@link String#valueOf(Object)}.
4214 >         *
4215 >         * @return a string representation of this collection
4216 >         */
4217          public final String toString() {
4218              StringBuilder sb = new StringBuilder();
4219              sb.append('[');
4220 <            Iterator<?> it = iterator();
4220 >            Iterator<E> it = iterator();
4221              if (it.hasNext()) {
4222                  for (;;) {
4223                      Object e = it.next();
# Line 4678 | Line 4232 | public class ConcurrentHashMapV8<K, V>
4232  
4233          public final boolean containsAll(Collection<?> c) {
4234              if (c != this) {
4235 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
4682 <                    Object e = it.next();
4235 >                for (Object e : c) {
4236                      if (e == null || !contains(e))
4237                          return false;
4238                  }
# Line 4689 | Line 4242 | public class ConcurrentHashMapV8<K, V>
4242  
4243          public final boolean removeAll(Collection<?> c) {
4244              boolean modified = false;
4245 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4245 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4246                  if (c.contains(it.next())) {
4247                      it.remove();
4248                      modified = true;
# Line 4700 | Line 4253 | public class ConcurrentHashMapV8<K, V>
4253  
4254          public final boolean retainAll(Collection<?> c) {
4255              boolean modified = false;
4256 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4256 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4257                  if (!c.contains(it.next())) {
4258                      it.remove();
4259                      modified = true;
# Line 4714 | Line 4267 | public class ConcurrentHashMapV8<K, V>
4267      /**
4268       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4269       * which additions may optionally be enabled by mapping to a
4270 <     * common value.  This class cannot be directly instantiated. See
4271 <     * {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()},
4272 <     * {@link #newKeySet(int)}.
4270 >     * common value.  This class cannot be directly instantiated.
4271 >     * See {@link #keySet() keySet()},
4272 >     * {@link #keySet(Object) keySet(V)},
4273 >     * {@link #newKeySet() newKeySet()},
4274 >     * {@link #newKeySet(int) newKeySet(int)}.
4275 >     *
4276 >     * @since 1.8
4277       */
4278 <    public static class KeySetView<K,V> extends CHMView<K,V>
4278 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4279          implements Set<K>, java.io.Serializable {
4280          private static final long serialVersionUID = 7249069246763182397L;
4281          private final V value;
4282 <        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4282 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4283              super(map);
4284              this.value = value;
4285          }
# Line 4736 | Line 4293 | public class ConcurrentHashMapV8<K, V>
4293           */
4294          public V getMappedValue() { return value; }
4295  
4296 <        // implement Set API
4297 <
4296 >        /**
4297 >         * {@inheritDoc}
4298 >         * @throws NullPointerException if the specified key is null
4299 >         */
4300          public boolean contains(Object o) { return map.containsKey(o); }
4742        public boolean remove(Object o)   { return map.remove(o) != null; }
4301  
4302          /**
4303 <         * Returns a "weakly consistent" iterator that will never
4304 <         * throw {@link ConcurrentModificationException}, and
4305 <         * guarantees to traverse elements as they existed upon
4748 <         * construction of the iterator, and may (but is not
4749 <         * guaranteed to) reflect any modifications subsequent to
4750 <         * construction.
4303 >         * Removes the key from this map view, by removing the key (and its
4304 >         * corresponding value) from the backing map.  This method does
4305 >         * nothing if the key is not in the map.
4306           *
4307 <         * @return an iterator over the keys of this map
4307 >         * @param  o the key to be removed from the backing map
4308 >         * @return {@code true} if the backing map contained the specified key
4309 >         * @throws NullPointerException if the specified key is null
4310 >         */
4311 >        public boolean remove(Object o) { return map.remove(o) != null; }
4312 >
4313 >        /**
4314 >         * @return an iterator over the keys of the backing map
4315 >         */
4316 >        public Iterator<K> iterator() {
4317 >            Node<K,V>[] t;
4318 >            ConcurrentHashMapV8<K,V> m = map;
4319 >            int f = (t = m.table) == null ? 0 : t.length;
4320 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4321 >        }
4322 >
4323 >        /**
4324 >         * Adds the specified key to this set view by mapping the key to
4325 >         * the default mapped value in the backing map, if defined.
4326 >         *
4327 >         * @param e key to be added
4328 >         * @return {@code true} if this set changed as a result of the call
4329 >         * @throws NullPointerException if the specified key is null
4330 >         * @throws UnsupportedOperationException if no default mapped value
4331 >         * for additions was provided
4332           */
4754        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4333          public boolean add(K e) {
4334              V v;
4335              if ((v = value) == null)
4336                  throw new UnsupportedOperationException();
4337 <            return map.internalPut(e, v, true) == null;
4337 >            return map.putVal(e, v, true) == null;
4338          }
4339 +
4340 +        /**
4341 +         * Adds all of the elements in the specified collection to this set,
4342 +         * as if by calling {@link #add} on each one.
4343 +         *
4344 +         * @param c the elements to be inserted into this set
4345 +         * @return {@code true} if this set changed as a result of the call
4346 +         * @throws NullPointerException if the collection or any of its
4347 +         * elements are {@code null}
4348 +         * @throws UnsupportedOperationException if no default mapped value
4349 +         * for additions was provided
4350 +         */
4351          public boolean addAll(Collection<? extends K> c) {
4352              boolean added = false;
4353              V v;
4354              if ((v = value) == null)
4355                  throw new UnsupportedOperationException();
4356              for (K e : c) {
4357 <                if (map.internalPut(e, v, true) == null)
4357 >                if (map.putVal(e, v, true) == null)
4358                      added = true;
4359              }
4360              return added;
4361          }
4362 +
4363 +        public int hashCode() {
4364 +            int h = 0;
4365 +            for (K e : this)
4366 +                h += e.hashCode();
4367 +            return h;
4368 +        }
4369 +
4370          public boolean equals(Object o) {
4371              Set<?> c;
4372              return ((o instanceof Set) &&
4373                      ((c = (Set<?>)o) == this ||
4374                       (containsAll(c) && c.containsAll(this))));
4375          }
4376 +
4377 +        public ConcurrentHashMapSpliterator<K> spliterator() {
4378 +            Node<K,V>[] t;
4379 +            ConcurrentHashMapV8<K,V> m = map;
4380 +            long n = m.sumCount();
4381 +            int f = (t = m.table) == null ? 0 : t.length;
4382 +            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4383 +        }
4384 +
4385 +        public void forEach(Action<? super K> action) {
4386 +            if (action == null) throw new NullPointerException();
4387 +            Node<K,V>[] t;
4388 +            if ((t = map.table) != null) {
4389 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4390 +                for (Node<K,V> p; (p = it.advance()) != null; )
4391 +                    action.apply(p.key);
4392 +            }
4393 +        }
4394      }
4395  
4396      /**
4397       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4398       * values, in which additions are disabled. This class cannot be
4399       * directly instantiated. See {@link #values()}.
4784     *
4785     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4786     * that will never throw {@link ConcurrentModificationException},
4787     * and guarantees to traverse elements as they existed upon
4788     * construction of the iterator, and may (but is not guaranteed to)
4789     * reflect any modifications subsequent to construction.
4400       */
4401 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4402 <        implements Collection<V> {
4403 <        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4404 <        public final boolean contains(Object o) { return map.containsValue(o); }
4401 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4402 >        implements Collection<V>, java.io.Serializable {
4403 >        private static final long serialVersionUID = 2249069246763182397L;
4404 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4405 >        public final boolean contains(Object o) {
4406 >            return map.containsValue(o);
4407 >        }
4408 >
4409          public final boolean remove(Object o) {
4410              if (o != null) {
4411 <                Iterator<V> it = new ValueIterator<K,V>(map);
4798 <                while (it.hasNext()) {
4411 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4412                      if (o.equals(it.next())) {
4413                          it.remove();
4414                          return true;
# Line 4805 | Line 4418 | public class ConcurrentHashMapV8<K, V>
4418              return false;
4419          }
4420  
4808        /**
4809         * Returns a "weakly consistent" iterator that will never
4810         * throw {@link ConcurrentModificationException}, and
4811         * guarantees to traverse elements as they existed upon
4812         * construction of the iterator, and may (but is not
4813         * guaranteed to) reflect any modifications subsequent to
4814         * construction.
4815         *
4816         * @return an iterator over the values of this map
4817         */
4421          public final Iterator<V> iterator() {
4422 <            return new ValueIterator<K,V>(map);
4422 >            ConcurrentHashMapV8<K,V> m = map;
4423 >            Node<K,V>[] t;
4424 >            int f = (t = m.table) == null ? 0 : t.length;
4425 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4426          }
4427 +
4428          public final boolean add(V e) {
4429              throw new UnsupportedOperationException();
4430          }
# Line 4825 | Line 4432 | public class ConcurrentHashMapV8<K, V>
4432              throw new UnsupportedOperationException();
4433          }
4434  
4435 +        public ConcurrentHashMapSpliterator<V> spliterator() {
4436 +            Node<K,V>[] t;
4437 +            ConcurrentHashMapV8<K,V> m = map;
4438 +            long n = m.sumCount();
4439 +            int f = (t = m.table) == null ? 0 : t.length;
4440 +            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4441 +        }
4442 +
4443 +        public void forEach(Action<? super V> action) {
4444 +            if (action == null) throw new NullPointerException();
4445 +            Node<K,V>[] t;
4446 +            if ((t = map.table) != null) {
4447 +                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4448 +                for (Node<K,V> p; (p = it.advance()) != null; )
4449 +                    action.apply(p.val);
4450 +            }
4451 +        }
4452      }
4453  
4454      /**
# Line 4832 | Line 4456 | public class ConcurrentHashMapV8<K, V>
4456       * entries.  This class cannot be directly instantiated. See
4457       * {@link #entrySet()}.
4458       */
4459 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4460 <        implements Set<Map.Entry<K,V>> {
4461 <        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4462 <        public final boolean contains(Object o) {
4459 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4460 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4461 >        private static final long serialVersionUID = 2249069246763182397L;
4462 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4463 >
4464 >        public boolean contains(Object o) {
4465              Object k, v, r; Map.Entry<?,?> e;
4466              return ((o instanceof Map.Entry) &&
4467                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4843 | Line 4469 | public class ConcurrentHashMapV8<K, V>
4469                      (v = e.getValue()) != null &&
4470                      (v == r || v.equals(r)));
4471          }
4472 <        public final boolean remove(Object o) {
4472 >
4473 >        public boolean remove(Object o) {
4474              Object k, v; Map.Entry<?,?> e;
4475              return ((o instanceof Map.Entry) &&
4476                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4852 | Line 4479 | public class ConcurrentHashMapV8<K, V>
4479          }
4480  
4481          /**
4482 <         * Returns a "weakly consistent" iterator that will never
4856 <         * throw {@link ConcurrentModificationException}, and
4857 <         * guarantees to traverse elements as they existed upon
4858 <         * construction of the iterator, and may (but is not
4859 <         * guaranteed to) reflect any modifications subsequent to
4860 <         * construction.
4861 <         *
4862 <         * @return an iterator over the entries of this map
4482 >         * @return an iterator over the entries of the backing map
4483           */
4484 <        public final Iterator<Map.Entry<K,V>> iterator() {
4485 <            return new EntryIterator<K,V>(map);
4484 >        public Iterator<Map.Entry<K,V>> iterator() {
4485 >            ConcurrentHashMapV8<K,V> m = map;
4486 >            Node<K,V>[] t;
4487 >            int f = (t = m.table) == null ? 0 : t.length;
4488 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4489          }
4490  
4491 <        public final boolean add(Entry<K,V> e) {
4492 <            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4491 >        public boolean add(Entry<K,V> e) {
4492 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4493          }
4494 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4494 >
4495 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4496              boolean added = false;
4497              for (Entry<K,V> e : c) {
4498                  if (add(e))
# Line 4876 | Line 4500 | public class ConcurrentHashMapV8<K, V>
4500              }
4501              return added;
4502          }
4503 <        public boolean equals(Object o) {
4503 >
4504 >        public final int hashCode() {
4505 >            int h = 0;
4506 >            Node<K,V>[] t;
4507 >            if ((t = map.table) != null) {
4508 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4509 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4510 >                    h += p.hashCode();
4511 >                }
4512 >            }
4513 >            return h;
4514 >        }
4515 >
4516 >        public final boolean equals(Object o) {
4517              Set<?> c;
4518              return ((o instanceof Set) &&
4519                      ((c = (Set<?>)o) == this ||
4520                       (containsAll(c) && c.containsAll(this))));
4521          }
4885    }
4886
4887    // ---------------------------------------------------------------------
4888
4889    /**
4890     * Predefined tasks for performing bulk parallel operations on
4891     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4892     * for bulk operations. Each method has the same name, but returns
4893     * a task rather than invoking it. These methods may be useful in
4894     * custom applications such as submitting a task without waiting
4895     * for completion, using a custom pool, or combining with other
4896     * tasks.
4897     */
4898    public static class ForkJoinTasks {
4899        private ForkJoinTasks() {}
4900
4901        /**
4902         * Returns a task that when invoked, performs the given
4903         * action for each (key, value)
4904         *
4905         * @param map the map
4906         * @param action the action
4907         * @return the task
4908         */
4909        public static <K,V> ForkJoinTask<Void> forEach
4910            (ConcurrentHashMapV8<K,V> map,
4911             BiAction<K,V> action) {
4912            if (action == null) throw new NullPointerException();
4913            return new ForEachMappingTask<K,V>(map, null, -1, action);
4914        }
4915
4916        /**
4917         * Returns a task that when invoked, performs the given
4918         * action for each non-null transformation of each (key, value)
4919         *
4920         * @param map the map
4921         * @param transformer a function returning the transformation
4922         * for an element, or null if there is no transformation (in
4923         * which case the action is not applied)
4924         * @param action the action
4925         * @return the task
4926         */
4927        public static <K,V,U> ForkJoinTask<Void> forEach
4928            (ConcurrentHashMapV8<K,V> map,
4929             BiFun<? super K, ? super V, ? extends U> transformer,
4930             Action<U> action) {
4931            if (transformer == null || action == null)
4932                throw new NullPointerException();
4933            return new ForEachTransformedMappingTask<K,V,U>
4934                (map, null, -1, transformer, action);
4935        }
4936
4937        /**
4938         * Returns a task that when invoked, returns a non-null result
4939         * from applying the given search function on each (key,
4940         * value), or null if none. Upon success, further element
4941         * processing is suppressed and the results of any other
4942         * parallel invocations of the search function are ignored.
4943         *
4944         * @param map the map
4945         * @param searchFunction a function returning a non-null
4946         * result on success, else null
4947         * @return the task
4948         */
4949        public static <K,V,U> ForkJoinTask<U> search
4950            (ConcurrentHashMapV8<K,V> map,
4951             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4952            if (searchFunction == null) throw new NullPointerException();
4953            return new SearchMappingsTask<K,V,U>
4954                (map, null, -1, searchFunction,
4955                 new AtomicReference<U>());
4956        }
4957
4958        /**
4959         * Returns a task that when invoked, returns the result of
4960         * accumulating the given transformation of all (key, value) pairs
4961         * using the given reducer to combine values, or null if none.
4962         *
4963         * @param map the map
4964         * @param transformer a function returning the transformation
4965         * for an element, or null if there is no transformation (in
4966         * which case it is not combined)
4967         * @param reducer a commutative associative combining function
4968         * @return the task
4969         */
4970        public static <K,V,U> ForkJoinTask<U> reduce
4971            (ConcurrentHashMapV8<K,V> map,
4972             BiFun<? super K, ? super V, ? extends U> transformer,
4973             BiFun<? super U, ? super U, ? extends U> reducer) {
4974            if (transformer == null || reducer == null)
4975                throw new NullPointerException();
4976            return new MapReduceMappingsTask<K,V,U>
4977                (map, null, -1, null, transformer, reducer);
4978        }
4979
4980        /**
4981         * Returns a task that when invoked, returns the result of
4982         * accumulating the given transformation of all (key, value) pairs
4983         * using the given reducer to combine values, and the given
4984         * basis as an identity value.
4985         *
4986         * @param map the map
4987         * @param transformer a function returning the transformation
4988         * for an element
4989         * @param basis the identity (initial default value) for the reduction
4990         * @param reducer a commutative associative combining function
4991         * @return the task
4992         */
4993        public static <K,V> ForkJoinTask<Double> reduceToDouble
4994            (ConcurrentHashMapV8<K,V> map,
4995             ObjectByObjectToDouble<? super K, ? super V> transformer,
4996             double basis,
4997             DoubleByDoubleToDouble reducer) {
4998            if (transformer == null || reducer == null)
4999                throw new NullPointerException();
5000            return new MapReduceMappingsToDoubleTask<K,V>
5001                (map, null, -1, null, transformer, basis, reducer);
5002        }
5003
5004        /**
5005         * Returns a task that when invoked, returns the result of
5006         * accumulating the given transformation of all (key, value) pairs
5007         * using the given reducer to combine values, and the given
5008         * basis as an identity value.
5009         *
5010         * @param map the map
5011         * @param transformer a function returning the transformation
5012         * for an element
5013         * @param basis the identity (initial default value) for the reduction
5014         * @param reducer a commutative associative combining function
5015         * @return the task
5016         */
5017        public static <K,V> ForkJoinTask<Long> reduceToLong
5018            (ConcurrentHashMapV8<K,V> map,
5019             ObjectByObjectToLong<? super K, ? super V> transformer,
5020             long basis,
5021             LongByLongToLong reducer) {
5022            if (transformer == null || reducer == null)
5023                throw new NullPointerException();
5024            return new MapReduceMappingsToLongTask<K,V>
5025                (map, null, -1, null, transformer, basis, reducer);
5026        }
4522  
4523 <        /**
4524 <         * Returns a task that when invoked, returns the result of
4525 <         * accumulating the given transformation of all (key, value) pairs
4526 <         * using the given reducer to combine values, and the given
4527 <         * basis as an identity value.
4528 <         *
5034 <         * @param transformer a function returning the transformation
5035 <         * for an element
5036 <         * @param basis the identity (initial default value) for the reduction
5037 <         * @param reducer a commutative associative combining function
5038 <         * @return the task
5039 <         */
5040 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
5041 <            (ConcurrentHashMapV8<K,V> map,
5042 <             ObjectByObjectToInt<? super K, ? super V> transformer,
5043 <             int basis,
5044 <             IntByIntToInt reducer) {
5045 <            if (transformer == null || reducer == null)
5046 <                throw new NullPointerException();
5047 <            return new MapReduceMappingsToIntTask<K,V>
5048 <                (map, null, -1, null, transformer, basis, reducer);
4523 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4524 >            Node<K,V>[] t;
4525 >            ConcurrentHashMapV8<K,V> m = map;
4526 >            long n = m.sumCount();
4527 >            int f = (t = m.table) == null ? 0 : t.length;
4528 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4529          }
4530  
4531 <        /**
5052 <         * Returns a task that when invoked, performs the given action
5053 <         * for each key.
5054 <         *
5055 <         * @param map the map
5056 <         * @param action the action
5057 <         * @return the task
5058 <         */
5059 <        public static <K,V> ForkJoinTask<Void> forEachKey
5060 <            (ConcurrentHashMapV8<K,V> map,
5061 <             Action<K> action) {
4531 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4532              if (action == null) throw new NullPointerException();
4533 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4534 <        }
4535 <
4536 <        /**
4537 <         * Returns a task that when invoked, performs the given action
4538 <         * for each non-null transformation of each key.
5069 <         *
5070 <         * @param map the map
5071 <         * @param transformer a function returning the transformation
5072 <         * for an element, or null if there is no transformation (in
5073 <         * which case the action is not applied)
5074 <         * @param action the action
5075 <         * @return the task
5076 <         */
5077 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
5078 <            (ConcurrentHashMapV8<K,V> map,
5079 <             Fun<? super K, ? extends U> transformer,
5080 <             Action<U> action) {
5081 <            if (transformer == null || action == null)
5082 <                throw new NullPointerException();
5083 <            return new ForEachTransformedKeyTask<K,V,U>
5084 <                (map, null, -1, transformer, action);
5085 <        }
5086 <
5087 <        /**
5088 <         * Returns a task that when invoked, returns a non-null result
5089 <         * from applying the given search function on each key, or
5090 <         * null if none.  Upon success, further element processing is
5091 <         * suppressed and the results of any other parallel
5092 <         * invocations of the search function are ignored.
5093 <         *
5094 <         * @param map the map
5095 <         * @param searchFunction a function returning a non-null
5096 <         * result on success, else null
5097 <         * @return the task
5098 <         */
5099 <        public static <K,V,U> ForkJoinTask<U> searchKeys
5100 <            (ConcurrentHashMapV8<K,V> map,
5101 <             Fun<? super K, ? extends U> searchFunction) {
5102 <            if (searchFunction == null) throw new NullPointerException();
5103 <            return new SearchKeysTask<K,V,U>
5104 <                (map, null, -1, searchFunction,
5105 <                 new AtomicReference<U>());
5106 <        }
5107 <
5108 <        /**
5109 <         * Returns a task that when invoked, returns the result of
5110 <         * accumulating all keys using the given reducer to combine
5111 <         * values, or null if none.
5112 <         *
5113 <         * @param map the map
5114 <         * @param reducer a commutative associative combining function
5115 <         * @return the task
5116 <         */
5117 <        public static <K,V> ForkJoinTask<K> reduceKeys
5118 <            (ConcurrentHashMapV8<K,V> map,
5119 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5120 <            if (reducer == null) throw new NullPointerException();
5121 <            return new ReduceKeysTask<K,V>
5122 <                (map, null, -1, null, reducer);
5123 <        }
5124 <
5125 <        /**
5126 <         * Returns a task that when invoked, returns the result of
5127 <         * accumulating the given transformation of all keys using the given
5128 <         * reducer to combine values, or null if none.
5129 <         *
5130 <         * @param map the map
5131 <         * @param transformer a function returning the transformation
5132 <         * for an element, or null if there is no transformation (in
5133 <         * which case it is not combined)
5134 <         * @param reducer a commutative associative combining function
5135 <         * @return the task
5136 <         */
5137 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
5138 <            (ConcurrentHashMapV8<K,V> map,
5139 <             Fun<? super K, ? extends U> transformer,
5140 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5141 <            if (transformer == null || reducer == null)
5142 <                throw new NullPointerException();
5143 <            return new MapReduceKeysTask<K,V,U>
5144 <                (map, null, -1, null, transformer, reducer);
5145 <        }
5146 <
5147 <        /**
5148 <         * Returns a task that when invoked, returns the result of
5149 <         * accumulating the given transformation of all keys using the given
5150 <         * reducer to combine values, and the given basis as an
5151 <         * identity value.
5152 <         *
5153 <         * @param map the map
5154 <         * @param transformer a function returning the transformation
5155 <         * for an element
5156 <         * @param basis the identity (initial default value) for the reduction
5157 <         * @param reducer a commutative associative combining function
5158 <         * @return the task
5159 <         */
5160 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5161 <            (ConcurrentHashMapV8<K,V> map,
5162 <             ObjectToDouble<? super K> transformer,
5163 <             double basis,
5164 <             DoubleByDoubleToDouble reducer) {
5165 <            if (transformer == null || reducer == null)
5166 <                throw new NullPointerException();
5167 <            return new MapReduceKeysToDoubleTask<K,V>
5168 <                (map, null, -1, null, transformer, basis, reducer);
5169 <        }
5170 <
5171 <        /**
5172 <         * Returns a task that when invoked, returns the result of
5173 <         * accumulating the given transformation of all keys using the given
5174 <         * reducer to combine values, and the given basis as an
5175 <         * identity value.
5176 <         *
5177 <         * @param map the map
5178 <         * @param transformer a function returning the transformation
5179 <         * for an element
5180 <         * @param basis the identity (initial default value) for the reduction
5181 <         * @param reducer a commutative associative combining function
5182 <         * @return the task
5183 <         */
5184 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5185 <            (ConcurrentHashMapV8<K,V> map,
5186 <             ObjectToLong<? super K> transformer,
5187 <             long basis,
5188 <             LongByLongToLong reducer) {
5189 <            if (transformer == null || reducer == null)
5190 <                throw new NullPointerException();
5191 <            return new MapReduceKeysToLongTask<K,V>
5192 <                (map, null, -1, null, transformer, basis, reducer);
5193 <        }
5194 <
5195 <        /**
5196 <         * Returns a task that when invoked, returns the result of
5197 <         * accumulating the given transformation of all keys using the given
5198 <         * reducer to combine values, and the given basis as an
5199 <         * identity value.
5200 <         *
5201 <         * @param map the map
5202 <         * @param transformer a function returning the transformation
5203 <         * for an element
5204 <         * @param basis the identity (initial default value) for the reduction
5205 <         * @param reducer a commutative associative combining function
5206 <         * @return the task
5207 <         */
5208 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5209 <            (ConcurrentHashMapV8<K,V> map,
5210 <             ObjectToInt<? super K> transformer,
5211 <             int basis,
5212 <             IntByIntToInt reducer) {
5213 <            if (transformer == null || reducer == null)
5214 <                throw new NullPointerException();
5215 <            return new MapReduceKeysToIntTask<K,V>
5216 <                (map, null, -1, null, transformer, basis, reducer);
5217 <        }
5218 <
5219 <        /**
5220 <         * Returns a task that when invoked, performs the given action
5221 <         * for each value.
5222 <         *
5223 <         * @param map the map
5224 <         * @param action the action
5225 <         */
5226 <        public static <K,V> ForkJoinTask<Void> forEachValue
5227 <            (ConcurrentHashMapV8<K,V> map,
5228 <             Action<V> action) {
5229 <            if (action == null) throw new NullPointerException();
5230 <            return new ForEachValueTask<K,V>(map, null, -1, action);
5231 <        }
5232 <
5233 <        /**
5234 <         * Returns a task that when invoked, performs the given action
5235 <         * for each non-null transformation of each value.
5236 <         *
5237 <         * @param map the map
5238 <         * @param transformer a function returning the transformation
5239 <         * for an element, or null if there is no transformation (in
5240 <         * which case the action is not applied)
5241 <         * @param action the action
5242 <         */
5243 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
5244 <            (ConcurrentHashMapV8<K,V> map,
5245 <             Fun<? super V, ? extends U> transformer,
5246 <             Action<U> action) {
5247 <            if (transformer == null || action == null)
5248 <                throw new NullPointerException();
5249 <            return new ForEachTransformedValueTask<K,V,U>
5250 <                (map, null, -1, transformer, action);
5251 <        }
5252 <
5253 <        /**
5254 <         * Returns a task that when invoked, returns a non-null result
5255 <         * from applying the given search function on each value, or
5256 <         * null if none.  Upon success, further element processing is
5257 <         * suppressed and the results of any other parallel
5258 <         * invocations of the search function are ignored.
5259 <         *
5260 <         * @param map the map
5261 <         * @param searchFunction a function returning a non-null
5262 <         * result on success, else null
5263 <         * @return the task
5264 <         */
5265 <        public static <K,V,U> ForkJoinTask<U> searchValues
5266 <            (ConcurrentHashMapV8<K,V> map,
5267 <             Fun<? super V, ? extends U> searchFunction) {
5268 <            if (searchFunction == null) throw new NullPointerException();
5269 <            return new SearchValuesTask<K,V,U>
5270 <                (map, null, -1, searchFunction,
5271 <                 new AtomicReference<U>());
5272 <        }
5273 <
5274 <        /**
5275 <         * Returns a task that when invoked, returns the result of
5276 <         * accumulating all values using the given reducer to combine
5277 <         * values, or null if none.
5278 <         *
5279 <         * @param map the map
5280 <         * @param reducer a commutative associative combining function
5281 <         * @return the task
5282 <         */
5283 <        public static <K,V> ForkJoinTask<V> reduceValues
5284 <            (ConcurrentHashMapV8<K,V> map,
5285 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5286 <            if (reducer == null) throw new NullPointerException();
5287 <            return new ReduceValuesTask<K,V>
5288 <                (map, null, -1, null, reducer);
5289 <        }
5290 <
5291 <        /**
5292 <         * Returns a task that when invoked, returns the result of
5293 <         * accumulating the given transformation of all values using the
5294 <         * given reducer to combine values, or null if none.
5295 <         *
5296 <         * @param map the map
5297 <         * @param transformer a function returning the transformation
5298 <         * for an element, or null if there is no transformation (in
5299 <         * which case it is not combined)
5300 <         * @param reducer a commutative associative combining function
5301 <         * @return the task
5302 <         */
5303 <        public static <K,V,U> ForkJoinTask<U> reduceValues
5304 <            (ConcurrentHashMapV8<K,V> map,
5305 <             Fun<? super V, ? extends U> transformer,
5306 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5307 <            if (transformer == null || reducer == null)
5308 <                throw new NullPointerException();
5309 <            return new MapReduceValuesTask<K,V,U>
5310 <                (map, null, -1, null, transformer, reducer);
5311 <        }
5312 <
5313 <        /**
5314 <         * Returns a task that when invoked, returns the result of
5315 <         * accumulating the given transformation of all values using the
5316 <         * given reducer to combine values, and the given basis as an
5317 <         * identity value.
5318 <         *
5319 <         * @param map the map
5320 <         * @param transformer a function returning the transformation
5321 <         * for an element
5322 <         * @param basis the identity (initial default value) for the reduction
5323 <         * @param reducer a commutative associative combining function
5324 <         * @return the task
5325 <         */
5326 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5327 <            (ConcurrentHashMapV8<K,V> map,
5328 <             ObjectToDouble<? super V> transformer,
5329 <             double basis,
5330 <             DoubleByDoubleToDouble reducer) {
5331 <            if (transformer == null || reducer == null)
5332 <                throw new NullPointerException();
5333 <            return new MapReduceValuesToDoubleTask<K,V>
5334 <                (map, null, -1, null, transformer, basis, reducer);
5335 <        }
5336 <
5337 <        /**
5338 <         * Returns a task that when invoked, returns the result of
5339 <         * accumulating the given transformation of all values using the
5340 <         * given reducer to combine values, and the given basis as an
5341 <         * identity value.
5342 <         *
5343 <         * @param map the map
5344 <         * @param transformer a function returning the transformation
5345 <         * for an element
5346 <         * @param basis the identity (initial default value) for the reduction
5347 <         * @param reducer a commutative associative combining function
5348 <         * @return the task
5349 <         */
5350 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5351 <            (ConcurrentHashMapV8<K,V> map,
5352 <             ObjectToLong<? super V> transformer,
5353 <             long basis,
5354 <             LongByLongToLong reducer) {
5355 <            if (transformer == null || reducer == null)
5356 <                throw new NullPointerException();
5357 <            return new MapReduceValuesToLongTask<K,V>
5358 <                (map, null, -1, null, transformer, basis, reducer);
5359 <        }
5360 <
5361 <        /**
5362 <         * Returns a task that when invoked, returns the result of
5363 <         * accumulating the given transformation of all values using the
5364 <         * given reducer to combine values, and the given basis as an
5365 <         * identity value.
5366 <         *
5367 <         * @param map the map
5368 <         * @param transformer a function returning the transformation
5369 <         * for an element
5370 <         * @param basis the identity (initial default value) for the reduction
5371 <         * @param reducer a commutative associative combining function
5372 <         * @return the task
5373 <         */
5374 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5375 <            (ConcurrentHashMapV8<K,V> map,
5376 <             ObjectToInt<? super V> transformer,
5377 <             int basis,
5378 <             IntByIntToInt reducer) {
5379 <            if (transformer == null || reducer == null)
5380 <                throw new NullPointerException();
5381 <            return new MapReduceValuesToIntTask<K,V>
5382 <                (map, null, -1, null, transformer, basis, reducer);
5383 <        }
5384 <
5385 <        /**
5386 <         * Returns a task that when invoked, perform the given action
5387 <         * for each entry.
5388 <         *
5389 <         * @param map the map
5390 <         * @param action the action
5391 <         */
5392 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5393 <            (ConcurrentHashMapV8<K,V> map,
5394 <             Action<Map.Entry<K,V>> action) {
5395 <            if (action == null) throw new NullPointerException();
5396 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5397 <        }
5398 <
5399 <        /**
5400 <         * Returns a task that when invoked, perform the given action
5401 <         * for each non-null transformation of each entry.
5402 <         *
5403 <         * @param map the map
5404 <         * @param transformer a function returning the transformation
5405 <         * for an element, or null if there is no transformation (in
5406 <         * which case the action is not applied)
5407 <         * @param action the action
5408 <         */
5409 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5410 <            (ConcurrentHashMapV8<K,V> map,
5411 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5412 <             Action<U> action) {
5413 <            if (transformer == null || action == null)
5414 <                throw new NullPointerException();
5415 <            return new ForEachTransformedEntryTask<K,V,U>
5416 <                (map, null, -1, transformer, action);
5417 <        }
5418 <
5419 <        /**
5420 <         * Returns a task that when invoked, returns a non-null result
5421 <         * from applying the given search function on each entry, or
5422 <         * null if none.  Upon success, further element processing is
5423 <         * suppressed and the results of any other parallel
5424 <         * invocations of the search function are ignored.
5425 <         *
5426 <         * @param map the map
5427 <         * @param searchFunction a function returning a non-null
5428 <         * result on success, else null
5429 <         * @return the task
5430 <         */
5431 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5432 <            (ConcurrentHashMapV8<K,V> map,
5433 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5434 <            if (searchFunction == null) throw new NullPointerException();
5435 <            return new SearchEntriesTask<K,V,U>
5436 <                (map, null, -1, searchFunction,
5437 <                 new AtomicReference<U>());
5438 <        }
5439 <
5440 <        /**
5441 <         * Returns a task that when invoked, returns the result of
5442 <         * accumulating all entries using the given reducer to combine
5443 <         * values, or null if none.
5444 <         *
5445 <         * @param map the map
5446 <         * @param reducer a commutative associative combining function
5447 <         * @return the task
5448 <         */
5449 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5450 <            (ConcurrentHashMapV8<K,V> map,
5451 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5452 <            if (reducer == null) throw new NullPointerException();
5453 <            return new ReduceEntriesTask<K,V>
5454 <                (map, null, -1, null, reducer);
4533 >            Node<K,V>[] t;
4534 >            if ((t = map.table) != null) {
4535 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4536 >                for (Node<K,V> p; (p = it.advance()) != null; )
4537 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4538 >            }
4539          }
4540  
4541 <        /**
5458 <         * Returns a task that when invoked, returns the result of
5459 <         * accumulating the given transformation of all entries using the
5460 <         * given reducer to combine values, or null if none.
5461 <         *
5462 <         * @param map the map
5463 <         * @param transformer a function returning the transformation
5464 <         * for an element, or null if there is no transformation (in
5465 <         * which case it is not combined)
5466 <         * @param reducer a commutative associative combining function
5467 <         * @return the task
5468 <         */
5469 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5470 <            (ConcurrentHashMapV8<K,V> map,
5471 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5472 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5473 <            if (transformer == null || reducer == null)
5474 <                throw new NullPointerException();
5475 <            return new MapReduceEntriesTask<K,V,U>
5476 <                (map, null, -1, null, transformer, reducer);
5477 <        }
4541 >    }
4542  
4543 <        /**
5480 <         * Returns a task that when invoked, returns the result of
5481 <         * accumulating the given transformation of all entries using the
5482 <         * given reducer to combine values, and the given basis as an
5483 <         * identity value.
5484 <         *
5485 <         * @param map the map
5486 <         * @param transformer a function returning the transformation
5487 <         * for an element
5488 <         * @param basis the identity (initial default value) for the reduction
5489 <         * @param reducer a commutative associative combining function
5490 <         * @return the task
5491 <         */
5492 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5493 <            (ConcurrentHashMapV8<K,V> map,
5494 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5495 <             double basis,
5496 <             DoubleByDoubleToDouble reducer) {
5497 <            if (transformer == null || reducer == null)
5498 <                throw new NullPointerException();
5499 <            return new MapReduceEntriesToDoubleTask<K,V>
5500 <                (map, null, -1, null, transformer, basis, reducer);
5501 <        }
4543 >    // -------------------------------------------------------
4544  
4545 <        /**
4546 <         * Returns a task that when invoked, returns the result of
4547 <         * accumulating the given transformation of all entries using the
4548 <         * given reducer to combine values, and the given basis as an
4549 <         * identity value.
4550 <         *
4551 <         * @param map the map
4552 <         * @param transformer a function returning the transformation
4553 <         * for an element
4554 <         * @param basis the identity (initial default value) for the reduction
4555 <         * @param reducer a commutative associative combining function
4556 <         * @return the task
4557 <         */
4558 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4559 <            (ConcurrentHashMapV8<K,V> map,
4560 <             ObjectToLong<Map.Entry<K,V>> transformer,
4561 <             long basis,
4562 <             LongByLongToLong reducer) {
4563 <            if (transformer == null || reducer == null)
4564 <                throw new NullPointerException();
4565 <            return new MapReduceEntriesToLongTask<K,V>
4566 <                (map, null, -1, null, transformer, basis, reducer);
4545 >    /**
4546 >     * Base class for bulk tasks. Repeats some fields and code from
4547 >     * class Traverser, because we need to subclass CountedCompleter.
4548 >     */
4549 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4550 >        Node<K,V>[] tab;        // same as Traverser
4551 >        Node<K,V> next;
4552 >        int index;
4553 >        int baseIndex;
4554 >        int baseLimit;
4555 >        final int baseSize;
4556 >        int batch;              // split control
4557 >
4558 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4559 >            super(par);
4560 >            this.batch = b;
4561 >            this.index = this.baseIndex = i;
4562 >            if ((this.tab = t) == null)
4563 >                this.baseSize = this.baseLimit = 0;
4564 >            else if (par == null)
4565 >                this.baseSize = this.baseLimit = t.length;
4566 >            else {
4567 >                this.baseLimit = f;
4568 >                this.baseSize = par.baseSize;
4569 >            }
4570          }
4571  
4572          /**
4573 <         * Returns a task that when invoked, returns the result of
5529 <         * accumulating the given transformation of all entries using the
5530 <         * given reducer to combine values, and the given basis as an
5531 <         * identity value.
5532 <         *
5533 <         * @param map the map
5534 <         * @param transformer a function returning the transformation
5535 <         * for an element
5536 <         * @param basis the identity (initial default value) for the reduction
5537 <         * @param reducer a commutative associative combining function
5538 <         * @return the task
4573 >         * Same as Traverser version
4574           */
4575 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4576 <            (ConcurrentHashMapV8<K,V> map,
4577 <             ObjectToInt<Map.Entry<K,V>> transformer,
4578 <             int basis,
4579 <             IntByIntToInt reducer) {
4580 <            if (transformer == null || reducer == null)
4581 <                throw new NullPointerException();
4582 <            return new MapReduceEntriesToIntTask<K,V>
4583 <                (map, null, -1, null, transformer, basis, reducer);
4575 >        final Node<K,V> advance() {
4576 >            Node<K,V> e;
4577 >            if ((e = next) != null)
4578 >                e = e.next;
4579 >            for (;;) {
4580 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4581 >                if (e != null)
4582 >                    return next = e;
4583 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4584 >                    (n = t.length) <= (i = index) || i < 0)
4585 >                    return next = null;
4586 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4587 >                    if (e instanceof ForwardingNode) {
4588 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4589 >                        e = null;
4590 >                        continue;
4591 >                    }
4592 >                    else if (e instanceof TreeBin)
4593 >                        e = ((TreeBin<K,V>)e).first;
4594 >                    else
4595 >                        e = null;
4596 >                }
4597 >                if ((index += baseSize) >= n)
4598 >                    index = ++baseIndex;    // visit upper slots if present
4599 >            }
4600          }
4601      }
4602  
5552    // -------------------------------------------------------
5553
4603      /*
4604       * Task classes. Coded in a regular but ugly format/style to
4605       * simplify checks that each variant differs in the right way from
# Line 5558 | Line 4607 | public class ConcurrentHashMapV8<K, V>
4607       * that we've already null-checked task arguments, so we force
4608       * simplest hoisted bypass to help avoid convoluted traps.
4609       */
4610 <
4611 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4612 <        extends Traverser<K,V,Void> {
4613 <        final Action<K> action;
4610 >    @SuppressWarnings("serial")
4611 >    static final class ForEachKeyTask<K,V>
4612 >        extends BulkTask<K,V,Void> {
4613 >        final Action<? super K> action;
4614          ForEachKeyTask
4615 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4616 <             Action<K> action) {
4617 <            super(m, p, b);
4615 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4616 >             Action<? super K> action) {
4617 >            super(p, b, i, f, t);
4618              this.action = action;
4619          }
4620 <        @SuppressWarnings("unchecked") public final void compute() {
4621 <            final Action<K> action;
4620 >        public final void compute() {
4621 >            final Action<? super K> action;
4622              if ((action = this.action) != null) {
4623 <                for (int b; (b = preSplit()) > 0;)
4624 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4625 <                while (advance() != null)
4626 <                    action.apply((K)nextKey);
4623 >                for (int i = baseIndex, f, h; batch > 0 &&
4624 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4625 >                    addToPendingCount(1);
4626 >                    new ForEachKeyTask<K,V>
4627 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4628 >                         action).fork();
4629 >                }
4630 >                for (Node<K,V> p; (p = advance()) != null;)
4631 >                    action.apply(p.key);
4632                  propagateCompletion();
4633              }
4634          }
4635      }
4636  
4637 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4638 <        extends Traverser<K,V,Void> {
4639 <        final Action<V> action;
4637 >    @SuppressWarnings("serial")
4638 >    static final class ForEachValueTask<K,V>
4639 >        extends BulkTask<K,V,Void> {
4640 >        final Action<? super V> action;
4641          ForEachValueTask
4642 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4643 <             Action<V> action) {
4644 <            super(m, p, b);
4642 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4643 >             Action<? super V> action) {
4644 >            super(p, b, i, f, t);
4645              this.action = action;
4646          }
4647 <        @SuppressWarnings("unchecked") public final void compute() {
4648 <            final Action<V> action;
4647 >        public final void compute() {
4648 >            final Action<? super V> action;
4649              if ((action = this.action) != null) {
4650 <                for (int b; (b = preSplit()) > 0;)
4651 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4652 <                V v;
4653 <                while ((v = advance()) != null)
4654 <                    action.apply(v);
4650 >                for (int i = baseIndex, f, h; batch > 0 &&
4651 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4652 >                    addToPendingCount(1);
4653 >                    new ForEachValueTask<K,V>
4654 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4655 >                         action).fork();
4656 >                }
4657 >                for (Node<K,V> p; (p = advance()) != null;)
4658 >                    action.apply(p.val);
4659                  propagateCompletion();
4660              }
4661          }
4662      }
4663  
4664 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4665 <        extends Traverser<K,V,Void> {
4666 <        final Action<Entry<K,V>> action;
4664 >    @SuppressWarnings("serial")
4665 >    static final class ForEachEntryTask<K,V>
4666 >        extends BulkTask<K,V,Void> {
4667 >        final Action<? super Entry<K,V>> action;
4668          ForEachEntryTask
4669 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4670 <             Action<Entry<K,V>> action) {
4671 <            super(m, p, b);
4669 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4670 >             Action<? super Entry<K,V>> action) {
4671 >            super(p, b, i, f, t);
4672              this.action = action;
4673          }
4674 <        @SuppressWarnings("unchecked") public final void compute() {
4675 <            final Action<Entry<K,V>> action;
4674 >        public final void compute() {
4675 >            final Action<? super Entry<K,V>> action;
4676              if ((action = this.action) != null) {
4677 <                for (int b; (b = preSplit()) > 0;)
4678 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4679 <                V v;
4680 <                while ((v = advance()) != null)
4681 <                    action.apply(entryFor((K)nextKey, v));
4677 >                for (int i = baseIndex, f, h; batch > 0 &&
4678 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4679 >                    addToPendingCount(1);
4680 >                    new ForEachEntryTask<K,V>
4681 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4682 >                         action).fork();
4683 >                }
4684 >                for (Node<K,V> p; (p = advance()) != null; )
4685 >                    action.apply(p);
4686                  propagateCompletion();
4687              }
4688          }
4689      }
4690  
4691 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4692 <        extends Traverser<K,V,Void> {
4693 <        final BiAction<K,V> action;
4691 >    @SuppressWarnings("serial")
4692 >    static final class ForEachMappingTask<K,V>
4693 >        extends BulkTask<K,V,Void> {
4694 >        final BiAction<? super K, ? super V> action;
4695          ForEachMappingTask
4696 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4697 <             BiAction<K,V> action) {
4698 <            super(m, p, b);
4696 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4697 >             BiAction<? super K,? super V> action) {
4698 >            super(p, b, i, f, t);
4699              this.action = action;
4700          }
4701 <        @SuppressWarnings("unchecked") public final void compute() {
4702 <            final BiAction<K,V> action;
4701 >        public final void compute() {
4702 >            final BiAction<? super K, ? super V> action;
4703              if ((action = this.action) != null) {
4704 <                for (int b; (b = preSplit()) > 0;)
4705 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4706 <                V v;
4707 <                while ((v = advance()) != null)
4708 <                    action.apply((K)nextKey, v);
4704 >                for (int i = baseIndex, f, h; batch > 0 &&
4705 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4706 >                    addToPendingCount(1);
4707 >                    new ForEachMappingTask<K,V>
4708 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4709 >                         action).fork();
4710 >                }
4711 >                for (Node<K,V> p; (p = advance()) != null; )
4712 >                    action.apply(p.key, p.val);
4713                  propagateCompletion();
4714              }
4715          }
4716      }
4717  
4718 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4719 <        extends Traverser<K,V,Void> {
4718 >    @SuppressWarnings("serial")
4719 >    static final class ForEachTransformedKeyTask<K,V,U>
4720 >        extends BulkTask<K,V,Void> {
4721          final Fun<? super K, ? extends U> transformer;
4722 <        final Action<U> action;
4722 >        final Action<? super U> action;
4723          ForEachTransformedKeyTask
4724 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4725 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
4726 <            super(m, p, b);
4724 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4725 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4726 >            super(p, b, i, f, t);
4727              this.transformer = transformer; this.action = action;
4728          }
4729 <        @SuppressWarnings("unchecked") public final void compute() {
4729 >        public final void compute() {
4730              final Fun<? super K, ? extends U> transformer;
4731 <            final Action<U> action;
4731 >            final Action<? super U> action;
4732              if ((transformer = this.transformer) != null &&
4733                  (action = this.action) != null) {
4734 <                for (int b; (b = preSplit()) > 0;)
4734 >                for (int i = baseIndex, f, h; batch > 0 &&
4735 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4736 >                    addToPendingCount(1);
4737                      new ForEachTransformedKeyTask<K,V,U>
4738 <                        (map, this, b, transformer, action).fork();
4739 <                U u;
4740 <                while (advance() != null) {
4741 <                    if ((u = transformer.apply((K)nextKey)) != null)
4738 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4739 >                         transformer, action).fork();
4740 >                }
4741 >                for (Node<K,V> p; (p = advance()) != null; ) {
4742 >                    U u;
4743 >                    if ((u = transformer.apply(p.key)) != null)
4744                          action.apply(u);
4745                  }
4746                  propagateCompletion();
# Line 5674 | Line 4748 | public class ConcurrentHashMapV8<K, V>
4748          }
4749      }
4750  
4751 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4752 <        extends Traverser<K,V,Void> {
4751 >    @SuppressWarnings("serial")
4752 >    static final class ForEachTransformedValueTask<K,V,U>
4753 >        extends BulkTask<K,V,Void> {
4754          final Fun<? super V, ? extends U> transformer;
4755 <        final Action<U> action;
4755 >        final Action<? super U> action;
4756          ForEachTransformedValueTask
4757 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4758 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
4759 <            super(m, p, b);
4757 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4758 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4759 >            super(p, b, i, f, t);
4760              this.transformer = transformer; this.action = action;
4761          }
4762 <        @SuppressWarnings("unchecked") public final void compute() {
4762 >        public final void compute() {
4763              final Fun<? super V, ? extends U> transformer;
4764 <            final Action<U> action;
4764 >            final Action<? super U> action;
4765              if ((transformer = this.transformer) != null &&
4766                  (action = this.action) != null) {
4767 <                for (int b; (b = preSplit()) > 0;)
4767 >                for (int i = baseIndex, f, h; batch > 0 &&
4768 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4769 >                    addToPendingCount(1);
4770                      new ForEachTransformedValueTask<K,V,U>
4771 <                        (map, this, b, transformer, action).fork();
4772 <                V v; U u;
4773 <                while ((v = advance()) != null) {
4774 <                    if ((u = transformer.apply(v)) != null)
4771 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4772 >                         transformer, action).fork();
4773 >                }
4774 >                for (Node<K,V> p; (p = advance()) != null; ) {
4775 >                    U u;
4776 >                    if ((u = transformer.apply(p.val)) != null)
4777                          action.apply(u);
4778                  }
4779                  propagateCompletion();
# Line 5702 | Line 4781 | public class ConcurrentHashMapV8<K, V>
4781          }
4782      }
4783  
4784 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4785 <        extends Traverser<K,V,Void> {
4784 >    @SuppressWarnings("serial")
4785 >    static final class ForEachTransformedEntryTask<K,V,U>
4786 >        extends BulkTask<K,V,Void> {
4787          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4788 <        final Action<U> action;
4788 >        final Action<? super U> action;
4789          ForEachTransformedEntryTask
4790 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4791 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
4792 <            super(m, p, b);
4790 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4791 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4792 >            super(p, b, i, f, t);
4793              this.transformer = transformer; this.action = action;
4794          }
4795 <        @SuppressWarnings("unchecked") public final void compute() {
4795 >        public final void compute() {
4796              final Fun<Map.Entry<K,V>, ? extends U> transformer;
4797 <            final Action<U> action;
4797 >            final Action<? super U> action;
4798              if ((transformer = this.transformer) != null &&
4799                  (action = this.action) != null) {
4800 <                for (int b; (b = preSplit()) > 0;)
4800 >                for (int i = baseIndex, f, h; batch > 0 &&
4801 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4802 >                    addToPendingCount(1);
4803                      new ForEachTransformedEntryTask<K,V,U>
4804 <                        (map, this, b, transformer, action).fork();
4805 <                V v; U u;
4806 <                while ((v = advance()) != null) {
4807 <                    if ((u = transformer.apply(entryFor((K)nextKey,
4808 <                                                        v))) != null)
4804 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4805 >                         transformer, action).fork();
4806 >                }
4807 >                for (Node<K,V> p; (p = advance()) != null; ) {
4808 >                    U u;
4809 >                    if ((u = transformer.apply(p)) != null)
4810                          action.apply(u);
4811                  }
4812                  propagateCompletion();
# Line 5731 | Line 4814 | public class ConcurrentHashMapV8<K, V>
4814          }
4815      }
4816  
4817 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4818 <        extends Traverser<K,V,Void> {
4817 >    @SuppressWarnings("serial")
4818 >    static final class ForEachTransformedMappingTask<K,V,U>
4819 >        extends BulkTask<K,V,Void> {
4820          final BiFun<? super K, ? super V, ? extends U> transformer;
4821 <        final Action<U> action;
4821 >        final Action<? super U> action;
4822          ForEachTransformedMappingTask
4823 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4823 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4824               BiFun<? super K, ? super V, ? extends U> transformer,
4825 <             Action<U> action) {
4826 <            super(m, p, b);
4825 >             Action<? super U> action) {
4826 >            super(p, b, i, f, t);
4827              this.transformer = transformer; this.action = action;
4828          }
4829 <        @SuppressWarnings("unchecked") public final void compute() {
4829 >        public final void compute() {
4830              final BiFun<? super K, ? super V, ? extends U> transformer;
4831 <            final Action<U> action;
4831 >            final Action<? super U> action;
4832              if ((transformer = this.transformer) != null &&
4833                  (action = this.action) != null) {
4834 <                for (int b; (b = preSplit()) > 0;)
4834 >                for (int i = baseIndex, f, h; batch > 0 &&
4835 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4836 >                    addToPendingCount(1);
4837                      new ForEachTransformedMappingTask<K,V,U>
4838 <                        (map, this, b, transformer, action).fork();
4839 <                V v; U u;
4840 <                while ((v = advance()) != null) {
4841 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
4838 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4839 >                         transformer, action).fork();
4840 >                }
4841 >                for (Node<K,V> p; (p = advance()) != null; ) {
4842 >                    U u;
4843 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4844                          action.apply(u);
4845                  }
4846                  propagateCompletion();
# Line 5760 | Line 4848 | public class ConcurrentHashMapV8<K, V>
4848          }
4849      }
4850  
4851 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4852 <        extends Traverser<K,V,U> {
4851 >    @SuppressWarnings("serial")
4852 >    static final class SearchKeysTask<K,V,U>
4853 >        extends BulkTask<K,V,U> {
4854          final Fun<? super K, ? extends U> searchFunction;
4855          final AtomicReference<U> result;
4856          SearchKeysTask
4857 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4857 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4858               Fun<? super K, ? extends U> searchFunction,
4859               AtomicReference<U> result) {
4860 <            super(m, p, b);
4860 >            super(p, b, i, f, t);
4861              this.searchFunction = searchFunction; this.result = result;
4862          }
4863          public final U getRawResult() { return result.get(); }
4864 <        @SuppressWarnings("unchecked") public final void compute() {
4864 >        public final void compute() {
4865              final Fun<? super K, ? extends U> searchFunction;
4866              final AtomicReference<U> result;
4867              if ((searchFunction = this.searchFunction) != null &&
4868                  (result = this.result) != null) {
4869 <                for (int b;;) {
4869 >                for (int i = baseIndex, f, h; batch > 0 &&
4870 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4871                      if (result.get() != null)
4872                          return;
4873 <                    if ((b = preSplit()) <= 0)
5784 <                        break;
4873 >                    addToPendingCount(1);
4874                      new SearchKeysTask<K,V,U>
4875 <                        (map, this, b, searchFunction, result).fork();
4875 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4876 >                         searchFunction, result).fork();
4877                  }
4878                  while (result.get() == null) {
4879                      U u;
4880 <                    if (advance() == null) {
4880 >                    Node<K,V> p;
4881 >                    if ((p = advance()) == null) {
4882                          propagateCompletion();
4883                          break;
4884                      }
4885 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4885 >                    if ((u = searchFunction.apply(p.key)) != null) {
4886                          if (result.compareAndSet(null, u))
4887                              quietlyCompleteRoot();
4888                          break;
# Line 5801 | Line 4892 | public class ConcurrentHashMapV8<K, V>
4892          }
4893      }
4894  
4895 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4896 <        extends Traverser<K,V,U> {
4895 >    @SuppressWarnings("serial")
4896 >    static final class SearchValuesTask<K,V,U>
4897 >        extends BulkTask<K,V,U> {
4898          final Fun<? super V, ? extends U> searchFunction;
4899          final AtomicReference<U> result;
4900          SearchValuesTask
4901 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4901 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4902               Fun<? super V, ? extends U> searchFunction,
4903               AtomicReference<U> result) {
4904 <            super(m, p, b);
4904 >            super(p, b, i, f, t);
4905              this.searchFunction = searchFunction; this.result = result;
4906          }
4907          public final U getRawResult() { return result.get(); }
4908 <        @SuppressWarnings("unchecked") public final void compute() {
4908 >        public final void compute() {
4909              final Fun<? super V, ? extends U> searchFunction;
4910              final AtomicReference<U> result;
4911              if ((searchFunction = this.searchFunction) != null &&
4912                  (result = this.result) != null) {
4913 <                for (int b;;) {
4913 >                for (int i = baseIndex, f, h; batch > 0 &&
4914 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4915                      if (result.get() != null)
4916                          return;
4917 <                    if ((b = preSplit()) <= 0)
5825 <                        break;
4917 >                    addToPendingCount(1);
4918                      new SearchValuesTask<K,V,U>
4919 <                        (map, this, b, searchFunction, result).fork();
4919 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4920 >                         searchFunction, result).fork();
4921                  }
4922                  while (result.get() == null) {
4923 <                    V v; U u;
4924 <                    if ((v = advance()) == null) {
4923 >                    U u;
4924 >                    Node<K,V> p;
4925 >                    if ((p = advance()) == null) {
4926                          propagateCompletion();
4927                          break;
4928                      }
4929 <                    if ((u = searchFunction.apply(v)) != null) {
4929 >                    if ((u = searchFunction.apply(p.val)) != null) {
4930                          if (result.compareAndSet(null, u))
4931                              quietlyCompleteRoot();
4932                          break;
# Line 5842 | Line 4936 | public class ConcurrentHashMapV8<K, V>
4936          }
4937      }
4938  
4939 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4940 <        extends Traverser<K,V,U> {
4939 >    @SuppressWarnings("serial")
4940 >    static final class SearchEntriesTask<K,V,U>
4941 >        extends BulkTask<K,V,U> {
4942          final Fun<Entry<K,V>, ? extends U> searchFunction;
4943          final AtomicReference<U> result;
4944          SearchEntriesTask
4945 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4945 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4946               Fun<Entry<K,V>, ? extends U> searchFunction,
4947               AtomicReference<U> result) {
4948 <            super(m, p, b);
4948 >            super(p, b, i, f, t);
4949              this.searchFunction = searchFunction; this.result = result;
4950          }
4951          public final U getRawResult() { return result.get(); }
4952 <        @SuppressWarnings("unchecked") public final void compute() {
4952 >        public final void compute() {
4953              final Fun<Entry<K,V>, ? extends U> searchFunction;
4954              final AtomicReference<U> result;
4955              if ((searchFunction = this.searchFunction) != null &&
4956                  (result = this.result) != null) {
4957 <                for (int b;;) {
4957 >                for (int i = baseIndex, f, h; batch > 0 &&
4958 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4959                      if (result.get() != null)
4960                          return;
4961 <                    if ((b = preSplit()) <= 0)
5866 <                        break;
4961 >                    addToPendingCount(1);
4962                      new SearchEntriesTask<K,V,U>
4963 <                        (map, this, b, searchFunction, result).fork();
4963 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4964 >                         searchFunction, result).fork();
4965                  }
4966                  while (result.get() == null) {
4967 <                    V v; U u;
4968 <                    if ((v = advance()) == null) {
4967 >                    U u;
4968 >                    Node<K,V> p;
4969 >                    if ((p = advance()) == null) {
4970                          propagateCompletion();
4971                          break;
4972                      }
4973 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5877 <                                                           v))) != null) {
4973 >                    if ((u = searchFunction.apply(p)) != null) {
4974                          if (result.compareAndSet(null, u))
4975                              quietlyCompleteRoot();
4976                          return;
# Line 5884 | Line 4980 | public class ConcurrentHashMapV8<K, V>
4980          }
4981      }
4982  
4983 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
4984 <        extends Traverser<K,V,U> {
4983 >    @SuppressWarnings("serial")
4984 >    static final class SearchMappingsTask<K,V,U>
4985 >        extends BulkTask<K,V,U> {
4986          final BiFun<? super K, ? super V, ? extends U> searchFunction;
4987          final AtomicReference<U> result;
4988          SearchMappingsTask
4989 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4989 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4990               BiFun<? super K, ? super V, ? extends U> searchFunction,
4991               AtomicReference<U> result) {
4992 <            super(m, p, b);
4992 >            super(p, b, i, f, t);
4993              this.searchFunction = searchFunction; this.result = result;
4994          }
4995          public final U getRawResult() { return result.get(); }
4996 <        @SuppressWarnings("unchecked") public final void compute() {
4996 >        public final void compute() {
4997              final BiFun<? super K, ? super V, ? extends U> searchFunction;
4998              final AtomicReference<U> result;
4999              if ((searchFunction = this.searchFunction) != null &&
5000                  (result = this.result) != null) {
5001 <                for (int b;;) {
5001 >                for (int i = baseIndex, f, h; batch > 0 &&
5002 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5003                      if (result.get() != null)
5004                          return;
5005 <                    if ((b = preSplit()) <= 0)
5908 <                        break;
5005 >                    addToPendingCount(1);
5006                      new SearchMappingsTask<K,V,U>
5007 <                        (map, this, b, searchFunction, result).fork();
5007 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5008 >                         searchFunction, result).fork();
5009                  }
5010                  while (result.get() == null) {
5011 <                    V v; U u;
5012 <                    if ((v = advance()) == null) {
5011 >                    U u;
5012 >                    Node<K,V> p;
5013 >                    if ((p = advance()) == null) {
5014                          propagateCompletion();
5015                          break;
5016                      }
5017 <                    if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5017 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5018                          if (result.compareAndSet(null, u))
5019                              quietlyCompleteRoot();
5020                          break;
# Line 5925 | Line 5024 | public class ConcurrentHashMapV8<K, V>
5024          }
5025      }
5026  
5027 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5028 <        extends Traverser<K,V,K> {
5027 >    @SuppressWarnings("serial")
5028 >    static final class ReduceKeysTask<K,V>
5029 >        extends BulkTask<K,V,K> {
5030          final BiFun<? super K, ? super K, ? extends K> reducer;
5031          K result;
5032          ReduceKeysTask<K,V> rights, nextRight;
5033          ReduceKeysTask
5034 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5034 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5035               ReduceKeysTask<K,V> nextRight,
5036               BiFun<? super K, ? super K, ? extends K> reducer) {
5037 <            super(m, p, b); this.nextRight = nextRight;
5037 >            super(p, b, i, f, t); this.nextRight = nextRight;
5038              this.reducer = reducer;
5039          }
5040          public final K getRawResult() { return result; }
5041 <        @SuppressWarnings("unchecked") public final void compute() {
5041 >        public final void compute() {
5042              final BiFun<? super K, ? super K, ? extends K> reducer;
5043              if ((reducer = this.reducer) != null) {
5044 <                for (int b; (b = preSplit()) > 0;)
5044 >                for (int i = baseIndex, f, h; batch > 0 &&
5045 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5046 >                    addToPendingCount(1);
5047                      (rights = new ReduceKeysTask<K,V>
5048 <                     (map, this, b, rights, reducer)).fork();
5048 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5049 >                      rights, reducer)).fork();
5050 >                }
5051                  K r = null;
5052 <                while (advance() != null) {
5053 <                    K u = (K)nextKey;
5054 <                    r = (r == null) ? u : reducer.apply(r, u);
5052 >                for (Node<K,V> p; (p = advance()) != null; ) {
5053 >                    K u = p.key;
5054 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5055                  }
5056                  result = r;
5057                  CountedCompleter<?> c;
5058                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5059 <                    ReduceKeysTask<K,V>
5059 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5060                          t = (ReduceKeysTask<K,V>)c,
5061                          s = t.rights;
5062                      while (s != null) {
# Line 5967 | Line 5071 | public class ConcurrentHashMapV8<K, V>
5071          }
5072      }
5073  
5074 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5075 <        extends Traverser<K,V,V> {
5074 >    @SuppressWarnings("serial")
5075 >    static final class ReduceValuesTask<K,V>
5076 >        extends BulkTask<K,V,V> {
5077          final BiFun<? super V, ? super V, ? extends V> reducer;
5078          V result;
5079          ReduceValuesTask<K,V> rights, nextRight;
5080          ReduceValuesTask
5081 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5081 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5082               ReduceValuesTask<K,V> nextRight,
5083               BiFun<? super V, ? super V, ? extends V> reducer) {
5084 <            super(m, p, b); this.nextRight = nextRight;
5084 >            super(p, b, i, f, t); this.nextRight = nextRight;
5085              this.reducer = reducer;
5086          }
5087          public final V getRawResult() { return result; }
5088 <        @SuppressWarnings("unchecked") public final void compute() {
5088 >        public final void compute() {
5089              final BiFun<? super V, ? super V, ? extends V> reducer;
5090              if ((reducer = this.reducer) != null) {
5091 <                for (int b; (b = preSplit()) > 0;)
5091 >                for (int i = baseIndex, f, h; batch > 0 &&
5092 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5093 >                    addToPendingCount(1);
5094                      (rights = new ReduceValuesTask<K,V>
5095 <                     (map, this, b, rights, reducer)).fork();
5095 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5096 >                      rights, reducer)).fork();
5097 >                }
5098                  V r = null;
5099 <                V v;
5100 <                while ((v = advance()) != null) {
5101 <                    V u = v;
5993 <                    r = (r == null) ? u : reducer.apply(r, u);
5099 >                for (Node<K,V> p; (p = advance()) != null; ) {
5100 >                    V v = p.val;
5101 >                    r = (r == null) ? v : reducer.apply(r, v);
5102                  }
5103                  result = r;
5104                  CountedCompleter<?> c;
5105                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5106 <                    ReduceValuesTask<K,V>
5106 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5107                          t = (ReduceValuesTask<K,V>)c,
5108                          s = t.rights;
5109                      while (s != null) {
# Line 6010 | Line 5118 | public class ConcurrentHashMapV8<K, V>
5118          }
5119      }
5120  
5121 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5122 <        extends Traverser<K,V,Map.Entry<K,V>> {
5121 >    @SuppressWarnings("serial")
5122 >    static final class ReduceEntriesTask<K,V>
5123 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5124          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5125          Map.Entry<K,V> result;
5126          ReduceEntriesTask<K,V> rights, nextRight;
5127          ReduceEntriesTask
5128 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5128 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5129               ReduceEntriesTask<K,V> nextRight,
5130               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5131 <            super(m, p, b); this.nextRight = nextRight;
5131 >            super(p, b, i, f, t); this.nextRight = nextRight;
5132              this.reducer = reducer;
5133          }
5134          public final Map.Entry<K,V> getRawResult() { return result; }
5135 <        @SuppressWarnings("unchecked") public final void compute() {
5135 >        public final void compute() {
5136              final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5137              if ((reducer = this.reducer) != null) {
5138 <                for (int b; (b = preSplit()) > 0;)
5138 >                for (int i = baseIndex, f, h; batch > 0 &&
5139 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5140 >                    addToPendingCount(1);
5141                      (rights = new ReduceEntriesTask<K,V>
5142 <                     (map, this, b, rights, reducer)).fork();
5143 <                Map.Entry<K,V> r = null;
6033 <                V v;
6034 <                while ((v = advance()) != null) {
6035 <                    Map.Entry<K,V> u = entryFor((K)nextKey, v);
6036 <                    r = (r == null) ? u : reducer.apply(r, u);
5142 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5143 >                      rights, reducer)).fork();
5144                  }
5145 +                Map.Entry<K,V> r = null;
5146 +                for (Node<K,V> p; (p = advance()) != null; )
5147 +                    r = (r == null) ? p : reducer.apply(r, p);
5148                  result = r;
5149                  CountedCompleter<?> c;
5150                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5151 <                    ReduceEntriesTask<K,V>
5151 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5152                          t = (ReduceEntriesTask<K,V>)c,
5153                          s = t.rights;
5154                      while (s != null) {
# Line 6053 | Line 5163 | public class ConcurrentHashMapV8<K, V>
5163          }
5164      }
5165  
5166 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5167 <        extends Traverser<K,V,U> {
5166 >    @SuppressWarnings("serial")
5167 >    static final class MapReduceKeysTask<K,V,U>
5168 >        extends BulkTask<K,V,U> {
5169          final Fun<? super K, ? extends U> transformer;
5170          final BiFun<? super U, ? super U, ? extends U> reducer;
5171          U result;
5172          MapReduceKeysTask<K,V,U> rights, nextRight;
5173          MapReduceKeysTask
5174 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5174 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5175               MapReduceKeysTask<K,V,U> nextRight,
5176               Fun<? super K, ? extends U> transformer,
5177               BiFun<? super U, ? super U, ? extends U> reducer) {
5178 <            super(m, p, b); this.nextRight = nextRight;
5178 >            super(p, b, i, f, t); this.nextRight = nextRight;
5179              this.transformer = transformer;
5180              this.reducer = reducer;
5181          }
5182          public final U getRawResult() { return result; }
5183 <        @SuppressWarnings("unchecked") public final void compute() {
5183 >        public final void compute() {
5184              final Fun<? super K, ? extends U> transformer;
5185              final BiFun<? super U, ? super U, ? extends U> reducer;
5186              if ((transformer = this.transformer) != null &&
5187                  (reducer = this.reducer) != null) {
5188 <                for (int b; (b = preSplit()) > 0;)
5188 >                for (int i = baseIndex, f, h; batch > 0 &&
5189 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5190 >                    addToPendingCount(1);
5191                      (rights = new MapReduceKeysTask<K,V,U>
5192 <                     (map, this, b, rights, transformer, reducer)).fork();
5193 <                U r = null, u;
5194 <                while (advance() != null) {
5195 <                    if ((u = transformer.apply((K)nextKey)) != null)
5192 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5193 >                      rights, transformer, reducer)).fork();
5194 >                }
5195 >                U r = null;
5196 >                for (Node<K,V> p; (p = advance()) != null; ) {
5197 >                    U u;
5198 >                    if ((u = transformer.apply(p.key)) != null)
5199                          r = (r == null) ? u : reducer.apply(r, u);
5200                  }
5201                  result = r;
5202                  CountedCompleter<?> c;
5203                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5204 <                    MapReduceKeysTask<K,V,U>
5204 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5205                          t = (MapReduceKeysTask<K,V,U>)c,
5206                          s = t.rights;
5207                      while (s != null) {
# Line 6100 | Line 5216 | public class ConcurrentHashMapV8<K, V>
5216          }
5217      }
5218  
5219 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5220 <        extends Traverser<K,V,U> {
5219 >    @SuppressWarnings("serial")
5220 >    static final class MapReduceValuesTask<K,V,U>
5221 >        extends BulkTask<K,V,U> {
5222          final Fun<? super V, ? extends U> transformer;
5223          final BiFun<? super U, ? super U, ? extends U> reducer;
5224          U result;
5225          MapReduceValuesTask<K,V,U> rights, nextRight;
5226          MapReduceValuesTask
5227 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5227 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5228               MapReduceValuesTask<K,V,U> nextRight,
5229               Fun<? super V, ? extends U> transformer,
5230               BiFun<? super U, ? super U, ? extends U> reducer) {
5231 <            super(m, p, b); this.nextRight = nextRight;
5231 >            super(p, b, i, f, t); this.nextRight = nextRight;
5232              this.transformer = transformer;
5233              this.reducer = reducer;
5234          }
5235          public final U getRawResult() { return result; }
5236 <        @SuppressWarnings("unchecked") public final void compute() {
5236 >        public final void compute() {
5237              final Fun<? super V, ? extends U> transformer;
5238              final BiFun<? super U, ? super U, ? extends U> reducer;
5239              if ((transformer = this.transformer) != null &&
5240                  (reducer = this.reducer) != null) {
5241 <                for (int b; (b = preSplit()) > 0;)
5241 >                for (int i = baseIndex, f, h; batch > 0 &&
5242 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5243 >                    addToPendingCount(1);
5244                      (rights = new MapReduceValuesTask<K,V,U>
5245 <                     (map, this, b, rights, transformer, reducer)).fork();
5246 <                U r = null, u;
5247 <                V v;
5248 <                while ((v = advance()) != null) {
5249 <                    if ((u = transformer.apply(v)) != null)
5245 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5246 >                      rights, transformer, reducer)).fork();
5247 >                }
5248 >                U r = null;
5249 >                for (Node<K,V> p; (p = advance()) != null; ) {
5250 >                    U u;
5251 >                    if ((u = transformer.apply(p.val)) != null)
5252                          r = (r == null) ? u : reducer.apply(r, u);
5253                  }
5254                  result = r;
5255                  CountedCompleter<?> c;
5256                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5257 <                    MapReduceValuesTask<K,V,U>
5257 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5258                          t = (MapReduceValuesTask<K,V,U>)c,
5259                          s = t.rights;
5260                      while (s != null) {
# Line 6148 | Line 5269 | public class ConcurrentHashMapV8<K, V>
5269          }
5270      }
5271  
5272 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5273 <        extends Traverser<K,V,U> {
5272 >    @SuppressWarnings("serial")
5273 >    static final class MapReduceEntriesTask<K,V,U>
5274 >        extends BulkTask<K,V,U> {
5275          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5276          final BiFun<? super U, ? super U, ? extends U> reducer;
5277          U result;
5278          MapReduceEntriesTask<K,V,U> rights, nextRight;
5279          MapReduceEntriesTask
5280 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5280 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5281               MapReduceEntriesTask<K,V,U> nextRight,
5282               Fun<Map.Entry<K,V>, ? extends U> transformer,
5283               BiFun<? super U, ? super U, ? extends U> reducer) {
5284 <            super(m, p, b); this.nextRight = nextRight;
5284 >            super(p, b, i, f, t); this.nextRight = nextRight;
5285              this.transformer = transformer;
5286              this.reducer = reducer;
5287          }
5288          public final U getRawResult() { return result; }
5289 <        @SuppressWarnings("unchecked") public final void compute() {
5289 >        public final void compute() {
5290              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5291              final BiFun<? super U, ? super U, ? extends U> reducer;
5292              if ((transformer = this.transformer) != null &&
5293                  (reducer = this.reducer) != null) {
5294 <                for (int b; (b = preSplit()) > 0;)
5294 >                for (int i = baseIndex, f, h; batch > 0 &&
5295 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5296 >                    addToPendingCount(1);
5297                      (rights = new MapReduceEntriesTask<K,V,U>
5298 <                     (map, this, b, rights, transformer, reducer)).fork();
5299 <                U r = null, u;
5300 <                V v;
5301 <                while ((v = advance()) != null) {
5302 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5303 <                                                        v))) != null)
5298 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5299 >                      rights, transformer, reducer)).fork();
5300 >                }
5301 >                U r = null;
5302 >                for (Node<K,V> p; (p = advance()) != null; ) {
5303 >                    U u;
5304 >                    if ((u = transformer.apply(p)) != null)
5305                          r = (r == null) ? u : reducer.apply(r, u);
5306                  }
5307                  result = r;
5308                  CountedCompleter<?> c;
5309                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5310 <                    MapReduceEntriesTask<K,V,U>
5310 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5311                          t = (MapReduceEntriesTask<K,V,U>)c,
5312                          s = t.rights;
5313                      while (s != null) {
# Line 6197 | Line 5322 | public class ConcurrentHashMapV8<K, V>
5322          }
5323      }
5324  
5325 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5326 <        extends Traverser<K,V,U> {
5325 >    @SuppressWarnings("serial")
5326 >    static final class MapReduceMappingsTask<K,V,U>
5327 >        extends BulkTask<K,V,U> {
5328          final BiFun<? super K, ? super V, ? extends U> transformer;
5329          final BiFun<? super U, ? super U, ? extends U> reducer;
5330          U result;
5331          MapReduceMappingsTask<K,V,U> rights, nextRight;
5332          MapReduceMappingsTask
5333 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5333 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5334               MapReduceMappingsTask<K,V,U> nextRight,
5335               BiFun<? super K, ? super V, ? extends U> transformer,
5336               BiFun<? super U, ? super U, ? extends U> reducer) {
5337 <            super(m, p, b); this.nextRight = nextRight;
5337 >            super(p, b, i, f, t); this.nextRight = nextRight;
5338              this.transformer = transformer;
5339              this.reducer = reducer;
5340          }
5341          public final U getRawResult() { return result; }
5342 <        @SuppressWarnings("unchecked") public final void compute() {
5342 >        public final void compute() {
5343              final BiFun<? super K, ? super V, ? extends U> transformer;
5344              final BiFun<? super U, ? super U, ? extends U> reducer;
5345              if ((transformer = this.transformer) != null &&
5346                  (reducer = this.reducer) != null) {
5347 <                for (int b; (b = preSplit()) > 0;)
5347 >                for (int i = baseIndex, f, h; batch > 0 &&
5348 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5349 >                    addToPendingCount(1);
5350                      (rights = new MapReduceMappingsTask<K,V,U>
5351 <                     (map, this, b, rights, transformer, reducer)).fork();
5352 <                U r = null, u;
5353 <                V v;
5354 <                while ((v = advance()) != null) {
5355 <                    if ((u = transformer.apply((K)nextKey, v)) != null)
5351 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5352 >                      rights, transformer, reducer)).fork();
5353 >                }
5354 >                U r = null;
5355 >                for (Node<K,V> p; (p = advance()) != null; ) {
5356 >                    U u;
5357 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5358                          r = (r == null) ? u : reducer.apply(r, u);
5359                  }
5360                  result = r;
5361                  CountedCompleter<?> c;
5362                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5363 <                    MapReduceMappingsTask<K,V,U>
5363 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5364                          t = (MapReduceMappingsTask<K,V,U>)c,
5365                          s = t.rights;
5366                      while (s != null) {
# Line 6245 | Line 5375 | public class ConcurrentHashMapV8<K, V>
5375          }
5376      }
5377  
5378 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5379 <        extends Traverser<K,V,Double> {
5378 >    @SuppressWarnings("serial")
5379 >    static final class MapReduceKeysToDoubleTask<K,V>
5380 >        extends BulkTask<K,V,Double> {
5381          final ObjectToDouble<? super K> transformer;
5382          final DoubleByDoubleToDouble reducer;
5383          final double basis;
5384          double result;
5385          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5386          MapReduceKeysToDoubleTask
5387 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5387 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5388               MapReduceKeysToDoubleTask<K,V> nextRight,
5389               ObjectToDouble<? super K> transformer,
5390               double basis,
5391               DoubleByDoubleToDouble reducer) {
5392 <            super(m, p, b); this.nextRight = nextRight;
5392 >            super(p, b, i, f, t); this.nextRight = nextRight;
5393              this.transformer = transformer;
5394              this.basis = basis; this.reducer = reducer;
5395          }
5396          public final Double getRawResult() { return result; }
5397 <        @SuppressWarnings("unchecked") public final void compute() {
5397 >        public final void compute() {
5398              final ObjectToDouble<? super K> transformer;
5399              final DoubleByDoubleToDouble reducer;
5400              if ((transformer = this.transformer) != null &&
5401                  (reducer = this.reducer) != null) {
5402                  double r = this.basis;
5403 <                for (int b; (b = preSplit()) > 0;)
5403 >                for (int i = baseIndex, f, h; batch > 0 &&
5404 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5405 >                    addToPendingCount(1);
5406                      (rights = new MapReduceKeysToDoubleTask<K,V>
5407 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5408 <                while (advance() != null)
5409 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5407 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5408 >                      rights, transformer, r, reducer)).fork();
5409 >                }
5410 >                for (Node<K,V> p; (p = advance()) != null; )
5411 >                    r = reducer.apply(r, transformer.apply(p.key));
5412                  result = r;
5413                  CountedCompleter<?> c;
5414                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5415 <                    MapReduceKeysToDoubleTask<K,V>
5415 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5416                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5417                          s = t.rights;
5418                      while (s != null) {
# Line 6289 | Line 5424 | public class ConcurrentHashMapV8<K, V>
5424          }
5425      }
5426  
5427 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5428 <        extends Traverser<K,V,Double> {
5427 >    @SuppressWarnings("serial")
5428 >    static final class MapReduceValuesToDoubleTask<K,V>
5429 >        extends BulkTask<K,V,Double> {
5430          final ObjectToDouble<? super V> transformer;
5431          final DoubleByDoubleToDouble reducer;
5432          final double basis;
5433          double result;
5434          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5435          MapReduceValuesToDoubleTask
5436 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5436 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5437               MapReduceValuesToDoubleTask<K,V> nextRight,
5438               ObjectToDouble<? super V> transformer,
5439               double basis,
5440               DoubleByDoubleToDouble reducer) {
5441 <            super(m, p, b); this.nextRight = nextRight;
5441 >            super(p, b, i, f, t); this.nextRight = nextRight;
5442              this.transformer = transformer;
5443              this.basis = basis; this.reducer = reducer;
5444          }
5445          public final Double getRawResult() { return result; }
5446 <        @SuppressWarnings("unchecked") public final void compute() {
5446 >        public final void compute() {
5447              final ObjectToDouble<? super V> transformer;
5448              final DoubleByDoubleToDouble reducer;
5449              if ((transformer = this.transformer) != null &&
5450                  (reducer = this.reducer) != null) {
5451                  double r = this.basis;
5452 <                for (int b; (b = preSplit()) > 0;)
5452 >                for (int i = baseIndex, f, h; batch > 0 &&
5453 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5454 >                    addToPendingCount(1);
5455                      (rights = new MapReduceValuesToDoubleTask<K,V>
5456 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5457 <                V v;
5458 <                while ((v = advance()) != null)
5459 <                    r = reducer.apply(r, transformer.apply(v));
5456 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5457 >                      rights, transformer, r, reducer)).fork();
5458 >                }
5459 >                for (Node<K,V> p; (p = advance()) != null; )
5460 >                    r = reducer.apply(r, transformer.apply(p.val));
5461                  result = r;
5462                  CountedCompleter<?> c;
5463                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5464 <                    MapReduceValuesToDoubleTask<K,V>
5464 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5465                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5466                          s = t.rights;
5467                      while (s != null) {
# Line 6334 | Line 5473 | public class ConcurrentHashMapV8<K, V>
5473          }
5474      }
5475  
5476 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5477 <        extends Traverser<K,V,Double> {
5476 >    @SuppressWarnings("serial")
5477 >    static final class MapReduceEntriesToDoubleTask<K,V>
5478 >        extends BulkTask<K,V,Double> {
5479          final ObjectToDouble<Map.Entry<K,V>> transformer;
5480          final DoubleByDoubleToDouble reducer;
5481          final double basis;
5482          double result;
5483          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5484          MapReduceEntriesToDoubleTask
5485 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5485 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5486               MapReduceEntriesToDoubleTask<K,V> nextRight,
5487               ObjectToDouble<Map.Entry<K,V>> transformer,
5488               double basis,
5489               DoubleByDoubleToDouble reducer) {
5490 <            super(m, p, b); this.nextRight = nextRight;
5490 >            super(p, b, i, f, t); this.nextRight = nextRight;
5491              this.transformer = transformer;
5492              this.basis = basis; this.reducer = reducer;
5493          }
5494          public final Double getRawResult() { return result; }
5495 <        @SuppressWarnings("unchecked") public final void compute() {
5495 >        public final void compute() {
5496              final ObjectToDouble<Map.Entry<K,V>> transformer;
5497              final DoubleByDoubleToDouble reducer;
5498              if ((transformer = this.transformer) != null &&
5499                  (reducer = this.reducer) != null) {
5500                  double r = this.basis;
5501 <                for (int b; (b = preSplit()) > 0;)
5501 >                for (int i = baseIndex, f, h; batch > 0 &&
5502 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5503 >                    addToPendingCount(1);
5504                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5505 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5506 <                V v;
5507 <                while ((v = advance()) != null)
5508 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5509 <                                                                    v)));
5505 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5506 >                      rights, transformer, r, reducer)).fork();
5507 >                }
5508 >                for (Node<K,V> p; (p = advance()) != null; )
5509 >                    r = reducer.apply(r, transformer.apply(p));
5510                  result = r;
5511                  CountedCompleter<?> c;
5512                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5513 <                    MapReduceEntriesToDoubleTask<K,V>
5513 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5514                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5515                          s = t.rights;
5516                      while (s != null) {
# Line 6380 | Line 5522 | public class ConcurrentHashMapV8<K, V>
5522          }
5523      }
5524  
5525 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5526 <        extends Traverser<K,V,Double> {
5525 >    @SuppressWarnings("serial")
5526 >    static final class MapReduceMappingsToDoubleTask<K,V>
5527 >        extends BulkTask<K,V,Double> {
5528          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5529          final DoubleByDoubleToDouble reducer;
5530          final double basis;
5531          double result;
5532          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5533          MapReduceMappingsToDoubleTask
5534 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5534 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5535               MapReduceMappingsToDoubleTask<K,V> nextRight,
5536               ObjectByObjectToDouble<? super K, ? super V> transformer,
5537               double basis,
5538               DoubleByDoubleToDouble reducer) {
5539 <            super(m, p, b); this.nextRight = nextRight;
5539 >            super(p, b, i, f, t); this.nextRight = nextRight;
5540              this.transformer = transformer;
5541              this.basis = basis; this.reducer = reducer;
5542          }
5543          public final Double getRawResult() { return result; }
5544 <        @SuppressWarnings("unchecked") public final void compute() {
5544 >        public final void compute() {
5545              final ObjectByObjectToDouble<? super K, ? super V> transformer;
5546              final DoubleByDoubleToDouble reducer;
5547              if ((transformer = this.transformer) != null &&
5548                  (reducer = this.reducer) != null) {
5549                  double r = this.basis;
5550 <                for (int b; (b = preSplit()) > 0;)
5550 >                for (int i = baseIndex, f, h; batch > 0 &&
5551 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5552 >                    addToPendingCount(1);
5553                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5554 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5555 <                V v;
5556 <                while ((v = advance()) != null)
5557 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5554 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5555 >                      rights, transformer, r, reducer)).fork();
5556 >                }
5557 >                for (Node<K,V> p; (p = advance()) != null; )
5558 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5559                  result = r;
5560                  CountedCompleter<?> c;
5561                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5562 <                    MapReduceMappingsToDoubleTask<K,V>
5562 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5563                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5564                          s = t.rights;
5565                      while (s != null) {
# Line 6425 | Line 5571 | public class ConcurrentHashMapV8<K, V>
5571          }
5572      }
5573  
5574 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5575 <        extends Traverser<K,V,Long> {
5574 >    @SuppressWarnings("serial")
5575 >    static final class MapReduceKeysToLongTask<K,V>
5576 >        extends BulkTask<K,V,Long> {
5577          final ObjectToLong<? super K> transformer;
5578          final LongByLongToLong reducer;
5579          final long basis;
5580          long result;
5581          MapReduceKeysToLongTask<K,V> rights, nextRight;
5582          MapReduceKeysToLongTask
5583 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5583 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5584               MapReduceKeysToLongTask<K,V> nextRight,
5585               ObjectToLong<? super K> transformer,
5586               long basis,
5587               LongByLongToLong reducer) {
5588 <            super(m, p, b); this.nextRight = nextRight;
5588 >            super(p, b, i, f, t); this.nextRight = nextRight;
5589              this.transformer = transformer;
5590              this.basis = basis; this.reducer = reducer;
5591          }
5592          public final Long getRawResult() { return result; }
5593 <        @SuppressWarnings("unchecked") public final void compute() {
5593 >        public final void compute() {
5594              final ObjectToLong<? super K> transformer;
5595              final LongByLongToLong reducer;
5596              if ((transformer = this.transformer) != null &&
5597                  (reducer = this.reducer) != null) {
5598                  long r = this.basis;
5599 <                for (int b; (b = preSplit()) > 0;)
5599 >                for (int i = baseIndex, f, h; batch > 0 &&
5600 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5601 >                    addToPendingCount(1);
5602                      (rights = new MapReduceKeysToLongTask<K,V>
5603 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5604 <                while (advance() != null)
5605 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5603 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5604 >                      rights, transformer, r, reducer)).fork();
5605 >                }
5606 >                for (Node<K,V> p; (p = advance()) != null; )
5607 >                    r = reducer.apply(r, transformer.apply(p.key));
5608                  result = r;
5609                  CountedCompleter<?> c;
5610                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5611 <                    MapReduceKeysToLongTask<K,V>
5611 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5612                          t = (MapReduceKeysToLongTask<K,V>)c,
5613                          s = t.rights;
5614                      while (s != null) {
# Line 6469 | Line 5620 | public class ConcurrentHashMapV8<K, V>
5620          }
5621      }
5622  
5623 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5624 <        extends Traverser<K,V,Long> {
5623 >    @SuppressWarnings("serial")
5624 >    static final class MapReduceValuesToLongTask<K,V>
5625 >        extends BulkTask<K,V,Long> {
5626          final ObjectToLong<? super V> transformer;
5627          final LongByLongToLong reducer;
5628          final long basis;
5629          long result;
5630          MapReduceValuesToLongTask<K,V> rights, nextRight;
5631          MapReduceValuesToLongTask
5632 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5632 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5633               MapReduceValuesToLongTask<K,V> nextRight,
5634               ObjectToLong<? super V> transformer,
5635               long basis,
5636               LongByLongToLong reducer) {
5637 <            super(m, p, b); this.nextRight = nextRight;
5637 >            super(p, b, i, f, t); this.nextRight = nextRight;
5638              this.transformer = transformer;
5639              this.basis = basis; this.reducer = reducer;
5640          }
5641          public final Long getRawResult() { return result; }
5642 <        @SuppressWarnings("unchecked") public final void compute() {
5642 >        public final void compute() {
5643              final ObjectToLong<? super V> transformer;
5644              final LongByLongToLong reducer;
5645              if ((transformer = this.transformer) != null &&
5646                  (reducer = this.reducer) != null) {
5647                  long r = this.basis;
5648 <                for (int b; (b = preSplit()) > 0;)
5648 >                for (int i = baseIndex, f, h; batch > 0 &&
5649 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5650 >                    addToPendingCount(1);
5651                      (rights = new MapReduceValuesToLongTask<K,V>
5652 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5653 <                V v;
5654 <                while ((v = advance()) != null)
5655 <                    r = reducer.apply(r, transformer.apply(v));
5652 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5653 >                      rights, transformer, r, reducer)).fork();
5654 >                }
5655 >                for (Node<K,V> p; (p = advance()) != null; )
5656 >                    r = reducer.apply(r, transformer.apply(p.val));
5657                  result = r;
5658                  CountedCompleter<?> c;
5659                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5660 <                    MapReduceValuesToLongTask<K,V>
5660 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5661                          t = (MapReduceValuesToLongTask<K,V>)c,
5662                          s = t.rights;
5663                      while (s != null) {
# Line 6514 | Line 5669 | public class ConcurrentHashMapV8<K, V>
5669          }
5670      }
5671  
5672 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5673 <        extends Traverser<K,V,Long> {
5672 >    @SuppressWarnings("serial")
5673 >    static final class MapReduceEntriesToLongTask<K,V>
5674 >        extends BulkTask<K,V,Long> {
5675          final ObjectToLong<Map.Entry<K,V>> transformer;
5676          final LongByLongToLong reducer;
5677          final long basis;
5678          long result;
5679          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5680          MapReduceEntriesToLongTask
5681 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5681 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5682               MapReduceEntriesToLongTask<K,V> nextRight,
5683               ObjectToLong<Map.Entry<K,V>> transformer,
5684               long basis,
5685               LongByLongToLong reducer) {
5686 <            super(m, p, b); this.nextRight = nextRight;
5686 >            super(p, b, i, f, t); this.nextRight = nextRight;
5687              this.transformer = transformer;
5688              this.basis = basis; this.reducer = reducer;
5689          }
5690          public final Long getRawResult() { return result; }
5691 <        @SuppressWarnings("unchecked") public final void compute() {
5691 >        public final void compute() {
5692              final ObjectToLong<Map.Entry<K,V>> transformer;
5693              final LongByLongToLong reducer;
5694              if ((transformer = this.transformer) != null &&
5695                  (reducer = this.reducer) != null) {
5696                  long r = this.basis;
5697 <                for (int b; (b = preSplit()) > 0;)
5697 >                for (int i = baseIndex, f, h; batch > 0 &&
5698 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5699 >                    addToPendingCount(1);
5700                      (rights = new MapReduceEntriesToLongTask<K,V>
5701 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5702 <                V v;
5703 <                while ((v = advance()) != null)
5704 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5705 <                                                                    v)));
5701 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5702 >                      rights, transformer, r, reducer)).fork();
5703 >                }
5704 >                for (Node<K,V> p; (p = advance()) != null; )
5705 >                    r = reducer.apply(r, transformer.apply(p));
5706                  result = r;
5707                  CountedCompleter<?> c;
5708                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5709 <                    MapReduceEntriesToLongTask<K,V>
5709 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5710                          t = (MapReduceEntriesToLongTask<K,V>)c,
5711                          s = t.rights;
5712                      while (s != null) {
# Line 6560 | Line 5718 | public class ConcurrentHashMapV8<K, V>
5718          }
5719      }
5720  
5721 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5722 <        extends Traverser<K,V,Long> {
5721 >    @SuppressWarnings("serial")
5722 >    static final class MapReduceMappingsToLongTask<K,V>
5723 >        extends BulkTask<K,V,Long> {
5724          final ObjectByObjectToLong<? super K, ? super V> transformer;
5725          final LongByLongToLong reducer;
5726          final long basis;
5727          long result;
5728          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5729          MapReduceMappingsToLongTask
5730 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5730 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5731               MapReduceMappingsToLongTask<K,V> nextRight,
5732               ObjectByObjectToLong<? super K, ? super V> transformer,
5733               long basis,
5734               LongByLongToLong reducer) {
5735 <            super(m, p, b); this.nextRight = nextRight;
5735 >            super(p, b, i, f, t); this.nextRight = nextRight;
5736              this.transformer = transformer;
5737              this.basis = basis; this.reducer = reducer;
5738          }
5739          public final Long getRawResult() { return result; }
5740 <        @SuppressWarnings("unchecked") public final void compute() {
5740 >        public final void compute() {
5741              final ObjectByObjectToLong<? super K, ? super V> transformer;
5742              final LongByLongToLong reducer;
5743              if ((transformer = this.transformer) != null &&
5744                  (reducer = this.reducer) != null) {
5745                  long r = this.basis;
5746 <                for (int b; (b = preSplit()) > 0;)
5746 >                for (int i = baseIndex, f, h; batch > 0 &&
5747 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5748 >                    addToPendingCount(1);
5749                      (rights = new MapReduceMappingsToLongTask<K,V>
5750 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5751 <                V v;
5752 <                while ((v = advance()) != null)
5753 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5750 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5751 >                      rights, transformer, r, reducer)).fork();
5752 >                }
5753 >                for (Node<K,V> p; (p = advance()) != null; )
5754 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5755                  result = r;
5756                  CountedCompleter<?> c;
5757                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5758 <                    MapReduceMappingsToLongTask<K,V>
5758 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5759                          t = (MapReduceMappingsToLongTask<K,V>)c,
5760                          s = t.rights;
5761                      while (s != null) {
# Line 6605 | Line 5767 | public class ConcurrentHashMapV8<K, V>
5767          }
5768      }
5769  
5770 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5771 <        extends Traverser<K,V,Integer> {
5770 >    @SuppressWarnings("serial")
5771 >    static final class MapReduceKeysToIntTask<K,V>
5772 >        extends BulkTask<K,V,Integer> {
5773          final ObjectToInt<? super K> transformer;
5774          final IntByIntToInt reducer;
5775          final int basis;
5776          int result;
5777          MapReduceKeysToIntTask<K,V> rights, nextRight;
5778          MapReduceKeysToIntTask
5779 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5779 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5780               MapReduceKeysToIntTask<K,V> nextRight,
5781               ObjectToInt<? super K> transformer,
5782               int basis,
5783               IntByIntToInt reducer) {
5784 <            super(m, p, b); this.nextRight = nextRight;
5784 >            super(p, b, i, f, t); this.nextRight = nextRight;
5785              this.transformer = transformer;
5786              this.basis = basis; this.reducer = reducer;
5787          }
5788          public final Integer getRawResult() { return result; }
5789 <        @SuppressWarnings("unchecked") public final void compute() {
5789 >        public final void compute() {
5790              final ObjectToInt<? super K> transformer;
5791              final IntByIntToInt reducer;
5792              if ((transformer = this.transformer) != null &&
5793                  (reducer = this.reducer) != null) {
5794                  int r = this.basis;
5795 <                for (int b; (b = preSplit()) > 0;)
5795 >                for (int i = baseIndex, f, h; batch > 0 &&
5796 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5797 >                    addToPendingCount(1);
5798                      (rights = new MapReduceKeysToIntTask<K,V>
5799 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5800 <                while (advance() != null)
5801 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5799 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5800 >                      rights, transformer, r, reducer)).fork();
5801 >                }
5802 >                for (Node<K,V> p; (p = advance()) != null; )
5803 >                    r = reducer.apply(r, transformer.apply(p.key));
5804                  result = r;
5805                  CountedCompleter<?> c;
5806                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5807 <                    MapReduceKeysToIntTask<K,V>
5807 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5808                          t = (MapReduceKeysToIntTask<K,V>)c,
5809                          s = t.rights;
5810                      while (s != null) {
# Line 6649 | Line 5816 | public class ConcurrentHashMapV8<K, V>
5816          }
5817      }
5818  
5819 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5820 <        extends Traverser<K,V,Integer> {
5819 >    @SuppressWarnings("serial")
5820 >    static final class MapReduceValuesToIntTask<K,V>
5821 >        extends BulkTask<K,V,Integer> {
5822          final ObjectToInt<? super V> transformer;
5823          final IntByIntToInt reducer;
5824          final int basis;
5825          int result;
5826          MapReduceValuesToIntTask<K,V> rights, nextRight;
5827          MapReduceValuesToIntTask
5828 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5828 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5829               MapReduceValuesToIntTask<K,V> nextRight,
5830               ObjectToInt<? super V> transformer,
5831               int basis,
5832               IntByIntToInt reducer) {
5833 <            super(m, p, b); this.nextRight = nextRight;
5833 >            super(p, b, i, f, t); this.nextRight = nextRight;
5834              this.transformer = transformer;
5835              this.basis = basis; this.reducer = reducer;
5836          }
5837          public final Integer getRawResult() { return result; }
5838 <        @SuppressWarnings("unchecked") public final void compute() {
5838 >        public final void compute() {
5839              final ObjectToInt<? super V> transformer;
5840              final IntByIntToInt reducer;
5841              if ((transformer = this.transformer) != null &&
5842                  (reducer = this.reducer) != null) {
5843                  int r = this.basis;
5844 <                for (int b; (b = preSplit()) > 0;)
5844 >                for (int i = baseIndex, f, h; batch > 0 &&
5845 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5846 >                    addToPendingCount(1);
5847                      (rights = new MapReduceValuesToIntTask<K,V>
5848 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5849 <                V v;
5850 <                while ((v = advance()) != null)
5851 <                    r = reducer.apply(r, transformer.apply(v));
5848 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5849 >                      rights, transformer, r, reducer)).fork();
5850 >                }
5851 >                for (Node<K,V> p; (p = advance()) != null; )
5852 >                    r = reducer.apply(r, transformer.apply(p.val));
5853                  result = r;
5854                  CountedCompleter<?> c;
5855                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5856 <                    MapReduceValuesToIntTask<K,V>
5856 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5857                          t = (MapReduceValuesToIntTask<K,V>)c,
5858                          s = t.rights;
5859                      while (s != null) {
# Line 6694 | Line 5865 | public class ConcurrentHashMapV8<K, V>
5865          }
5866      }
5867  
5868 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5869 <        extends Traverser<K,V,Integer> {
5868 >    @SuppressWarnings("serial")
5869 >    static final class MapReduceEntriesToIntTask<K,V>
5870 >        extends BulkTask<K,V,Integer> {
5871          final ObjectToInt<Map.Entry<K,V>> transformer;
5872          final IntByIntToInt reducer;
5873          final int basis;
5874          int result;
5875          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5876          MapReduceEntriesToIntTask
5877 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5877 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5878               MapReduceEntriesToIntTask<K,V> nextRight,
5879               ObjectToInt<Map.Entry<K,V>> transformer,
5880               int basis,
5881               IntByIntToInt reducer) {
5882 <            super(m, p, b); this.nextRight = nextRight;
5882 >            super(p, b, i, f, t); this.nextRight = nextRight;
5883              this.transformer = transformer;
5884              this.basis = basis; this.reducer = reducer;
5885          }
5886          public final Integer getRawResult() { return result; }
5887 <        @SuppressWarnings("unchecked") public final void compute() {
5887 >        public final void compute() {
5888              final ObjectToInt<Map.Entry<K,V>> transformer;
5889              final IntByIntToInt reducer;
5890              if ((transformer = this.transformer) != null &&
5891                  (reducer = this.reducer) != null) {
5892                  int r = this.basis;
5893 <                for (int b; (b = preSplit()) > 0;)
5893 >                for (int i = baseIndex, f, h; batch > 0 &&
5894 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5895 >                    addToPendingCount(1);
5896                      (rights = new MapReduceEntriesToIntTask<K,V>
5897 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5898 <                V v;
5899 <                while ((v = advance()) != null)
5900 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5901 <                                                                    v)));
5897 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5898 >                      rights, transformer, r, reducer)).fork();
5899 >                }
5900 >                for (Node<K,V> p; (p = advance()) != null; )
5901 >                    r = reducer.apply(r, transformer.apply(p));
5902                  result = r;
5903                  CountedCompleter<?> c;
5904                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5905 <                    MapReduceEntriesToIntTask<K,V>
5905 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5906                          t = (MapReduceEntriesToIntTask<K,V>)c,
5907                          s = t.rights;
5908                      while (s != null) {
# Line 6740 | Line 5914 | public class ConcurrentHashMapV8<K, V>
5914          }
5915      }
5916  
5917 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5918 <        extends Traverser<K,V,Integer> {
5917 >    @SuppressWarnings("serial")
5918 >    static final class MapReduceMappingsToIntTask<K,V>
5919 >        extends BulkTask<K,V,Integer> {
5920          final ObjectByObjectToInt<? super K, ? super V> transformer;
5921          final IntByIntToInt reducer;
5922          final int basis;
5923          int result;
5924          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5925          MapReduceMappingsToIntTask
5926 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5926 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5927               MapReduceMappingsToIntTask<K,V> nextRight,
5928               ObjectByObjectToInt<? super K, ? super V> transformer,
5929               int basis,
5930               IntByIntToInt reducer) {
5931 <            super(m, p, b); this.nextRight = nextRight;
5931 >            super(p, b, i, f, t); this.nextRight = nextRight;
5932              this.transformer = transformer;
5933              this.basis = basis; this.reducer = reducer;
5934          }
5935          public final Integer getRawResult() { return result; }
5936 <        @SuppressWarnings("unchecked") public final void compute() {
5936 >        public final void compute() {
5937              final ObjectByObjectToInt<? super K, ? super V> transformer;
5938              final IntByIntToInt reducer;
5939              if ((transformer = this.transformer) != null &&
5940                  (reducer = this.reducer) != null) {
5941                  int r = this.basis;
5942 <                for (int b; (b = preSplit()) > 0;)
5942 >                for (int i = baseIndex, f, h; batch > 0 &&
5943 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5944 >                    addToPendingCount(1);
5945                      (rights = new MapReduceMappingsToIntTask<K,V>
5946 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5947 <                V v;
5948 <                while ((v = advance()) != null)
5949 <                    r = reducer.apply(r, transformer.apply((K)nextKey, v));
5946 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5947 >                      rights, transformer, r, reducer)).fork();
5948 >                }
5949 >                for (Node<K,V> p; (p = advance()) != null; )
5950 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5951                  result = r;
5952                  CountedCompleter<?> c;
5953                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5954 <                    MapReduceMappingsToIntTask<K,V>
5954 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
5955                          t = (MapReduceMappingsToIntTask<K,V>)c,
5956                          s = t.rights;
5957                      while (s != null) {
# Line 6785 | Line 5963 | public class ConcurrentHashMapV8<K, V>
5963          }
5964      }
5965  
5966 +    /* ---------------- Counters -------------- */
5967 +
5968 +    // Adapted from LongAdder and Striped64.
5969 +    // See their internal docs for explanation.
5970 +
5971 +    // A padded cell for distributing counts
5972 +    static final class CounterCell {
5973 +        volatile long p0, p1, p2, p3, p4, p5, p6;
5974 +        volatile long value;
5975 +        volatile long q0, q1, q2, q3, q4, q5, q6;
5976 +        CounterCell(long x) { value = x; }
5977 +    }
5978 +
5979 +    /**
5980 +     * Holder for the thread-local hash code determining which
5981 +     * CounterCell to use. The code is initialized via the
5982 +     * counterHashCodeGenerator, but may be moved upon collisions.
5983 +     */
5984 +    static final class CounterHashCode {
5985 +        int code;
5986 +    }
5987 +
5988 +    /**
5989 +     * Generates initial value for per-thread CounterHashCodes.
5990 +     */
5991 +    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
5992 +
5993 +    /**
5994 +     * Increment for counterHashCodeGenerator. See class ThreadLocal
5995 +     * for explanation.
5996 +     */
5997 +    static final int SEED_INCREMENT = 0x61c88647;
5998 +
5999 +    /**
6000 +     * Per-thread counter hash codes. Shared across all instances.
6001 +     */
6002 +    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6003 +        new ThreadLocal<CounterHashCode>();
6004 +
6005 +
6006 +    final long sumCount() {
6007 +        CounterCell[] as = counterCells; CounterCell a;
6008 +        long sum = baseCount;
6009 +        if (as != null) {
6010 +            for (int i = 0; i < as.length; ++i) {
6011 +                if ((a = as[i]) != null)
6012 +                    sum += a.value;
6013 +            }
6014 +        }
6015 +        return sum;
6016 +    }
6017 +
6018 +    // See LongAdder version for explanation
6019 +    private final void fullAddCount(long x, CounterHashCode hc,
6020 +                                    boolean wasUncontended) {
6021 +        int h;
6022 +        if (hc == null) {
6023 +            hc = new CounterHashCode();
6024 +            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6025 +            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6026 +            threadCounterHashCode.set(hc);
6027 +        }
6028 +        else
6029 +            h = hc.code;
6030 +        boolean collide = false;                // True if last slot nonempty
6031 +        for (;;) {
6032 +            CounterCell[] as; CounterCell a; int n; long v;
6033 +            if ((as = counterCells) != null && (n = as.length) > 0) {
6034 +                if ((a = as[(n - 1) & h]) == null) {
6035 +                    if (cellsBusy == 0) {            // Try to attach new Cell
6036 +                        CounterCell r = new CounterCell(x); // Optimistic create
6037 +                        if (cellsBusy == 0 &&
6038 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6039 +                            boolean created = false;
6040 +                            try {               // Recheck under lock
6041 +                                CounterCell[] rs; int m, j;
6042 +                                if ((rs = counterCells) != null &&
6043 +                                    (m = rs.length) > 0 &&
6044 +                                    rs[j = (m - 1) & h] == null) {
6045 +                                    rs[j] = r;
6046 +                                    created = true;
6047 +                                }
6048 +                            } finally {
6049 +                                cellsBusy = 0;
6050 +                            }
6051 +                            if (created)
6052 +                                break;
6053 +                            continue;           // Slot is now non-empty
6054 +                        }
6055 +                    }
6056 +                    collide = false;
6057 +                }
6058 +                else if (!wasUncontended)       // CAS already known to fail
6059 +                    wasUncontended = true;      // Continue after rehash
6060 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6061 +                    break;
6062 +                else if (counterCells != as || n >= NCPU)
6063 +                    collide = false;            // At max size or stale
6064 +                else if (!collide)
6065 +                    collide = true;
6066 +                else if (cellsBusy == 0 &&
6067 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6068 +                    try {
6069 +                        if (counterCells == as) {// Expand table unless stale
6070 +                            CounterCell[] rs = new CounterCell[n << 1];
6071 +                            for (int i = 0; i < n; ++i)
6072 +                                rs[i] = as[i];
6073 +                            counterCells = rs;
6074 +                        }
6075 +                    } finally {
6076 +                        cellsBusy = 0;
6077 +                    }
6078 +                    collide = false;
6079 +                    continue;                   // Retry with expanded table
6080 +                }
6081 +                h ^= h << 13;                   // Rehash
6082 +                h ^= h >>> 17;
6083 +                h ^= h << 5;
6084 +            }
6085 +            else if (cellsBusy == 0 && counterCells == as &&
6086 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6087 +                boolean init = false;
6088 +                try {                           // Initialize table
6089 +                    if (counterCells == as) {
6090 +                        CounterCell[] rs = new CounterCell[2];
6091 +                        rs[h & 1] = new CounterCell(x);
6092 +                        counterCells = rs;
6093 +                        init = true;
6094 +                    }
6095 +                } finally {
6096 +                    cellsBusy = 0;
6097 +                }
6098 +                if (init)
6099 +                    break;
6100 +            }
6101 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6102 +                break;                          // Fall back on using base
6103 +        }
6104 +        hc.code = h;                            // Record index for next time
6105 +    }
6106 +
6107      // Unsafe mechanics
6108      private static final sun.misc.Unsafe U;
6109      private static final long SIZECTL;
6110      private static final long TRANSFERINDEX;
6111      private static final long TRANSFERORIGIN;
6112      private static final long BASECOUNT;
6113 <    private static final long COUNTERBUSY;
6113 >    private static final long CELLSBUSY;
6114      private static final long CELLVALUE;
6115      private static final long ABASE;
6116      private static final int ASHIFT;
# Line 6808 | Line 6127 | public class ConcurrentHashMapV8<K, V>
6127                  (k.getDeclaredField("transferOrigin"));
6128              BASECOUNT = U.objectFieldOffset
6129                  (k.getDeclaredField("baseCount"));
6130 <            COUNTERBUSY = U.objectFieldOffset
6131 <                (k.getDeclaredField("counterBusy"));
6130 >            CELLSBUSY = U.objectFieldOffset
6131 >                (k.getDeclaredField("cellsBusy"));
6132              Class<?> ck = CounterCell.class;
6133              CELLVALUE = U.objectFieldOffset
6134                  (ck.getDeclaredField("value"));
6135 <            Class<?> sc = Node[].class;
6136 <            ABASE = U.arrayBaseOffset(sc);
6137 <            int scale = U.arrayIndexScale(sc);
6135 >            Class<?> ak = Node[].class;
6136 >            ABASE = U.arrayBaseOffset(ak);
6137 >            int scale = U.arrayIndexScale(ak);
6138              if ((scale & (scale - 1)) != 0)
6139                  throw new Error("data type scale not a power of two");
6140              ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines