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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines