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.82 by dl, Thu Dec 13 20:34:00 2012 UTC vs.
Revision 1.118 by dl, Sun Dec 1 16:08:12 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 parallel operations using the {@link
102 < * ForkJoinPool#commonPool}. (Tasks that may be used in other contexts
103 < * are available in class {@link ForkJoinTasks}). These operations are
104 < * designed to be safely, and often sensibly, applied even with maps
105 < * that are being concurrently updated by other threads; for example,
106 < * when computing a snapshot summary of the values in a shared
107 < * registry.  There are three kinds of operation, each with four
108 < * forms, accepting functions with Keys, Values, Entries, and (Key,
109 < * Value) arguments and/or return values. (The first three forms are
110 < * also available via the {@link #keySet()}, {@link #values()} and
111 < * {@link #entrySet()} views). Because the elements of a
112 < * ConcurrentHashMapV8 are not ordered in any particular way, and may be
113 < * processed in different orders in different parallel executions, the
114 < * correctness of supplied functions should not depend on any
115 < * ordering, or on any other objects or values that may transiently
118 < * change while computation is in progress; and except for forEach
119 < * actions, should ideally be side-effect-free.
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 189 | Line 196 | import java.io.Serializable;
196   * exceptions, or would have done so if the first exception had
197   * not occurred.
198   *
199 < * <p>Parallel speedups for bulk operations compared to sequential
200 < * processing are common but not guaranteed.  Operations involving
201 < * brief functions on small maps may execute more slowly than
202 < * sequential loops if the underlying work to parallelize the
203 < * computation is more expensive than the computation itself.
204 < * Similarly, parallelization may not lead to much actual parallelism
205 < * if all processors are busy performing unrelated tasks.
199 > * <p>Speedups for parallel compared to sequential forms are common
200 > * but not guaranteed.  Parallel operations involving brief functions
201 > * on small maps may execute more slowly than sequential forms if the
202 > * underlying work to parallelize the computation is more expensive
203 > * than the computation itself.  Similarly, parallelization may not
204 > * lead to much actual parallelism if all processors are busy
205 > * performing unrelated tasks.
206   *
207   * <p>All arguments to all task methods must be non-null.
208   *
# 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
237 <         * the elements of the returned Spliterator, but the two
238 <         * Spliterators together will produce all of the elements that
239 <         * would have been produced by this Spliterator had this
240 <         * method not been called. The exact number of elements
241 <         * 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 >        ConcurrentHashMapSpliterator<T> trySplit();
239 >        /**
240 >         * Returns an estimate of the number of elements covered by
241 >         * this Spliterator.
242           */
243 <        Spliterator<T> split();
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 fields
291 <     * can contain special values, they are defined using plain Object
292 <     * types. Similarly in turn, all internal methods that use them
293 <     * work off Object types. And similarly, so do the internal
294 <     * methods of auxiliary iterator and view classes. This also
295 <     * allows many of the public methods to be factored into a smaller
296 <     * number of internal methods (although sadly not so for the five
297 <     * variants of put-related operations). The validation-based
298 <     * approach 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
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.  A generation stamp in field
393 >     * sizeCtl ensures that resizings do not overlap. Because we are
394       * using power-of-two expansion, the elements from each bin must
395       * either stay at same index, or move with a power of two
396       * offset. We eliminate unnecessary node creation by catching
# Line 424 | Line 411 | public class ConcurrentHashMapV8<K, V>
411       * locks, average aggregate waits become shorter as resizing
412       * progresses.  The transfer operation must also ensure that all
413       * accessible bins in both the old and new table are usable by any
414 <     * traversal.  This is arranged by proceeding from the last bin
415 <     * (table.length - 1) up towards the first.  Upon seeing a
416 <     * forwarding node, traversals (see class Traverser) arrange to
417 <     * move to the new table without revisiting nodes.  However, to
418 <     * ensure that no intervening nodes are skipped, bin splitting can
419 <     * only begin after the associated reverse-forwarders are in
420 <     * place.
414 >     * traversal.  This is arranged in part by proceeding from the
415 >     * last bin (table.length - 1) up towards the first.  Upon seeing
416 >     * a forwarding node, traversals (see class Traverser) arrange to
417 >     * move to the new table without revisiting nodes.  To ensure that
418 >     * no intervening nodes are skipped even when moved out of order,
419 >     * a stack (see class TableStack) is created on first encounter of
420 >     * a forwarding node during a traversal, to maintain its place if
421 >     * later processing the current table. The need for these
422 >     * save/restore mechanics is relatively rare, but when one
423 >     * forwarding node is encountered, typically many more will be.
424 >     * So Traversers use a simple caching scheme to avoid creating so
425 >     * many new TableStack nodes. (Thanks to Peter Levart for
426 >     * suggesting use of a stack here.)
427       *
428       * The traversal scheme also applies to partial traversals of
429       * ranges of bins (via an alternate Traverser constructor)
# Line 456 | Line 449 | public class ConcurrentHashMapV8<K, V>
449       * bin already holding two or more nodes. Under uniform hash
450       * distributions, the probability of this occurring at threshold
451       * is around 13%, meaning that only about 1 in 8 puts check
452 <     * threshold (and after resizing, many fewer do so). The bulk
453 <     * putAll operation further reduces contention by only committing
454 <     * count updates upon these size checks.
452 >     * threshold (and after resizing, many fewer do so).
453 >     *
454 >     * TreeBins use a special form of comparison for search and
455 >     * related operations (which is the main reason we cannot use
456 >     * existing collections such as TreeMaps). TreeBins contain
457 >     * Comparable elements, but may contain others, as well as
458 >     * elements that are Comparable but not necessarily Comparable for
459 >     * the same T, so we cannot invoke compareTo among them. To handle
460 >     * this, the tree is ordered primarily by hash value, then by
461 >     * Comparable.compareTo order if applicable.  On lookup at a node,
462 >     * if elements are not comparable or compare as 0 then both left
463 >     * and right children may need to be searched in the case of tied
464 >     * hash values. (This corresponds to the full list search that
465 >     * would be necessary if all elements were non-Comparable and had
466 >     * tied hashes.) On insertion, to keep a total ordering (or as
467 >     * close as is required here) across rebalancings, we compare
468 >     * classes and identityHashCodes as tie-breakers. The red-black
469 >     * balancing code is updated from pre-jdk-collections
470 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
471 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
472 >     * Algorithms" (CLR).
473 >     *
474 >     * TreeBins also require an additional locking mechanism.  While
475 >     * list traversal is always possible by readers even during
476 >     * updates, tree traversal is not, mainly because of tree-rotations
477 >     * that may change the root node and/or its linkages.  TreeBins
478 >     * include a simple read-write lock mechanism parasitic on the
479 >     * main bin-synchronization strategy: Structural adjustments
480 >     * associated with an insertion or removal are already bin-locked
481 >     * (and so cannot conflict with other writers) but must wait for
482 >     * ongoing readers to finish. Since there can be only one such
483 >     * waiter, we use a simple scheme using a single "waiter" field to
484 >     * block writers.  However, readers need never block.  If the root
485 >     * lock is held, they proceed along the slow traversal path (via
486 >     * next-pointers) until the lock becomes available or the list is
487 >     * exhausted, whichever comes first. These cases are not fast, but
488 >     * maximize aggregate expected throughput.
489       *
490       * Maintaining API and serialization compatibility with previous
491       * versions of this class introduces several oddities. Mainly: We
# Line 468 | Line 495 | public class ConcurrentHashMapV8<K, V>
495       * time that we can guarantee to honor it.) We also declare an
496       * unused "Segment" class that is instantiated in minimal form
497       * only when serializing.
498 +     *
499 +     * Also, solely for compatibility with previous versions of this
500 +     * class, it extends AbstractMap, even though all of its methods
501 +     * are overridden, so it is just useless baggage.
502 +     *
503 +     * This file is organized to make things a little easier to follow
504 +     * while reading than they might otherwise: First the main static
505 +     * declarations and utilities, then fields, then main public
506 +     * methods (with a few factorings of multiple public methods into
507 +     * internal ones), then sizing methods, trees, traversers, and
508 +     * bulk operations.
509       */
510  
511      /* ---------------- Constants -------------- */
# Line 510 | Line 548 | public class ConcurrentHashMapV8<K, V>
548  
549      /**
550       * The bin count threshold for using a tree rather than list for a
551 <     * bin.  The value reflects the approximate break-even point for
552 <     * using tree-based operations.
551 >     * bin.  Bins are converted to trees when adding an element to a
552 >     * bin with at least this many nodes. The value must be greater
553 >     * than 2, and should be at least 8 to mesh with assumptions in
554 >     * tree removal about conversion back to plain bins upon
555 >     * shrinkage.
556 >     */
557 >    static final int TREEIFY_THRESHOLD = 8;
558 >
559 >    /**
560 >     * The bin count threshold for untreeifying a (split) bin during a
561 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
562 >     * most 6 to mesh with shrinkage detection under removal.
563       */
564 <    private static final int TREE_THRESHOLD = 8;
564 >    static final int UNTREEIFY_THRESHOLD = 6;
565 >
566 >    /**
567 >     * The smallest table capacity for which bins may be treeified.
568 >     * (Otherwise the table is resized if too many nodes in a bin.)
569 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
570 >     * conflicts between resizing and treeification thresholds.
571 >     */
572 >    static final int MIN_TREEIFY_CAPACITY = 64;
573  
574      /**
575       * Minimum number of rebinnings per transfer step. Ranges are
# Line 524 | Line 580 | public class ConcurrentHashMapV8<K, V>
580       */
581      private static final int MIN_TRANSFER_STRIDE = 16;
582  
583 +    /**
584 +     * The number of bits used for generation stamp in sizeCtl.
585 +     * Must be at least 6 for 32bit arrays.
586 +     */
587 +    private static int RESIZE_STAMP_BITS = 16;
588 +
589 +    /**
590 +     * The maximum number of threads that can help resize.
591 +     * Must fit in 32 - RESIZE_STAMP_BITS bits.
592 +     */
593 +    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
594 +
595 +    /**
596 +     * The bit shift for recording size stamp in sizeCtl.
597 +     */
598 +    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
599 +
600      /*
601       * Encodings for Node hash fields. See above for explanation.
602       */
603 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
603 >    static final int MOVED     = -1; // hash for forwarding nodes
604 >    static final int TREEBIN   = -2; // hash for roots of trees
605 >    static final int RESERVED  = -3; // hash for transient reservations
606      static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
607  
608      /** Number of CPUS, to place bounds on some sizings */
609      static final int NCPU = Runtime.getRuntime().availableProcessors();
610  
611 <    /* ---------------- Counters -------------- */
611 >    /** For serialization compatibility. */
612 >    private static final ObjectStreamField[] serialPersistentFields = {
613 >        new ObjectStreamField("segments", Segment[].class),
614 >        new ObjectStreamField("segmentMask", Integer.TYPE),
615 >        new ObjectStreamField("segmentShift", Integer.TYPE)
616 >    };
617  
618 <    // Adapted from LongAdder and Striped64.
539 <    // See their internal docs for explanation.
618 >    /* ---------------- Nodes -------------- */
619  
620 <    // A padded cell for distributing counts
621 <    static final class CounterCell {
622 <        volatile long p0, p1, p2, p3, p4, p5, p6;
623 <        volatile long value;
624 <        volatile long q0, q1, q2, q3, q4, q5, q6;
625 <        CounterCell(long x) { value = x; }
620 >    /**
621 >     * Key-value entry.  This class is never exported out as a
622 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
623 >     * MapEntry below), but can be used for read-only traversals used
624 >     * in bulk tasks.  Subclasses of Node with a negative hash field
625 >     * are special, and contain null keys and values (but are never
626 >     * exported).  Otherwise, keys and vals are never null.
627 >     */
628 >    static class Node<K,V> implements Map.Entry<K,V> {
629 >        final int hash;
630 >        final K key;
631 >        volatile V val;
632 >        volatile Node<K,V> next;
633 >
634 >        Node(int hash, K key, V val, Node<K,V> next) {
635 >            this.hash = hash;
636 >            this.key = key;
637 >            this.val = val;
638 >            this.next = next;
639 >        }
640 >
641 >        public final K getKey()       { return key; }
642 >        public final V getValue()     { return val; }
643 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
644 >        public final String toString(){ return key + "=" + val; }
645 >        public final V setValue(V value) {
646 >            throw new UnsupportedOperationException();
647 >        }
648 >
649 >        public final boolean equals(Object o) {
650 >            Object k, v, u; Map.Entry<?,?> e;
651 >            return ((o instanceof Map.Entry) &&
652 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
653 >                    (v = e.getValue()) != null &&
654 >                    (k == key || k.equals(key)) &&
655 >                    (v == (u = val) || v.equals(u)));
656 >        }
657 >
658 >        /**
659 >         * Virtualized support for map.get(); overridden in subclasses.
660 >         */
661 >        Node<K,V> find(int h, Object k) {
662 >            Node<K,V> e = this;
663 >            if (k != null) {
664 >                do {
665 >                    K ek;
666 >                    if (e.hash == h &&
667 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
668 >                        return e;
669 >                } while ((e = e.next) != null);
670 >            }
671 >            return null;
672 >        }
673      }
674  
675 +    /* ---------------- Static utilities -------------- */
676 +
677      /**
678 <     * Holder for the thread-local hash code determining which
679 <     * CounterCell to use. The code is initialized via the
680 <     * counterHashCodeGenerator, but may be moved upon collisions.
678 >     * Spreads (XORs) higher bits of hash to lower and also forces top
679 >     * bit to 0. Because the table uses power-of-two masking, sets of
680 >     * hashes that vary only in bits above the current mask will
681 >     * always collide. (Among known examples are sets of Float keys
682 >     * holding consecutive whole numbers in small tables.)  So we
683 >     * apply a transform that spreads the impact of higher bits
684 >     * downward. There is a tradeoff between speed, utility, and
685 >     * quality of bit-spreading. Because many common sets of hashes
686 >     * are already reasonably distributed (so don't benefit from
687 >     * spreading), and because we use trees to handle large sets of
688 >     * collisions in bins, we just XOR some shifted bits in the
689 >     * cheapest possible way to reduce systematic lossage, as well as
690 >     * to incorporate impact of the highest bits that would otherwise
691 >     * never be used in index calculations because of table bounds.
692       */
693 <    static final class CounterHashCode {
694 <        int code;
693 >    static final int spread(int h) {
694 >        return (h ^ (h >>> 16)) & HASH_BITS;
695      }
696  
697      /**
698 <     * Generates initial value for per-thread CounterHashCodes
698 >     * Returns a power of two table size for the given desired capacity.
699 >     * See Hackers Delight, sec 3.2
700       */
701 <    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
701 >    private static final int tableSizeFor(int c) {
702 >        int n = c - 1;
703 >        n |= n >>> 1;
704 >        n |= n >>> 2;
705 >        n |= n >>> 4;
706 >        n |= n >>> 8;
707 >        n |= n >>> 16;
708 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
709 >    }
710  
711      /**
712 <     * Increment for counterHashCodeGenerator. See class ThreadLocal
713 <     * for explanation.
712 >     * Returns x's Class if it is of the form "class C implements
713 >     * Comparable<C>", else null.
714       */
715 <    static final int SEED_INCREMENT = 0x61c88647;
715 >    static Class<?> comparableClassFor(Object x) {
716 >        if (x instanceof Comparable) {
717 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
718 >            if ((c = x.getClass()) == String.class) // bypass checks
719 >                return c;
720 >            if ((ts = c.getGenericInterfaces()) != null) {
721 >                for (int i = 0; i < ts.length; ++i) {
722 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
723 >                        ((p = (ParameterizedType)t).getRawType() ==
724 >                         Comparable.class) &&
725 >                        (as = p.getActualTypeArguments()) != null &&
726 >                        as.length == 1 && as[0] == c) // type arg is c
727 >                        return c;
728 >                }
729 >            }
730 >        }
731 >        return null;
732 >    }
733  
734      /**
735 <     * Per-thread counter hash codes. Shared across all instances
735 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
736 >     * class), else 0.
737       */
738 <    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
739 <        new ThreadLocal<CounterHashCode>();
738 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
739 >    static int compareComparables(Class<?> kc, Object k, Object x) {
740 >        return (x == null || x.getClass() != kc ? 0 :
741 >                ((Comparable)k).compareTo(x));
742 >    }
743 >
744 >    /* ---------------- Table element access -------------- */
745 >
746 >    /*
747 >     * Volatile access methods are used for table elements as well as
748 >     * elements of in-progress next table while resizing.  All uses of
749 >     * the tab arguments must be null checked by callers.  All callers
750 >     * also paranoically precheck that tab's length is not zero (or an
751 >     * equivalent check), thus ensuring that any index argument taking
752 >     * the form of a hash value anded with (length - 1) is a valid
753 >     * index.  Note that, to be correct wrt arbitrary concurrency
754 >     * errors by users, these checks must operate on local variables,
755 >     * which accounts for some odd-looking inline assignments below.
756 >     * Note that calls to setTabAt always occur within locked regions,
757 >     * and so in principle require only release ordering, not
758 >     * full volatile semantics, but are currently coded as volatile
759 >     * writes to be conservative.
760 >     */
761 >
762 >    @SuppressWarnings("unchecked")
763 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
764 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
765 >    }
766 >
767 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
768 >                                        Node<K,V> c, Node<K,V> v) {
769 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
770 >    }
771 >
772 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
773 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
774 >    }
775  
776      /* ---------------- Fields -------------- */
777  
# Line 578 | Line 779 | public class ConcurrentHashMapV8<K, V>
779       * The array of bins. Lazily initialized upon first insertion.
780       * Size is always a power of two. Accessed directly by iterators.
781       */
782 <    transient volatile Node[] table;
782 >    transient volatile Node<K,V>[] table;
783  
784      /**
785       * The next table to use; non-null only while resizing.
786       */
787 <    private transient volatile Node[] nextTable;
787 >    private transient volatile Node<K,V>[] nextTable;
788  
789      /**
790       * Base counter value, used mainly when there is no contention,
# Line 608 | Line 809 | public class ConcurrentHashMapV8<K, V>
809      private transient volatile int transferIndex;
810  
811      /**
812 <     * 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.
812 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
813       */
814 <    private transient volatile int counterBusy;
814 >    private transient volatile int cellsBusy;
815  
816      /**
817       * Table of counter cells. When non-null, size is a power of 2.
# Line 627 | Line 823 | public class ConcurrentHashMapV8<K, V>
823      private transient ValuesView<K,V> values;
824      private transient EntrySetView<K,V> entrySet;
825  
630    /** For serialization compatibility. Null unless serialized; see below */
631    private Segment<K,V>[] segments;
826  
827 <    /* ---------------- Table element access -------------- */
827 >    /* ---------------- Public operations -------------- */
828  
829 <    /*
830 <     * Volatile access methods are used for table elements as well as
637 <     * elements of in-progress next table while resizing.  Uses are
638 <     * 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.
829 >    /**
830 >     * Creates a new, empty map with the default initial table size (16).
831       */
832 <
647 <    static final Node tabAt(Node[] tab, int i) { // used by Traverser
648 <        return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
832 >    public ConcurrentHashMapV8() {
833      }
834  
835 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
836 <        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
835 >    /**
836 >     * Creates a new, empty map with an initial table size
837 >     * accommodating the specified number of elements without the need
838 >     * to dynamically resize.
839 >     *
840 >     * @param initialCapacity The implementation performs internal
841 >     * sizing to accommodate this many elements.
842 >     * @throws IllegalArgumentException if the initial capacity of
843 >     * elements is negative
844 >     */
845 >    public ConcurrentHashMapV8(int initialCapacity) {
846 >        if (initialCapacity < 0)
847 >            throw new IllegalArgumentException();
848 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
849 >                   MAXIMUM_CAPACITY :
850 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
851 >        this.sizeCtl = cap;
852      }
853  
854 <    private static final void setTabAt(Node[] tab, int i, Node v) {
855 <        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
854 >    /**
855 >     * Creates a new map with the same mappings as the given map.
856 >     *
857 >     * @param m the map
858 >     */
859 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
860 >        this.sizeCtl = DEFAULT_CAPACITY;
861 >        putAll(m);
862      }
863  
659    /* ---------------- Nodes -------------- */
660
864      /**
865 <     * Key-value entry. Note that this is never exported out as a
866 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
867 <     * field of MOVED are special, and do not contain user keys or
868 <     * values.  Otherwise, keys are never null, and null val fields
869 <     * indicate that a node is in the process of being deleted or
870 <     * created. For purposes of read-only access, a key may be read
871 <     * before a val, but can only be used after checking val to be
872 <     * non-null.
865 >     * Creates a new, empty map with an initial table size based on
866 >     * the given number of elements ({@code initialCapacity}) and
867 >     * initial table density ({@code loadFactor}).
868 >     *
869 >     * @param initialCapacity the initial capacity. The implementation
870 >     * performs internal sizing to accommodate this many elements,
871 >     * given the specified load factor.
872 >     * @param loadFactor the load factor (table density) for
873 >     * establishing the initial table size
874 >     * @throws IllegalArgumentException if the initial capacity of
875 >     * elements is negative or the load factor is nonpositive
876 >     *
877 >     * @since 1.6
878       */
879 <    static class Node {
880 <        final int hash;
881 <        final Object key;
674 <        volatile Object val;
675 <        volatile Node next;
879 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
880 >        this(initialCapacity, loadFactor, 1);
881 >    }
882  
883 <        Node(int hash, Object key, Object val, Node next) {
884 <            this.hash = hash;
885 <            this.key = key;
886 <            this.val = val;
887 <            this.next = next;
888 <        }
883 >    /**
884 >     * Creates a new, empty map with an initial table size based on
885 >     * the given number of elements ({@code initialCapacity}), table
886 >     * density ({@code loadFactor}), and number of concurrently
887 >     * updating threads ({@code concurrencyLevel}).
888 >     *
889 >     * @param initialCapacity the initial capacity. The implementation
890 >     * performs internal sizing to accommodate this many elements,
891 >     * given the specified load factor.
892 >     * @param loadFactor the load factor (table density) for
893 >     * establishing the initial table size
894 >     * @param concurrencyLevel the estimated number of concurrently
895 >     * updating threads. The implementation may use this value as
896 >     * a sizing hint.
897 >     * @throws IllegalArgumentException if the initial capacity is
898 >     * negative or the load factor or concurrencyLevel are
899 >     * nonpositive
900 >     */
901 >    public ConcurrentHashMapV8(int initialCapacity,
902 >                             float loadFactor, int concurrencyLevel) {
903 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
904 >            throw new IllegalArgumentException();
905 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
906 >            initialCapacity = concurrencyLevel;   // as estimated threads
907 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
908 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
909 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
910 >        this.sizeCtl = cap;
911      }
912  
913 <    /* ---------------- TreeBins -------------- */
913 >    // Original (since JDK1.2) Map methods
914  
915      /**
916 <     * Nodes for use in TreeBins
916 >     * {@inheritDoc}
917       */
918 <    static final class TreeNode extends Node {
919 <        TreeNode parent;  // red-black tree links
920 <        TreeNode left;
921 <        TreeNode right;
922 <        TreeNode prev;    // needed to unlink next upon deletion
923 <        boolean red;
918 >    public int size() {
919 >        long n = sumCount();
920 >        return ((n < 0L) ? 0 :
921 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
922 >                (int)n);
923 >    }
924  
925 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
926 <            super(hash, key, val, next);
927 <            this.parent = parent;
928 <        }
925 >    /**
926 >     * {@inheritDoc}
927 >     */
928 >    public boolean isEmpty() {
929 >        return sumCount() <= 0L; // ignore transient negative values
930      }
931  
932      /**
933 <     * A specialized form of red-black tree for use in bins
934 <     * whose size exceeds a threshold.
933 >     * Returns the value to which the specified key is mapped,
934 >     * or {@code null} if this map contains no mapping for the key.
935       *
936 <     * TreeBins use a special form of comparison for search and
937 <     * related operations (which is the main reason we cannot use
938 <     * existing collections such as TreeMaps). TreeBins contain
939 <     * Comparable elements, but may contain others, as well as
711 <     * elements that are Comparable but not necessarily Comparable<T>
712 <     * for the same T, so we cannot invoke compareTo among them. To
713 <     * handle this, the tree is ordered primarily by hash value, then
714 <     * by getClass().getName() order, and then by Comparator order
715 <     * among elements of the same class.  On lookup at a node, if
716 <     * elements are not comparable or compare as 0, both left and
717 <     * right children may need to be searched in the case of tied hash
718 <     * values. (This corresponds to the full list search that would be
719 <     * necessary if all elements were non-Comparable and had tied
720 <     * hashes.)  The red-black balancing code is updated from
721 <     * pre-jdk-collections
722 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
723 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
724 <     * Algorithms" (CLR).
936 >     * <p>More formally, if this map contains a mapping from a key
937 >     * {@code k} to a value {@code v} such that {@code key.equals(k)},
938 >     * then this method returns {@code v}; otherwise it returns
939 >     * {@code null}.  (There can be at most one such mapping.)
940       *
941 <     * TreeBins also maintain a separate locking discipline than
727 <     * regular bins. Because they are forwarded via special MOVED
728 <     * nodes at bin heads (which can never change once established),
729 <     * we cannot use those nodes as locks. Instead, TreeBin
730 <     * extends AbstractQueuedSynchronizer to support a simple form of
731 <     * read-write lock. For update operations and table validation,
732 <     * the exclusive form of lock behaves in the same way as bin-head
733 <     * locks. However, lookups use shared read-lock mechanics to allow
734 <     * multiple readers in the absence of writers.  Additionally,
735 <     * these lookups do not ever block: While the lock is not
736 <     * available, they proceed along the slow traversal path (via
737 <     * next-pointers) until the lock becomes available or the list is
738 <     * exhausted, whichever comes first. (These cases are not fast,
739 <     * but maximize aggregate expected throughput.)  The AQS mechanics
740 <     * for doing this are straightforward.  The lock state is held as
741 <     * AQS getState().  Read counts are negative; the write count (1)
742 <     * is positive.  There are no signalling preferences among readers
743 <     * and writers. Since we don't need to export full Lock API, we
744 <     * just override the minimal AQS methods and use them directly.
941 >     * @throws NullPointerException if the specified key is null
942       */
943 <    static final class TreeBin extends AbstractQueuedSynchronizer {
944 <        private static final long serialVersionUID = 2249069246763182397L;
945 <        transient TreeNode root;  // root of tree
946 <        transient TreeNode first; // head of next-pointer list
947 <
948 <        /* AQS overrides */
949 <        public final boolean isHeldExclusively() { return getState() > 0; }
950 <        public final boolean tryAcquire(int ignore) {
951 <            if (compareAndSetState(0, 1)) {
952 <                setExclusiveOwnerThread(Thread.currentThread());
953 <                return true;
954 <            }
955 <            return false;
956 <        }
957 <        public final boolean tryRelease(int ignore) {
761 <            setExclusiveOwnerThread(null);
762 <            setState(0);
763 <            return true;
764 <        }
765 <        public final int tryAcquireShared(int ignore) {
766 <            for (int c;;) {
767 <                if ((c = getState()) > 0)
768 <                    return -1;
769 <                if (compareAndSetState(c, c -1))
770 <                    return 1;
771 <            }
772 <        }
773 <        public final boolean tryReleaseShared(int ignore) {
774 <            int c;
775 <            do {} while (!compareAndSetState(c = getState(), c + 1));
776 <            return c == -1;
777 <        }
778 <
779 <        /** From CLR */
780 <        private void rotateLeft(TreeNode p) {
781 <            if (p != null) {
782 <                TreeNode r = p.right, pp, rl;
783 <                if ((rl = p.right = r.left) != null)
784 <                    rl.parent = p;
785 <                if ((pp = r.parent = p.parent) == null)
786 <                    root = r;
787 <                else if (pp.left == p)
788 <                    pp.left = r;
789 <                else
790 <                    pp.right = r;
791 <                r.left = p;
792 <                p.parent = r;
943 >    public V get(Object key) {
944 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
945 >        int h = spread(key.hashCode());
946 >        if ((tab = table) != null && (n = tab.length) > 0 &&
947 >            (e = tabAt(tab, (n - 1) & h)) != null) {
948 >            if ((eh = e.hash) == h) {
949 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
950 >                    return e.val;
951 >            }
952 >            else if (eh < 0)
953 >                return (p = e.find(h, key)) != null ? p.val : null;
954 >            while ((e = e.next) != null) {
955 >                if (e.hash == h &&
956 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
957 >                    return e.val;
958              }
959          }
960 +        return null;
961 +    }
962  
963 <        /** From CLR */
964 <        private void rotateRight(TreeNode p) {
965 <            if (p != null) {
966 <                TreeNode l = p.left, pp, lr;
967 <                if ((lr = p.left = l.right) != null)
968 <                    lr.parent = p;
969 <                if ((pp = l.parent = p.parent) == null)
970 <                    root = l;
971 <                else if (pp.right == p)
972 <                    pp.right = l;
973 <                else
974 <                    pp.left = l;
808 <                l.right = p;
809 <                p.parent = l;
810 <            }
811 <        }
963 >    /**
964 >     * Tests if the specified object is a key in this table.
965 >     *
966 >     * @param  key possible key
967 >     * @return {@code true} if and only if the specified object
968 >     *         is a key in this table, as determined by the
969 >     *         {@code equals} method; {@code false} otherwise
970 >     * @throws NullPointerException if the specified key is null
971 >     */
972 >    public boolean containsKey(Object key) {
973 >        return get(key) != null;
974 >    }
975  
976 <        /**
977 <         * Returns the TreeNode (or null if not found) for the given key
978 <         * starting at given root.
979 <         */
980 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
981 <            (int h, Object k, TreeNode p) {
982 <            Class<?> c = k.getClass();
983 <            while (p != null) {
984 <                int dir, ph;  Object pk; Class<?> pc;
985 <                if ((ph = p.hash) == h) {
986 <                    if ((pk = p.key) == k || k.equals(pk))
987 <                        return p;
988 <                    if (c != (pc = pk.getClass()) ||
989 <                        !(k instanceof Comparable) ||
990 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
991 <                        if ((dir = (c == pc) ? 0 :
992 <                             c.getName().compareTo(pc.getName())) == 0) {
993 <                            TreeNode r = null, pl, pr; // check both sides
994 <                            if ((pr = p.right) != null && h >= pr.hash &&
995 <                                (r = getTreeNode(h, k, pr)) != null)
833 <                                return r;
834 <                            else if ((pl = p.left) != null && h <= pl.hash)
835 <                                dir = -1;
836 <                            else // nothing there
837 <                                return null;
838 <                        }
839 <                    }
840 <                }
841 <                else
842 <                    dir = (h < ph) ? -1 : 1;
843 <                p = (dir > 0) ? p.right : p.left;
976 >    /**
977 >     * Returns {@code true} if this map maps one or more keys to the
978 >     * specified value. Note: This method may require a full traversal
979 >     * of the map, and is much slower than method {@code containsKey}.
980 >     *
981 >     * @param value value whose presence in this map is to be tested
982 >     * @return {@code true} if this map maps one or more keys to the
983 >     *         specified value
984 >     * @throws NullPointerException if the specified value is null
985 >     */
986 >    public boolean containsValue(Object value) {
987 >        if (value == null)
988 >            throw new NullPointerException();
989 >        Node<K,V>[] t;
990 >        if ((t = table) != null) {
991 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
992 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
993 >                V v;
994 >                if ((v = p.val) == value || (v != null && value.equals(v)))
995 >                    return true;
996              }
845            return null;
997          }
998 +        return false;
999 +    }
1000  
1001 <        /**
1002 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
1003 <         * read-lock to call getTreeNode, but during failure to get
1004 <         * lock, searches along next links.
1005 <         */
1006 <        final Object getValue(int h, Object k) {
1007 <            Node r = null;
1008 <            int c = getState(); // Must read lock state first
1009 <            for (Node e = first; e != null; e = e.next) {
1010 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
1011 <                    try {
1012 <                        r = getTreeNode(h, k, root);
1013 <                    } finally {
1014 <                        releaseShared(0);
1001 >    /**
1002 >     * Maps the specified key to the specified value in this table.
1003 >     * Neither the key nor the value can be null.
1004 >     *
1005 >     * <p>The value can be retrieved by calling the {@code get} method
1006 >     * with a key that is equal to the original key.
1007 >     *
1008 >     * @param key key with which the specified value is to be associated
1009 >     * @param value value to be associated with the specified key
1010 >     * @return the previous value associated with {@code key}, or
1011 >     *         {@code null} if there was no mapping for {@code key}
1012 >     * @throws NullPointerException if the specified key or value is null
1013 >     */
1014 >    public V put(K key, V value) {
1015 >        return putVal(key, value, false);
1016 >    }
1017 >
1018 >    /** Implementation for put and putIfAbsent */
1019 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
1020 >        if (key == null || value == null) throw new NullPointerException();
1021 >        int hash = spread(key.hashCode());
1022 >        int binCount = 0;
1023 >        for (Node<K,V>[] tab = table;;) {
1024 >            Node<K,V> f; int n, i, fh;
1025 >            if (tab == null || (n = tab.length) == 0)
1026 >                tab = initTable();
1027 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1028 >                if (casTabAt(tab, i, null,
1029 >                             new Node<K,V>(hash, key, value, null)))
1030 >                    break;                   // no lock when adding to empty bin
1031 >            }
1032 >            else if ((fh = f.hash) == MOVED)
1033 >                tab = helpTransfer(tab, f);
1034 >            else {
1035 >                V oldVal = null;
1036 >                synchronized (f) {
1037 >                    if (tabAt(tab, i) == f) {
1038 >                        if (fh >= 0) {
1039 >                            binCount = 1;
1040 >                            for (Node<K,V> e = f;; ++binCount) {
1041 >                                K ek;
1042 >                                if (e.hash == hash &&
1043 >                                    ((ek = e.key) == key ||
1044 >                                     (ek != null && key.equals(ek)))) {
1045 >                                    oldVal = e.val;
1046 >                                    if (!onlyIfAbsent)
1047 >                                        e.val = value;
1048 >                                    break;
1049 >                                }
1050 >                                Node<K,V> pred = e;
1051 >                                if ((e = e.next) == null) {
1052 >                                    pred.next = new Node<K,V>(hash, key,
1053 >                                                              value, null);
1054 >                                    break;
1055 >                                }
1056 >                            }
1057 >                        }
1058 >                        else if (f instanceof TreeBin) {
1059 >                            Node<K,V> p;
1060 >                            binCount = 2;
1061 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1062 >                                                           value)) != null) {
1063 >                                oldVal = p.val;
1064 >                                if (!onlyIfAbsent)
1065 >                                    p.val = value;
1066 >                            }
1067 >                        }
1068                      }
863                    break;
1069                  }
1070 <                else if (e.hash == h && k.equals(e.key)) {
1071 <                    r = e;
1070 >                if (binCount != 0) {
1071 >                    if (binCount >= TREEIFY_THRESHOLD)
1072 >                        treeifyBin(tab, i);
1073 >                    if (oldVal != null)
1074 >                        return oldVal;
1075                      break;
1076                  }
869                else
870                    c = getState();
1077              }
872            return r == null ? null : r.val;
1078          }
1079 +        addCount(1L, binCount);
1080 +        return null;
1081 +    }
1082  
1083 <        /**
1084 <         * Finds or adds a node.
1085 <         * @return null if added
1086 <         */
1087 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
1088 <            (int h, Object k, Object v) {
1089 <            Class<?> c = k.getClass();
1090 <            TreeNode pp = root, p = null;
1091 <            int dir = 0;
1092 <            while (pp != null) { // find existing node or leaf to insert at
1093 <                int ph;  Object pk; Class<?> pc;
1094 <                p = pp;
887 <                if ((ph = p.hash) == h) {
888 <                    if ((pk = p.key) == k || k.equals(pk))
889 <                        return p;
890 <                    if (c != (pc = pk.getClass()) ||
891 <                        !(k instanceof Comparable) ||
892 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
893 <                        TreeNode s = null, r = null, pr;
894 <                        if ((dir = (c == pc) ? 0 :
895 <                             c.getName().compareTo(pc.getName())) == 0) {
896 <                            if ((pr = p.right) != null && h >= pr.hash &&
897 <                                (r = getTreeNode(h, k, pr)) != null)
898 <                                return r;
899 <                            else // continue left
900 <                                dir = -1;
901 <                        }
902 <                        else if ((pr = p.right) != null && h >= pr.hash)
903 <                            s = pr;
904 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
905 <                            return r;
906 <                    }
907 <                }
908 <                else
909 <                    dir = (h < ph) ? -1 : 1;
910 <                pp = (dir > 0) ? p.right : p.left;
911 <            }
1083 >    /**
1084 >     * Copies all of the mappings from the specified map to this one.
1085 >     * These mappings replace any mappings that this map had for any of the
1086 >     * keys currently in the specified map.
1087 >     *
1088 >     * @param m mappings to be stored in this map
1089 >     */
1090 >    public void putAll(Map<? extends K, ? extends V> m) {
1091 >        tryPresize(m.size());
1092 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1093 >            putVal(e.getKey(), e.getValue(), false);
1094 >    }
1095  
1096 <            TreeNode f = first;
1097 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
1098 <            if (p == null)
1099 <                root = x;
1100 <            else { // attach and rebalance; adapted from CLR
1101 <                TreeNode xp, xpp;
1102 <                if (f != null)
1103 <                    f.prev = x;
1104 <                if (dir <= 0)
1105 <                    p.left = x;
1106 <                else
1107 <                    p.right = x;
1108 <                x.red = true;
1109 <                while (x != null && (xp = x.parent) != null && xp.red &&
1110 <                       (xpp = xp.parent) != null) {
1111 <                    TreeNode xppl = xpp.left;
1112 <                    if (xp == xppl) {
1113 <                        TreeNode y = xpp.right;
1114 <                        if (y != null && y.red) {
1115 <                            y.red = false;
1116 <                            xp.red = false;
1117 <                            xpp.red = true;
1118 <                            x = xpp;
1119 <                        }
1120 <                        else {
1121 <                            if (x == xp.right) {
1122 <                                rotateLeft(x = xp);
1123 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1124 <                            }
1125 <                            if (xp != null) {
1126 <                                xp.red = false;
1127 <                                if (xpp != null) {
1128 <                                    xpp.red = true;
1129 <                                    rotateRight(xpp);
1096 >    /**
1097 >     * Removes the key (and its corresponding value) from this map.
1098 >     * This method does nothing if the key is not in the map.
1099 >     *
1100 >     * @param  key the key that needs to be removed
1101 >     * @return the previous value associated with {@code key}, or
1102 >     *         {@code null} if there was no mapping for {@code key}
1103 >     * @throws NullPointerException if the specified key is null
1104 >     */
1105 >    public V remove(Object key) {
1106 >        return replaceNode(key, null, null);
1107 >    }
1108 >
1109 >    /**
1110 >     * Implementation for the four public remove/replace methods:
1111 >     * Replaces node value with v, conditional upon match of cv if
1112 >     * non-null.  If resulting value is null, delete.
1113 >     */
1114 >    final V replaceNode(Object key, V value, Object cv) {
1115 >        int hash = spread(key.hashCode());
1116 >        for (Node<K,V>[] tab = table;;) {
1117 >            Node<K,V> f; int n, i, fh;
1118 >            if (tab == null || (n = tab.length) == 0 ||
1119 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1120 >                break;
1121 >            else if ((fh = f.hash) == MOVED)
1122 >                tab = helpTransfer(tab, f);
1123 >            else {
1124 >                V oldVal = null;
1125 >                boolean validated = false;
1126 >                synchronized (f) {
1127 >                    if (tabAt(tab, i) == f) {
1128 >                        if (fh >= 0) {
1129 >                            validated = true;
1130 >                            for (Node<K,V> e = f, pred = null;;) {
1131 >                                K ek;
1132 >                                if (e.hash == hash &&
1133 >                                    ((ek = e.key) == key ||
1134 >                                     (ek != null && key.equals(ek)))) {
1135 >                                    V ev = e.val;
1136 >                                    if (cv == null || cv == ev ||
1137 >                                        (ev != null && cv.equals(ev))) {
1138 >                                        oldVal = ev;
1139 >                                        if (value != null)
1140 >                                            e.val = value;
1141 >                                        else if (pred != null)
1142 >                                            pred.next = e.next;
1143 >                                        else
1144 >                                            setTabAt(tab, i, e.next);
1145 >                                    }
1146 >                                    break;
1147                                  }
1148 +                                pred = e;
1149 +                                if ((e = e.next) == null)
1150 +                                    break;
1151                              }
1152                          }
1153 <                    }
1154 <                    else {
1155 <                        TreeNode y = xppl;
1156 <                        if (y != null && y.red) {
1157 <                            y.red = false;
1158 <                            xp.red = false;
1159 <                            xpp.red = true;
1160 <                            x = xpp;
1161 <                        }
1162 <                        else {
1163 <                            if (x == xp.left) {
1164 <                                rotateRight(x = xp);
1165 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
1166 <                            }
964 <                            if (xp != null) {
965 <                                xp.red = false;
966 <                                if (xpp != null) {
967 <                                    xpp.red = true;
968 <                                    rotateLeft(xpp);
1153 >                        else if (f instanceof TreeBin) {
1154 >                            validated = true;
1155 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1156 >                            TreeNode<K,V> r, p;
1157 >                            if ((r = t.root) != null &&
1158 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1159 >                                V pv = p.val;
1160 >                                if (cv == null || cv == pv ||
1161 >                                    (pv != null && cv.equals(pv))) {
1162 >                                    oldVal = pv;
1163 >                                    if (value != null)
1164 >                                        p.val = value;
1165 >                                    else if (t.removeTreeNode(p))
1166 >                                        setTabAt(tab, i, untreeify(t.first));
1167                                  }
1168                              }
1169                          }
1170                      }
1171                  }
1172 <                TreeNode r = root;
1173 <                if (r != null && r.red)
1174 <                    r.red = false;
1175 <            }
1176 <            return null;
979 <        }
980 <
981 <        /**
982 <         * Removes the given node, that must be present before this
983 <         * call.  This is messier than typical red-black deletion code
984 <         * because we cannot swap the contents of an interior node
985 <         * with a leaf successor that is pinned by "next" pointers
986 <         * that are accessible independently of lock. So instead we
987 <         * swap the tree linkages.
988 <         */
989 <        final void deleteTreeNode(TreeNode p) {
990 <            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
991 <            TreeNode pred = p.prev;
992 <            if (pred == null)
993 <                first = next;
994 <            else
995 <                pred.next = next;
996 <            if (next != null)
997 <                next.prev = pred;
998 <            TreeNode replacement;
999 <            TreeNode pl = p.left;
1000 <            TreeNode pr = p.right;
1001 <            if (pl != null && pr != null) {
1002 <                TreeNode s = pr, sl;
1003 <                while ((sl = s.left) != null) // find successor
1004 <                    s = sl;
1005 <                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
1006 <                TreeNode sr = s.right;
1007 <                TreeNode pp = p.parent;
1008 <                if (s == pr) { // p was s's direct parent
1009 <                    p.parent = s;
1010 <                    s.right = p;
1011 <                }
1012 <                else {
1013 <                    TreeNode sp = s.parent;
1014 <                    if ((p.parent = sp) != null) {
1015 <                        if (s == sp.left)
1016 <                            sp.left = p;
1017 <                        else
1018 <                            sp.right = p;
1172 >                if (validated) {
1173 >                    if (oldVal != null) {
1174 >                        if (value == null)
1175 >                            addCount(-1L, -1);
1176 >                        return oldVal;
1177                      }
1178 <                    if ((s.right = pr) != null)
1021 <                        pr.parent = s;
1178 >                    break;
1179                  }
1023                p.left = null;
1024                if ((p.right = sr) != null)
1025                    sr.parent = p;
1026                if ((s.left = pl) != null)
1027                    pl.parent = s;
1028                if ((s.parent = pp) == null)
1029                    root = s;
1030                else if (p == pp.left)
1031                    pp.left = s;
1032                else
1033                    pp.right = s;
1034                replacement = sr;
1180              }
1181 <            else
1182 <                replacement = (pl != null) ? pl : pr;
1183 <            TreeNode pp = p.parent;
1184 <            if (replacement == null) {
1185 <                if (pp == null) {
1186 <                    root = null;
1187 <                    return;
1188 <                }
1189 <                replacement = p;
1181 >        }
1182 >        return null;
1183 >    }
1184 >
1185 >    /**
1186 >     * Removes all of the mappings from this map.
1187 >     */
1188 >    public void clear() {
1189 >        long delta = 0L; // negative number of deletions
1190 >        int i = 0;
1191 >        Node<K,V>[] tab = table;
1192 >        while (tab != null && i < tab.length) {
1193 >            int fh;
1194 >            Node<K,V> f = tabAt(tab, i);
1195 >            if (f == null)
1196 >                ++i;
1197 >            else if ((fh = f.hash) == MOVED) {
1198 >                tab = helpTransfer(tab, f);
1199 >                i = 0; // restart
1200              }
1201              else {
1202 <                replacement.parent = pp;
1203 <                if (pp == null)
1204 <                    root = replacement;
1205 <                else if (p == pp.left)
1206 <                    pp.left = replacement;
1207 <                else
1208 <                    pp.right = replacement;
1209 <                p.left = p.right = p.parent = null;
1055 <            }
1056 <            if (!p.red) { // rebalance, from CLR
1057 <                TreeNode x = replacement;
1058 <                while (x != null) {
1059 <                    TreeNode xp, xpl;
1060 <                    if (x.red || (xp = x.parent) == null) {
1061 <                        x.red = false;
1062 <                        break;
1063 <                    }
1064 <                    if (x == (xpl = xp.left)) {
1065 <                        TreeNode sib = xp.right;
1066 <                        if (sib != null && sib.red) {
1067 <                            sib.red = false;
1068 <                            xp.red = true;
1069 <                            rotateLeft(xp);
1070 <                            sib = (xp = x.parent) == null ? null : xp.right;
1071 <                        }
1072 <                        if (sib == null)
1073 <                            x = xp;
1074 <                        else {
1075 <                            TreeNode sl = sib.left, sr = sib.right;
1076 <                            if ((sr == null || !sr.red) &&
1077 <                                (sl == null || !sl.red)) {
1078 <                                sib.red = true;
1079 <                                x = xp;
1080 <                            }
1081 <                            else {
1082 <                                if (sr == null || !sr.red) {
1083 <                                    if (sl != null)
1084 <                                        sl.red = false;
1085 <                                    sib.red = true;
1086 <                                    rotateRight(sib);
1087 <                                    sib = (xp = x.parent) == null ?
1088 <                                        null : xp.right;
1089 <                                }
1090 <                                if (sib != null) {
1091 <                                    sib.red = (xp == null) ? false : xp.red;
1092 <                                    if ((sr = sib.right) != null)
1093 <                                        sr.red = false;
1094 <                                }
1095 <                                if (xp != null) {
1096 <                                    xp.red = false;
1097 <                                    rotateLeft(xp);
1098 <                                }
1099 <                                x = root;
1100 <                            }
1101 <                        }
1102 <                    }
1103 <                    else { // symmetric
1104 <                        TreeNode sib = xpl;
1105 <                        if (sib != null && sib.red) {
1106 <                            sib.red = false;
1107 <                            xp.red = true;
1108 <                            rotateRight(xp);
1109 <                            sib = (xp = x.parent) == null ? null : xp.left;
1110 <                        }
1111 <                        if (sib == null)
1112 <                            x = xp;
1113 <                        else {
1114 <                            TreeNode sl = sib.left, sr = sib.right;
1115 <                            if ((sl == null || !sl.red) &&
1116 <                                (sr == null || !sr.red)) {
1117 <                                sib.red = true;
1118 <                                x = xp;
1119 <                            }
1120 <                            else {
1121 <                                if (sl == null || !sl.red) {
1122 <                                    if (sr != null)
1123 <                                        sr.red = false;
1124 <                                    sib.red = true;
1125 <                                    rotateLeft(sib);
1126 <                                    sib = (xp = x.parent) == null ?
1127 <                                        null : xp.left;
1128 <                                }
1129 <                                if (sib != null) {
1130 <                                    sib.red = (xp == null) ? false : xp.red;
1131 <                                    if ((sl = sib.left) != null)
1132 <                                        sl.red = false;
1133 <                                }
1134 <                                if (xp != null) {
1135 <                                    xp.red = false;
1136 <                                    rotateRight(xp);
1137 <                                }
1138 <                                x = root;
1139 <                            }
1202 >                synchronized (f) {
1203 >                    if (tabAt(tab, i) == f) {
1204 >                        Node<K,V> p = (fh >= 0 ? f :
1205 >                                       (f instanceof TreeBin) ?
1206 >                                       ((TreeBin<K,V>)f).first : null);
1207 >                        while (p != null) {
1208 >                            --delta;
1209 >                            p = p.next;
1210                          }
1211 +                        setTabAt(tab, i++, null);
1212                      }
1213                  }
1214              }
1144            if (p == replacement && (pp = p.parent) != null) {
1145                if (p == pp.left) // detach pointers
1146                    pp.left = null;
1147                else if (p == pp.right)
1148                    pp.right = null;
1149                p.parent = null;
1150            }
1215          }
1216 +        if (delta != 0L)
1217 +            addCount(delta, -1);
1218      }
1219  
1220 <    /* ---------------- Collision reduction methods -------------- */
1220 >    /**
1221 >     * Returns a {@link Set} view of the keys contained in this map.
1222 >     * The set is backed by the map, so changes to the map are
1223 >     * reflected in the set, and vice-versa. The set supports element
1224 >     * removal, which removes the corresponding mapping from this map,
1225 >     * via the {@code Iterator.remove}, {@code Set.remove},
1226 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1227 >     * operations.  It does not support the {@code add} or
1228 >     * {@code addAll} operations.
1229 >     *
1230 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1231 >     * that will never throw {@link ConcurrentModificationException},
1232 >     * and guarantees to traverse elements as they existed upon
1233 >     * construction of the iterator, and may (but is not guaranteed to)
1234 >     * reflect any modifications subsequent to construction.
1235 >     *
1236 >     * @return the set view
1237 >     */
1238 >    public KeySetView<K,V> keySet() {
1239 >        KeySetView<K,V> ks;
1240 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1241 >    }
1242  
1243      /**
1244 <     * Spreads higher bits to lower, and also forces top bit to 0.
1245 <     * Because the table uses power-of-two masking, sets of hashes
1246 <     * that vary only in bits above the current mask will always
1247 <     * collide. (Among known examples are sets of Float keys holding
1248 <     * consecutive whole numbers in small tables.)  To counter this,
1249 <     * we apply a transform that spreads the impact of higher bits
1250 <     * downward. There is a tradeoff between speed, utility, and
1251 <     * quality of bit-spreading. Because many common sets of hashes
1252 <     * are already reasonably distributed across bits (so don't benefit
1253 <     * from spreading), and because we use trees to handle large sets
1254 <     * of collisions in bins, we don't need excessively high quality.
1244 >     * Returns a {@link Collection} view of the values contained in this map.
1245 >     * The collection is backed by the map, so changes to the map are
1246 >     * reflected in the collection, and vice-versa.  The collection
1247 >     * supports element removal, which removes the corresponding
1248 >     * mapping from this map, via the {@code Iterator.remove},
1249 >     * {@code Collection.remove}, {@code removeAll},
1250 >     * {@code retainAll}, and {@code clear} operations.  It does not
1251 >     * support the {@code add} or {@code addAll} operations.
1252 >     *
1253 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1254 >     * that will never throw {@link ConcurrentModificationException},
1255 >     * and guarantees to traverse elements as they existed upon
1256 >     * construction of the iterator, and may (but is not guaranteed to)
1257 >     * reflect any modifications subsequent to construction.
1258 >     *
1259 >     * @return the collection view
1260 >     */
1261 >    public Collection<V> values() {
1262 >        ValuesView<K,V> vs;
1263 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1264 >    }
1265 >
1266 >    /**
1267 >     * Returns a {@link Set} view of the mappings contained in this map.
1268 >     * The set is backed by the map, so changes to the map are
1269 >     * reflected in the set, and vice-versa.  The set supports element
1270 >     * removal, which removes the corresponding mapping from the map,
1271 >     * via the {@code Iterator.remove}, {@code Set.remove},
1272 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
1273 >     * operations.
1274 >     *
1275 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1276 >     * that will never throw {@link ConcurrentModificationException},
1277 >     * and guarantees to traverse elements as they existed upon
1278 >     * construction of the iterator, and may (but is not guaranteed to)
1279 >     * reflect any modifications subsequent to construction.
1280 >     *
1281 >     * @return the set view
1282 >     */
1283 >    public Set<Map.Entry<K,V>> entrySet() {
1284 >        EntrySetView<K,V> es;
1285 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1286 >    }
1287 >
1288 >    /**
1289 >     * Returns the hash code value for this {@link Map}, i.e.,
1290 >     * the sum of, for each key-value pair in the map,
1291 >     * {@code key.hashCode() ^ value.hashCode()}.
1292 >     *
1293 >     * @return the hash code value for this map
1294 >     */
1295 >    public int hashCode() {
1296 >        int h = 0;
1297 >        Node<K,V>[] t;
1298 >        if ((t = table) != null) {
1299 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1300 >            for (Node<K,V> p; (p = it.advance()) != null; )
1301 >                h += p.key.hashCode() ^ p.val.hashCode();
1302 >        }
1303 >        return h;
1304 >    }
1305 >
1306 >    /**
1307 >     * Returns a string representation of this map.  The string
1308 >     * representation consists of a list of key-value mappings (in no
1309 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
1310 >     * mappings are separated by the characters {@code ", "} (comma
1311 >     * and space).  Each key-value mapping is rendered as the key
1312 >     * followed by an equals sign ("{@code =}") followed by the
1313 >     * associated value.
1314 >     *
1315 >     * @return a string representation of this map
1316       */
1317 <    private static final int spread(int h) {
1318 <        h ^= (h >>> 18) ^ (h >>> 12);
1319 <        return (h ^ (h >>> 10)) & HASH_BITS;
1317 >    public String toString() {
1318 >        Node<K,V>[] t;
1319 >        int f = (t = table) == null ? 0 : t.length;
1320 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1321 >        StringBuilder sb = new StringBuilder();
1322 >        sb.append('{');
1323 >        Node<K,V> p;
1324 >        if ((p = it.advance()) != null) {
1325 >            for (;;) {
1326 >                K k = p.key;
1327 >                V v = p.val;
1328 >                sb.append(k == this ? "(this Map)" : k);
1329 >                sb.append('=');
1330 >                sb.append(v == this ? "(this Map)" : v);
1331 >                if ((p = it.advance()) == null)
1332 >                    break;
1333 >                sb.append(',').append(' ');
1334 >            }
1335 >        }
1336 >        return sb.append('}').toString();
1337      }
1338  
1339      /**
1340 <     * Replaces a list bin with a tree bin if key is comparable.  Call
1341 <     * only when locked.
1340 >     * Compares the specified object with this map for equality.
1341 >     * Returns {@code true} if the given object is a map with the same
1342 >     * mappings as this map.  This operation may return misleading
1343 >     * results if either map is concurrently modified during execution
1344 >     * of this method.
1345 >     *
1346 >     * @param o object to be compared for equality with this map
1347 >     * @return {@code true} if the specified object is equal to this map
1348       */
1349 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1350 <        if (key instanceof Comparable) {
1351 <            TreeBin t = new TreeBin();
1352 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1353 <                t.putTreeNode(e.hash, e.key, e.val);
1354 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
1349 >    public boolean equals(Object o) {
1350 >        if (o != this) {
1351 >            if (!(o instanceof Map))
1352 >                return false;
1353 >            Map<?,?> m = (Map<?,?>) o;
1354 >            Node<K,V>[] t;
1355 >            int f = (t = table) == null ? 0 : t.length;
1356 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1357 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1358 >                V val = p.val;
1359 >                Object v = m.get(p.key);
1360 >                if (v == null || (v != val && !v.equals(val)))
1361 >                    return false;
1362 >            }
1363 >            for (Map.Entry<?,?> e : m.entrySet()) {
1364 >                Object mk, mv, v;
1365 >                if ((mk = e.getKey()) == null ||
1366 >                    (mv = e.getValue()) == null ||
1367 >                    (v = get(mk)) == null ||
1368 >                    (mv != v && !mv.equals(v)))
1369 >                    return false;
1370 >            }
1371          }
1372 +        return true;
1373      }
1374  
1375 <    /* ---------------- Internal access and update methods -------------- */
1375 >    /**
1376 >     * Stripped-down version of helper class used in previous version,
1377 >     * declared for the sake of serialization compatibility
1378 >     */
1379 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1380 >        private static final long serialVersionUID = 2249069246763182397L;
1381 >        final float loadFactor;
1382 >        Segment(float lf) { this.loadFactor = lf; }
1383 >    }
1384  
1385 <    /** Implementation for get and containsKey */
1386 <    @SuppressWarnings("unchecked") private final V internalGet(Object k) {
1387 <        int h = spread(k.hashCode());
1388 <        retry: for (Node[] tab = table; tab != null;) {
1389 <            Node e; Object ek, ev; int eh;      // locals to read fields once
1390 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1391 <                if ((eh = e.hash) < 0) {
1392 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1393 <                        return (V)((TreeBin)ek).getValue(h, k);
1394 <                    else {                        // restart with new table
1395 <                        tab = (Node[])ek;
1396 <                        continue retry;
1397 <                    }
1398 <                }
1399 <                else if (eh == h && (ev = e.val) != null &&
1400 <                         ((ek = e.key) == k || k.equals(ek)))
1401 <                    return (V)ev;
1385 >    /**
1386 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1387 >     * stream (i.e., serializes it).
1388 >     * @param s the stream
1389 >     * @throws java.io.IOException if an I/O error occurs
1390 >     * @serialData
1391 >     * the key (Object) and value (Object)
1392 >     * for each key-value mapping, followed by a null pair.
1393 >     * The key-value mappings are emitted in no particular order.
1394 >     */
1395 >    private void writeObject(java.io.ObjectOutputStream s)
1396 >        throws java.io.IOException {
1397 >        // For serialization compatibility
1398 >        // Emulate segment calculation from previous version of this class
1399 >        int sshift = 0;
1400 >        int ssize = 1;
1401 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1402 >            ++sshift;
1403 >            ssize <<= 1;
1404 >        }
1405 >        int segmentShift = 32 - sshift;
1406 >        int segmentMask = ssize - 1;
1407 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1408 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1409 >        for (int i = 0; i < segments.length; ++i)
1410 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1411 >        s.putFields().put("segments", segments);
1412 >        s.putFields().put("segmentShift", segmentShift);
1413 >        s.putFields().put("segmentMask", segmentMask);
1414 >        s.writeFields();
1415 >
1416 >        Node<K,V>[] t;
1417 >        if ((t = table) != null) {
1418 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1419 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1420 >                s.writeObject(p.key);
1421 >                s.writeObject(p.val);
1422              }
1207            break;
1423          }
1424 <        return null;
1424 >        s.writeObject(null);
1425 >        s.writeObject(null);
1426 >        segments = null; // throw away
1427      }
1428  
1429      /**
1430 <     * Implementation for the four public remove/replace methods:
1431 <     * Replaces node value with v, conditional upon match of cv if
1432 <     * non-null.  If resulting value is null, delete.
1430 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1431 >     * @param s the stream
1432 >     * @throws ClassNotFoundException if the class of a serialized object
1433 >     *         could not be found
1434 >     * @throws java.io.IOException if an I/O error occurs
1435       */
1436 <    @SuppressWarnings("unchecked") private final V internalReplace
1437 <        (Object k, V v, Object cv) {
1438 <        int h = spread(k.hashCode());
1439 <        Object oldVal = null;
1440 <        for (Node[] tab = table;;) {
1441 <            Node f; int i, fh; Object fk;
1442 <            if (tab == null ||
1443 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1444 <                break;
1445 <            else if ((fh = f.hash) < 0) {
1446 <                if ((fk = f.key) instanceof TreeBin) {
1447 <                    TreeBin t = (TreeBin)fk;
1448 <                    boolean validated = false;
1449 <                    boolean deleted = false;
1450 <                    t.acquire(0);
1451 <                    try {
1452 <                        if (tabAt(tab, i) == f) {
1453 <                            validated = true;
1454 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1236 <                            if (p != null) {
1237 <                                Object pv = p.val;
1238 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1239 <                                    oldVal = pv;
1240 <                                    if ((p.val = v) == null) {
1241 <                                        deleted = true;
1242 <                                        t.deleteTreeNode(p);
1243 <                                    }
1244 <                                }
1245 <                            }
1246 <                        }
1247 <                    } finally {
1248 <                        t.release(0);
1249 <                    }
1250 <                    if (validated) {
1251 <                        if (deleted)
1252 <                            addCount(-1L, -1);
1253 <                        break;
1254 <                    }
1255 <                }
1256 <                else
1257 <                    tab = (Node[])fk;
1436 >    private void readObject(java.io.ObjectInputStream s)
1437 >        throws java.io.IOException, ClassNotFoundException {
1438 >        /*
1439 >         * To improve performance in typical cases, we create nodes
1440 >         * while reading, then place in table once size is known.
1441 >         * However, we must also validate uniqueness and deal with
1442 >         * overpopulated bins while doing so, which requires
1443 >         * specialized versions of putVal mechanics.
1444 >         */
1445 >        sizeCtl = -1; // force exclusion for table construction
1446 >        s.defaultReadObject();
1447 >        long size = 0L;
1448 >        Node<K,V> p = null;
1449 >        for (;;) {
1450 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1451 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1452 >            if (k != null && v != null) {
1453 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1454 >                ++size;
1455              }
1456 <            else if (fh != h && f.next == null) // precheck
1457 <                break;                          // rules out possible existence
1456 >            else
1457 >                break;
1458 >        }
1459 >        if (size == 0L)
1460 >            sizeCtl = 0;
1461 >        else {
1462 >            int n;
1463 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1464 >                n = MAXIMUM_CAPACITY;
1465              else {
1466 <                boolean validated = false;
1467 <                boolean deleted = false;
1468 <                synchronized(f) {
1469 <                    if (tabAt(tab, i) == f) {
1470 <                        validated = true;
1471 <                        for (Node e = f, pred = null;;) {
1472 <                            Object ek, ev;
1473 <                            if (e.hash == h &&
1474 <                                ((ev = e.val) != null) &&
1475 <                                ((ek = e.key) == k || k.equals(ek))) {
1476 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1477 <                                    oldVal = ev;
1478 <                                    if ((e.val = v) == null) {
1479 <                                        deleted = true;
1480 <                                        Node en = e.next;
1481 <                                        if (pred != null)
1482 <                                            pred.next = en;
1483 <                                        else
1484 <                                            setTabAt(tab, i, en);
1485 <                                    }
1486 <                                }
1466 >                int sz = (int)size;
1467 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1468 >            }
1469 >            @SuppressWarnings("unchecked")
1470 >                Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1471 >            int mask = n - 1;
1472 >            long added = 0L;
1473 >            while (p != null) {
1474 >                boolean insertAtFront;
1475 >                Node<K,V> next = p.next, first;
1476 >                int h = p.hash, j = h & mask;
1477 >                if ((first = tabAt(tab, j)) == null)
1478 >                    insertAtFront = true;
1479 >                else {
1480 >                    K k = p.key;
1481 >                    if (first.hash < 0) {
1482 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1483 >                        if (t.putTreeVal(h, k, p.val) == null)
1484 >                            ++added;
1485 >                        insertAtFront = false;
1486 >                    }
1487 >                    else {
1488 >                        int binCount = 0;
1489 >                        insertAtFront = true;
1490 >                        Node<K,V> q; K qk;
1491 >                        for (q = first; q != null; q = q.next) {
1492 >                            if (q.hash == h &&
1493 >                                ((qk = q.key) == k ||
1494 >                                 (qk != null && k.equals(qk)))) {
1495 >                                insertAtFront = false;
1496                                  break;
1497                              }
1498 <                            pred = e;
1499 <                            if ((e = e.next) == null)
1500 <                                break;
1498 >                            ++binCount;
1499 >                        }
1500 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1501 >                            insertAtFront = false;
1502 >                            ++added;
1503 >                            p.next = first;
1504 >                            TreeNode<K,V> hd = null, tl = null;
1505 >                            for (q = p; q != null; q = q.next) {
1506 >                                TreeNode<K,V> t = new TreeNode<K,V>
1507 >                                    (q.hash, q.key, q.val, null, null);
1508 >                                if ((t.prev = tl) == null)
1509 >                                    hd = t;
1510 >                                else
1511 >                                    tl.next = t;
1512 >                                tl = t;
1513 >                            }
1514 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1515                          }
1516                      }
1517                  }
1518 <                if (validated) {
1519 <                    if (deleted)
1520 <                        addCount(-1L, -1);
1521 <                    break;
1518 >                if (insertAtFront) {
1519 >                    ++added;
1520 >                    p.next = first;
1521 >                    setTabAt(tab, j, p);
1522                  }
1523 +                p = next;
1524              }
1525 +            table = tab;
1526 +            sizeCtl = n - (n >>> 2);
1527 +            baseCount = added;
1528          }
1298        return (V)oldVal;
1529      }
1530  
1531 <    /*
1532 <     * Internal versions of insertion methods
1533 <     * All have the same basic structure as the first (internalPut):
1534 <     *  1. If table uninitialized, create
1535 <     *  2. If bin empty, try to CAS new node
1536 <     *  3. If bin stale, use new table
1537 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1538 <     *  5. Lock and validate; if valid, scan and add or update
1309 <     *
1310 <     * The putAll method differs mainly in attempting to pre-allocate
1311 <     * enough table space, and also more lazily performs count updates
1312 <     * and checks.
1313 <     *
1314 <     * Most of the function-accepting methods can't be factored nicely
1315 <     * because they require different functional forms, so instead
1316 <     * sprawl out similar mechanics.
1531 >    // ConcurrentMap methods
1532 >
1533 >    /**
1534 >     * {@inheritDoc}
1535 >     *
1536 >     * @return the previous value associated with the specified key,
1537 >     *         or {@code null} if there was no mapping for the key
1538 >     * @throws NullPointerException if the specified key or value is null
1539       */
1540 +    public V putIfAbsent(K key, V value) {
1541 +        return putVal(key, value, true);
1542 +    }
1543  
1544 <    /** Implementation for put and putIfAbsent */
1545 <    @SuppressWarnings("unchecked") private final V internalPut
1546 <        (K k, V v, boolean onlyIfAbsent) {
1547 <        if (k == null || v == null) throw new NullPointerException();
1548 <        int h = spread(k.hashCode());
1549 <        int len = 0;
1550 <        for (Node[] tab = table;;) {
1551 <            int i, fh; Node f; Object fk, fv;
1552 <            if (tab == null)
1553 <                tab = initTable();
1554 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1555 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1556 <                    break;                   // no lock when adding to empty bin
1544 >    /**
1545 >     * {@inheritDoc}
1546 >     *
1547 >     * @throws NullPointerException if the specified key is null
1548 >     */
1549 >    public boolean remove(Object key, Object value) {
1550 >        if (key == null)
1551 >            throw new NullPointerException();
1552 >        return value != null && replaceNode(key, null, value) != null;
1553 >    }
1554 >
1555 >    /**
1556 >     * {@inheritDoc}
1557 >     *
1558 >     * @throws NullPointerException if any of the arguments are null
1559 >     */
1560 >    public boolean replace(K key, V oldValue, V newValue) {
1561 >        if (key == null || oldValue == null || newValue == null)
1562 >            throw new NullPointerException();
1563 >        return replaceNode(key, newValue, oldValue) != null;
1564 >    }
1565 >
1566 >    /**
1567 >     * {@inheritDoc}
1568 >     *
1569 >     * @return the previous value associated with the specified key,
1570 >     *         or {@code null} if there was no mapping for the key
1571 >     * @throws NullPointerException if the specified key or value is null
1572 >     */
1573 >    public V replace(K key, V value) {
1574 >        if (key == null || value == null)
1575 >            throw new NullPointerException();
1576 >        return replaceNode(key, value, null);
1577 >    }
1578 >
1579 >    // Overrides of JDK8+ Map extension method defaults
1580 >
1581 >    /**
1582 >     * Returns the value to which the specified key is mapped, or the
1583 >     * given default value if this map contains no mapping for the
1584 >     * key.
1585 >     *
1586 >     * @param key the key whose associated value is to be returned
1587 >     * @param defaultValue the value to return if this map contains
1588 >     * no mapping for the given key
1589 >     * @return the mapping for the key, if present; else the default value
1590 >     * @throws NullPointerException if the specified key is null
1591 >     */
1592 >    public V getOrDefault(Object key, V defaultValue) {
1593 >        V v;
1594 >        return (v = get(key)) == null ? defaultValue : v;
1595 >    }
1596 >
1597 >    public void forEach(BiAction<? super K, ? super V> action) {
1598 >        if (action == null) throw new NullPointerException();
1599 >        Node<K,V>[] t;
1600 >        if ((t = table) != null) {
1601 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1602 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1603 >                action.apply(p.key, p.val);
1604              }
1605 <            else if ((fh = f.hash) < 0) {
1606 <                if ((fk = f.key) instanceof TreeBin) {
1607 <                    TreeBin t = (TreeBin)fk;
1608 <                    Object oldVal = null;
1609 <                    t.acquire(0);
1610 <                    try {
1611 <                        if (tabAt(tab, i) == f) {
1612 <                            len = 2;
1613 <                            TreeNode p = t.putTreeNode(h, k, v);
1614 <                            if (p != null) {
1615 <                                oldVal = p.val;
1616 <                                if (!onlyIfAbsent)
1617 <                                    p.val = v;
1618 <                            }
1619 <                        }
1620 <                    } finally {
1349 <                        t.release(0);
1350 <                    }
1351 <                    if (len != 0) {
1352 <                        if (oldVal != null)
1353 <                            return (V)oldVal;
1605 >        }
1606 >    }
1607 >
1608 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1609 >        if (function == null) throw new NullPointerException();
1610 >        Node<K,V>[] t;
1611 >        if ((t = table) != null) {
1612 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1613 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1614 >                V oldValue = p.val;
1615 >                for (K key = p.key;;) {
1616 >                    V newValue = function.apply(key, oldValue);
1617 >                    if (newValue == null)
1618 >                        throw new NullPointerException();
1619 >                    if (replaceNode(key, newValue, oldValue) != null ||
1620 >                        (oldValue = get(key)) == null)
1621                          break;
1355                    }
1356                }
1357                else
1358                    tab = (Node[])fk;
1359            }
1360            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1361                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1362                return (V)fv;
1363            else {
1364                Object oldVal = null;
1365                synchronized(f) {
1366                    if (tabAt(tab, i) == f) {
1367                        len = 1;
1368                        for (Node e = f;; ++len) {
1369                            Object ek, ev;
1370                            if (e.hash == h &&
1371                                (ev = e.val) != null &&
1372                                ((ek = e.key) == k || k.equals(ek))) {
1373                                oldVal = ev;
1374                                if (!onlyIfAbsent)
1375                                    e.val = v;
1376                                break;
1377                            }
1378                            Node last = e;
1379                            if ((e = e.next) == null) {
1380                                last.next = new Node(h, k, v, null);
1381                                if (len >= TREE_THRESHOLD)
1382                                    replaceWithTreeBin(tab, i, k);
1383                                break;
1384                            }
1385                        }
1386                    }
1387                }
1388                if (len != 0) {
1389                    if (oldVal != null)
1390                        return (V)oldVal;
1391                    break;
1622                  }
1623              }
1624          }
1395        addCount(1L, len);
1396        return null;
1625      }
1626  
1627 <    /** Implementation for computeIfAbsent */
1628 <    @SuppressWarnings("unchecked") private final V internalComputeIfAbsent
1629 <        (K k, Fun<? super K, ?> mf) {
1630 <        if (k == null || mf == null)
1627 >    /**
1628 >     * If the specified key is not already associated with a value,
1629 >     * attempts to compute its value using the given mapping function
1630 >     * and enters it into this map unless {@code null}.  The entire
1631 >     * method invocation is performed atomically, so the function is
1632 >     * applied at most once per key.  Some attempted update operations
1633 >     * on this map by other threads may be blocked while computation
1634 >     * is in progress, so the computation should be short and simple,
1635 >     * and must not attempt to update any other mappings of this map.
1636 >     *
1637 >     * @param key key with which the specified value is to be associated
1638 >     * @param mappingFunction the function to compute a value
1639 >     * @return the current (existing or computed) value associated with
1640 >     *         the specified key, or null if the computed value is null
1641 >     * @throws NullPointerException if the specified key or mappingFunction
1642 >     *         is null
1643 >     * @throws IllegalStateException if the computation detectably
1644 >     *         attempts a recursive update to this map that would
1645 >     *         otherwise never complete
1646 >     * @throws RuntimeException or Error if the mappingFunction does so,
1647 >     *         in which case the mapping is left unestablished
1648 >     */
1649 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1650 >        if (key == null || mappingFunction == null)
1651              throw new NullPointerException();
1652 <        int h = spread(k.hashCode());
1653 <        Object val = null;
1654 <        int len = 0;
1655 <        for (Node[] tab = table;;) {
1656 <            Node f; int i; Object fk;
1657 <            if (tab == null)
1652 >        int h = spread(key.hashCode());
1653 >        V val = null;
1654 >        int binCount = 0;
1655 >        for (Node<K,V>[] tab = table;;) {
1656 >            Node<K,V> f; int n, i, fh;
1657 >            if (tab == null || (n = tab.length) == 0)
1658                  tab = initTable();
1659 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1660 <                Node node = new Node(h, k, null, null);
1661 <                synchronized(node) {
1662 <                    if (casTabAt(tab, i, null, node)) {
1663 <                        len = 1;
1659 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1660 >                Node<K,V> r = new ReservationNode<K,V>();
1661 >                synchronized (r) {
1662 >                    if (casTabAt(tab, i, null, r)) {
1663 >                        binCount = 1;
1664 >                        Node<K,V> node = null;
1665                          try {
1666 <                            if ((val = mf.apply(k)) != null)
1667 <                                node.val = val;
1666 >                            if ((val = mappingFunction.apply(key)) != null)
1667 >                                node = new Node<K,V>(h, key, val, null);
1668                          } finally {
1669 <                            if (val == null)
1421 <                                setTabAt(tab, i, null);
1669 >                            setTabAt(tab, i, node);
1670                          }
1671                      }
1672                  }
1673 <                if (len != 0)
1673 >                if (binCount != 0)
1674                      break;
1675              }
1676 <            else if (f.hash < 0) {
1677 <                if ((fk = f.key) instanceof TreeBin) {
1678 <                    TreeBin t = (TreeBin)fk;
1679 <                    boolean added = false;
1680 <                    t.acquire(0);
1681 <                    try {
1682 <                        if (tabAt(tab, i) == f) {
1683 <                            len = 1;
1684 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1685 <                            if (p != null)
1676 >            else if ((fh = f.hash) == MOVED)
1677 >                tab = helpTransfer(tab, f);
1678 >            else {
1679 >                boolean added = false;
1680 >                synchronized (f) {
1681 >                    if (tabAt(tab, i) == f) {
1682 >                        if (fh >= 0) {
1683 >                            binCount = 1;
1684 >                            for (Node<K,V> e = f;; ++binCount) {
1685 >                                K ek; V ev;
1686 >                                if (e.hash == h &&
1687 >                                    ((ek = e.key) == key ||
1688 >                                     (ek != null && key.equals(ek)))) {
1689 >                                    val = e.val;
1690 >                                    break;
1691 >                                }
1692 >                                Node<K,V> pred = e;
1693 >                                if ((e = e.next) == null) {
1694 >                                    if ((val = mappingFunction.apply(key)) != null) {
1695 >                                        added = true;
1696 >                                        pred.next = new Node<K,V>(h, key, val, null);
1697 >                                    }
1698 >                                    break;
1699 >                                }
1700 >                            }
1701 >                        }
1702 >                        else if (f instanceof TreeBin) {
1703 >                            binCount = 2;
1704 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1705 >                            TreeNode<K,V> r, p;
1706 >                            if ((r = t.root) != null &&
1707 >                                (p = r.findTreeNode(h, key, null)) != null)
1708                                  val = p.val;
1709 <                            else if ((val = mf.apply(k)) != null) {
1709 >                            else if ((val = mappingFunction.apply(key)) != null) {
1710                                  added = true;
1711 <                                len = 2;
1442 <                                t.putTreeNode(h, k, val);
1711 >                                t.putTreeVal(h, key, val);
1712                              }
1713                          }
1445                    } finally {
1446                        t.release(0);
1447                    }
1448                    if (len != 0) {
1449                        if (!added)
1450                            return (V)val;
1451                        break;
1714                      }
1715                  }
1716 <                else
1717 <                    tab = (Node[])fk;
1716 >                if (binCount != 0) {
1717 >                    if (binCount >= TREEIFY_THRESHOLD)
1718 >                        treeifyBin(tab, i);
1719 >                    if (!added)
1720 >                        return val;
1721 >                    break;
1722 >                }
1723              }
1724 +        }
1725 +        if (val != null)
1726 +            addCount(1L, binCount);
1727 +        return val;
1728 +    }
1729 +
1730 +    /**
1731 +     * If the value for the specified key is present, attempts to
1732 +     * compute a new mapping given the key and its current mapped
1733 +     * value.  The entire method invocation is performed atomically.
1734 +     * Some attempted update operations on this map by other threads
1735 +     * may be blocked while computation is in progress, so the
1736 +     * computation should be short and simple, and must not attempt to
1737 +     * update any other mappings of this map.
1738 +     *
1739 +     * @param key key with which a value may be associated
1740 +     * @param remappingFunction the function to compute a value
1741 +     * @return the new value associated with the specified key, or null if none
1742 +     * @throws NullPointerException if the specified key or remappingFunction
1743 +     *         is null
1744 +     * @throws IllegalStateException if the computation detectably
1745 +     *         attempts a recursive update to this map that would
1746 +     *         otherwise never complete
1747 +     * @throws RuntimeException or Error if the remappingFunction does so,
1748 +     *         in which case the mapping is unchanged
1749 +     */
1750 +    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1751 +        if (key == null || remappingFunction == null)
1752 +            throw new NullPointerException();
1753 +        int h = spread(key.hashCode());
1754 +        V val = null;
1755 +        int delta = 0;
1756 +        int binCount = 0;
1757 +        for (Node<K,V>[] tab = table;;) {
1758 +            Node<K,V> f; int n, i, fh;
1759 +            if (tab == null || (n = tab.length) == 0)
1760 +                tab = initTable();
1761 +            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1762 +                break;
1763 +            else if ((fh = f.hash) == MOVED)
1764 +                tab = helpTransfer(tab, f);
1765              else {
1766 <                for (Node e = f; e != null; e = e.next) { // prescan
1459 <                    Object ek, ev;
1460 <                    if (e.hash == h && (ev = e.val) != null &&
1461 <                        ((ek = e.key) == k || k.equals(ek)))
1462 <                        return (V)ev;
1463 <                }
1464 <                boolean added = false;
1465 <                synchronized(f) {
1766 >                synchronized (f) {
1767                      if (tabAt(tab, i) == f) {
1768 <                        len = 1;
1769 <                        for (Node e = f;; ++len) {
1770 <                            Object ek, ev;
1771 <                            if (e.hash == h &&
1772 <                                (ev = e.val) != null &&
1773 <                                ((ek = e.key) == k || k.equals(ek))) {
1774 <                                val = ev;
1775 <                                break;
1768 >                        if (fh >= 0) {
1769 >                            binCount = 1;
1770 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1771 >                                K ek;
1772 >                                if (e.hash == h &&
1773 >                                    ((ek = e.key) == key ||
1774 >                                     (ek != null && key.equals(ek)))) {
1775 >                                    val = remappingFunction.apply(key, e.val);
1776 >                                    if (val != null)
1777 >                                        e.val = val;
1778 >                                    else {
1779 >                                        delta = -1;
1780 >                                        Node<K,V> en = e.next;
1781 >                                        if (pred != null)
1782 >                                            pred.next = en;
1783 >                                        else
1784 >                                            setTabAt(tab, i, en);
1785 >                                    }
1786 >                                    break;
1787 >                                }
1788 >                                pred = e;
1789 >                                if ((e = e.next) == null)
1790 >                                    break;
1791                              }
1792 <                            Node last = e;
1793 <                            if ((e = e.next) == null) {
1794 <                                if ((val = mf.apply(k)) != null) {
1795 <                                    added = true;
1796 <                                    last.next = new Node(h, k, val, null);
1797 <                                    if (len >= TREE_THRESHOLD)
1798 <                                        replaceWithTreeBin(tab, i, k);
1792 >                        }
1793 >                        else if (f instanceof TreeBin) {
1794 >                            binCount = 2;
1795 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1796 >                            TreeNode<K,V> r, p;
1797 >                            if ((r = t.root) != null &&
1798 >                                (p = r.findTreeNode(h, key, null)) != null) {
1799 >                                val = remappingFunction.apply(key, p.val);
1800 >                                if (val != null)
1801 >                                    p.val = val;
1802 >                                else {
1803 >                                    delta = -1;
1804 >                                    if (t.removeTreeNode(p))
1805 >                                        setTabAt(tab, i, untreeify(t.first));
1806                                  }
1484                                break;
1807                              }
1808                          }
1809                      }
1810                  }
1811 <                if (len != 0) {
1490 <                    if (!added)
1491 <                        return (V)val;
1811 >                if (binCount != 0)
1812                      break;
1493                }
1813              }
1814          }
1815 <        if (val != null)
1816 <            addCount(1L, len);
1817 <        return (V)val;
1815 >        if (delta != 0)
1816 >            addCount((long)delta, binCount);
1817 >        return val;
1818      }
1819  
1820 <    /** Implementation for compute */
1821 <    @SuppressWarnings("unchecked") private final V internalCompute
1822 <        (K k, boolean onlyIfPresent,
1823 <         BiFun<? super K, ? super V, ? extends V> mf) {
1824 <        if (k == null || mf == null)
1820 >    /**
1821 >     * Attempts to compute a mapping for the specified key and its
1822 >     * current mapped value (or {@code null} if there is no current
1823 >     * mapping). The entire method invocation is performed atomically.
1824 >     * Some attempted update operations on this map by other threads
1825 >     * may be blocked while computation is in progress, so the
1826 >     * computation should be short and simple, and must not attempt to
1827 >     * update any other mappings of this Map.
1828 >     *
1829 >     * @param key key with which the specified value is to be associated
1830 >     * @param remappingFunction the function to compute a value
1831 >     * @return the new value associated with the specified key, or null if none
1832 >     * @throws NullPointerException if the specified key or remappingFunction
1833 >     *         is null
1834 >     * @throws IllegalStateException if the computation detectably
1835 >     *         attempts a recursive update to this map that would
1836 >     *         otherwise never complete
1837 >     * @throws RuntimeException or Error if the remappingFunction does so,
1838 >     *         in which case the mapping is unchanged
1839 >     */
1840 >    public V compute(K key,
1841 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1842 >        if (key == null || remappingFunction == null)
1843              throw new NullPointerException();
1844 <        int h = spread(k.hashCode());
1845 <        Object val = null;
1844 >        int h = spread(key.hashCode());
1845 >        V val = null;
1846          int delta = 0;
1847 <        int len = 0;
1848 <        for (Node[] tab = table;;) {
1849 <            Node f; int i, fh; Object fk;
1850 <            if (tab == null)
1847 >        int binCount = 0;
1848 >        for (Node<K,V>[] tab = table;;) {
1849 >            Node<K,V> f; int n, i, fh;
1850 >            if (tab == null || (n = tab.length) == 0)
1851                  tab = initTable();
1852 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1853 <                if (onlyIfPresent)
1854 <                    break;
1855 <                Node node = new Node(h, k, null, null);
1856 <                synchronized(node) {
1857 <                    if (casTabAt(tab, i, null, node)) {
1852 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1853 >                Node<K,V> r = new ReservationNode<K,V>();
1854 >                synchronized (r) {
1855 >                    if (casTabAt(tab, i, null, r)) {
1856 >                        binCount = 1;
1857 >                        Node<K,V> node = null;
1858                          try {
1859 <                            len = 1;
1523 <                            if ((val = mf.apply(k, null)) != null) {
1524 <                                node.val = val;
1859 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1860                                  delta = 1;
1861 +                                node = new Node<K,V>(h, key, val, null);
1862                              }
1863                          } finally {
1864 <                            if (delta == 0)
1529 <                                setTabAt(tab, i, null);
1864 >                            setTabAt(tab, i, node);
1865                          }
1866                      }
1867                  }
1868 <                if (len != 0)
1868 >                if (binCount != 0)
1869                      break;
1870              }
1871 <            else if ((fh = f.hash) < 0) {
1872 <                if ((fk = f.key) instanceof TreeBin) {
1873 <                    TreeBin t = (TreeBin)fk;
1874 <                    t.acquire(0);
1875 <                    try {
1876 <                        if (tabAt(tab, i) == f) {
1877 <                            len = 1;
1878 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1879 <                            if (p == null && onlyIfPresent)
1880 <                                break;
1881 <                            Object pv = (p == null) ? null : p.val;
1882 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1871 >            else if ((fh = f.hash) == MOVED)
1872 >                tab = helpTransfer(tab, f);
1873 >            else {
1874 >                synchronized (f) {
1875 >                    if (tabAt(tab, i) == f) {
1876 >                        if (fh >= 0) {
1877 >                            binCount = 1;
1878 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1879 >                                K ek;
1880 >                                if (e.hash == h &&
1881 >                                    ((ek = e.key) == key ||
1882 >                                     (ek != null && key.equals(ek)))) {
1883 >                                    val = remappingFunction.apply(key, e.val);
1884 >                                    if (val != null)
1885 >                                        e.val = val;
1886 >                                    else {
1887 >                                        delta = -1;
1888 >                                        Node<K,V> en = e.next;
1889 >                                        if (pred != null)
1890 >                                            pred.next = en;
1891 >                                        else
1892 >                                            setTabAt(tab, i, en);
1893 >                                    }
1894 >                                    break;
1895 >                                }
1896 >                                pred = e;
1897 >                                if ((e = e.next) == null) {
1898 >                                    val = remappingFunction.apply(key, null);
1899 >                                    if (val != null) {
1900 >                                        delta = 1;
1901 >                                        pred.next =
1902 >                                            new Node<K,V>(h, key, val, null);
1903 >                                    }
1904 >                                    break;
1905 >                                }
1906 >                            }
1907 >                        }
1908 >                        else if (f instanceof TreeBin) {
1909 >                            binCount = 1;
1910 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1911 >                            TreeNode<K,V> r, p;
1912 >                            if ((r = t.root) != null)
1913 >                                p = r.findTreeNode(h, key, null);
1914 >                            else
1915 >                                p = null;
1916 >                            V pv = (p == null) ? null : p.val;
1917 >                            val = remappingFunction.apply(key, pv);
1918 >                            if (val != null) {
1919                                  if (p != null)
1920                                      p.val = val;
1921                                  else {
1551                                    len = 2;
1922                                      delta = 1;
1923 <                                    t.putTreeNode(h, k, val);
1923 >                                    t.putTreeVal(h, key, val);
1924                                  }
1925                              }
1926                              else if (p != null) {
1927                                  delta = -1;
1928 <                                t.deleteTreeNode(p);
1928 >                                if (t.removeTreeNode(p))
1929 >                                    setTabAt(tab, i, untreeify(t.first));
1930                              }
1931                          }
1561                    } finally {
1562                        t.release(0);
1932                      }
1564                    if (len != 0)
1565                        break;
1933                  }
1934 <                else
1935 <                    tab = (Node[])fk;
1936 <            }
1570 <            else {
1571 <                synchronized(f) {
1572 <                    if (tabAt(tab, i) == f) {
1573 <                        len = 1;
1574 <                        for (Node e = f, pred = null;; ++len) {
1575 <                            Object ek, ev;
1576 <                            if (e.hash == h &&
1577 <                                (ev = e.val) != null &&
1578 <                                ((ek = e.key) == k || k.equals(ek))) {
1579 <                                val = mf.apply(k, (V)ev);
1580 <                                if (val != null)
1581 <                                    e.val = val;
1582 <                                else {
1583 <                                    delta = -1;
1584 <                                    Node en = e.next;
1585 <                                    if (pred != null)
1586 <                                        pred.next = en;
1587 <                                    else
1588 <                                        setTabAt(tab, i, en);
1589 <                                }
1590 <                                break;
1591 <                            }
1592 <                            pred = e;
1593 <                            if ((e = e.next) == null) {
1594 <                                if (!onlyIfPresent &&
1595 <                                    (val = mf.apply(k, null)) != null) {
1596 <                                    pred.next = new Node(h, k, val, null);
1597 <                                    delta = 1;
1598 <                                    if (len >= TREE_THRESHOLD)
1599 <                                        replaceWithTreeBin(tab, i, k);
1600 <                                }
1601 <                                break;
1602 <                            }
1603 <                        }
1604 <                    }
1605 <                }
1606 <                if (len != 0)
1934 >                if (binCount != 0) {
1935 >                    if (binCount >= TREEIFY_THRESHOLD)
1936 >                        treeifyBin(tab, i);
1937                      break;
1938 +                }
1939              }
1940          }
1941          if (delta != 0)
1942 <            addCount((long)delta, len);
1943 <        return (V)val;
1942 >            addCount((long)delta, binCount);
1943 >        return val;
1944      }
1945  
1946 <    /** Implementation for merge */
1947 <    @SuppressWarnings("unchecked") private final V internalMerge
1948 <        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1949 <        if (k == null || v == null || mf == null)
1946 >    /**
1947 >     * If the specified key is not already associated with a
1948 >     * (non-null) value, associates it with the given value.
1949 >     * Otherwise, replaces the value with the results of the given
1950 >     * remapping function, or removes if {@code null}. The entire
1951 >     * method invocation is performed atomically.  Some attempted
1952 >     * update operations on this map by other threads may be blocked
1953 >     * while computation is in progress, so the computation should be
1954 >     * short and simple, and must not attempt to update any other
1955 >     * mappings of this Map.
1956 >     *
1957 >     * @param key key with which the specified value is to be associated
1958 >     * @param value the value to use if absent
1959 >     * @param remappingFunction the function to recompute a value if present
1960 >     * @return the new value associated with the specified key, or null if none
1961 >     * @throws NullPointerException if the specified key or the
1962 >     *         remappingFunction is null
1963 >     * @throws RuntimeException or Error if the remappingFunction does so,
1964 >     *         in which case the mapping is unchanged
1965 >     */
1966 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1967 >        if (key == null || value == null || remappingFunction == null)
1968              throw new NullPointerException();
1969 <        int h = spread(k.hashCode());
1970 <        Object val = null;
1969 >        int h = spread(key.hashCode());
1970 >        V val = null;
1971          int delta = 0;
1972 <        int len = 0;
1973 <        for (Node[] tab = table;;) {
1974 <            int i; Node f; Object fk, fv;
1975 <            if (tab == null)
1972 >        int binCount = 0;
1973 >        for (Node<K,V>[] tab = table;;) {
1974 >            Node<K,V> f; int n, i, fh;
1975 >            if (tab == null || (n = tab.length) == 0)
1976                  tab = initTable();
1977 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1978 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1977 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1978 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1979                      delta = 1;
1980 <                    val = v;
1980 >                    val = value;
1981                      break;
1982                  }
1983              }
1984 <            else if (f.hash < 0) {
1985 <                if ((fk = f.key) instanceof TreeBin) {
1986 <                    TreeBin t = (TreeBin)fk;
1987 <                    t.acquire(0);
1988 <                    try {
1989 <                        if (tabAt(tab, i) == f) {
1990 <                            len = 1;
1991 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1992 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1984 >            else if ((fh = f.hash) == MOVED)
1985 >                tab = helpTransfer(tab, f);
1986 >            else {
1987 >                synchronized (f) {
1988 >                    if (tabAt(tab, i) == f) {
1989 >                        if (fh >= 0) {
1990 >                            binCount = 1;
1991 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1992 >                                K ek;
1993 >                                if (e.hash == h &&
1994 >                                    ((ek = e.key) == key ||
1995 >                                     (ek != null && key.equals(ek)))) {
1996 >                                    val = remappingFunction.apply(e.val, value);
1997 >                                    if (val != null)
1998 >                                        e.val = val;
1999 >                                    else {
2000 >                                        delta = -1;
2001 >                                        Node<K,V> en = e.next;
2002 >                                        if (pred != null)
2003 >                                            pred.next = en;
2004 >                                        else
2005 >                                            setTabAt(tab, i, en);
2006 >                                    }
2007 >                                    break;
2008 >                                }
2009 >                                pred = e;
2010 >                                if ((e = e.next) == null) {
2011 >                                    delta = 1;
2012 >                                    val = value;
2013 >                                    pred.next =
2014 >                                        new Node<K,V>(h, key, val, null);
2015 >                                    break;
2016 >                                }
2017 >                            }
2018 >                        }
2019 >                        else if (f instanceof TreeBin) {
2020 >                            binCount = 2;
2021 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2022 >                            TreeNode<K,V> r = t.root;
2023 >                            TreeNode<K,V> p = (r == null) ? null :
2024 >                                r.findTreeNode(h, key, null);
2025 >                            val = (p == null) ? value :
2026 >                                remappingFunction.apply(p.val, value);
2027                              if (val != null) {
2028                                  if (p != null)
2029                                      p.val = val;
2030                                  else {
1648                                    len = 2;
2031                                      delta = 1;
2032 <                                    t.putTreeNode(h, k, val);
2032 >                                    t.putTreeVal(h, key, val);
2033                                  }
2034                              }
2035                              else if (p != null) {
2036                                  delta = -1;
2037 <                                t.deleteTreeNode(p);
2038 <                            }
1657 <                        }
1658 <                    } finally {
1659 <                        t.release(0);
1660 <                    }
1661 <                    if (len != 0)
1662 <                        break;
1663 <                }
1664 <                else
1665 <                    tab = (Node[])fk;
1666 <            }
1667 <            else {
1668 <                synchronized(f) {
1669 <                    if (tabAt(tab, i) == f) {
1670 <                        len = 1;
1671 <                        for (Node e = f, pred = null;; ++len) {
1672 <                            Object ek, ev;
1673 <                            if (e.hash == h &&
1674 <                                (ev = e.val) != null &&
1675 <                                ((ek = e.key) == k || k.equals(ek))) {
1676 <                                val = mf.apply((V)ev, v);
1677 <                                if (val != null)
1678 <                                    e.val = val;
1679 <                                else {
1680 <                                    delta = -1;
1681 <                                    Node en = e.next;
1682 <                                    if (pred != null)
1683 <                                        pred.next = en;
1684 <                                    else
1685 <                                        setTabAt(tab, i, en);
1686 <                                }
1687 <                                break;
1688 <                            }
1689 <                            pred = e;
1690 <                            if ((e = e.next) == null) {
1691 <                                val = v;
1692 <                                pred.next = new Node(h, k, val, null);
1693 <                                delta = 1;
1694 <                                if (len >= TREE_THRESHOLD)
1695 <                                    replaceWithTreeBin(tab, i, k);
1696 <                                break;
2037 >                                if (t.removeTreeNode(p))
2038 >                                    setTabAt(tab, i, untreeify(t.first));
2039                              }
2040                          }
2041                      }
2042                  }
2043 <                if (len != 0)
2043 >                if (binCount != 0) {
2044 >                    if (binCount >= TREEIFY_THRESHOLD)
2045 >                        treeifyBin(tab, i);
2046                      break;
2047 +                }
2048              }
2049          }
2050          if (delta != 0)
2051 <            addCount((long)delta, len);
2052 <        return (V)val;
2051 >            addCount((long)delta, binCount);
2052 >        return val;
2053      }
2054  
2055 <    /** Implementation for putAll */
2056 <    private final void internalPutAll(Map<?, ?> m) {
2057 <        tryPresize(m.size());
2058 <        long delta = 0L;     // number of uncommitted additions
2059 <        boolean npe = false; // to throw exception on exit for nulls
2060 <        try {                // to clean up counts on other exceptions
2061 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
2062 <                Object k, v;
2063 <                if (entry == null || (k = entry.getKey()) == null ||
2064 <                    (v = entry.getValue()) == null) {
2065 <                    npe = true;
2066 <                    break;
2067 <                }
2068 <                int h = spread(k.hashCode());
2069 <                for (Node[] tab = table;;) {
2070 <                    int i; Node f; int fh; Object fk;
2071 <                    if (tab == null)
2072 <                        tab = initTable();
2073 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
2074 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
2075 <                            ++delta;
2076 <                            break;
2077 <                        }
2078 <                    }
2079 <                    else if ((fh = f.hash) < 0) {
2080 <                        if ((fk = f.key) instanceof TreeBin) {
2081 <                            TreeBin t = (TreeBin)fk;
2082 <                            boolean validated = false;
2083 <                            t.acquire(0);
2084 <                            try {
2085 <                                if (tabAt(tab, i) == f) {
2086 <                                    validated = true;
2087 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
2088 <                                    if (p != null)
2089 <                                        p.val = v;
2090 <                                    else {
2091 <                                        t.putTreeNode(h, k, v);
2092 <                                        ++delta;
2093 <                                    }
2094 <                                }
2095 <                            } finally {
2096 <                                t.release(0);
2097 <                            }
2098 <                            if (validated)
2099 <                                break;
2055 >    // Hashtable legacy methods
2056 >
2057 >    /**
2058 >     * Legacy method testing if some key maps into the specified value
2059 >     * in this table.  This method is identical in functionality to
2060 >     * {@link #containsValue(Object)}, and exists solely to ensure
2061 >     * full compatibility with class {@link java.util.Hashtable},
2062 >     * which supported this method prior to introduction of the
2063 >     * Java Collections framework.
2064 >     *
2065 >     * @param  value a value to search for
2066 >     * @return {@code true} if and only if some key maps to the
2067 >     *         {@code value} argument in this table as
2068 >     *         determined by the {@code equals} method;
2069 >     *         {@code false} otherwise
2070 >     * @throws NullPointerException if the specified value is null
2071 >     */
2072 >    @Deprecated public boolean contains(Object value) {
2073 >        return containsValue(value);
2074 >    }
2075 >
2076 >    /**
2077 >     * Returns an enumeration of the keys in this table.
2078 >     *
2079 >     * @return an enumeration of the keys in this table
2080 >     * @see #keySet()
2081 >     */
2082 >    public Enumeration<K> keys() {
2083 >        Node<K,V>[] t;
2084 >        int f = (t = table) == null ? 0 : t.length;
2085 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2086 >    }
2087 >
2088 >    /**
2089 >     * Returns an enumeration of the values in this table.
2090 >     *
2091 >     * @return an enumeration of the values in this table
2092 >     * @see #values()
2093 >     */
2094 >    public Enumeration<V> elements() {
2095 >        Node<K,V>[] t;
2096 >        int f = (t = table) == null ? 0 : t.length;
2097 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2098 >    }
2099 >
2100 >    // ConcurrentHashMapV8-only methods
2101 >
2102 >    /**
2103 >     * Returns the number of mappings. This method should be used
2104 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2105 >     * contain more mappings than can be represented as an int. The
2106 >     * value returned is an estimate; the actual count may differ if
2107 >     * there are concurrent insertions or removals.
2108 >     *
2109 >     * @return the number of mappings
2110 >     * @since 1.8
2111 >     */
2112 >    public long mappingCount() {
2113 >        long n = sumCount();
2114 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2115 >    }
2116 >
2117 >    /**
2118 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2119 >     * from the given type to {@code Boolean.TRUE}.
2120 >     *
2121 >     * @return the new set
2122 >     * @since 1.8
2123 >     */
2124 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2125 >        return new KeySetView<K,Boolean>
2126 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2127 >    }
2128 >
2129 >    /**
2130 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2131 >     * from the given type to {@code Boolean.TRUE}.
2132 >     *
2133 >     * @param initialCapacity The implementation performs internal
2134 >     * sizing to accommodate this many elements.
2135 >     * @return the new set
2136 >     * @throws IllegalArgumentException if the initial capacity of
2137 >     * elements is negative
2138 >     * @since 1.8
2139 >     */
2140 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2141 >        return new KeySetView<K,Boolean>
2142 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2143 >    }
2144 >
2145 >    /**
2146 >     * Returns a {@link Set} view of the keys in this map, using the
2147 >     * given common mapped value for any additions (i.e., {@link
2148 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2149 >     * This is of course only appropriate if it is acceptable to use
2150 >     * the same value for all additions from this view.
2151 >     *
2152 >     * @param mappedValue the mapped value to use for any additions
2153 >     * @return the set view
2154 >     * @throws NullPointerException if the mappedValue is null
2155 >     */
2156 >    public KeySetView<K,V> keySet(V mappedValue) {
2157 >        if (mappedValue == null)
2158 >            throw new NullPointerException();
2159 >        return new KeySetView<K,V>(this, mappedValue);
2160 >    }
2161 >
2162 >    /* ---------------- Special Nodes -------------- */
2163 >
2164 >    /**
2165 >     * A node inserted at head of bins during transfer operations.
2166 >     */
2167 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2168 >        final Node<K,V>[] nextTable;
2169 >        ForwardingNode(Node<K,V>[] tab) {
2170 >            super(MOVED, null, null, null);
2171 >            this.nextTable = tab;
2172 >        }
2173 >
2174 >        Node<K,V> find(int h, Object k) {
2175 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2176 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2177 >                Node<K,V> e; int n;
2178 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2179 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2180 >                    return null;
2181 >                for (;;) {
2182 >                    int eh; K ek;
2183 >                    if ((eh = e.hash) == h &&
2184 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2185 >                        return e;
2186 >                    if (eh < 0) {
2187 >                        if (e instanceof ForwardingNode) {
2188 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2189 >                            continue outer;
2190                          }
2191                          else
2192 <                            tab = (Node[])fk;
1758 <                    }
1759 <                    else {
1760 <                        int len = 0;
1761 <                        synchronized(f) {
1762 <                            if (tabAt(tab, i) == f) {
1763 <                                len = 1;
1764 <                                for (Node e = f;; ++len) {
1765 <                                    Object ek, ev;
1766 <                                    if (e.hash == h &&
1767 <                                        (ev = e.val) != null &&
1768 <                                        ((ek = e.key) == k || k.equals(ek))) {
1769 <                                        e.val = v;
1770 <                                        break;
1771 <                                    }
1772 <                                    Node last = e;
1773 <                                    if ((e = e.next) == null) {
1774 <                                        ++delta;
1775 <                                        last.next = new Node(h, k, v, null);
1776 <                                        if (len >= TREE_THRESHOLD)
1777 <                                            replaceWithTreeBin(tab, i, k);
1778 <                                        break;
1779 <                                    }
1780 <                                }
1781 <                            }
1782 <                        }
1783 <                        if (len != 0) {
1784 <                            if (len > 1)
1785 <                                addCount(delta, len);
1786 <                            break;
1787 <                        }
2192 >                            return e.find(h, k);
2193                      }
2194 +                    if ((e = e.next) == null)
2195 +                        return null;
2196                  }
2197              }
1791        } finally {
1792            if (delta != 0L)
1793                addCount(delta, 2);
2198          }
1795        if (npe)
1796            throw new NullPointerException();
2199      }
2200  
2201      /**
2202 <     * Implementation for clear. Steps through each bin, removing all
1801 <     * nodes.
2202 >     * A place-holder node used in computeIfAbsent and compute
2203       */
2204 <    private final void internalClear() {
2205 <        long delta = 0L; // negative number of deletions
2206 <        int i = 0;
2207 <        Node[] tab = table;
2208 <        while (tab != null && i < tab.length) {
2209 <            Node f = tabAt(tab, i);
2210 <            if (f == null)
1810 <                ++i;
1811 <            else if (f.hash < 0) {
1812 <                Object fk;
1813 <                if ((fk = f.key) instanceof TreeBin) {
1814 <                    TreeBin t = (TreeBin)fk;
1815 <                    t.acquire(0);
1816 <                    try {
1817 <                        if (tabAt(tab, i) == f) {
1818 <                            for (Node p = t.first; p != null; p = p.next) {
1819 <                                if (p.val != null) { // (currently always true)
1820 <                                    p.val = null;
1821 <                                    --delta;
1822 <                                }
1823 <                            }
1824 <                            t.first = null;
1825 <                            t.root = null;
1826 <                            ++i;
1827 <                        }
1828 <                    } finally {
1829 <                        t.release(0);
1830 <                    }
1831 <                }
1832 <                else
1833 <                    tab = (Node[])fk;
1834 <            }
1835 <            else {
1836 <                synchronized(f) {
1837 <                    if (tabAt(tab, i) == f) {
1838 <                        for (Node e = f; e != null; e = e.next) {
1839 <                            if (e.val != null) {  // (currently always true)
1840 <                                e.val = null;
1841 <                                --delta;
1842 <                            }
1843 <                        }
1844 <                        setTabAt(tab, i, null);
1845 <                        ++i;
1846 <                    }
1847 <                }
1848 <            }
2204 >    static final class ReservationNode<K,V> extends Node<K,V> {
2205 >        ReservationNode() {
2206 >            super(RESERVED, null, null, null);
2207 >        }
2208 >
2209 >        Node<K,V> find(int h, Object k) {
2210 >            return null;
2211          }
1850        if (delta != 0L)
1851            addCount(delta, -1);
2212      }
2213  
2214      /* ---------------- Table Initialization and Resizing -------------- */
2215  
2216      /**
2217 <     * Returns a power of two table size for the given desired capacity.
2218 <     * See Hackers Delight, sec 3.2
2217 >     * Returns the stamp bits for resizing a table of size n.
2218 >     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2219       */
2220 <    private static final int tableSizeFor(int c) {
2221 <        int n = c - 1;
1862 <        n |= n >>> 1;
1863 <        n |= n >>> 2;
1864 <        n |= n >>> 4;
1865 <        n |= n >>> 8;
1866 <        n |= n >>> 16;
1867 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
2220 >    static final int resizeStamp(int n) {
2221 >        return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2222      }
2223  
2224      /**
2225       * Initializes table, using the size recorded in sizeCtl.
2226       */
2227 <    private final Node[] initTable() {
2228 <        Node[] tab; int sc;
2229 <        while ((tab = table) == null) {
2227 >    private final Node<K,V>[] initTable() {
2228 >        Node<K,V>[] tab; int sc;
2229 >        while ((tab = table) == null || tab.length == 0) {
2230              if ((sc = sizeCtl) < 0)
2231                  Thread.yield(); // lost initialization race; just spin
2232              else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2233                  try {
2234 <                    if ((tab = table) == null) {
2234 >                    if ((tab = table) == null || tab.length == 0) {
2235                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2236 <                        tab = table = new Node[n];
2236 >                        @SuppressWarnings("unchecked")
2237 >                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2238 >                        table = tab = nt;
2239                          sc = n - (n >>> 2);
2240                      }
2241                  } finally {
# Line 1920 | Line 2276 | public class ConcurrentHashMapV8<K, V>
2276              s = sumCount();
2277          }
2278          if (check >= 0) {
2279 <            Node[] tab, nt; int sc;
2279 >            Node<K,V>[] tab, nt; int n, sc;
2280              while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2281 <                   tab.length < MAXIMUM_CAPACITY) {
2281 >                   (n = tab.length) < MAXIMUM_CAPACITY) {
2282 >                int rs = resizeStamp(n);
2283                  if (sc < 0) {
2284 <                    if (sc == -1 || transferIndex <= transferOrigin ||
2285 <                        (nt = nextTable) == null)
2284 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2285 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2286 >                        transferIndex <= 0)
2287                          break;
2288 <                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2288 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2289                          transfer(tab, nt);
2290                  }
2291 <                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2291 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2292 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2293                      transfer(tab, null);
2294                  s = sumCount();
2295              }
# Line 1938 | Line 2297 | public class ConcurrentHashMapV8<K, V>
2297      }
2298  
2299      /**
2300 +     * Helps transfer if a resize is in progress.
2301 +     */
2302 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2303 +        Node<K,V>[] nextTab; int sc;
2304 +        if (tab != null && (f instanceof ForwardingNode) &&
2305 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2306 +            int rs = resizeStamp(tab.length);
2307 +            while (nextTab == nextTable && table == tab &&
2308 +                   (sc = sizeCtl) < 0) {
2309 +                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2310 +                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
2311 +                    break;
2312 +                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2313 +                    transfer(tab, nextTab);
2314 +                    break;
2315 +                }
2316 +            }
2317 +            return nextTab;
2318 +        }
2319 +        return table;
2320 +    }
2321 +
2322 +    /**
2323       * Tries to presize table to accommodate the given number of elements.
2324       *
2325       * @param size number of elements (doesn't need to be perfectly accurate)
# Line 1947 | Line 2329 | public class ConcurrentHashMapV8<K, V>
2329              tableSizeFor(size + (size >>> 1) + 1);
2330          int sc;
2331          while ((sc = sizeCtl) >= 0) {
2332 <            Node[] tab = table; int n;
2332 >            Node<K,V>[] tab = table; int n;
2333              if (tab == null || (n = tab.length) == 0) {
2334                  n = (sc > c) ? sc : c;
2335                  if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2336                      try {
2337                          if (table == tab) {
2338 <                            table = new Node[n];
2338 >                            @SuppressWarnings("unchecked")
2339 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2340 >                            table = nt;
2341                              sc = n - (n >>> 2);
2342                          }
2343                      } finally {
# Line 1963 | Line 2347 | public class ConcurrentHashMapV8<K, V>
2347              }
2348              else if (c <= sc || n >= MAXIMUM_CAPACITY)
2349                  break;
2350 <            else if (tab == table &&
2351 <                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2352 <                transfer(tab, null);
2350 >            else if (tab == table) {
2351 >                int rs = resizeStamp(n);
2352 >                if (sc < 0) {
2353 >                    Node<K,V>[] nt;
2354 >                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2355 >                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2356 >                        transferIndex <= 0)
2357 >                        break;
2358 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2359 >                        transfer(tab, nt);
2360 >                }
2361 >                else if (U.compareAndSwapInt(this, SIZECTL, sc,
2362 >                                             (rs << RESIZE_STAMP_SHIFT) + 2))
2363 >                    transfer(tab, null);
2364 >            }
2365          }
2366      }
2367  
2368 <    /*
2368 >    /**
2369       * Moves and/or copies the nodes in each bin to new table. See
2370       * above for explanation.
2371       */
2372 <    private final void transfer(Node[] tab, Node[] nextTab) {
2372 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2373          int n = tab.length, stride;
2374          if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2375              stride = MIN_TRANSFER_STRIDE; // subdivide range
2376          if (nextTab == null) {            // initiating
2377              try {
2378 <                nextTab = new Node[n << 1];
2379 <            } catch(Throwable ex) {       // try to cope with OOME
2378 >                @SuppressWarnings("unchecked")
2379 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2380 >                nextTab = nt;
2381 >            } catch (Throwable ex) {      // try to cope with OOME
2382                  sizeCtl = Integer.MAX_VALUE;
2383                  return;
2384              }
2385              nextTable = nextTab;
1988            transferOrigin = n;
2386              transferIndex = n;
1990            Node rev = new Node(MOVED, tab, null, null);
1991            for (int k = n; k > 0;) {    // progressively reveal ready slots
1992                int nextk = k > stride? k - stride : 0;
1993                for (int m = nextk; m < k; ++m)
1994                    nextTab[m] = rev;
1995                for (int m = n + nextk; m < n + k; ++m)
1996                    nextTab[m] = rev;
1997                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1998            }
2387          }
2388          int nextn = nextTab.length;
2389 <        Node fwd = new Node(MOVED, nextTab, null, null);
2389 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2390          boolean advance = true;
2391 +        boolean finishing = false; // to ensure sweep before committing nextTab
2392          for (int i = 0, bound = 0;;) {
2393 <            int nextIndex, nextBound; Node f; Object fk;
2393 >            Node<K,V> f; int fh;
2394              while (advance) {
2395 <                if (--i >= bound)
2395 >                int nextIndex, nextBound;
2396 >                if (--i >= bound || finishing)
2397                      advance = false;
2398 <                else if ((nextIndex = transferIndex) <= transferOrigin) {
2398 >                else if ((nextIndex = transferIndex) <= 0) {
2399                      i = -1;
2400                      advance = false;
2401                  }
2402                  else if (U.compareAndSwapInt
2403                           (this, TRANSFERINDEX, nextIndex,
2404 <                          nextBound = (nextIndex > stride?
2404 >                          nextBound = (nextIndex > stride ?
2405                                         nextIndex - stride : 0))) {
2406                      bound = nextBound;
2407                      i = nextIndex - 1;
# Line 2019 | Line 2409 | public class ConcurrentHashMapV8<K, V>
2409                  }
2410              }
2411              if (i < 0 || i >= n || i + n >= nextn) {
2412 <                for (int sc;;) {
2413 <                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2414 <                        if (sc == -1) {
2415 <                            nextTable = null;
2416 <                            table = nextTab;
2417 <                            sizeCtl = (n << 1) - (n >>> 1);
2028 <                        }
2029 <                        return;
2030 <                    }
2412 >                int sc;
2413 >                if (finishing) {
2414 >                    nextTable = null;
2415 >                    table = nextTab;
2416 >                    sizeCtl = (n << 1) - (n >>> 1);
2417 >                    return;
2418                  }
2419 <            }
2420 <            else if ((f = tabAt(tab, i)) == null) {
2421 <                if (casTabAt(tab, i, null, fwd)) {
2422 <                    setTabAt(nextTab, i, null);
2423 <                    setTabAt(nextTab, i + n, null);
2037 <                    advance = true;
2419 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2420 >                    if ((sc - 2) != resizeStamp(n))
2421 >                        return;
2422 >                    finishing = advance = true;
2423 >                    i = n; // recheck before commit
2424                  }
2425              }
2426 <            else if (f.hash >= 0) {
2427 <                synchronized(f) {
2426 >            else if ((f = tabAt(tab, i)) == null)
2427 >                advance = casTabAt(tab, i, null, fwd);
2428 >            else if ((fh = f.hash) == MOVED)
2429 >                advance = true; // already processed
2430 >            else {
2431 >                synchronized (f) {
2432                      if (tabAt(tab, i) == f) {
2433 <                        int runBit = f.hash & n;
2434 <                        Node lastRun = f, lo = null, hi = null;
2435 <                        for (Node p = f.next; p != null; p = p.next) {
2436 <                            int b = p.hash & n;
2437 <                            if (b != runBit) {
2438 <                                runBit = b;
2439 <                                lastRun = p;
2433 >                        Node<K,V> ln, hn;
2434 >                        if (fh >= 0) {
2435 >                            int runBit = fh & n;
2436 >                            Node<K,V> lastRun = f;
2437 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2438 >                                int b = p.hash & n;
2439 >                                if (b != runBit) {
2440 >                                    runBit = b;
2441 >                                    lastRun = p;
2442 >                                }
2443                              }
2444 <                        }
2445 <                        if (runBit == 0)
2446 <                            lo = lastRun;
2054 <                        else
2055 <                            hi = lastRun;
2056 <                        for (Node p = f; p != lastRun; p = p.next) {
2057 <                            int ph = p.hash;
2058 <                            Object pk = p.key, pv = p.val;
2059 <                            if ((ph & n) == 0)
2060 <                                lo = new Node(ph, pk, pv, lo);
2061 <                            else
2062 <                                hi = new Node(ph, pk, pv, hi);
2063 <                        }
2064 <                        setTabAt(nextTab, i, lo);
2065 <                        setTabAt(nextTab, i + n, hi);
2066 <                        setTabAt(tab, i, fwd);
2067 <                        advance = true;
2068 <                    }
2069 <                }
2070 <            }
2071 <            else if ((fk = f.key) instanceof TreeBin) {
2072 <                TreeBin t = (TreeBin)fk;
2073 <                t.acquire(0);
2074 <                try {
2075 <                    if (tabAt(tab, i) == f) {
2076 <                        TreeBin lt = new TreeBin();
2077 <                        TreeBin ht = new TreeBin();
2078 <                        int lc = 0, hc = 0;
2079 <                        for (Node e = t.first; e != null; e = e.next) {
2080 <                            int h = e.hash;
2081 <                            Object k = e.key, v = e.val;
2082 <                            if ((h & n) == 0) {
2083 <                                ++lc;
2084 <                                lt.putTreeNode(h, k, v);
2444 >                            if (runBit == 0) {
2445 >                                ln = lastRun;
2446 >                                hn = null;
2447                              }
2448                              else {
2449 <                                ++hc;
2450 <                                ht.putTreeNode(h, k, v);
2449 >                                hn = lastRun;
2450 >                                ln = null;
2451                              }
2452 +                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2453 +                                int ph = p.hash; K pk = p.key; V pv = p.val;
2454 +                                if ((ph & n) == 0)
2455 +                                    ln = new Node<K,V>(ph, pk, pv, ln);
2456 +                                else
2457 +                                    hn = new Node<K,V>(ph, pk, pv, hn);
2458 +                            }
2459 +                            setTabAt(nextTab, i, ln);
2460 +                            setTabAt(nextTab, i + n, hn);
2461 +                            setTabAt(tab, i, fwd);
2462 +                            advance = true;
2463                          }
2464 <                        Node ln, hn; // throw away trees if too small
2465 <                        if (lc < TREE_THRESHOLD) {
2466 <                            ln = null;
2467 <                            for (Node p = lt.first; p != null; p = p.next)
2468 <                                ln = new Node(p.hash, p.key, p.val, ln);
2469 <                        }
2470 <                        else
2471 <                            ln = new Node(MOVED, lt, null, null);
2472 <                        setTabAt(nextTab, i, ln);
2473 <                        if (hc < TREE_THRESHOLD) {
2474 <                            hn = null;
2475 <                            for (Node p = ht.first; p != null; p = p.next)
2476 <                                hn = new Node(p.hash, p.key, p.val, hn);
2464 >                        else if (f instanceof TreeBin) {
2465 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2466 >                            TreeNode<K,V> lo = null, loTail = null;
2467 >                            TreeNode<K,V> hi = null, hiTail = null;
2468 >                            int lc = 0, hc = 0;
2469 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2470 >                                int h = e.hash;
2471 >                                TreeNode<K,V> p = new TreeNode<K,V>
2472 >                                    (h, e.key, e.val, null, null);
2473 >                                if ((h & n) == 0) {
2474 >                                    if ((p.prev = loTail) == null)
2475 >                                        lo = p;
2476 >                                    else
2477 >                                        loTail.next = p;
2478 >                                    loTail = p;
2479 >                                    ++lc;
2480 >                                }
2481 >                                else {
2482 >                                    if ((p.prev = hiTail) == null)
2483 >                                        hi = p;
2484 >                                    else
2485 >                                        hiTail.next = p;
2486 >                                    hiTail = p;
2487 >                                    ++hc;
2488 >                                }
2489 >                            }
2490 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2491 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2492 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2493 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2494 >                            setTabAt(nextTab, i, ln);
2495 >                            setTabAt(nextTab, i + n, hn);
2496 >                            setTabAt(tab, i, fwd);
2497 >                            advance = true;
2498                          }
2105                        else
2106                            hn = new Node(MOVED, ht, null, null);
2107                        setTabAt(nextTab, i + n, hn);
2108                        setTabAt(tab, i, fwd);
2109                        advance = true;
2499                      }
2111                } finally {
2112                    t.release(0);
2500                  }
2501              }
2115            else
2116                advance = true; // already processed
2502          }
2503      }
2504  
2505 <    /* ---------------- Counter support -------------- */
2505 >    /* ---------------- Conversion from/to TreeBins -------------- */
2506  
2507 <    final long sumCount() {
2508 <        CounterCell[] as = counterCells; CounterCell a;
2509 <        long sum = baseCount;
2510 <        if (as != null) {
2511 <            for (int i = 0; i < as.length; ++i) {
2512 <                if ((a = as[i]) != null)
2513 <                    sum += a.value;
2514 <            }
2515 <        }
2516 <        return sum;
2517 <    }
2518 <
2519 <    // See LongAdder version for explanation
2520 <    private final void fullAddCount(long x, CounterHashCode hc,
2521 <                                    boolean wasUncontended) {
2522 <        int h;
2523 <        if (hc == null) {
2524 <            hc = new CounterHashCode();
2525 <            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
2526 <            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
2527 <            threadCounterHashCode.set(hc);
2528 <        }
2144 <        else
2145 <            h = hc.code;
2146 <        boolean collide = false;                // True if last slot nonempty
2147 <        for (;;) {
2148 <            CounterCell[] as; CounterCell a; int n; long v;
2149 <            if ((as = counterCells) != null && (n = as.length) > 0) {
2150 <                if ((a = as[(n - 1) & h]) == null) {
2151 <                    if (counterBusy == 0) {            // Try to attach new Cell
2152 <                        CounterCell r = new CounterCell(x); // Optimistic create
2153 <                        if (counterBusy == 0 &&
2154 <                            U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2155 <                            boolean created = false;
2156 <                            try {               // Recheck under lock
2157 <                                CounterCell[] rs; int m, j;
2158 <                                if ((rs = counterCells) != null &&
2159 <                                    (m = rs.length) > 0 &&
2160 <                                    rs[j = (m - 1) & h] == null) {
2161 <                                    rs[j] = r;
2162 <                                    created = true;
2163 <                                }
2164 <                            } finally {
2165 <                                counterBusy = 0;
2166 <                            }
2167 <                            if (created)
2168 <                                break;
2169 <                            continue;           // Slot is now non-empty
2170 <                        }
2171 <                    }
2172 <                    collide = false;
2173 <                }
2174 <                else if (!wasUncontended)       // CAS already known to fail
2175 <                    wasUncontended = true;      // Continue after rehash
2176 <                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2177 <                    break;
2178 <                else if (counterCells != as || n >= NCPU)
2179 <                    collide = false;            // At max size or stale
2180 <                else if (!collide)
2181 <                    collide = true;
2182 <                else if (counterBusy == 0 &&
2183 <                         U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2184 <                    try {
2185 <                        if (counterCells == as) {// Expand table unless stale
2186 <                            CounterCell[] rs = new CounterCell[n << 1];
2187 <                            for (int i = 0; i < n; ++i)
2188 <                                rs[i] = as[i];
2189 <                            counterCells = rs;
2507 >    /**
2508 >     * Replaces all linked nodes in bin at given index unless table is
2509 >     * too small, in which case resizes instead.
2510 >     */
2511 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2512 >        Node<K,V> b; int n, sc;
2513 >        if (tab != null) {
2514 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2515 >                tryPresize(n << 1);
2516 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2517 >                synchronized (b) {
2518 >                    if (tabAt(tab, index) == b) {
2519 >                        TreeNode<K,V> hd = null, tl = null;
2520 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2521 >                            TreeNode<K,V> p =
2522 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2523 >                                                  null, null);
2524 >                            if ((p.prev = tl) == null)
2525 >                                hd = p;
2526 >                            else
2527 >                                tl.next = p;
2528 >                            tl = p;
2529                          }
2530 <                    } finally {
2192 <                        counterBusy = 0;
2530 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2531                      }
2194                    collide = false;
2195                    continue;                   // Retry with expanded table
2532                  }
2197                h ^= h << 13;                   // Rehash
2198                h ^= h >>> 17;
2199                h ^= h << 5;
2533              }
2201            else if (counterBusy == 0 && counterCells == as &&
2202                     U.compareAndSwapInt(this, COUNTERBUSY, 0, 1)) {
2203                boolean init = false;
2204                try {                           // Initialize table
2205                    if (counterCells == as) {
2206                        CounterCell[] rs = new CounterCell[2];
2207                        rs[h & 1] = new CounterCell(x);
2208                        counterCells = rs;
2209                        init = true;
2210                    }
2211                } finally {
2212                    counterBusy = 0;
2213                }
2214                if (init)
2215                    break;
2216            }
2217            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2218                break;                          // Fall back on using base
2534          }
2535 <        hc.code = h;                            // Record index for next time
2535 >    }
2536 >    /**
2537 >     * Returns a list on non-TreeNodes replacing those in given list.
2538 >     */
2539 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2540 >        Node<K,V> hd = null, tl = null;
2541 >        for (Node<K,V> q = b; q != null; q = q.next) {
2542 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2543 >            if (tl == null)
2544 >                hd = p;
2545 >            else
2546 >                tl.next = p;
2547 >            tl = p;
2548 >        }
2549 >        return hd;
2550      }
2551  
2552 <    /* ----------------Table Traversal -------------- */
2552 >    /* ---------------- TreeNodes -------------- */
2553  
2554      /**
2555 <     * Encapsulates traversal for methods such as containsValue; also
2556 <     * serves as a base class for other iterators and bulk tasks.
2557 <     *
2558 <     * At each step, the iterator snapshots the key ("nextKey") and
2559 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2560 <     * snapshot, has a non-null user value). Because val fields can
2561 <     * change (including to null, indicating deletion), field nextVal
2562 <     * might not be accurate at point of use, but still maintains the
2234 <     * weak consistency property of holding a value that was once
2235 <     * valid. To support iterator.remove, the nextKey field is not
2236 <     * updated (nulled out) when the iterator cannot advance.
2237 <     *
2238 <     * Internal traversals directly access these fields, as in:
2239 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2240 <     *
2241 <     * Exported iterators must track whether the iterator has advanced
2242 <     * (in hasNext vs next) (by setting/checking/nulling field
2243 <     * nextVal), and then extract key, value, or key-value pairs as
2244 <     * return values of next().
2245 <     *
2246 <     * The iterator visits once each still-valid node that was
2247 <     * reachable upon iterator construction. It might miss some that
2248 <     * were added to a bin after the bin was visited, which is OK wrt
2249 <     * consistency guarantees. Maintaining this property in the face
2250 <     * of possible ongoing resizes requires a fair amount of
2251 <     * bookkeeping state that is difficult to optimize away amidst
2252 <     * volatile accesses.  Even so, traversal maintains reasonable
2253 <     * throughput.
2254 <     *
2255 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2256 <     * However, if the table has been resized, then all future steps
2257 <     * must traverse both the bin at the current index as well as at
2258 <     * (index + baseSize); and so on for further resizings. To
2259 <     * paranoically cope with potential sharing by users of iterators
2260 <     * across threads, iteration terminates if a bounds checks fails
2261 <     * for a table read.
2262 <     *
2263 <     * This class extends CountedCompleter to streamline parallel
2264 <     * iteration in bulk operations. This adds only a few fields of
2265 <     * space overhead, which is small enough in cases where it is not
2266 <     * needed to not worry about it.  Because CountedCompleter is
2267 <     * Serializable, but iterators need not be, we need to add warning
2268 <     * suppressions.
2269 <     */
2270 <    @SuppressWarnings("serial") static class Traverser<K,V,R>
2271 <        extends CountedCompleter<R> {
2272 <        final ConcurrentHashMapV8<K, V> map;
2273 <        Node next;           // the next entry to use
2274 <        Object nextKey;      // cached key field of next
2275 <        Object nextVal;      // cached val field of next
2276 <        Node[] tab;          // current table; updated if resized
2277 <        int index;           // index of bin to use next
2278 <        int baseIndex;       // current index of initial table
2279 <        int baseLimit;       // index bound for initial table
2280 <        int baseSize;        // initial table size
2281 <        int batch;           // split control
2555 >     * Nodes for use in TreeBins
2556 >     */
2557 >    static final class TreeNode<K,V> extends Node<K,V> {
2558 >        TreeNode<K,V> parent;  // red-black tree links
2559 >        TreeNode<K,V> left;
2560 >        TreeNode<K,V> right;
2561 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2562 >        boolean red;
2563  
2564 <        /** Creates iterator for all entries in the table. */
2565 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2566 <            this.map = map;
2564 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2565 >                 TreeNode<K,V> parent) {
2566 >            super(hash, key, val, next);
2567 >            this.parent = parent;
2568          }
2569  
2570 <        /** Creates iterator for split() methods and task constructors */
2571 <        Traverser(ConcurrentHashMapV8<K,V> map, Traverser<K,V,?> it, int batch) {
2290 <            super(it);
2291 <            this.batch = batch;
2292 <            if ((this.map = map) != null && it != null) { // split parent
2293 <                Node[] t;
2294 <                if ((t = it.tab) == null &&
2295 <                    (t = it.tab = map.table) != null)
2296 <                    it.baseLimit = it.baseSize = t.length;
2297 <                this.tab = t;
2298 <                this.baseSize = it.baseSize;
2299 <                int hi = this.baseLimit = it.baseLimit;
2300 <                it.baseLimit = this.index = this.baseIndex =
2301 <                    (hi + it.baseIndex + 1) >>> 1;
2302 <            }
2570 >        Node<K,V> find(int h, Object k) {
2571 >            return findTreeNode(h, k, null);
2572          }
2573  
2574          /**
2575 <         * Advances next; returns nextVal or null if terminated.
2576 <         * See above for explanation.
2575 >         * Returns the TreeNode (or null if not found) for the given key
2576 >         * starting at given root.
2577           */
2578 <        final Object advance() {
2579 <            Node e = next;
2580 <            Object ev = null;
2581 <            outer: do {
2582 <                if (e != null)                  // advance past used/skipped node
2583 <                    e = e.next;
2584 <                while (e == null) {             // get to next non-null bin
2585 <                    ConcurrentHashMapV8<K, V> m;
2586 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2587 <                    if ((t = tab) != null)
2588 <                        n = t.length;
2589 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2590 <                        n = baseLimit = baseSize = t.length;
2578 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2579 >            if (k != null) {
2580 >                TreeNode<K,V> p = this;
2581 >                do  {
2582 >                    int ph, dir; K pk; TreeNode<K,V> q;
2583 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2584 >                    if ((ph = p.hash) > h)
2585 >                        p = pl;
2586 >                    else if (ph < h)
2587 >                        p = pr;
2588 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2589 >                        return p;
2590 >                    else if (pl == null)
2591 >                        p = pr;
2592 >                    else if (pr == null)
2593 >                        p = pl;
2594 >                    else if ((kc != null ||
2595 >                              (kc = comparableClassFor(k)) != null) &&
2596 >                             (dir = compareComparables(kc, k, pk)) != 0)
2597 >                        p = (dir < 0) ? pl : pr;
2598 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2599 >                        return q;
2600                      else
2601 <                        break outer;
2602 <                    if ((b = baseIndex) >= baseLimit ||
2603 <                        (i = index) < 0 || i >= n)
2604 <                        break outer;
2327 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2328 <                        if ((ek = e.key) instanceof TreeBin)
2329 <                            e = ((TreeBin)ek).first;
2330 <                        else {
2331 <                            tab = (Node[])ek;
2332 <                            continue;           // restarts due to null val
2333 <                        }
2334 <                    }                           // visit upper slots if present
2335 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2336 <                }
2337 <                nextKey = e.key;
2338 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2339 <            next = e;
2340 <            return nextVal = ev;
2601 >                        p = pl;
2602 >                } while (p != null);
2603 >            }
2604 >            return null;
2605          }
2606 +    }
2607  
2608 <        public final void remove() {
2344 <            Object k = nextKey;
2345 <            if (k == null && (advance() == null || (k = nextKey) == null))
2346 <                throw new IllegalStateException();
2347 <            map.internalReplace(k, null, null);
2348 <        }
2608 >    /* ---------------- TreeBins -------------- */
2609  
2610 <        public final boolean hasNext() {
2611 <            return nextVal != null || advance() != null;
2610 >    /**
2611 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2612 >     * keys or values, but instead point to list of TreeNodes and
2613 >     * their root. They also maintain a parasitic read-write lock
2614 >     * forcing writers (who hold bin lock) to wait for readers (who do
2615 >     * not) to complete before tree restructuring operations.
2616 >     */
2617 >    static final class TreeBin<K,V> extends Node<K,V> {
2618 >        TreeNode<K,V> root;
2619 >        volatile TreeNode<K,V> first;
2620 >        volatile Thread waiter;
2621 >        volatile int lockState;
2622 >        // values for lockState
2623 >        static final int WRITER = 1; // set while holding write lock
2624 >        static final int WAITER = 2; // set when waiting for write lock
2625 >        static final int READER = 4; // increment value for setting read lock
2626 >
2627 >        /**
2628 >         * Tie-breaking utility for ordering insertions when equal
2629 >         * hashCodes and non-comparable. We don't require a total
2630 >         * order, just a consistent insertion rule to maintain
2631 >         * equivalence across rebalancings. Tie-breaking further than
2632 >         * necessary simplifies testing a bit.
2633 >         */
2634 >        static int tieBreakOrder(Object a, Object b) {
2635 >            int d;
2636 >            if (a == null || b == null ||
2637 >                (d = a.getClass().getName().
2638 >                 compareTo(b.getClass().getName())) == 0)
2639 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2640 >                     -1 : 1);
2641 >            return d;
2642          }
2643  
2644 <        public final boolean hasMoreElements() { return hasNext(); }
2645 <
2646 <        public void compute() { } // default no-op CountedCompleter body
2644 >        /**
2645 >         * Creates bin with initial set of nodes headed by b.
2646 >         */
2647 >        TreeBin(TreeNode<K,V> b) {
2648 >            super(TREEBIN, null, null, null);
2649 >            this.first = b;
2650 >            TreeNode<K,V> r = null;
2651 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2652 >                next = (TreeNode<K,V>)x.next;
2653 >                x.left = x.right = null;
2654 >                if (r == null) {
2655 >                    x.parent = null;
2656 >                    x.red = false;
2657 >                    r = x;
2658 >                }
2659 >                else {
2660 >                    K k = x.key;
2661 >                    int h = x.hash;
2662 >                    Class<?> kc = null;
2663 >                    for (TreeNode<K,V> p = r;;) {
2664 >                        int dir, ph;
2665 >                        K pk = p.key;
2666 >                        if ((ph = p.hash) > h)
2667 >                            dir = -1;
2668 >                        else if (ph < h)
2669 >                            dir = 1;
2670 >                        else if ((kc == null &&
2671 >                                  (kc = comparableClassFor(k)) == null) ||
2672 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2673 >                            dir = tieBreakOrder(k, pk);
2674 >                            TreeNode<K,V> xp = p;
2675 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2676 >                            x.parent = xp;
2677 >                            if (dir <= 0)
2678 >                                xp.left = x;
2679 >                            else
2680 >                                xp.right = x;
2681 >                            r = balanceInsertion(r, x);
2682 >                            break;
2683 >                        }
2684 >                    }
2685 >                }
2686 >            }
2687 >            this.root = r;
2688 >            assert checkInvariants(root);
2689 >        }
2690  
2691          /**
2692 <         * Returns a batch value > 0 if this task should (and must) be
2360 <         * split, if so, adding to pending count, and in any case
2361 <         * updating batch value. The initial batch value is approx
2362 <         * exp2 of the number of times (minus one) to split task by
2363 <         * two before executing leaf action. This value is faster to
2364 <         * compute and more convenient to use as a guide to splitting
2365 <         * than is the depth, since it is used while dividing by two
2366 <         * anyway.
2692 >         * Acquires write lock for tree restructuring.
2693           */
2694 <        final int preSplit() {
2695 <            ConcurrentHashMapV8<K, V> m; int b; Node[] t;  ForkJoinPool pool;
2696 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
2371 <                if ((t = tab) == null && (t = tab = m.table) != null)
2372 <                    baseLimit = baseSize = t.length;
2373 <                if (t != null) {
2374 <                    long n = m.sumCount();
2375 <                    int par = ((pool = getPool()) == null) ?
2376 <                        ForkJoinPool.getCommonPoolParallelism() :
2377 <                        pool.getParallelism();
2378 <                    int sp = par << 3; // slack of 8
2379 <                    b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2380 <                }
2381 <            }
2382 <            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2383 <            if ((batch = b) > 0)
2384 <                addToPendingCount(1);
2385 <            return b;
2694 >        private final void lockRoot() {
2695 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2696 >                contendedLock(); // offload to separate method
2697          }
2698  
2699 <    }
2700 <
2701 <    /* ---------------- Public operations -------------- */
2702 <
2703 <    /**
2393 <     * Creates a new, empty map with the default initial table size (16).
2394 <     */
2395 <    public ConcurrentHashMapV8() {
2396 <    }
2397 <
2398 <    /**
2399 <     * Creates a new, empty map with an initial table size
2400 <     * accommodating the specified number of elements without the need
2401 <     * to dynamically resize.
2402 <     *
2403 <     * @param initialCapacity The implementation performs internal
2404 <     * sizing to accommodate this many elements.
2405 <     * @throws IllegalArgumentException if the initial capacity of
2406 <     * elements is negative
2407 <     */
2408 <    public ConcurrentHashMapV8(int initialCapacity) {
2409 <        if (initialCapacity < 0)
2410 <            throw new IllegalArgumentException();
2411 <        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2412 <                   MAXIMUM_CAPACITY :
2413 <                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2414 <        this.sizeCtl = cap;
2415 <    }
2416 <
2417 <    /**
2418 <     * Creates a new map with the same mappings as the given map.
2419 <     *
2420 <     * @param m the map
2421 <     */
2422 <    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2423 <        this.sizeCtl = DEFAULT_CAPACITY;
2424 <        internalPutAll(m);
2425 <    }
2426 <
2427 <    /**
2428 <     * Creates a new, empty map with an initial table size based on
2429 <     * the given number of elements ({@code initialCapacity}) and
2430 <     * initial table density ({@code loadFactor}).
2431 <     *
2432 <     * @param initialCapacity the initial capacity. The implementation
2433 <     * performs internal sizing to accommodate this many elements,
2434 <     * given the specified load factor.
2435 <     * @param loadFactor the load factor (table density) for
2436 <     * establishing the initial table size
2437 <     * @throws IllegalArgumentException if the initial capacity of
2438 <     * elements is negative or the load factor is nonpositive
2439 <     *
2440 <     * @since 1.6
2441 <     */
2442 <    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
2443 <        this(initialCapacity, loadFactor, 1);
2444 <    }
2445 <
2446 <    /**
2447 <     * Creates a new, empty map with an initial table size based on
2448 <     * the given number of elements ({@code initialCapacity}), table
2449 <     * density ({@code loadFactor}), and number of concurrently
2450 <     * updating threads ({@code concurrencyLevel}).
2451 <     *
2452 <     * @param initialCapacity the initial capacity. The implementation
2453 <     * performs internal sizing to accommodate this many elements,
2454 <     * given the specified load factor.
2455 <     * @param loadFactor the load factor (table density) for
2456 <     * establishing the initial table size
2457 <     * @param concurrencyLevel the estimated number of concurrently
2458 <     * updating threads. The implementation may use this value as
2459 <     * a sizing hint.
2460 <     * @throws IllegalArgumentException if the initial capacity is
2461 <     * negative or the load factor or concurrencyLevel are
2462 <     * nonpositive
2463 <     */
2464 <    public ConcurrentHashMapV8(int initialCapacity,
2465 <                               float loadFactor, int concurrencyLevel) {
2466 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2467 <            throw new IllegalArgumentException();
2468 <        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2469 <            initialCapacity = concurrencyLevel;   // as estimated threads
2470 <        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2471 <        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2472 <            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2473 <        this.sizeCtl = cap;
2474 <    }
2475 <
2476 <    /**
2477 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2478 <     * from the given type to {@code Boolean.TRUE}.
2479 <     *
2480 <     * @return the new set
2481 <     */
2482 <    public static <K> KeySetView<K,Boolean> newKeySet() {
2483 <        return new KeySetView<K,Boolean>(new ConcurrentHashMapV8<K,Boolean>(),
2484 <                                      Boolean.TRUE);
2485 <    }
2486 <
2487 <    /**
2488 <     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2489 <     * from the given type to {@code Boolean.TRUE}.
2490 <     *
2491 <     * @param initialCapacity The implementation performs internal
2492 <     * sizing to accommodate this many elements.
2493 <     * @throws IllegalArgumentException if the initial capacity of
2494 <     * elements is negative
2495 <     * @return the new set
2496 <     */
2497 <    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2498 <        return new KeySetView<K,Boolean>
2499 <            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2500 <    }
2501 <
2502 <    /**
2503 <     * {@inheritDoc}
2504 <     */
2505 <    public boolean isEmpty() {
2506 <        return sumCount() <= 0L; // ignore transient negative values
2507 <    }
2508 <
2509 <    /**
2510 <     * {@inheritDoc}
2511 <     */
2512 <    public int size() {
2513 <        long n = sumCount();
2514 <        return ((n < 0L) ? 0 :
2515 <                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2516 <                (int)n);
2517 <    }
2518 <
2519 <    /**
2520 <     * Returns the number of mappings. This method should be used
2521 <     * instead of {@link #size} because a ConcurrentHashMapV8 may
2522 <     * contain more mappings than can be represented as an int. The
2523 <     * value returned is an estimate; the actual count may differ if
2524 <     * there are concurrent insertions or removals.
2525 <     *
2526 <     * @return the number of mappings
2527 <     */
2528 <    public long mappingCount() {
2529 <        long n = sumCount();
2530 <        return (n < 0L) ? 0L : n; // ignore transient negative values
2531 <    }
2532 <
2533 <    /**
2534 <     * Returns the value to which the specified key is mapped,
2535 <     * or {@code null} if this map contains no mapping for the key.
2536 <     *
2537 <     * <p>More formally, if this map contains a mapping from a key
2538 <     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2539 <     * then this method returns {@code v}; otherwise it returns
2540 <     * {@code null}.  (There can be at most one such mapping.)
2541 <     *
2542 <     * @throws NullPointerException if the specified key is null
2543 <     */
2544 <    public V get(Object key) {
2545 <        return internalGet(key);
2546 <    }
2547 <
2548 <    /**
2549 <     * Returns the value to which the specified key is mapped,
2550 <     * or the given defaultValue if this map contains no mapping for the key.
2551 <     *
2552 <     * @param key the key
2553 <     * @param defaultValue the value to return if this map contains
2554 <     * no mapping for the given key
2555 <     * @return the mapping for the key, if present; else the defaultValue
2556 <     * @throws NullPointerException if the specified key is null
2557 <     */
2558 <    public V getValueOrDefault(Object key, V defaultValue) {
2559 <        V v;
2560 <        return (v = internalGet(key)) == null ? defaultValue : v;
2561 <    }
2562 <
2563 <    /**
2564 <     * Tests if the specified object is a key in this table.
2565 <     *
2566 <     * @param  key   possible key
2567 <     * @return {@code true} if and only if the specified object
2568 <     *         is a key in this table, as determined by the
2569 <     *         {@code equals} method; {@code false} otherwise
2570 <     * @throws NullPointerException if the specified key is null
2571 <     */
2572 <    public boolean containsKey(Object key) {
2573 <        return internalGet(key) != null;
2574 <    }
2575 <
2576 <    /**
2577 <     * Returns {@code true} if this map maps one or more keys to the
2578 <     * specified value. Note: This method may require a full traversal
2579 <     * of the map, and is much slower than method {@code containsKey}.
2580 <     *
2581 <     * @param value value whose presence in this map is to be tested
2582 <     * @return {@code true} if this map maps one or more keys to the
2583 <     *         specified value
2584 <     * @throws NullPointerException if the specified value is null
2585 <     */
2586 <    public boolean containsValue(Object value) {
2587 <        if (value == null)
2588 <            throw new NullPointerException();
2589 <        Object v;
2590 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2591 <        while ((v = it.advance()) != null) {
2592 <            if (v == value || value.equals(v))
2593 <                return true;
2699 >        /**
2700 >         * Releases write lock for tree restructuring.
2701 >         */
2702 >        private final void unlockRoot() {
2703 >            lockState = 0;
2704          }
2595        return false;
2596    }
2597
2598    /**
2599     * Legacy method testing if some key maps into the specified value
2600     * in this table.  This method is identical in functionality to
2601     * {@link #containsValue}, and exists solely to ensure
2602     * full compatibility with class {@link java.util.Hashtable},
2603     * which supported this method prior to introduction of the
2604     * Java Collections framework.
2605     *
2606     * @param  value a value to search for
2607     * @return {@code true} if and only if some key maps to the
2608     *         {@code value} argument in this table as
2609     *         determined by the {@code equals} method;
2610     *         {@code false} otherwise
2611     * @throws NullPointerException if the specified value is null
2612     */
2613    public boolean contains(Object value) {
2614        return containsValue(value);
2615    }
2616
2617    /**
2618     * Maps the specified key to the specified value in this table.
2619     * Neither the key nor the value can be null.
2620     *
2621     * <p>The value can be retrieved by calling the {@code get} method
2622     * with a key that is equal to the original key.
2623     *
2624     * @param key key with which the specified value is to be associated
2625     * @param value value to be associated with the specified key
2626     * @return the previous value associated with {@code key}, or
2627     *         {@code null} if there was no mapping for {@code key}
2628     * @throws NullPointerException if the specified key or value is null
2629     */
2630    public V put(K key, V value) {
2631        return internalPut(key, value, false);
2632    }
2705  
2706 <    /**
2707 <     * {@inheritDoc}
2708 <     *
2709 <     * @return the previous value associated with the specified key,
2710 <     *         or {@code null} if there was no mapping for the key
2711 <     * @throws NullPointerException if the specified key or value is null
2712 <     */
2713 <    public V putIfAbsent(K key, V value) {
2714 <        return internalPut(key, value, true);
2715 <    }
2716 <
2717 <    /**
2718 <     * Copies all of the mappings from the specified map to this one.
2719 <     * These mappings replace any mappings that this map had for any of the
2720 <     * keys currently in the specified map.
2721 <     *
2722 <     * @param m mappings to be stored in this map
2723 <     */
2724 <    public void putAll(Map<? extends K, ? extends V> m) {
2725 <        internalPutAll(m);
2726 <    }
2727 <
2728 <    /**
2657 <     * If the specified key is not already associated with a value,
2658 <     * computes its value using the given mappingFunction and enters
2659 <     * it into the map unless null.  This is equivalent to
2660 <     * <pre> {@code
2661 <     * if (map.containsKey(key))
2662 <     *   return map.get(key);
2663 <     * value = mappingFunction.apply(key);
2664 <     * if (value != null)
2665 <     *   map.put(key, value);
2666 <     * return value;}</pre>
2667 <     *
2668 <     * except that the action is performed atomically.  If the
2669 <     * function returns {@code null} no mapping is recorded. If the
2670 <     * function itself throws an (unchecked) exception, the exception
2671 <     * is rethrown to its caller, and no mapping is recorded.  Some
2672 <     * attempted update operations on this map by other threads may be
2673 <     * blocked while computation is in progress, so the computation
2674 <     * should be short and simple, and must not attempt to update any
2675 <     * other mappings of this Map. The most appropriate usage is to
2676 <     * construct a new object serving as an initial mapped value, or
2677 <     * memoized result, as in:
2678 <     *
2679 <     *  <pre> {@code
2680 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2681 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2682 <     *
2683 <     * @param key key with which the specified value is to be associated
2684 <     * @param mappingFunction the function to compute a value
2685 <     * @return the current (existing or computed) value associated with
2686 <     *         the specified key, or null if the computed value is null
2687 <     * @throws NullPointerException if the specified key or mappingFunction
2688 <     *         is null
2689 <     * @throws IllegalStateException if the computation detectably
2690 <     *         attempts a recursive update to this map that would
2691 <     *         otherwise never complete
2692 <     * @throws RuntimeException or Error if the mappingFunction does so,
2693 <     *         in which case the mapping is left unestablished
2694 <     */
2695 <    public V computeIfAbsent
2696 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2697 <        return internalComputeIfAbsent(key, mappingFunction);
2698 <    }
2706 >        /**
2707 >         * Possibly blocks awaiting root lock.
2708 >         */
2709 >        private final void contendedLock() {
2710 >            boolean waiting = false;
2711 >            for (int s;;) {
2712 >                if (((s = lockState) & ~WAITER) == 0) {
2713 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2714 >                        if (waiting)
2715 >                            waiter = null;
2716 >                        return;
2717 >                    }
2718 >                }
2719 >                else if ((s & WAITER) == 0) {
2720 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2721 >                        waiting = true;
2722 >                        waiter = Thread.currentThread();
2723 >                    }
2724 >                }
2725 >                else if (waiting)
2726 >                    LockSupport.park(this);
2727 >            }
2728 >        }
2729  
2730 <    /**
2731 <     * If the given key is present, computes a new mapping value given a key and
2732 <     * its current mapped value. This is equivalent to
2733 <     *  <pre> {@code
2734 <     *   if (map.containsKey(key)) {
2735 <     *     value = remappingFunction.apply(key, map.get(key));
2736 <     *     if (value != null)
2737 <     *       map.put(key, value);
2738 <     *     else
2739 <     *       map.remove(key);
2740 <     *   }
2741 <     * }</pre>
2742 <     *
2743 <     * except that the action is performed atomically.  If the
2744 <     * function returns {@code null}, the mapping is removed.  If the
2745 <     * function itself throws an (unchecked) exception, the exception
2746 <     * is rethrown to its caller, and the current mapping is left
2747 <     * unchanged.  Some attempted update operations on this map by
2748 <     * other threads may be blocked while computation is in progress,
2749 <     * so the computation should be short and simple, and must not
2750 <     * attempt to update any other mappings of this Map. For example,
2751 <     * to either create or append new messages to a value mapping:
2752 <     *
2753 <     * @param key key with which the specified value is to be associated
2754 <     * @param remappingFunction the function to compute a value
2755 <     * @return the new value associated with the specified key, or null if none
2756 <     * @throws NullPointerException if the specified key or remappingFunction
2757 <     *         is null
2758 <     * @throws IllegalStateException if the computation detectably
2759 <     *         attempts a recursive update to this map that would
2760 <     *         otherwise never complete
2761 <     * @throws RuntimeException or Error if the remappingFunction does so,
2762 <     *         in which case the mapping is unchanged
2763 <     */
2764 <    public V computeIfPresent
2765 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2736 <        return internalCompute(key, true, remappingFunction);
2737 <    }
2730 >        /**
2731 >         * Returns matching node or null if none. Tries to search
2732 >         * using tree comparisons from root, but continues linear
2733 >         * search when lock not available.
2734 >         */
2735 >        final Node<K,V> find(int h, Object k) {
2736 >            if (k != null) {
2737 >                for (Node<K,V> e = first; e != null; ) {
2738 >                    int s; K ek;
2739 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2740 >                        if (e.hash == h &&
2741 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2742 >                            return e;
2743 >                        e = e.next;
2744 >                    }
2745 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2746 >                                                 s + READER)) {
2747 >                        TreeNode<K,V> r, p;
2748 >                        try {
2749 >                            p = ((r = root) == null ? null :
2750 >                                 r.findTreeNode(h, k, null));
2751 >                        } finally {
2752 >                            Thread w;
2753 >                            int ls;
2754 >                            do {} while (!U.compareAndSwapInt
2755 >                                         (this, LOCKSTATE,
2756 >                                          ls = lockState, ls - READER));
2757 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2758 >                                LockSupport.unpark(w);
2759 >                        }
2760 >                        return p;
2761 >                    }
2762 >                }
2763 >            }
2764 >            return null;
2765 >        }
2766  
2767 <    /**
2768 <     * Computes a new mapping value given a key and
2769 <     * its current mapped value (or {@code null} if there is no current
2770 <     * mapping). This is equivalent to
2771 <     *  <pre> {@code
2772 <     *   value = remappingFunction.apply(key, map.get(key));
2773 <     *   if (value != null)
2774 <     *     map.put(key, value);
2775 <     *   else
2776 <     *     map.remove(key);
2777 <     * }</pre>
2778 <     *
2779 <     * except that the action is performed atomically.  If the
2780 <     * function returns {@code null}, the mapping is removed.  If the
2781 <     * function itself throws an (unchecked) exception, the exception
2782 <     * is rethrown to its caller, and the current mapping is left
2783 <     * unchanged.  Some attempted update operations on this map by
2784 <     * other threads may be blocked while computation is in progress,
2785 <     * so the computation should be short and simple, and must not
2786 <     * attempt to update any other mappings of this Map. For example,
2787 <     * to either create or append new messages to a value mapping:
2788 <     *
2789 <     * <pre> {@code
2790 <     * Map<Key, String> map = ...;
2791 <     * final String msg = ...;
2792 <     * map.compute(key, new BiFun<Key, String, String>() {
2793 <     *   public String apply(Key k, String v) {
2794 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2795 <     *
2796 <     * @param key key with which the specified value is to be associated
2797 <     * @param remappingFunction the function to compute a value
2798 <     * @return the new value associated with the specified key, or null if none
2799 <     * @throws NullPointerException if the specified key or remappingFunction
2800 <     *         is null
2801 <     * @throws IllegalStateException if the computation detectably
2802 <     *         attempts a recursive update to this map that would
2803 <     *         otherwise never complete
2804 <     * @throws RuntimeException or Error if the remappingFunction does so,
2805 <     *         in which case the mapping is unchanged
2806 <     */
2807 <    public V compute
2808 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2809 <        return internalCompute(key, false, remappingFunction);
2810 <    }
2767 >        /**
2768 >         * Finds or adds a node.
2769 >         * @return null if added
2770 >         */
2771 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2772 >            Class<?> kc = null;
2773 >            boolean searched = false;
2774 >            for (TreeNode<K,V> p = root;;) {
2775 >                int dir, ph; K pk;
2776 >                if (p == null) {
2777 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2778 >                    break;
2779 >                }
2780 >                else if ((ph = p.hash) > h)
2781 >                    dir = -1;
2782 >                else if (ph < h)
2783 >                    dir = 1;
2784 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2785 >                    return p;
2786 >                else if ((kc == null &&
2787 >                          (kc = comparableClassFor(k)) == null) ||
2788 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2789 >                    if (!searched) {
2790 >                        TreeNode<K,V> q, ch;
2791 >                        searched = true;
2792 >                        if (((ch = p.left) != null &&
2793 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2794 >                            ((ch = p.right) != null &&
2795 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2796 >                            return q;
2797 >                    }
2798 >                    dir = tieBreakOrder(k, pk);
2799 >                }
2800 >
2801 >                TreeNode<K,V> xp = p;
2802 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2803 >                    TreeNode<K,V> x, f = first;
2804 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2805 >                    if (f != null)
2806 >                        f.prev = x;
2807 >                    if (dir <= 0)
2808 >                        xp.left = x;
2809 >                    else
2810 >                        xp.right = x;
2811 >                    if (!xp.red)
2812 >                        x.red = true;
2813 >                    else {
2814 >                        lockRoot();
2815 >                        try {
2816 >                            root = balanceInsertion(root, x);
2817 >                        } finally {
2818 >                            unlockRoot();
2819 >                        }
2820 >                    }
2821 >                    break;
2822 >                }
2823 >            }
2824 >            assert checkInvariants(root);
2825 >            return null;
2826 >        }
2827  
2828 <    /**
2829 <     * If the specified key is not already associated
2830 <     * with a value, associate it with the given value.
2831 <     * Otherwise, replace the value with the results of
2832 <     * the given remapping function. This is equivalent to:
2833 <     *  <pre> {@code
2834 <     *   if (!map.containsKey(key))
2835 <     *     map.put(value);
2836 <     *   else {
2837 <     *     newValue = remappingFunction.apply(map.get(key), value);
2838 <     *     if (value != null)
2839 <     *       map.put(key, value);
2840 <     *     else
2841 <     *       map.remove(key);
2842 <     *   }
2843 <     * }</pre>
2844 <     * except that the action is performed atomically.  If the
2845 <     * function returns {@code null}, the mapping is removed.  If the
2846 <     * function itself throws an (unchecked) exception, the exception
2847 <     * is rethrown to its caller, and the current mapping is left
2848 <     * unchanged.  Some attempted update operations on this map by
2849 <     * other threads may be blocked while computation is in progress,
2850 <     * so the computation should be short and simple, and must not
2851 <     * attempt to update any other mappings of this Map.
2852 <     */
2853 <    public V merge
2854 <        (K key, V value,
2855 <         BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2856 <        return internalMerge(key, value, remappingFunction);
2857 <    }
2828 >        /**
2829 >         * Removes the given node, that must be present before this
2830 >         * call.  This is messier than typical red-black deletion code
2831 >         * because we cannot swap the contents of an interior node
2832 >         * with a leaf successor that is pinned by "next" pointers
2833 >         * that are accessible independently of lock. So instead we
2834 >         * swap the tree linkages.
2835 >         *
2836 >         * @return true if now too small, so should be untreeified
2837 >         */
2838 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2839 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2840 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2841 >            TreeNode<K,V> r, rl;
2842 >            if (pred == null)
2843 >                first = next;
2844 >            else
2845 >                pred.next = next;
2846 >            if (next != null)
2847 >                next.prev = pred;
2848 >            if (first == null) {
2849 >                root = null;
2850 >                return true;
2851 >            }
2852 >            if ((r = root) == null || r.right == null || // too small
2853 >                (rl = r.left) == null || rl.left == null)
2854 >                return true;
2855 >            lockRoot();
2856 >            try {
2857 >                TreeNode<K,V> replacement;
2858 >                TreeNode<K,V> pl = p.left;
2859 >                TreeNode<K,V> pr = p.right;
2860 >                if (pl != null && pr != null) {
2861 >                    TreeNode<K,V> s = pr, sl;
2862 >                    while ((sl = s.left) != null) // find successor
2863 >                        s = sl;
2864 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2865 >                    TreeNode<K,V> sr = s.right;
2866 >                    TreeNode<K,V> pp = p.parent;
2867 >                    if (s == pr) { // p was s's direct parent
2868 >                        p.parent = s;
2869 >                        s.right = p;
2870 >                    }
2871 >                    else {
2872 >                        TreeNode<K,V> sp = s.parent;
2873 >                        if ((p.parent = sp) != null) {
2874 >                            if (s == sp.left)
2875 >                                sp.left = p;
2876 >                            else
2877 >                                sp.right = p;
2878 >                        }
2879 >                        if ((s.right = pr) != null)
2880 >                            pr.parent = s;
2881 >                    }
2882 >                    p.left = null;
2883 >                    if ((p.right = sr) != null)
2884 >                        sr.parent = p;
2885 >                    if ((s.left = pl) != null)
2886 >                        pl.parent = s;
2887 >                    if ((s.parent = pp) == null)
2888 >                        r = s;
2889 >                    else if (p == pp.left)
2890 >                        pp.left = s;
2891 >                    else
2892 >                        pp.right = s;
2893 >                    if (sr != null)
2894 >                        replacement = sr;
2895 >                    else
2896 >                        replacement = p;
2897 >                }
2898 >                else if (pl != null)
2899 >                    replacement = pl;
2900 >                else if (pr != null)
2901 >                    replacement = pr;
2902 >                else
2903 >                    replacement = p;
2904 >                if (replacement != p) {
2905 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2906 >                    if (pp == null)
2907 >                        r = replacement;
2908 >                    else if (p == pp.left)
2909 >                        pp.left = replacement;
2910 >                    else
2911 >                        pp.right = replacement;
2912 >                    p.left = p.right = p.parent = null;
2913 >                }
2914  
2915 <    /**
2816 <     * Removes the key (and its corresponding value) from this map.
2817 <     * This method does nothing if the key is not in the map.
2818 <     *
2819 <     * @param  key the key that needs to be removed
2820 <     * @return the previous value associated with {@code key}, or
2821 <     *         {@code null} if there was no mapping for {@code key}
2822 <     * @throws NullPointerException if the specified key is null
2823 <     */
2824 <    public V remove(Object key) {
2825 <        return internalReplace(key, null, null);
2826 <    }
2915 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2916  
2917 <    /**
2918 <     * {@inheritDoc}
2919 <     *
2920 <     * @throws NullPointerException if the specified key is null
2921 <     */
2922 <    public boolean remove(Object key, Object value) {
2923 <        return value != null && internalReplace(key, null, value) != null;
2924 <    }
2917 >                if (p == replacement) {  // detach pointers
2918 >                    TreeNode<K,V> pp;
2919 >                    if ((pp = p.parent) != null) {
2920 >                        if (p == pp.left)
2921 >                            pp.left = null;
2922 >                        else if (p == pp.right)
2923 >                            pp.right = null;
2924 >                        p.parent = null;
2925 >                    }
2926 >                }
2927 >            } finally {
2928 >                unlockRoot();
2929 >            }
2930 >            assert checkInvariants(root);
2931 >            return false;
2932 >        }
2933  
2934 <    /**
2935 <     * {@inheritDoc}
2839 <     *
2840 <     * @throws NullPointerException if any of the arguments are null
2841 <     */
2842 <    public boolean replace(K key, V oldValue, V newValue) {
2843 <        if (key == null || oldValue == null || newValue == null)
2844 <            throw new NullPointerException();
2845 <        return internalReplace(key, newValue, oldValue) != null;
2846 <    }
2934 >        /* ------------------------------------------------------------ */
2935 >        // Red-black tree methods, all adapted from CLR
2936  
2937 <    /**
2938 <     * {@inheritDoc}
2939 <     *
2940 <     * @return the previous value associated with the specified key,
2941 <     *         or {@code null} if there was no mapping for the key
2942 <     * @throws NullPointerException if the specified key or value is null
2943 <     */
2944 <    public V replace(K key, V value) {
2945 <        if (key == null || value == null)
2946 <            throw new NullPointerException();
2947 <        return internalReplace(key, value, null);
2948 <    }
2937 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2938 >                                              TreeNode<K,V> p) {
2939 >            TreeNode<K,V> r, pp, rl;
2940 >            if (p != null && (r = p.right) != null) {
2941 >                if ((rl = p.right = r.left) != null)
2942 >                    rl.parent = p;
2943 >                if ((pp = r.parent = p.parent) == null)
2944 >                    (root = r).red = false;
2945 >                else if (pp.left == p)
2946 >                    pp.left = r;
2947 >                else
2948 >                    pp.right = r;
2949 >                r.left = p;
2950 >                p.parent = r;
2951 >            }
2952 >            return root;
2953 >        }
2954  
2955 <    /**
2956 <     * Removes all of the mappings from this map.
2957 <     */
2958 <    public void clear() {
2959 <        internalClear();
2960 <    }
2955 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2956 >                                               TreeNode<K,V> p) {
2957 >            TreeNode<K,V> l, pp, lr;
2958 >            if (p != null && (l = p.left) != null) {
2959 >                if ((lr = p.left = l.right) != null)
2960 >                    lr.parent = p;
2961 >                if ((pp = l.parent = p.parent) == null)
2962 >                    (root = l).red = false;
2963 >                else if (pp.right == p)
2964 >                    pp.right = l;
2965 >                else
2966 >                    pp.left = l;
2967 >                l.right = p;
2968 >                p.parent = l;
2969 >            }
2970 >            return root;
2971 >        }
2972  
2973 <    /**
2974 <     * Returns a {@link Set} view of the keys contained in this map.
2975 <     * The set is backed by the map, so changes to the map are
2976 <     * reflected in the set, and vice-versa.
2977 <     *
2978 <     * @return the set view
2979 <     */
2980 <    public KeySetView<K,V> keySet() {
2981 <        KeySetView<K,V> ks = keySet;
2982 <        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2983 <    }
2973 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2974 >                                                    TreeNode<K,V> x) {
2975 >            x.red = true;
2976 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2977 >                if ((xp = x.parent) == null) {
2978 >                    x.red = false;
2979 >                    return x;
2980 >                }
2981 >                else if (!xp.red || (xpp = xp.parent) == null)
2982 >                    return root;
2983 >                if (xp == (xppl = xpp.left)) {
2984 >                    if ((xppr = xpp.right) != null && xppr.red) {
2985 >                        xppr.red = false;
2986 >                        xp.red = false;
2987 >                        xpp.red = true;
2988 >                        x = xpp;
2989 >                    }
2990 >                    else {
2991 >                        if (x == xp.right) {
2992 >                            root = rotateLeft(root, x = xp);
2993 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2994 >                        }
2995 >                        if (xp != null) {
2996 >                            xp.red = false;
2997 >                            if (xpp != null) {
2998 >                                xpp.red = true;
2999 >                                root = rotateRight(root, xpp);
3000 >                            }
3001 >                        }
3002 >                    }
3003 >                }
3004 >                else {
3005 >                    if (xppl != null && xppl.red) {
3006 >                        xppl.red = false;
3007 >                        xp.red = false;
3008 >                        xpp.red = true;
3009 >                        x = xpp;
3010 >                    }
3011 >                    else {
3012 >                        if (x == xp.left) {
3013 >                            root = rotateRight(root, x = xp);
3014 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3015 >                        }
3016 >                        if (xp != null) {
3017 >                            xp.red = false;
3018 >                            if (xpp != null) {
3019 >                                xpp.red = true;
3020 >                                root = rotateLeft(root, xpp);
3021 >                            }
3022 >                        }
3023 >                    }
3024 >                }
3025 >            }
3026 >        }
3027  
3028 <    /**
3029 <     * Returns a {@link Set} view of the keys in this map, using the
3030 <     * given common mapped value for any additions (i.e., {@link
3031 <     * Collection#add} and {@link Collection#addAll}). This is of
3032 <     * course only appropriate if it is acceptable to use the same
3033 <     * value for all additions from this view.
3034 <     *
3035 <     * @param mappedValue the mapped value to use for any
3036 <     * additions.
3037 <     * @return the set view
3038 <     * @throws NullPointerException if the mappedValue is null
3039 <     */
3040 <    public KeySetView<K,V> keySet(V mappedValue) {
3041 <        if (mappedValue == null)
3042 <            throw new NullPointerException();
3043 <        return new KeySetView<K,V>(this, mappedValue);
3044 <    }
3028 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3029 >                                                   TreeNode<K,V> x) {
3030 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3031 >                if (x == null || x == root)
3032 >                    return root;
3033 >                else if ((xp = x.parent) == null) {
3034 >                    x.red = false;
3035 >                    return x;
3036 >                }
3037 >                else if (x.red) {
3038 >                    x.red = false;
3039 >                    return root;
3040 >                }
3041 >                else if ((xpl = xp.left) == x) {
3042 >                    if ((xpr = xp.right) != null && xpr.red) {
3043 >                        xpr.red = false;
3044 >                        xp.red = true;
3045 >                        root = rotateLeft(root, xp);
3046 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3047 >                    }
3048 >                    if (xpr == null)
3049 >                        x = xp;
3050 >                    else {
3051 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3052 >                        if ((sr == null || !sr.red) &&
3053 >                            (sl == null || !sl.red)) {
3054 >                            xpr.red = true;
3055 >                            x = xp;
3056 >                        }
3057 >                        else {
3058 >                            if (sr == null || !sr.red) {
3059 >                                if (sl != null)
3060 >                                    sl.red = false;
3061 >                                xpr.red = true;
3062 >                                root = rotateRight(root, xpr);
3063 >                                xpr = (xp = x.parent) == null ?
3064 >                                    null : xp.right;
3065 >                            }
3066 >                            if (xpr != null) {
3067 >                                xpr.red = (xp == null) ? false : xp.red;
3068 >                                if ((sr = xpr.right) != null)
3069 >                                    sr.red = false;
3070 >                            }
3071 >                            if (xp != null) {
3072 >                                xp.red = false;
3073 >                                root = rotateLeft(root, xp);
3074 >                            }
3075 >                            x = root;
3076 >                        }
3077 >                    }
3078 >                }
3079 >                else { // symmetric
3080 >                    if (xpl != null && xpl.red) {
3081 >                        xpl.red = false;
3082 >                        xp.red = true;
3083 >                        root = rotateRight(root, xp);
3084 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3085 >                    }
3086 >                    if (xpl == null)
3087 >                        x = xp;
3088 >                    else {
3089 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3090 >                        if ((sl == null || !sl.red) &&
3091 >                            (sr == null || !sr.red)) {
3092 >                            xpl.red = true;
3093 >                            x = xp;
3094 >                        }
3095 >                        else {
3096 >                            if (sl == null || !sl.red) {
3097 >                                if (sr != null)
3098 >                                    sr.red = false;
3099 >                                xpl.red = true;
3100 >                                root = rotateLeft(root, xpl);
3101 >                                xpl = (xp = x.parent) == null ?
3102 >                                    null : xp.left;
3103 >                            }
3104 >                            if (xpl != null) {
3105 >                                xpl.red = (xp == null) ? false : xp.red;
3106 >                                if ((sl = xpl.left) != null)
3107 >                                    sl.red = false;
3108 >                            }
3109 >                            if (xp != null) {
3110 >                                xp.red = false;
3111 >                                root = rotateRight(root, xp);
3112 >                            }
3113 >                            x = root;
3114 >                        }
3115 >                    }
3116 >                }
3117 >            }
3118 >        }
3119  
3120 <    /**
3121 <     * Returns a {@link Collection} view of the values contained in this map.
3122 <     * The collection is backed by the map, so changes to the map are
3123 <     * reflected in the collection, and vice-versa.
3124 <     */
3125 <    public ValuesView<K,V> values() {
3126 <        ValuesView<K,V> vs = values;
3127 <        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
3128 <    }
3120 >        /**
3121 >         * Recursive invariant check
3122 >         */
3123 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3124 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3125 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3126 >            if (tb != null && tb.next != t)
3127 >                return false;
3128 >            if (tn != null && tn.prev != t)
3129 >                return false;
3130 >            if (tp != null && t != tp.left && t != tp.right)
3131 >                return false;
3132 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3133 >                return false;
3134 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3135 >                return false;
3136 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3137 >                return false;
3138 >            if (tl != null && !checkInvariants(tl))
3139 >                return false;
3140 >            if (tr != null && !checkInvariants(tr))
3141 >                return false;
3142 >            return true;
3143 >        }
3144  
3145 <    /**
3146 <     * Returns a {@link Set} view of the mappings contained in this map.
3147 <     * The set is backed by the map, so changes to the map are
3148 <     * reflected in the set, and vice-versa.  The set supports element
3149 <     * removal, which removes the corresponding mapping from the map,
3150 <     * via the {@code Iterator.remove}, {@code Set.remove},
3151 <     * {@code removeAll}, {@code retainAll}, and {@code clear}
3152 <     * operations.  It does not support the {@code add} or
3153 <     * {@code addAll} operations.
3154 <     *
3155 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
3156 <     * that will never throw {@link ConcurrentModificationException},
2920 <     * and guarantees to traverse elements as they existed upon
2921 <     * construction of the iterator, and may (but is not guaranteed to)
2922 <     * reflect any modifications subsequent to construction.
2923 <     */
2924 <    public Set<Map.Entry<K,V>> entrySet() {
2925 <        EntrySetView<K,V> es = entrySet;
2926 <        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
3145 >        private static final sun.misc.Unsafe U;
3146 >        private static final long LOCKSTATE;
3147 >        static {
3148 >            try {
3149 >                U = getUnsafe();
3150 >                Class<?> k = TreeBin.class;
3151 >                LOCKSTATE = U.objectFieldOffset
3152 >                    (k.getDeclaredField("lockState"));
3153 >            } catch (Exception e) {
3154 >                throw new Error(e);
3155 >            }
3156 >        }
3157      }
3158  
3159 <    /**
2930 <     * Returns an enumeration of the keys in this table.
2931 <     *
2932 <     * @return an enumeration of the keys in this table
2933 <     * @see #keySet()
2934 <     */
2935 <    public Enumeration<K> keys() {
2936 <        return new KeyIterator<K,V>(this);
2937 <    }
3159 >    /* ----------------Table Traversal -------------- */
3160  
3161      /**
3162 <     * Returns an enumeration of the values in this table.
3163 <     *
3164 <     * @return an enumeration of the values in this table
3165 <     * @see #values()
3166 <     */
3167 <    public Enumeration<V> elements() {
3168 <        return new ValueIterator<K,V>(this);
3162 >     * Records the table, its length, and current traversal index for a
3163 >     * traverser that must process a region of a forwarded table before
3164 >     * proceeding with current table.
3165 >     */
3166 >    static final class TableStack<K,V> {
3167 >        int length;
3168 >        int index;
3169 >        Node<K,V>[] tab;
3170 >        TableStack<K,V> next;
3171      }
3172  
3173      /**
3174 <     * Returns a partitionable iterator of the keys in this map.
3174 >     * Encapsulates traversal for methods such as containsValue; also
3175 >     * serves as a base class for other iterators and spliterators.
3176       *
3177 <     * @return a partitionable iterator of the keys in this map
3178 <     */
3179 <    public Spliterator<K> keySpliterator() {
3180 <        return new KeyIterator<K,V>(this);
3181 <    }
3182 <
3183 <    /**
3184 <     * Returns a partitionable iterator of the values in this map.
3177 >     * Method advance visits once each still-valid node that was
3178 >     * reachable upon iterator construction. It might miss some that
3179 >     * were added to a bin after the bin was visited, which is OK wrt
3180 >     * consistency guarantees. Maintaining this property in the face
3181 >     * of possible ongoing resizes requires a fair amount of
3182 >     * bookkeeping state that is difficult to optimize away amidst
3183 >     * volatile accesses.  Even so, traversal maintains reasonable
3184 >     * throughput.
3185       *
3186 <     * @return a partitionable iterator of the values in this map
3186 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3187 >     * However, if the table has been resized, then all future steps
3188 >     * must traverse both the bin at the current index as well as at
3189 >     * (index + baseSize); and so on for further resizings. To
3190 >     * paranoically cope with potential sharing by users of iterators
3191 >     * across threads, iteration terminates if a bounds checks fails
3192 >     * for a table read.
3193       */
3194 <    public Spliterator<V> valueSpliterator() {
3195 <        return new ValueIterator<K,V>(this);
3196 <    }
3194 >    static class Traverser<K,V> {
3195 >        Node<K,V>[] tab;        // current table; updated if resized
3196 >        Node<K,V> next;         // the next entry to use
3197 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3198 >        int index;              // index of bin to use next
3199 >        int baseIndex;          // current index of initial table
3200 >        int baseLimit;          // index bound for initial table
3201 >        final int baseSize;     // initial table size
3202 >
3203 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3204 >            this.tab = tab;
3205 >            this.baseSize = size;
3206 >            this.baseIndex = this.index = index;
3207 >            this.baseLimit = limit;
3208 >            this.next = null;
3209 >        }
3210  
3211 <    /**
3212 <     * Returns a partitionable iterator of the entries in this map.
3213 <     *
3214 <     * @return a partitionable iterator of the entries in this map
3215 <     */
3216 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
3217 <        return new EntryIterator<K,V>(this);
3218 <    }
3211 >        /**
3212 >         * Advances if possible, returning next valid node, or null if none.
3213 >         */
3214 >        final Node<K,V> advance() {
3215 >            Node<K,V> e;
3216 >            if ((e = next) != null)
3217 >                e = e.next;
3218 >            for (;;) {
3219 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3220 >                if (e != null)
3221 >                    return next = e;
3222 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3223 >                    (n = t.length) <= (i = index) || i < 0)
3224 >                    return next = null;
3225 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3226 >                    if (e instanceof ForwardingNode) {
3227 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3228 >                        e = null;
3229 >                        pushState(t, i, n);
3230 >                        continue;
3231 >                    }
3232 >                    else if (e instanceof TreeBin)
3233 >                        e = ((TreeBin<K,V>)e).first;
3234 >                    else
3235 >                        e = null;
3236 >                }
3237 >                if (stack != null)
3238 >                    recoverState(n);
3239 >                else if ((index = i + baseSize) >= n)
3240 >                    index = ++baseIndex; // visit upper slots if present
3241 >            }
3242 >        }
3243  
3244 <    /**
3245 <     * Returns the hash code value for this {@link Map}, i.e.,
3246 <     * the sum of, for each key-value pair in the map,
3247 <     * {@code key.hashCode() ^ value.hashCode()}.
3248 <     *
3249 <     * @return the hash code value for this map
3250 <     */
3251 <    public int hashCode() {
3252 <        int h = 0;
3253 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3254 <        Object v;
3255 <        while ((v = it.advance()) != null) {
3256 <            h += it.nextKey.hashCode() ^ v.hashCode();
3244 >        /**
3245 >         * Saves traversal state upon encountering a forwarding node.
3246 >         */
3247 >        private void pushState(Node<K,V>[] t, int i, int n) {
3248 >            TableStack<K,V> s = spare;  // reuse if possible
3249 >            if (s != null)
3250 >                spare = s.next;
3251 >            else
3252 >                s = new TableStack<K,V>();
3253 >            s.tab = t;
3254 >            s.length = n;
3255 >            s.index = i;
3256 >            s.next = stack;
3257 >            stack = s;
3258          }
2990        return h;
2991    }
3259  
3260 <    /**
3261 <     * Returns a string representation of this map.  The string
3262 <     * representation consists of a list of key-value mappings (in no
3263 <     * particular order) enclosed in braces ("{@code {}}").  Adjacent
3264 <     * mappings are separated by the characters {@code ", "} (comma
3265 <     * and space).  Each key-value mapping is rendered as the key
3266 <     * followed by an equals sign ("{@code =}") followed by the
3267 <     * associated value.
3268 <     *
3269 <     * @return a string representation of this map
3270 <     */
3271 <    public String toString() {
3272 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3273 <        StringBuilder sb = new StringBuilder();
3274 <        sb.append('{');
3275 <        Object v;
3009 <        if ((v = it.advance()) != null) {
3010 <            for (;;) {
3011 <                Object k = it.nextKey;
3012 <                sb.append(k == this ? "(this Map)" : k);
3013 <                sb.append('=');
3014 <                sb.append(v == this ? "(this Map)" : v);
3015 <                if ((v = it.advance()) == null)
3016 <                    break;
3017 <                sb.append(',').append(' ');
3260 >        /**
3261 >         * Possibly pops traversal state.
3262 >         *
3263 >         * @param n length of current table
3264 >         */
3265 >        private void recoverState(int n) {
3266 >            TableStack<K,V> s; int len;
3267 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3268 >                n = len;
3269 >                index = s.index;
3270 >                tab = s.tab;
3271 >                s.tab = null;
3272 >                TableStack<K,V> next = s.next;
3273 >                s.next = spare; // save for reuse
3274 >                stack = next;
3275 >                spare = s;
3276              }
3277 +            if (s == null && (index += baseSize) >= n)
3278 +                index = ++baseIndex;
3279          }
3020        return sb.append('}').toString();
3280      }
3281  
3282      /**
3283 <     * Compares the specified object with this map for equality.
3284 <     * Returns {@code true} if the given object is a map with the same
3026 <     * mappings as this map.  This operation may return misleading
3027 <     * results if either map is concurrently modified during execution
3028 <     * of this method.
3029 <     *
3030 <     * @param o object to be compared for equality with this map
3031 <     * @return {@code true} if the specified object is equal to this map
3283 >     * Base of key, value, and entry Iterators. Adds fields to
3284 >     * Traverser to support iterator.remove.
3285       */
3286 <    public boolean equals(Object o) {
3287 <        if (o != this) {
3288 <            if (!(o instanceof Map))
3289 <                return false;
3290 <            Map<?,?> m = (Map<?,?>) o;
3291 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3292 <            Object val;
3293 <            while ((val = it.advance()) != null) {
3041 <                Object v = m.get(it.nextKey);
3042 <                if (v == null || (v != val && !v.equals(val)))
3043 <                    return false;
3044 <            }
3045 <            for (Map.Entry<?,?> e : m.entrySet()) {
3046 <                Object mk, mv, v;
3047 <                if ((mk = e.getKey()) == null ||
3048 <                    (mv = e.getValue()) == null ||
3049 <                    (v = internalGet(mk)) == null ||
3050 <                    (mv != v && !mv.equals(v)))
3051 <                    return false;
3052 <            }
3286 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3287 >        final ConcurrentHashMapV8<K,V> map;
3288 >        Node<K,V> lastReturned;
3289 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3290 >                    ConcurrentHashMapV8<K,V> map) {
3291 >            super(tab, size, index, limit);
3292 >            this.map = map;
3293 >            advance();
3294          }
3054        return true;
3055    }
3295  
3296 <    /* ----------------Iterators -------------- */
3296 >        public final boolean hasNext() { return next != null; }
3297 >        public final boolean hasMoreElements() { return next != null; }
3298  
3299 <    @SuppressWarnings("serial") static final class KeyIterator<K,V>
3300 <        extends Traverser<K,V,Object>
3301 <        implements Spliterator<K>, Enumeration<K> {
3062 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3063 <        KeyIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3064 <            super(map, it, -1);
3065 <        }
3066 <        public KeyIterator<K,V> split() {
3067 <            if (nextKey != null)
3299 >        public final void remove() {
3300 >            Node<K,V> p;
3301 >            if ((p = lastReturned) == null)
3302                  throw new IllegalStateException();
3303 <            return new KeyIterator<K,V>(map, this);
3303 >            lastReturned = null;
3304 >            map.replaceNode(p.key, null, null);
3305          }
3306 <        @SuppressWarnings("unchecked") public final K next() {
3307 <            if (nextVal == null && advance() == null)
3306 >    }
3307 >
3308 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3309 >        implements Iterator<K>, Enumeration<K> {
3310 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3311 >                    ConcurrentHashMapV8<K,V> map) {
3312 >            super(tab, index, size, limit, map);
3313 >        }
3314 >
3315 >        public final K next() {
3316 >            Node<K,V> p;
3317 >            if ((p = next) == null)
3318                  throw new NoSuchElementException();
3319 <            Object k = nextKey;
3320 <            nextVal = null;
3321 <            return (K) k;
3319 >            K k = p.key;
3320 >            lastReturned = p;
3321 >            advance();
3322 >            return k;
3323          }
3324  
3325          public final K nextElement() { return next(); }
3326      }
3327  
3328 <    @SuppressWarnings("serial") static final class ValueIterator<K,V>
3329 <        extends Traverser<K,V,Object>
3330 <        implements Spliterator<V>, Enumeration<V> {
3331 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3332 <        ValueIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3087 <            super(map, it, -1);
3088 <        }
3089 <        public ValueIterator<K,V> split() {
3090 <            if (nextKey != null)
3091 <                throw new IllegalStateException();
3092 <            return new ValueIterator<K,V>(map, this);
3328 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3329 >        implements Iterator<V>, Enumeration<V> {
3330 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3331 >                      ConcurrentHashMapV8<K,V> map) {
3332 >            super(tab, index, size, limit, map);
3333          }
3334  
3335 <        @SuppressWarnings("unchecked") public final V next() {
3336 <            Object v;
3337 <            if ((v = nextVal) == null && (v = advance()) == null)
3335 >        public final V next() {
3336 >            Node<K,V> p;
3337 >            if ((p = next) == null)
3338                  throw new NoSuchElementException();
3339 <            nextVal = null;
3340 <            return (V) v;
3339 >            V v = p.val;
3340 >            lastReturned = p;
3341 >            advance();
3342 >            return v;
3343          }
3344  
3345          public final V nextElement() { return next(); }
3346      }
3347  
3348 <    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3349 <        extends Traverser<K,V,Object>
3350 <        implements Spliterator<Map.Entry<K,V>> {
3351 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3352 <        EntryIterator(ConcurrentHashMapV8<K, V> map, Traverser<K,V,Object> it) {
3111 <            super(map, it, -1);
3112 <        }
3113 <        public EntryIterator<K,V> split() {
3114 <            if (nextKey != null)
3115 <                throw new IllegalStateException();
3116 <            return new EntryIterator<K,V>(map, this);
3348 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3349 >        implements Iterator<Map.Entry<K,V>> {
3350 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3351 >                      ConcurrentHashMapV8<K,V> map) {
3352 >            super(tab, index, size, limit, map);
3353          }
3354  
3355 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3356 <            Object v;
3357 <            if ((v = nextVal) == null && (v = advance()) == null)
3355 >        public final Map.Entry<K,V> next() {
3356 >            Node<K,V> p;
3357 >            if ((p = next) == null)
3358                  throw new NoSuchElementException();
3359 <            Object k = nextKey;
3360 <            nextVal = null;
3361 <            return new MapEntry<K,V>((K)k, (V)v, map);
3359 >            K k = p.key;
3360 >            V v = p.val;
3361 >            lastReturned = p;
3362 >            advance();
3363 >            return new MapEntry<K,V>(k, v, map);
3364          }
3365      }
3366  
3367      /**
3368 <     * Exported Entry for iterators
3368 >     * Exported Entry for EntryIterator
3369       */
3370 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3370 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3371          final K key; // non-null
3372          V val;       // non-null
3373 <        final ConcurrentHashMapV8<K, V> map;
3374 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3373 >        final ConcurrentHashMapV8<K,V> map;
3374 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3375              this.key = key;
3376              this.val = val;
3377              this.map = map;
3378          }
3379 <        public final K getKey()       { return key; }
3380 <        public final V getValue()     { return val; }
3381 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3382 <        public final String toString(){ return key + "=" + val; }
3379 >        public K getKey()        { return key; }
3380 >        public V getValue()      { return val; }
3381 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3382 >        public String toString() { return key + "=" + val; }
3383  
3384 <        public final boolean equals(Object o) {
3384 >        public boolean equals(Object o) {
3385              Object k, v; Map.Entry<?,?> e;
3386              return ((o instanceof Map.Entry) &&
3387                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 3157 | Line 3395 | public class ConcurrentHashMapV8<K, V>
3395           * value to return is somewhat arbitrary here. Since we do not
3396           * necessarily track asynchronous changes, the most recent
3397           * "previous" value could be different from what we return (or
3398 <         * could even have been removed in which case the put will
3398 >         * could even have been removed, in which case the put will
3399           * re-establish). We do not and cannot guarantee more.
3400           */
3401 <        public final V setValue(V value) {
3401 >        public V setValue(V value) {
3402              if (value == null) throw new NullPointerException();
3403              V v = val;
3404              val = value;
# Line 3169 | Line 3407 | public class ConcurrentHashMapV8<K, V>
3407          }
3408      }
3409  
3410 <    /**
3411 <     * Returns exportable snapshot entry for the given key and value
3412 <     * when write-through can't or shouldn't be used.
3413 <     */
3414 <    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3415 <        return new AbstractMap.SimpleEntry<K,V>(k, v);
3416 <    }
3410 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3411 >        implements ConcurrentHashMapSpliterator<K> {
3412 >        long est;               // size estimate
3413 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3414 >                       long est) {
3415 >            super(tab, size, index, limit);
3416 >            this.est = est;
3417 >        }
3418 >
3419 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3420 >            int i, f, h;
3421 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3422 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3423 >                                        f, est >>>= 1);
3424 >        }
3425  
3426 <    /* ---------------- Serialization Support -------------- */
3426 >        public void forEachRemaining(Action<? super K> action) {
3427 >            if (action == null) throw new NullPointerException();
3428 >            for (Node<K,V> p; (p = advance()) != null;)
3429 >                action.apply(p.key);
3430 >        }
3431 >
3432 >        public boolean tryAdvance(Action<? super K> action) {
3433 >            if (action == null) throw new NullPointerException();
3434 >            Node<K,V> p;
3435 >            if ((p = advance()) == null)
3436 >                return false;
3437 >            action.apply(p.key);
3438 >            return true;
3439 >        }
3440 >
3441 >        public long estimateSize() { return est; }
3442  
3182    /**
3183     * Stripped-down version of helper class used in previous version,
3184     * declared for the sake of serialization compatibility
3185     */
3186    static class Segment<K,V> implements Serializable {
3187        private static final long serialVersionUID = 2249069246763182397L;
3188        final float loadFactor;
3189        Segment(float lf) { this.loadFactor = lf; }
3443      }
3444  
3445 <    /**
3446 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3447 <     * stream (i.e., serializes it).
3448 <     * @param s the stream
3449 <     * @serialData
3450 <     * the key (Object) and value (Object)
3451 <     * for each key-value mapping, followed by a null pair.
3199 <     * The key-value mappings are emitted in no particular order.
3200 <     */
3201 <    @SuppressWarnings("unchecked") private void writeObject
3202 <        (java.io.ObjectOutputStream s)
3203 <        throws java.io.IOException {
3204 <        if (segments == null) { // for serialization compatibility
3205 <            segments = (Segment<K,V>[])
3206 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3207 <            for (int i = 0; i < segments.length; ++i)
3208 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3209 <        }
3210 <        s.defaultWriteObject();
3211 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3212 <        Object v;
3213 <        while ((v = it.advance()) != null) {
3214 <            s.writeObject(it.nextKey);
3215 <            s.writeObject(v);
3445 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3446 >        implements ConcurrentHashMapSpliterator<V> {
3447 >        long est;               // size estimate
3448 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3449 >                         long est) {
3450 >            super(tab, size, index, limit);
3451 >            this.est = est;
3452          }
3217        s.writeObject(null);
3218        s.writeObject(null);
3219        segments = null; // throw away
3220    }
3453  
3454 <    /**
3455 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3456 <     * @param s the stream
3457 <     */
3458 <    @SuppressWarnings("unchecked") private void readObject
3459 <        (java.io.ObjectInputStream s)
3228 <        throws java.io.IOException, ClassNotFoundException {
3229 <        s.defaultReadObject();
3230 <        this.segments = null; // unneeded
3454 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3455 >            int i, f, h;
3456 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3457 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3458 >                                          f, est >>>= 1);
3459 >        }
3460  
3461 <        // Create all nodes, then place in table once size is known
3462 <        long size = 0L;
3463 <        Node p = null;
3464 <        for (;;) {
3236 <            K k = (K) s.readObject();
3237 <            V v = (V) s.readObject();
3238 <            if (k != null && v != null) {
3239 <                int h = spread(k.hashCode());
3240 <                p = new Node(h, k, v, p);
3241 <                ++size;
3242 <            }
3243 <            else
3244 <                break;
3461 >        public void forEachRemaining(Action<? super V> action) {
3462 >            if (action == null) throw new NullPointerException();
3463 >            for (Node<K,V> p; (p = advance()) != null;)
3464 >                action.apply(p.val);
3465          }
3466 <        if (p != null) {
3467 <            boolean init = false;
3468 <            int n;
3469 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3470 <                n = MAXIMUM_CAPACITY;
3471 <            else {
3472 <                int sz = (int)size;
3473 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
3254 <            }
3255 <            int sc = sizeCtl;
3256 <            boolean collide = false;
3257 <            if (n > sc &&
3258 <                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3259 <                try {
3260 <                    if (table == null) {
3261 <                        init = true;
3262 <                        Node[] tab = new Node[n];
3263 <                        int mask = n - 1;
3264 <                        while (p != null) {
3265 <                            int j = p.hash & mask;
3266 <                            Node next = p.next;
3267 <                            Node q = p.next = tabAt(tab, j);
3268 <                            setTabAt(tab, j, p);
3269 <                            if (!collide && q != null && q.hash == p.hash)
3270 <                                collide = true;
3271 <                            p = next;
3272 <                        }
3273 <                        table = tab;
3274 <                        addCount(size, -1);
3275 <                        sc = n - (n >>> 2);
3276 <                    }
3277 <                } finally {
3278 <                    sizeCtl = sc;
3279 <                }
3280 <                if (collide) { // rescan and convert to TreeBins
3281 <                    Node[] tab = table;
3282 <                    for (int i = 0; i < tab.length; ++i) {
3283 <                        int c = 0;
3284 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3285 <                            if (++c > TREE_THRESHOLD &&
3286 <                                (e.key instanceof Comparable)) {
3287 <                                replaceWithTreeBin(tab, i, e.key);
3288 <                                break;
3289 <                            }
3290 <                        }
3291 <                    }
3292 <                }
3293 <            }
3294 <            if (!init) { // Can only happen if unsafely published.
3295 <                while (p != null) {
3296 <                    internalPut((K)p.key, (V)p.val, false);
3297 <                    p = p.next;
3298 <                }
3299 <            }
3466 >
3467 >        public boolean tryAdvance(Action<? super V> action) {
3468 >            if (action == null) throw new NullPointerException();
3469 >            Node<K,V> p;
3470 >            if ((p = advance()) == null)
3471 >                return false;
3472 >            action.apply(p.val);
3473 >            return true;
3474          }
3475 +
3476 +        public long estimateSize() { return est; }
3477 +
3478      }
3479  
3480 <    // -------------------------------------------------------
3480 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3481 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3482 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3483 >        long est;               // size estimate
3484 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3485 >                         long est, ConcurrentHashMapV8<K,V> map) {
3486 >            super(tab, size, index, limit);
3487 >            this.map = map;
3488 >            this.est = est;
3489 >        }
3490  
3491 <    // Sams
3492 <    /** Interface describing a void action of one argument */
3493 <    public interface Action<A> { void apply(A a); }
3494 <    /** Interface describing a void action of two arguments */
3495 <    public interface BiAction<A,B> { void apply(A a, B b); }
3496 <    /** Interface describing a function of one argument */
3311 <    public interface Fun<A,T> { T apply(A a); }
3312 <    /** Interface describing a function of two arguments */
3313 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
3314 <    /** Interface describing a function of no arguments */
3315 <    public interface Generator<T> { T apply(); }
3316 <    /** Interface describing a function mapping its argument to a double */
3317 <    public interface ObjectToDouble<A> { double apply(A a); }
3318 <    /** Interface describing a function mapping its argument to a long */
3319 <    public interface ObjectToLong<A> { long apply(A a); }
3320 <    /** Interface describing a function mapping its argument to an int */
3321 <    public interface ObjectToInt<A> {int apply(A a); }
3322 <    /** Interface describing a function mapping two arguments to a double */
3323 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3324 <    /** Interface describing a function mapping two arguments to a long */
3325 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3326 <    /** Interface describing a function mapping two arguments to an int */
3327 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3328 <    /** Interface describing a function mapping a double to a double */
3329 <    public interface DoubleToDouble { double apply(double a); }
3330 <    /** Interface describing a function mapping a long to a long */
3331 <    public interface LongToLong { long apply(long a); }
3332 <    /** Interface describing a function mapping an int to an int */
3333 <    public interface IntToInt { int apply(int a); }
3334 <    /** Interface describing a function mapping two doubles to a double */
3335 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3336 <    /** Interface describing a function mapping two longs to a long */
3337 <    public interface LongByLongToLong { long apply(long a, long b); }
3338 <    /** Interface describing a function mapping two ints to an int */
3339 <    public interface IntByIntToInt { int apply(int a, int b); }
3491 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3492 >            int i, f, h;
3493 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3494 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3495 >                                          f, est >>>= 1, map);
3496 >        }
3497  
3498 +        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3499 +            if (action == null) throw new NullPointerException();
3500 +            for (Node<K,V> p; (p = advance()) != null; )
3501 +                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3502 +        }
3503  
3504 <    // -------------------------------------------------------
3504 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3505 >            if (action == null) throw new NullPointerException();
3506 >            Node<K,V> p;
3507 >            if ((p = advance()) == null)
3508 >                return false;
3509 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3510 >            return true;
3511 >        }
3512 >
3513 >        public long estimateSize() { return est; }
3514 >
3515 >    }
3516 >
3517 >    // Parallel bulk operations
3518 >
3519 >    /**
3520 >     * Computes initial batch value for bulk tasks. The returned value
3521 >     * is approximately exp2 of the number of times (minus one) to
3522 >     * split task by two before executing leaf action. This value is
3523 >     * faster to compute and more convenient to use as a guide to
3524 >     * splitting than is the depth, since it is used while dividing by
3525 >     * two anyway.
3526 >     */
3527 >    final int batchFor(long b) {
3528 >        long n;
3529 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3530 >            return 0;
3531 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3532 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3533 >    }
3534  
3535      /**
3536       * Performs the given action for each (key, value).
3537       *
3538 +     * @param parallelismThreshold the (estimated) number of elements
3539 +     * needed for this operation to be executed in parallel
3540       * @param action the action
3541 +     * @since 1.8
3542       */
3543 <    public void forEach(BiAction<K,V> action) {
3544 <        ForkJoinTasks.forEach
3545 <            (this, action).invoke();
3543 >    public void forEach(long parallelismThreshold,
3544 >                        BiAction<? super K,? super V> action) {
3545 >        if (action == null) throw new NullPointerException();
3546 >        new ForEachMappingTask<K,V>
3547 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3548 >             action).invoke();
3549      }
3550  
3551      /**
3552       * Performs the given action for each non-null transformation
3553       * of each (key, value).
3554       *
3555 +     * @param parallelismThreshold the (estimated) number of elements
3556 +     * needed for this operation to be executed in parallel
3557       * @param transformer a function returning the transformation
3558 <     * for an element, or null of there is no transformation (in
3559 <     * which case the action is not applied).
3558 >     * for an element, or null if there is no transformation (in
3559 >     * which case the action is not applied)
3560       * @param action the action
3561 +     * @since 1.8
3562       */
3563 <    public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3564 <                            Action<U> action) {
3565 <        ForkJoinTasks.forEach
3566 <            (this, transformer, action).invoke();
3563 >    public <U> void forEach(long parallelismThreshold,
3564 >                            BiFun<? super K, ? super V, ? extends U> transformer,
3565 >                            Action<? super U> action) {
3566 >        if (transformer == null || action == null)
3567 >            throw new NullPointerException();
3568 >        new ForEachTransformedMappingTask<K,V,U>
3569 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3570 >             transformer, action).invoke();
3571      }
3572  
3573      /**
# Line 3373 | Line 3577 | public class ConcurrentHashMapV8<K, V>
3577       * results of any other parallel invocations of the search
3578       * function are ignored.
3579       *
3580 +     * @param parallelismThreshold the (estimated) number of elements
3581 +     * needed for this operation to be executed in parallel
3582       * @param searchFunction a function returning a non-null
3583       * result on success, else null
3584       * @return a non-null result from applying the given search
3585       * function on each (key, value), or null if none
3586 +     * @since 1.8
3587       */
3588 <    public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3589 <        return ForkJoinTasks.search
3590 <            (this, searchFunction).invoke();
3588 >    public <U> U search(long parallelismThreshold,
3589 >                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3590 >        if (searchFunction == null) throw new NullPointerException();
3591 >        return new SearchMappingsTask<K,V,U>
3592 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3593 >             searchFunction, new AtomicReference<U>()).invoke();
3594      }
3595  
3596      /**
# Line 3388 | Line 3598 | public class ConcurrentHashMapV8<K, V>
3598       * of all (key, value) pairs using the given reducer to
3599       * combine values, or null if none.
3600       *
3601 +     * @param parallelismThreshold the (estimated) number of elements
3602 +     * needed for this operation to be executed in parallel
3603       * @param transformer a function returning the transformation
3604 <     * for an element, or null of there is no transformation (in
3605 <     * which case it is not combined).
3604 >     * for an element, or null if there is no transformation (in
3605 >     * which case it is not combined)
3606       * @param reducer a commutative associative combining function
3607       * @return the result of accumulating the given transformation
3608       * of all (key, value) pairs
3609 +     * @since 1.8
3610       */
3611 <    public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3611 >    public <U> U reduce(long parallelismThreshold,
3612 >                        BiFun<? super K, ? super V, ? extends U> transformer,
3613                          BiFun<? super U, ? super U, ? extends U> reducer) {
3614 <        return ForkJoinTasks.reduce
3615 <            (this, transformer, reducer).invoke();
3614 >        if (transformer == null || reducer == null)
3615 >            throw new NullPointerException();
3616 >        return new MapReduceMappingsTask<K,V,U>
3617 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3618 >             null, transformer, reducer).invoke();
3619      }
3620  
3621      /**
# Line 3406 | Line 3623 | public class ConcurrentHashMapV8<K, V>
3623       * of all (key, value) pairs using the given reducer to
3624       * combine values, and the given basis as an identity value.
3625       *
3626 +     * @param parallelismThreshold the (estimated) number of elements
3627 +     * needed for this operation to be executed in parallel
3628       * @param transformer a function returning the transformation
3629       * for an element
3630       * @param basis the identity (initial default value) for the reduction
3631       * @param reducer a commutative associative combining function
3632       * @return the result of accumulating the given transformation
3633       * of all (key, value) pairs
3634 +     * @since 1.8
3635       */
3636 <    public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3636 >    public double reduceToDouble(long parallelismThreshold,
3637 >                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3638                                   double basis,
3639                                   DoubleByDoubleToDouble reducer) {
3640 <        return ForkJoinTasks.reduceToDouble
3641 <            (this, transformer, basis, reducer).invoke();
3640 >        if (transformer == null || reducer == null)
3641 >            throw new NullPointerException();
3642 >        return new MapReduceMappingsToDoubleTask<K,V>
3643 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3644 >             null, transformer, basis, reducer).invoke();
3645      }
3646  
3647      /**
# Line 3425 | Line 3649 | public class ConcurrentHashMapV8<K, V>
3649       * of all (key, value) pairs using the given reducer to
3650       * combine values, and the given basis as an identity value.
3651       *
3652 +     * @param parallelismThreshold the (estimated) number of elements
3653 +     * needed for this operation to be executed in parallel
3654       * @param transformer a function returning the transformation
3655       * for an element
3656       * @param basis the identity (initial default value) for the reduction
3657       * @param reducer a commutative associative combining function
3658       * @return the result of accumulating the given transformation
3659       * of all (key, value) pairs
3660 +     * @since 1.8
3661       */
3662 <    public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3662 >    public long reduceToLong(long parallelismThreshold,
3663 >                             ObjectByObjectToLong<? super K, ? super V> transformer,
3664                               long basis,
3665                               LongByLongToLong reducer) {
3666 <        return ForkJoinTasks.reduceToLong
3667 <            (this, transformer, basis, reducer).invoke();
3666 >        if (transformer == null || reducer == null)
3667 >            throw new NullPointerException();
3668 >        return new MapReduceMappingsToLongTask<K,V>
3669 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3670 >             null, transformer, basis, reducer).invoke();
3671      }
3672  
3673      /**
# Line 3444 | Line 3675 | public class ConcurrentHashMapV8<K, V>
3675       * of all (key, value) pairs using the given reducer to
3676       * combine values, and the given basis as an identity value.
3677       *
3678 +     * @param parallelismThreshold the (estimated) number of elements
3679 +     * needed for this operation to be executed in parallel
3680       * @param transformer a function returning the transformation
3681       * for an element
3682       * @param basis the identity (initial default value) for the reduction
3683       * @param reducer a commutative associative combining function
3684       * @return the result of accumulating the given transformation
3685       * of all (key, value) pairs
3686 +     * @since 1.8
3687       */
3688 <    public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3688 >    public int reduceToInt(long parallelismThreshold,
3689 >                           ObjectByObjectToInt<? super K, ? super V> transformer,
3690                             int basis,
3691                             IntByIntToInt reducer) {
3692 <        return ForkJoinTasks.reduceToInt
3693 <            (this, transformer, basis, reducer).invoke();
3692 >        if (transformer == null || reducer == null)
3693 >            throw new NullPointerException();
3694 >        return new MapReduceMappingsToIntTask<K,V>
3695 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3696 >             null, transformer, basis, reducer).invoke();
3697      }
3698  
3699      /**
3700       * Performs the given action for each key.
3701       *
3702 +     * @param parallelismThreshold the (estimated) number of elements
3703 +     * needed for this operation to be executed in parallel
3704       * @param action the action
3705 +     * @since 1.8
3706       */
3707 <    public void forEachKey(Action<K> action) {
3708 <        ForkJoinTasks.forEachKey
3709 <            (this, action).invoke();
3707 >    public void forEachKey(long parallelismThreshold,
3708 >                           Action<? super K> action) {
3709 >        if (action == null) throw new NullPointerException();
3710 >        new ForEachKeyTask<K,V>
3711 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3712 >             action).invoke();
3713      }
3714  
3715      /**
3716       * Performs the given action for each non-null transformation
3717       * of each key.
3718       *
3719 +     * @param parallelismThreshold the (estimated) number of elements
3720 +     * needed for this operation to be executed in parallel
3721       * @param transformer a function returning the transformation
3722 <     * for an element, or null of there is no transformation (in
3723 <     * which case the action is not applied).
3722 >     * for an element, or null if there is no transformation (in
3723 >     * which case the action is not applied)
3724       * @param action the action
3725 +     * @since 1.8
3726       */
3727 <    public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3728 <                               Action<U> action) {
3729 <        ForkJoinTasks.forEachKey
3730 <            (this, transformer, action).invoke();
3727 >    public <U> void forEachKey(long parallelismThreshold,
3728 >                               Fun<? super K, ? extends U> transformer,
3729 >                               Action<? super U> action) {
3730 >        if (transformer == null || action == null)
3731 >            throw new NullPointerException();
3732 >        new ForEachTransformedKeyTask<K,V,U>
3733 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3734 >             transformer, action).invoke();
3735      }
3736  
3737      /**
# Line 3490 | Line 3741 | public class ConcurrentHashMapV8<K, V>
3741       * any other parallel invocations of the search function are
3742       * ignored.
3743       *
3744 +     * @param parallelismThreshold the (estimated) number of elements
3745 +     * needed for this operation to be executed in parallel
3746       * @param searchFunction a function returning a non-null
3747       * result on success, else null
3748       * @return a non-null result from applying the given search
3749       * function on each key, or null if none
3750 +     * @since 1.8
3751       */
3752 <    public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3753 <        return ForkJoinTasks.searchKeys
3754 <            (this, searchFunction).invoke();
3752 >    public <U> U searchKeys(long parallelismThreshold,
3753 >                            Fun<? super K, ? extends U> searchFunction) {
3754 >        if (searchFunction == null) throw new NullPointerException();
3755 >        return new SearchKeysTask<K,V,U>
3756 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3757 >             searchFunction, new AtomicReference<U>()).invoke();
3758      }
3759  
3760      /**
3761       * Returns the result of accumulating all keys using the given
3762       * reducer to combine values, or null if none.
3763       *
3764 +     * @param parallelismThreshold the (estimated) number of elements
3765 +     * needed for this operation to be executed in parallel
3766       * @param reducer a commutative associative combining function
3767       * @return the result of accumulating all keys using the given
3768       * reducer to combine values, or null if none
3769 +     * @since 1.8
3770       */
3771 <    public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3772 <        return ForkJoinTasks.reduceKeys
3773 <            (this, reducer).invoke();
3771 >    public K reduceKeys(long parallelismThreshold,
3772 >                        BiFun<? super K, ? super K, ? extends K> reducer) {
3773 >        if (reducer == null) throw new NullPointerException();
3774 >        return new ReduceKeysTask<K,V>
3775 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3776 >             null, reducer).invoke();
3777      }
3778  
3779      /**
# Line 3518 | Line 3781 | public class ConcurrentHashMapV8<K, V>
3781       * of all keys using the given reducer to combine values, or
3782       * null if none.
3783       *
3784 +     * @param parallelismThreshold the (estimated) number of elements
3785 +     * needed for this operation to be executed in parallel
3786       * @param transformer a function returning the transformation
3787 <     * for an element, or null of there is no transformation (in
3788 <     * which case it is not combined).
3787 >     * for an element, or null if there is no transformation (in
3788 >     * which case it is not combined)
3789       * @param reducer a commutative associative combining function
3790       * @return the result of accumulating the given transformation
3791       * of all keys
3792 +     * @since 1.8
3793       */
3794 <    public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3795 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
3796 <        return ForkJoinTasks.reduceKeys
3797 <            (this, transformer, reducer).invoke();
3794 >    public <U> U reduceKeys(long parallelismThreshold,
3795 >                            Fun<? super K, ? extends U> transformer,
3796 >         BiFun<? super U, ? super U, ? extends U> reducer) {
3797 >        if (transformer == null || reducer == null)
3798 >            throw new NullPointerException();
3799 >        return new MapReduceKeysTask<K,V,U>
3800 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3801 >             null, transformer, reducer).invoke();
3802      }
3803  
3804      /**
# Line 3536 | Line 3806 | public class ConcurrentHashMapV8<K, V>
3806       * of all keys using the given reducer to combine values, and
3807       * the given basis as an identity value.
3808       *
3809 +     * @param parallelismThreshold the (estimated) number of elements
3810 +     * needed for this operation to be executed in parallel
3811       * @param transformer a function returning the transformation
3812       * for an element
3813       * @param basis the identity (initial default value) for the reduction
3814       * @param reducer a commutative associative combining function
3815 <     * @return  the result of accumulating the given transformation
3815 >     * @return the result of accumulating the given transformation
3816       * of all keys
3817 +     * @since 1.8
3818       */
3819 <    public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3819 >    public double reduceKeysToDouble(long parallelismThreshold,
3820 >                                     ObjectToDouble<? super K> transformer,
3821                                       double basis,
3822                                       DoubleByDoubleToDouble reducer) {
3823 <        return ForkJoinTasks.reduceKeysToDouble
3824 <            (this, transformer, basis, reducer).invoke();
3823 >        if (transformer == null || reducer == null)
3824 >            throw new NullPointerException();
3825 >        return new MapReduceKeysToDoubleTask<K,V>
3826 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3827 >             null, transformer, basis, reducer).invoke();
3828      }
3829  
3830      /**
# Line 3555 | Line 3832 | public class ConcurrentHashMapV8<K, V>
3832       * of all keys using the given reducer to combine values, and
3833       * the given basis as an identity value.
3834       *
3835 +     * @param parallelismThreshold the (estimated) number of elements
3836 +     * needed for this operation to be executed in parallel
3837       * @param transformer a function returning the transformation
3838       * for an element
3839       * @param basis the identity (initial default value) for the reduction
3840       * @param reducer a commutative associative combining function
3841       * @return the result of accumulating the given transformation
3842       * of all keys
3843 +     * @since 1.8
3844       */
3845 <    public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3845 >    public long reduceKeysToLong(long parallelismThreshold,
3846 >                                 ObjectToLong<? super K> transformer,
3847                                   long basis,
3848                                   LongByLongToLong reducer) {
3849 <        return ForkJoinTasks.reduceKeysToLong
3850 <            (this, transformer, basis, reducer).invoke();
3849 >        if (transformer == null || reducer == null)
3850 >            throw new NullPointerException();
3851 >        return new MapReduceKeysToLongTask<K,V>
3852 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3853 >             null, transformer, basis, reducer).invoke();
3854      }
3855  
3856      /**
# Line 3574 | Line 3858 | public class ConcurrentHashMapV8<K, V>
3858       * of all keys using the given reducer to combine values, and
3859       * the given basis as an identity value.
3860       *
3861 +     * @param parallelismThreshold the (estimated) number of elements
3862 +     * needed for this operation to be executed in parallel
3863       * @param transformer a function returning the transformation
3864       * for an element
3865       * @param basis the identity (initial default value) for the reduction
3866       * @param reducer a commutative associative combining function
3867       * @return the result of accumulating the given transformation
3868       * of all keys
3869 +     * @since 1.8
3870       */
3871 <    public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3871 >    public int reduceKeysToInt(long parallelismThreshold,
3872 >                               ObjectToInt<? super K> transformer,
3873                                 int basis,
3874                                 IntByIntToInt reducer) {
3875 <        return ForkJoinTasks.reduceKeysToInt
3876 <            (this, transformer, basis, reducer).invoke();
3875 >        if (transformer == null || reducer == null)
3876 >            throw new NullPointerException();
3877 >        return new MapReduceKeysToIntTask<K,V>
3878 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3879 >             null, transformer, basis, reducer).invoke();
3880      }
3881  
3882      /**
3883       * Performs the given action for each value.
3884       *
3885 +     * @param parallelismThreshold the (estimated) number of elements
3886 +     * needed for this operation to be executed in parallel
3887       * @param action the action
3888 +     * @since 1.8
3889       */
3890 <    public void forEachValue(Action<V> action) {
3891 <        ForkJoinTasks.forEachValue
3892 <            (this, action).invoke();
3890 >    public void forEachValue(long parallelismThreshold,
3891 >                             Action<? super V> action) {
3892 >        if (action == null)
3893 >            throw new NullPointerException();
3894 >        new ForEachValueTask<K,V>
3895 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3896 >             action).invoke();
3897      }
3898  
3899      /**
3900       * Performs the given action for each non-null transformation
3901       * of each value.
3902       *
3903 +     * @param parallelismThreshold the (estimated) number of elements
3904 +     * needed for this operation to be executed in parallel
3905       * @param transformer a function returning the transformation
3906 <     * for an element, or null of there is no transformation (in
3907 <     * which case the action is not applied).
3906 >     * for an element, or null if there is no transformation (in
3907 >     * which case the action is not applied)
3908 >     * @param action the action
3909 >     * @since 1.8
3910       */
3911 <    public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3912 <                                 Action<U> action) {
3913 <        ForkJoinTasks.forEachValue
3914 <            (this, transformer, action).invoke();
3911 >    public <U> void forEachValue(long parallelismThreshold,
3912 >                                 Fun<? super V, ? extends U> transformer,
3913 >                                 Action<? super U> action) {
3914 >        if (transformer == null || action == null)
3915 >            throw new NullPointerException();
3916 >        new ForEachTransformedValueTask<K,V,U>
3917 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3918 >             transformer, action).invoke();
3919      }
3920  
3921      /**
# Line 3619 | Line 3925 | public class ConcurrentHashMapV8<K, V>
3925       * any other parallel invocations of the search function are
3926       * ignored.
3927       *
3928 +     * @param parallelismThreshold the (estimated) number of elements
3929 +     * needed for this operation to be executed in parallel
3930       * @param searchFunction a function returning a non-null
3931       * result on success, else null
3932       * @return a non-null result from applying the given search
3933       * function on each value, or null if none
3934 <     *
3934 >     * @since 1.8
3935       */
3936 <    public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3937 <        return ForkJoinTasks.searchValues
3938 <            (this, searchFunction).invoke();
3936 >    public <U> U searchValues(long parallelismThreshold,
3937 >                              Fun<? super V, ? extends U> searchFunction) {
3938 >        if (searchFunction == null) throw new NullPointerException();
3939 >        return new SearchValuesTask<K,V,U>
3940 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3941 >             searchFunction, new AtomicReference<U>()).invoke();
3942      }
3943  
3944      /**
3945       * Returns the result of accumulating all values using the
3946       * given reducer to combine values, or null if none.
3947       *
3948 +     * @param parallelismThreshold the (estimated) number of elements
3949 +     * needed for this operation to be executed in parallel
3950       * @param reducer a commutative associative combining function
3951 <     * @return  the result of accumulating all values
3951 >     * @return the result of accumulating all values
3952 >     * @since 1.8
3953       */
3954 <    public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3955 <        return ForkJoinTasks.reduceValues
3956 <            (this, reducer).invoke();
3954 >    public V reduceValues(long parallelismThreshold,
3955 >                          BiFun<? super V, ? super V, ? extends V> reducer) {
3956 >        if (reducer == null) throw new NullPointerException();
3957 >        return new ReduceValuesTask<K,V>
3958 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3959 >             null, reducer).invoke();
3960      }
3961  
3962      /**
# Line 3647 | Line 3964 | public class ConcurrentHashMapV8<K, V>
3964       * of all values using the given reducer to combine values, or
3965       * null if none.
3966       *
3967 +     * @param parallelismThreshold the (estimated) number of elements
3968 +     * needed for this operation to be executed in parallel
3969       * @param transformer a function returning the transformation
3970 <     * for an element, or null of there is no transformation (in
3971 <     * which case it is not combined).
3970 >     * for an element, or null if there is no transformation (in
3971 >     * which case it is not combined)
3972       * @param reducer a commutative associative combining function
3973       * @return the result of accumulating the given transformation
3974       * of all values
3975 +     * @since 1.8
3976       */
3977 <    public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3977 >    public <U> U reduceValues(long parallelismThreshold,
3978 >                              Fun<? super V, ? extends U> transformer,
3979                                BiFun<? super U, ? super U, ? extends U> reducer) {
3980 <        return ForkJoinTasks.reduceValues
3981 <            (this, transformer, reducer).invoke();
3980 >        if (transformer == null || reducer == null)
3981 >            throw new NullPointerException();
3982 >        return new MapReduceValuesTask<K,V,U>
3983 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3984 >             null, transformer, reducer).invoke();
3985      }
3986  
3987      /**
# Line 3665 | Line 3989 | public class ConcurrentHashMapV8<K, V>
3989       * of all values using the given reducer to combine values,
3990       * and the given basis as an identity value.
3991       *
3992 +     * @param parallelismThreshold the (estimated) number of elements
3993 +     * needed for this operation to be executed in parallel
3994       * @param transformer a function returning the transformation
3995       * for an element
3996       * @param basis the identity (initial default value) for the reduction
3997       * @param reducer a commutative associative combining function
3998       * @return the result of accumulating the given transformation
3999       * of all values
4000 +     * @since 1.8
4001       */
4002 <    public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
4002 >    public double reduceValuesToDouble(long parallelismThreshold,
4003 >                                       ObjectToDouble<? super V> transformer,
4004                                         double basis,
4005                                         DoubleByDoubleToDouble reducer) {
4006 <        return ForkJoinTasks.reduceValuesToDouble
4007 <            (this, transformer, basis, reducer).invoke();
4006 >        if (transformer == null || reducer == null)
4007 >            throw new NullPointerException();
4008 >        return new MapReduceValuesToDoubleTask<K,V>
4009 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4010 >             null, transformer, basis, reducer).invoke();
4011      }
4012  
4013      /**
# Line 3684 | Line 4015 | public class ConcurrentHashMapV8<K, V>
4015       * of all values using the given reducer to combine values,
4016       * and the given basis as an identity value.
4017       *
4018 +     * @param parallelismThreshold the (estimated) number of elements
4019 +     * needed for this operation to be executed in parallel
4020       * @param transformer a function returning the transformation
4021       * for an element
4022       * @param basis the identity (initial default value) for the reduction
4023       * @param reducer a commutative associative combining function
4024       * @return the result of accumulating the given transformation
4025       * of all values
4026 +     * @since 1.8
4027       */
4028 <    public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4028 >    public long reduceValuesToLong(long parallelismThreshold,
4029 >                                   ObjectToLong<? super V> transformer,
4030                                     long basis,
4031                                     LongByLongToLong reducer) {
4032 <        return ForkJoinTasks.reduceValuesToLong
4033 <            (this, transformer, basis, reducer).invoke();
4032 >        if (transformer == null || reducer == null)
4033 >            throw new NullPointerException();
4034 >        return new MapReduceValuesToLongTask<K,V>
4035 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4036 >             null, transformer, basis, reducer).invoke();
4037      }
4038  
4039      /**
# Line 3703 | Line 4041 | public class ConcurrentHashMapV8<K, V>
4041       * of all values using the given reducer to combine values,
4042       * and the given basis as an identity value.
4043       *
4044 +     * @param parallelismThreshold the (estimated) number of elements
4045 +     * needed for this operation to be executed in parallel
4046       * @param transformer a function returning the transformation
4047       * for an element
4048       * @param basis the identity (initial default value) for the reduction
4049       * @param reducer a commutative associative combining function
4050       * @return the result of accumulating the given transformation
4051       * of all values
4052 +     * @since 1.8
4053       */
4054 <    public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4054 >    public int reduceValuesToInt(long parallelismThreshold,
4055 >                                 ObjectToInt<? super V> transformer,
4056                                   int basis,
4057                                   IntByIntToInt reducer) {
4058 <        return ForkJoinTasks.reduceValuesToInt
4059 <            (this, transformer, basis, reducer).invoke();
4058 >        if (transformer == null || reducer == null)
4059 >            throw new NullPointerException();
4060 >        return new MapReduceValuesToIntTask<K,V>
4061 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4062 >             null, transformer, basis, reducer).invoke();
4063      }
4064  
4065      /**
4066       * Performs the given action for each entry.
4067       *
4068 +     * @param parallelismThreshold the (estimated) number of elements
4069 +     * needed for this operation to be executed in parallel
4070       * @param action the action
4071 +     * @since 1.8
4072       */
4073 <    public void forEachEntry(Action<Map.Entry<K,V>> action) {
4074 <        ForkJoinTasks.forEachEntry
4075 <            (this, action).invoke();
4073 >    public void forEachEntry(long parallelismThreshold,
4074 >                             Action<? super Map.Entry<K,V>> action) {
4075 >        if (action == null) throw new NullPointerException();
4076 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4077 >                                  action).invoke();
4078      }
4079  
4080      /**
4081       * Performs the given action for each non-null transformation
4082       * of each entry.
4083       *
4084 +     * @param parallelismThreshold the (estimated) number of elements
4085 +     * needed for this operation to be executed in parallel
4086       * @param transformer a function returning the transformation
4087 <     * for an element, or null of there is no transformation (in
4088 <     * which case the action is not applied).
4087 >     * for an element, or null if there is no transformation (in
4088 >     * which case the action is not applied)
4089       * @param action the action
4090 +     * @since 1.8
4091       */
4092 <    public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4093 <                                 Action<U> action) {
4094 <        ForkJoinTasks.forEachEntry
4095 <            (this, transformer, action).invoke();
4092 >    public <U> void forEachEntry(long parallelismThreshold,
4093 >                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
4094 >                                 Action<? super U> action) {
4095 >        if (transformer == null || action == null)
4096 >            throw new NullPointerException();
4097 >        new ForEachTransformedEntryTask<K,V,U>
4098 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4099 >             transformer, action).invoke();
4100      }
4101  
4102      /**
# Line 3749 | Line 4106 | public class ConcurrentHashMapV8<K, V>
4106       * any other parallel invocations of the search function are
4107       * ignored.
4108       *
4109 +     * @param parallelismThreshold the (estimated) number of elements
4110 +     * needed for this operation to be executed in parallel
4111       * @param searchFunction a function returning a non-null
4112       * result on success, else null
4113       * @return a non-null result from applying the given search
4114       * function on each entry, or null if none
4115 +     * @since 1.8
4116       */
4117 <    public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4118 <        return ForkJoinTasks.searchEntries
4119 <            (this, searchFunction).invoke();
4117 >    public <U> U searchEntries(long parallelismThreshold,
4118 >                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4119 >        if (searchFunction == null) throw new NullPointerException();
4120 >        return new SearchEntriesTask<K,V,U>
4121 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4122 >             searchFunction, new AtomicReference<U>()).invoke();
4123      }
4124  
4125      /**
4126       * Returns the result of accumulating all entries using the
4127       * given reducer to combine values, or null if none.
4128       *
4129 +     * @param parallelismThreshold the (estimated) number of elements
4130 +     * needed for this operation to be executed in parallel
4131       * @param reducer a commutative associative combining function
4132       * @return the result of accumulating all entries
4133 +     * @since 1.8
4134       */
4135 <    public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4136 <        return ForkJoinTasks.reduceEntries
4137 <            (this, reducer).invoke();
4135 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4136 >                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4137 >        if (reducer == null) throw new NullPointerException();
4138 >        return new ReduceEntriesTask<K,V>
4139 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4140 >             null, reducer).invoke();
4141      }
4142  
4143      /**
# Line 3776 | Line 4145 | public class ConcurrentHashMapV8<K, V>
4145       * of all entries using the given reducer to combine values,
4146       * or null if none.
4147       *
4148 +     * @param parallelismThreshold the (estimated) number of elements
4149 +     * needed for this operation to be executed in parallel
4150       * @param transformer a function returning the transformation
4151 <     * for an element, or null of there is no transformation (in
4152 <     * which case it is not combined).
4151 >     * for an element, or null if there is no transformation (in
4152 >     * which case it is not combined)
4153       * @param reducer a commutative associative combining function
4154       * @return the result of accumulating the given transformation
4155       * of all entries
4156 +     * @since 1.8
4157       */
4158 <    public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4158 >    public <U> U reduceEntries(long parallelismThreshold,
4159 >                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4160                                 BiFun<? super U, ? super U, ? extends U> reducer) {
4161 <        return ForkJoinTasks.reduceEntries
4162 <            (this, transformer, reducer).invoke();
4161 >        if (transformer == null || reducer == null)
4162 >            throw new NullPointerException();
4163 >        return new MapReduceEntriesTask<K,V,U>
4164 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4165 >             null, transformer, reducer).invoke();
4166      }
4167  
4168      /**
# Line 3794 | Line 4170 | public class ConcurrentHashMapV8<K, V>
4170       * of all entries using the given reducer to combine values,
4171       * and the given basis as an identity value.
4172       *
4173 +     * @param parallelismThreshold the (estimated) number of elements
4174 +     * needed for this operation to be executed in parallel
4175       * @param transformer a function returning the transformation
4176       * for an element
4177       * @param basis the identity (initial default value) for the reduction
4178       * @param reducer a commutative associative combining function
4179       * @return the result of accumulating the given transformation
4180       * of all entries
4181 +     * @since 1.8
4182       */
4183 <    public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4183 >    public double reduceEntriesToDouble(long parallelismThreshold,
4184 >                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4185                                          double basis,
4186                                          DoubleByDoubleToDouble reducer) {
4187 <        return ForkJoinTasks.reduceEntriesToDouble
4188 <            (this, transformer, basis, reducer).invoke();
4187 >        if (transformer == null || reducer == null)
4188 >            throw new NullPointerException();
4189 >        return new MapReduceEntriesToDoubleTask<K,V>
4190 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4191 >             null, transformer, basis, reducer).invoke();
4192      }
4193  
4194      /**
# Line 3813 | Line 4196 | public class ConcurrentHashMapV8<K, V>
4196       * of all entries using the given reducer to combine values,
4197       * and the given basis as an identity value.
4198       *
4199 +     * @param parallelismThreshold the (estimated) number of elements
4200 +     * needed for this operation to be executed in parallel
4201       * @param transformer a function returning the transformation
4202       * for an element
4203       * @param basis the identity (initial default value) for the reduction
4204       * @param reducer a commutative associative combining function
4205 <     * @return  the result of accumulating the given transformation
4205 >     * @return the result of accumulating the given transformation
4206       * of all entries
4207 +     * @since 1.8
4208       */
4209 <    public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4209 >    public long reduceEntriesToLong(long parallelismThreshold,
4210 >                                    ObjectToLong<Map.Entry<K,V>> transformer,
4211                                      long basis,
4212                                      LongByLongToLong reducer) {
4213 <        return ForkJoinTasks.reduceEntriesToLong
4214 <            (this, transformer, basis, reducer).invoke();
4213 >        if (transformer == null || reducer == null)
4214 >            throw new NullPointerException();
4215 >        return new MapReduceEntriesToLongTask<K,V>
4216 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4217 >             null, transformer, basis, reducer).invoke();
4218      }
4219  
4220      /**
# Line 3832 | Line 4222 | public class ConcurrentHashMapV8<K, V>
4222       * of all entries using the given reducer to combine values,
4223       * and the given basis as an identity value.
4224       *
4225 +     * @param parallelismThreshold the (estimated) number of elements
4226 +     * needed for this operation to be executed in parallel
4227       * @param transformer a function returning the transformation
4228       * for an element
4229       * @param basis the identity (initial default value) for the reduction
4230       * @param reducer a commutative associative combining function
4231       * @return the result of accumulating the given transformation
4232       * of all entries
4233 +     * @since 1.8
4234       */
4235 <    public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4235 >    public int reduceEntriesToInt(long parallelismThreshold,
4236 >                                  ObjectToInt<Map.Entry<K,V>> transformer,
4237                                    int basis,
4238                                    IntByIntToInt reducer) {
4239 <        return ForkJoinTasks.reduceEntriesToInt
4240 <            (this, transformer, basis, reducer).invoke();
4239 >        if (transformer == null || reducer == null)
4240 >            throw new NullPointerException();
4241 >        return new MapReduceEntriesToIntTask<K,V>
4242 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4243 >             null, transformer, basis, reducer).invoke();
4244      }
4245  
4246 +
4247      /* ----------------Views -------------- */
4248  
4249      /**
4250       * Base class for views.
4251       */
4252 <    static abstract class CHMView<K, V> {
4253 <        final ConcurrentHashMapV8<K, V> map;
4254 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
4252 >    abstract static class CollectionView<K,V,E>
4253 >        implements Collection<E>, java.io.Serializable {
4254 >        private static final long serialVersionUID = 7249069246763182397L;
4255 >        final ConcurrentHashMapV8<K,V> map;
4256 >        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4257  
4258          /**
4259           * Returns the map backing this view.
# Line 3862 | Line 4262 | public class ConcurrentHashMapV8<K, V>
4262           */
4263          public ConcurrentHashMapV8<K,V> getMap() { return map; }
4264  
4265 <        public final int size()                 { return map.size(); }
4266 <        public final boolean isEmpty()          { return map.isEmpty(); }
4267 <        public final void clear()               { map.clear(); }
4265 >        /**
4266 >         * Removes all of the elements from this view, by removing all
4267 >         * the mappings from the map backing this view.
4268 >         */
4269 >        public final void clear()      { map.clear(); }
4270 >        public final int size()        { return map.size(); }
4271 >        public final boolean isEmpty() { return map.isEmpty(); }
4272  
4273          // implementations below rely on concrete classes supplying these
4274 <        abstract public Iterator<?> iterator();
4275 <        abstract public boolean contains(Object o);
4276 <        abstract public boolean remove(Object o);
4274 >        // abstract methods
4275 >        /**
4276 >         * Returns a "weakly consistent" iterator that will never
4277 >         * throw {@link ConcurrentModificationException}, and
4278 >         * guarantees to traverse elements as they existed upon
4279 >         * construction of the iterator, and may (but is not
4280 >         * guaranteed to) reflect any modifications subsequent to
4281 >         * construction.
4282 >         */
4283 >        public abstract Iterator<E> iterator();
4284 >        public abstract boolean contains(Object o);
4285 >        public abstract boolean remove(Object o);
4286  
4287          private static final String oomeMsg = "Required array size too large";
4288  
4289          public final Object[] toArray() {
4290              long sz = map.mappingCount();
4291 <            if (sz > (long)(MAX_ARRAY_SIZE))
4291 >            if (sz > MAX_ARRAY_SIZE)
4292                  throw new OutOfMemoryError(oomeMsg);
4293              int n = (int)sz;
4294              Object[] r = new Object[n];
4295              int i = 0;
4296 <            Iterator<?> it = iterator();
3884 <            while (it.hasNext()) {
4296 >            for (E e : this) {
4297                  if (i == n) {
4298                      if (n >= MAX_ARRAY_SIZE)
4299                          throw new OutOfMemoryError(oomeMsg);
# Line 3891 | Line 4303 | public class ConcurrentHashMapV8<K, V>
4303                          n += (n >>> 1) + 1;
4304                      r = Arrays.copyOf(r, n);
4305                  }
4306 <                r[i++] = it.next();
4306 >                r[i++] = e;
4307              }
4308              return (i == n) ? r : Arrays.copyOf(r, i);
4309          }
4310  
4311 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4311 >        @SuppressWarnings("unchecked")
4312 >        public final <T> T[] toArray(T[] a) {
4313              long sz = map.mappingCount();
4314 <            if (sz > (long)(MAX_ARRAY_SIZE))
4314 >            if (sz > MAX_ARRAY_SIZE)
4315                  throw new OutOfMemoryError(oomeMsg);
4316              int m = (int)sz;
4317              T[] r = (a.length >= m) ? a :
# Line 3906 | Line 4319 | public class ConcurrentHashMapV8<K, V>
4319                  .newInstance(a.getClass().getComponentType(), m);
4320              int n = r.length;
4321              int i = 0;
4322 <            Iterator<?> it = iterator();
3910 <            while (it.hasNext()) {
4322 >            for (E e : this) {
4323                  if (i == n) {
4324                      if (n >= MAX_ARRAY_SIZE)
4325                          throw new OutOfMemoryError(oomeMsg);
# Line 3917 | Line 4329 | public class ConcurrentHashMapV8<K, V>
4329                          n += (n >>> 1) + 1;
4330                      r = Arrays.copyOf(r, n);
4331                  }
4332 <                r[i++] = (T)it.next();
4332 >                r[i++] = (T)e;
4333              }
4334              if (a == r && i < n) {
4335                  r[i] = null; // null-terminate
# Line 3926 | Line 4338 | public class ConcurrentHashMapV8<K, V>
4338              return (i == n) ? r : Arrays.copyOf(r, i);
4339          }
4340  
4341 <        public final int hashCode() {
4342 <            int h = 0;
4343 <            for (Iterator<?> it = iterator(); it.hasNext();)
4344 <                h += it.next().hashCode();
4345 <            return h;
4346 <        }
4347 <
4341 >        /**
4342 >         * Returns a string representation of this collection.
4343 >         * The string representation consists of the string representations
4344 >         * of the collection's elements in the order they are returned by
4345 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4346 >         * Adjacent elements are separated by the characters {@code ", "}
4347 >         * (comma and space).  Elements are converted to strings as by
4348 >         * {@link String#valueOf(Object)}.
4349 >         *
4350 >         * @return a string representation of this collection
4351 >         */
4352          public final String toString() {
4353              StringBuilder sb = new StringBuilder();
4354              sb.append('[');
4355 <            Iterator<?> it = iterator();
4355 >            Iterator<E> it = iterator();
4356              if (it.hasNext()) {
4357                  for (;;) {
4358                      Object e = it.next();
# Line 3951 | Line 4367 | public class ConcurrentHashMapV8<K, V>
4367  
4368          public final boolean containsAll(Collection<?> c) {
4369              if (c != this) {
4370 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3955 <                    Object e = it.next();
4370 >                for (Object e : c) {
4371                      if (e == null || !contains(e))
4372                          return false;
4373                  }
# Line 3962 | Line 4377 | public class ConcurrentHashMapV8<K, V>
4377  
4378          public final boolean removeAll(Collection<?> c) {
4379              boolean modified = false;
4380 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4380 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4381                  if (c.contains(it.next())) {
4382                      it.remove();
4383                      modified = true;
# Line 3973 | Line 4388 | public class ConcurrentHashMapV8<K, V>
4388  
4389          public final boolean retainAll(Collection<?> c) {
4390              boolean modified = false;
4391 <            for (Iterator<?> it = iterator(); it.hasNext();) {
4391 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4392                  if (!c.contains(it.next())) {
4393                      it.remove();
4394                      modified = true;
# Line 3987 | Line 4402 | public class ConcurrentHashMapV8<K, V>
4402      /**
4403       * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4404       * which additions may optionally be enabled by mapping to a
4405 <     * common value.  This class cannot be directly instantiated. See
4406 <     * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4407 <     * {@link #newKeySet(int)}.
4405 >     * common value.  This class cannot be directly instantiated.
4406 >     * See {@link #keySet() keySet()},
4407 >     * {@link #keySet(Object) keySet(V)},
4408 >     * {@link #newKeySet() newKeySet()},
4409 >     * {@link #newKeySet(int) newKeySet(int)}.
4410 >     *
4411 >     * @since 1.8
4412       */
4413 <    public static class KeySetView<K,V> extends CHMView<K,V>
4413 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4414          implements Set<K>, java.io.Serializable {
4415          private static final long serialVersionUID = 7249069246763182397L;
4416          private final V value;
4417 <        KeySetView(ConcurrentHashMapV8<K, V> map, V value) {  // non-public
4417 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4418              super(map);
4419              this.value = value;
4420          }
# Line 4005 | Line 4424 | public class ConcurrentHashMapV8<K, V>
4424           * or {@code null} if additions are not supported.
4425           *
4426           * @return the default mapped value for additions, or {@code null}
4427 <         * if not supported.
4427 >         * if not supported
4428           */
4429          public V getMappedValue() { return value; }
4430  
4431 <        // implement Set API
4432 <
4431 >        /**
4432 >         * {@inheritDoc}
4433 >         * @throws NullPointerException if the specified key is null
4434 >         */
4435          public boolean contains(Object o) { return map.containsKey(o); }
4015        public boolean remove(Object o)   { return map.remove(o) != null; }
4436  
4437          /**
4438 <         * Returns a "weakly consistent" iterator that will never
4439 <         * throw {@link ConcurrentModificationException}, and
4440 <         * guarantees to traverse elements as they existed upon
4021 <         * construction of the iterator, and may (but is not
4022 <         * guaranteed to) reflect any modifications subsequent to
4023 <         * construction.
4438 >         * Removes the key from this map view, by removing the key (and its
4439 >         * corresponding value) from the backing map.  This method does
4440 >         * nothing if the key is not in the map.
4441           *
4442 <         * @return an iterator over the keys of this map
4442 >         * @param  o the key to be removed from the backing map
4443 >         * @return {@code true} if the backing map contained the specified key
4444 >         * @throws NullPointerException if the specified key is null
4445 >         */
4446 >        public boolean remove(Object o) { return map.remove(o) != null; }
4447 >
4448 >        /**
4449 >         * @return an iterator over the keys of the backing map
4450 >         */
4451 >        public Iterator<K> iterator() {
4452 >            Node<K,V>[] t;
4453 >            ConcurrentHashMapV8<K,V> m = map;
4454 >            int f = (t = m.table) == null ? 0 : t.length;
4455 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4456 >        }
4457 >
4458 >        /**
4459 >         * Adds the specified key to this set view by mapping the key to
4460 >         * the default mapped value in the backing map, if defined.
4461 >         *
4462 >         * @param e key to be added
4463 >         * @return {@code true} if this set changed as a result of the call
4464 >         * @throws NullPointerException if the specified key is null
4465 >         * @throws UnsupportedOperationException if no default mapped value
4466 >         * for additions was provided
4467           */
4027        public Iterator<K> iterator()     { return new KeyIterator<K,V>(map); }
4468          public boolean add(K e) {
4469              V v;
4470              if ((v = value) == null)
4471                  throw new UnsupportedOperationException();
4472 <            if (e == null)
4033 <                throw new NullPointerException();
4034 <            return map.internalPut(e, v, true) == null;
4472 >            return map.putVal(e, v, true) == null;
4473          }
4474 +
4475 +        /**
4476 +         * Adds all of the elements in the specified collection to this set,
4477 +         * as if by calling {@link #add} on each one.
4478 +         *
4479 +         * @param c the elements to be inserted into this set
4480 +         * @return {@code true} if this set changed as a result of the call
4481 +         * @throws NullPointerException if the collection or any of its
4482 +         * elements are {@code null}
4483 +         * @throws UnsupportedOperationException if no default mapped value
4484 +         * for additions was provided
4485 +         */
4486          public boolean addAll(Collection<? extends K> c) {
4487              boolean added = false;
4488              V v;
4489              if ((v = value) == null)
4490                  throw new UnsupportedOperationException();
4491              for (K e : c) {
4492 <                if (e == null)
4043 <                    throw new NullPointerException();
4044 <                if (map.internalPut(e, v, true) == null)
4492 >                if (map.putVal(e, v, true) == null)
4493                      added = true;
4494              }
4495              return added;
4496          }
4497 +
4498 +        public int hashCode() {
4499 +            int h = 0;
4500 +            for (K e : this)
4501 +                h += e.hashCode();
4502 +            return h;
4503 +        }
4504 +
4505          public boolean equals(Object o) {
4506              Set<?> c;
4507              return ((o instanceof Set) &&
# Line 4053 | Line 4509 | public class ConcurrentHashMapV8<K, V>
4509                       (containsAll(c) && c.containsAll(this))));
4510          }
4511  
4512 <        /**
4513 <         * Performs the given action for each key.
4514 <         *
4515 <         * @param action the action
4516 <         */
4517 <        public void forEach(Action<K> action) {
4062 <            ForkJoinTasks.forEachKey
4063 <                (map, action).invoke();
4064 <        }
4065 <
4066 <        /**
4067 <         * Performs the given action for each non-null transformation
4068 <         * of each key.
4069 <         *
4070 <         * @param transformer a function returning the transformation
4071 <         * for an element, or null of there is no transformation (in
4072 <         * which case the action is not applied).
4073 <         * @param action the action
4074 <         */
4075 <        public <U> void forEach(Fun<? super K, ? extends U> transformer,
4076 <                                Action<U> action) {
4077 <            ForkJoinTasks.forEachKey
4078 <                (map, transformer, action).invoke();
4512 >        public ConcurrentHashMapSpliterator<K> spliterator() {
4513 >            Node<K,V>[] t;
4514 >            ConcurrentHashMapV8<K,V> m = map;
4515 >            long n = m.sumCount();
4516 >            int f = (t = m.table) == null ? 0 : t.length;
4517 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4518          }
4519  
4520 <        /**
4521 <         * Returns a non-null result from applying the given search
4522 <         * function on each key, or null if none. Upon success,
4523 <         * further element processing is suppressed and the results of
4524 <         * any other parallel invocations of the search function are
4525 <         * ignored.
4526 <         *
4527 <         * @param searchFunction a function returning a non-null
4089 <         * result on success, else null
4090 <         * @return a non-null result from applying the given search
4091 <         * function on each key, or null if none
4092 <         */
4093 <        public <U> U search(Fun<? super K, ? extends U> searchFunction) {
4094 <            return ForkJoinTasks.searchKeys
4095 <                (map, searchFunction).invoke();
4096 <        }
4097 <
4098 <        /**
4099 <         * Returns the result of accumulating all keys using the given
4100 <         * reducer to combine values, or null if none.
4101 <         *
4102 <         * @param reducer a commutative associative combining function
4103 <         * @return the result of accumulating all keys using the given
4104 <         * reducer to combine values, or null if none
4105 <         */
4106 <        public K reduce(BiFun<? super K, ? super K, ? extends K> reducer) {
4107 <            return ForkJoinTasks.reduceKeys
4108 <                (map, reducer).invoke();
4109 <        }
4110 <
4111 <        /**
4112 <         * Returns the result of accumulating the given transformation
4113 <         * of all keys using the given reducer to combine values, and
4114 <         * the given basis as an identity value.
4115 <         *
4116 <         * @param transformer a function returning the transformation
4117 <         * for an element
4118 <         * @param basis the identity (initial default value) for the reduction
4119 <         * @param reducer a commutative associative combining function
4120 <         * @return  the result of accumulating the given transformation
4121 <         * of all keys
4122 <         */
4123 <        public double reduceToDouble(ObjectToDouble<? super K> transformer,
4124 <                                     double basis,
4125 <                                     DoubleByDoubleToDouble reducer) {
4126 <            return ForkJoinTasks.reduceKeysToDouble
4127 <                (map, transformer, basis, reducer).invoke();
4128 <        }
4129 <
4130 <        /**
4131 <         * Returns the result of accumulating the given transformation
4132 <         * of all keys using the given reducer to combine values, and
4133 <         * the given basis as an identity value.
4134 <         *
4135 <         * @param transformer a function returning the transformation
4136 <         * for an element
4137 <         * @param basis the identity (initial default value) for the reduction
4138 <         * @param reducer a commutative associative combining function
4139 <         * @return the result of accumulating the given transformation
4140 <         * of all keys
4141 <         */
4142 <        public long reduceToLong(ObjectToLong<? super K> transformer,
4143 <                                 long basis,
4144 <                                 LongByLongToLong reducer) {
4145 <            return ForkJoinTasks.reduceKeysToLong
4146 <                (map, transformer, basis, reducer).invoke();
4147 <        }
4148 <
4149 <        /**
4150 <         * Returns the result of accumulating the given transformation
4151 <         * of all keys using the given reducer to combine values, and
4152 <         * the given basis as an identity value.
4153 <         *
4154 <         * @param transformer a function returning the transformation
4155 <         * for an element
4156 <         * @param basis the identity (initial default value) for the reduction
4157 <         * @param reducer a commutative associative combining function
4158 <         * @return the result of accumulating the given transformation
4159 <         * of all keys
4160 <         */
4161 <        public int reduceToInt(ObjectToInt<? super K> transformer,
4162 <                               int basis,
4163 <                               IntByIntToInt reducer) {
4164 <            return ForkJoinTasks.reduceKeysToInt
4165 <                (map, transformer, basis, reducer).invoke();
4520 >        public void forEach(Action<? super K> action) {
4521 >            if (action == null) throw new NullPointerException();
4522 >            Node<K,V>[] t;
4523 >            if ((t = map.table) != null) {
4524 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4525 >                for (Node<K,V> p; (p = it.advance()) != null; )
4526 >                    action.apply(p.key);
4527 >            }
4528          }
4167
4529      }
4530  
4531      /**
4532       * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4533       * values, in which additions are disabled. This class cannot be
4534 <     * directly instantiated. See {@link #values},
4174 <     *
4175 <     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4176 <     * that will never throw {@link ConcurrentModificationException},
4177 <     * and guarantees to traverse elements as they existed upon
4178 <     * construction of the iterator, and may (but is not guaranteed to)
4179 <     * reflect any modifications subsequent to construction.
4534 >     * directly instantiated. See {@link #values()}.
4535       */
4536 <    public static final class ValuesView<K,V> extends CHMView<K,V>
4537 <        implements Collection<V> {
4538 <        ValuesView(ConcurrentHashMapV8<K, V> map)   { super(map); }
4539 <        public final boolean contains(Object o) { return map.containsValue(o); }
4536 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4537 >        implements Collection<V>, java.io.Serializable {
4538 >        private static final long serialVersionUID = 2249069246763182397L;
4539 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4540 >        public final boolean contains(Object o) {
4541 >            return map.containsValue(o);
4542 >        }
4543 >
4544          public final boolean remove(Object o) {
4545              if (o != null) {
4546 <                Iterator<V> it = new ValueIterator<K,V>(map);
4188 <                while (it.hasNext()) {
4546 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4547                      if (o.equals(it.next())) {
4548                          it.remove();
4549                          return true;
# Line 4195 | Line 4553 | public class ConcurrentHashMapV8<K, V>
4553              return false;
4554          }
4555  
4198        /**
4199         * Returns a "weakly consistent" iterator that will never
4200         * throw {@link ConcurrentModificationException}, and
4201         * guarantees to traverse elements as they existed upon
4202         * construction of the iterator, and may (but is not
4203         * guaranteed to) reflect any modifications subsequent to
4204         * construction.
4205         *
4206         * @return an iterator over the values of this map
4207         */
4556          public final Iterator<V> iterator() {
4557 <            return new ValueIterator<K,V>(map);
4557 >            ConcurrentHashMapV8<K,V> m = map;
4558 >            Node<K,V>[] t;
4559 >            int f = (t = m.table) == null ? 0 : t.length;
4560 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4561          }
4562 +
4563          public final boolean add(V e) {
4564              throw new UnsupportedOperationException();
4565          }
# Line 4215 | Line 4567 | public class ConcurrentHashMapV8<K, V>
4567              throw new UnsupportedOperationException();
4568          }
4569  
4570 <        /**
4571 <         * Performs the given action for each value.
4572 <         *
4573 <         * @param action the action
4574 <         */
4575 <        public void forEach(Action<V> action) {
4224 <            ForkJoinTasks.forEachValue
4225 <                (map, action).invoke();
4226 <        }
4227 <
4228 <        /**
4229 <         * Performs the given action for each non-null transformation
4230 <         * of each value.
4231 <         *
4232 <         * @param transformer a function returning the transformation
4233 <         * for an element, or null of there is no transformation (in
4234 <         * which case the action is not applied).
4235 <         */
4236 <        public <U> void forEach(Fun<? super V, ? extends U> transformer,
4237 <                                     Action<U> action) {
4238 <            ForkJoinTasks.forEachValue
4239 <                (map, transformer, action).invoke();
4570 >        public ConcurrentHashMapSpliterator<V> spliterator() {
4571 >            Node<K,V>[] t;
4572 >            ConcurrentHashMapV8<K,V> m = map;
4573 >            long n = m.sumCount();
4574 >            int f = (t = m.table) == null ? 0 : t.length;
4575 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4576          }
4577  
4578 <        /**
4579 <         * Returns a non-null result from applying the given search
4580 <         * function on each value, or null if none.  Upon success,
4581 <         * further element processing is suppressed and the results of
4582 <         * any other parallel invocations of the search function are
4583 <         * ignored.
4584 <         *
4585 <         * @param searchFunction a function returning a non-null
4250 <         * result on success, else null
4251 <         * @return a non-null result from applying the given search
4252 <         * function on each value, or null if none
4253 <         *
4254 <         */
4255 <        public <U> U search(Fun<? super V, ? extends U> searchFunction) {
4256 <            return ForkJoinTasks.searchValues
4257 <                (map, searchFunction).invoke();
4258 <        }
4259 <
4260 <        /**
4261 <         * Returns the result of accumulating all values using the
4262 <         * given reducer to combine values, or null if none.
4263 <         *
4264 <         * @param reducer a commutative associative combining function
4265 <         * @return  the result of accumulating all values
4266 <         */
4267 <        public V reduce(BiFun<? super V, ? super V, ? extends V> reducer) {
4268 <            return ForkJoinTasks.reduceValues
4269 <                (map, reducer).invoke();
4270 <        }
4271 <
4272 <        /**
4273 <         * Returns the result of accumulating the given transformation
4274 <         * of all values using the given reducer to combine values, or
4275 <         * null if none.
4276 <         *
4277 <         * @param transformer a function returning the transformation
4278 <         * for an element, or null of there is no transformation (in
4279 <         * which case it is not combined).
4280 <         * @param reducer a commutative associative combining function
4281 <         * @return the result of accumulating the given transformation
4282 <         * of all values
4283 <         */
4284 <        public <U> U reduce(Fun<? super V, ? extends U> transformer,
4285 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4286 <            return ForkJoinTasks.reduceValues
4287 <                (map, transformer, reducer).invoke();
4288 <        }
4289 <
4290 <        /**
4291 <         * Returns the result of accumulating the given transformation
4292 <         * of all values using the given reducer to combine values,
4293 <         * and the given basis as an identity value.
4294 <         *
4295 <         * @param transformer a function returning the transformation
4296 <         * for an element
4297 <         * @param basis the identity (initial default value) for the reduction
4298 <         * @param reducer a commutative associative combining function
4299 <         * @return the result of accumulating the given transformation
4300 <         * of all values
4301 <         */
4302 <        public double reduceToDouble(ObjectToDouble<? super V> transformer,
4303 <                                     double basis,
4304 <                                     DoubleByDoubleToDouble reducer) {
4305 <            return ForkJoinTasks.reduceValuesToDouble
4306 <                (map, transformer, basis, reducer).invoke();
4307 <        }
4308 <
4309 <        /**
4310 <         * Returns the result of accumulating the given transformation
4311 <         * of all values using the given reducer to combine values,
4312 <         * and the given basis as an identity value.
4313 <         *
4314 <         * @param transformer a function returning the transformation
4315 <         * for an element
4316 <         * @param basis the identity (initial default value) for the reduction
4317 <         * @param reducer a commutative associative combining function
4318 <         * @return the result of accumulating the given transformation
4319 <         * of all values
4320 <         */
4321 <        public long reduceToLong(ObjectToLong<? super V> transformer,
4322 <                                 long basis,
4323 <                                 LongByLongToLong reducer) {
4324 <            return ForkJoinTasks.reduceValuesToLong
4325 <                (map, transformer, basis, reducer).invoke();
4326 <        }
4327 <
4328 <        /**
4329 <         * Returns the result of accumulating the given transformation
4330 <         * of all values using the given reducer to combine values,
4331 <         * and the given basis as an identity value.
4332 <         *
4333 <         * @param transformer a function returning the transformation
4334 <         * for an element
4335 <         * @param basis the identity (initial default value) for the reduction
4336 <         * @param reducer a commutative associative combining function
4337 <         * @return the result of accumulating the given transformation
4338 <         * of all values
4339 <         */
4340 <        public int reduceToInt(ObjectToInt<? super V> transformer,
4341 <                               int basis,
4342 <                               IntByIntToInt reducer) {
4343 <            return ForkJoinTasks.reduceValuesToInt
4344 <                (map, transformer, basis, reducer).invoke();
4578 >        public void forEach(Action<? super V> action) {
4579 >            if (action == null) throw new NullPointerException();
4580 >            Node<K,V>[] t;
4581 >            if ((t = map.table) != null) {
4582 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4583 >                for (Node<K,V> p; (p = it.advance()) != null; )
4584 >                    action.apply(p.val);
4585 >            }
4586          }
4346
4587      }
4588  
4589      /**
4590       * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4591       * entries.  This class cannot be directly instantiated. See
4592 <     * {@link #entrySet}.
4592 >     * {@link #entrySet()}.
4593       */
4594 <    public static final class EntrySetView<K,V> extends CHMView<K,V>
4595 <        implements Set<Map.Entry<K,V>> {
4596 <        EntrySetView(ConcurrentHashMapV8<K, V> map) { super(map); }
4597 <        public final boolean contains(Object o) {
4594 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4595 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4596 >        private static final long serialVersionUID = 2249069246763182397L;
4597 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4598 >
4599 >        public boolean contains(Object o) {
4600              Object k, v, r; Map.Entry<?,?> e;
4601              return ((o instanceof Map.Entry) &&
4602                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4362 | Line 4604 | public class ConcurrentHashMapV8<K, V>
4604                      (v = e.getValue()) != null &&
4605                      (v == r || v.equals(r)));
4606          }
4607 <        public final boolean remove(Object o) {
4607 >
4608 >        public boolean remove(Object o) {
4609              Object k, v; Map.Entry<?,?> e;
4610              return ((o instanceof Map.Entry) &&
4611                      (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
# Line 4371 | Line 4614 | public class ConcurrentHashMapV8<K, V>
4614          }
4615  
4616          /**
4617 <         * Returns a "weakly consistent" iterator that will never
4375 <         * throw {@link ConcurrentModificationException}, and
4376 <         * guarantees to traverse elements as they existed upon
4377 <         * construction of the iterator, and may (but is not
4378 <         * guaranteed to) reflect any modifications subsequent to
4379 <         * construction.
4380 <         *
4381 <         * @return an iterator over the entries of this map
4617 >         * @return an iterator over the entries of the backing map
4618           */
4619 <        public final Iterator<Map.Entry<K,V>> iterator() {
4620 <            return new EntryIterator<K,V>(map);
4619 >        public Iterator<Map.Entry<K,V>> iterator() {
4620 >            ConcurrentHashMapV8<K,V> m = map;
4621 >            Node<K,V>[] t;
4622 >            int f = (t = m.table) == null ? 0 : t.length;
4623 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4624          }
4625  
4626 <        public final boolean add(Entry<K,V> e) {
4627 <            K key = e.getKey();
4389 <            V value = e.getValue();
4390 <            if (key == null || value == null)
4391 <                throw new NullPointerException();
4392 <            return map.internalPut(key, value, false) == null;
4626 >        public boolean add(Entry<K,V> e) {
4627 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4628          }
4629 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4629 >
4630 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4631              boolean added = false;
4632              for (Entry<K,V> e : c) {
4633                  if (add(e))
# Line 4399 | Line 4635 | public class ConcurrentHashMapV8<K, V>
4635              }
4636              return added;
4637          }
4638 <        public boolean equals(Object o) {
4638 >
4639 >        public final int hashCode() {
4640 >            int h = 0;
4641 >            Node<K,V>[] t;
4642 >            if ((t = map.table) != null) {
4643 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4644 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4645 >                    h += p.hashCode();
4646 >                }
4647 >            }
4648 >            return h;
4649 >        }
4650 >
4651 >        public final boolean equals(Object o) {
4652              Set<?> c;
4653              return ((o instanceof Set) &&
4654                      ((c = (Set<?>)o) == this ||
4655                       (containsAll(c) && c.containsAll(this))));
4656          }
4657  
4658 <        /**
4659 <         * Performs the given action for each entry.
4660 <         *
4661 <         * @param action the action
4662 <         */
4663 <        public void forEach(Action<Map.Entry<K,V>> action) {
4415 <            ForkJoinTasks.forEachEntry
4416 <                (map, action).invoke();
4417 <        }
4418 <
4419 <        /**
4420 <         * Performs the given action for each non-null transformation
4421 <         * of each entry.
4422 <         *
4423 <         * @param transformer a function returning the transformation
4424 <         * for an element, or null of there is no transformation (in
4425 <         * which case the action is not applied).
4426 <         * @param action the action
4427 <         */
4428 <        public <U> void forEach(Fun<Map.Entry<K,V>, ? extends U> transformer,
4429 <                                Action<U> action) {
4430 <            ForkJoinTasks.forEachEntry
4431 <                (map, transformer, action).invoke();
4432 <        }
4433 <
4434 <        /**
4435 <         * Returns a non-null result from applying the given search
4436 <         * function on each entry, or null if none.  Upon success,
4437 <         * further element processing is suppressed and the results of
4438 <         * any other parallel invocations of the search function are
4439 <         * ignored.
4440 <         *
4441 <         * @param searchFunction a function returning a non-null
4442 <         * result on success, else null
4443 <         * @return a non-null result from applying the given search
4444 <         * function on each entry, or null if none
4445 <         */
4446 <        public <U> U search(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4447 <            return ForkJoinTasks.searchEntries
4448 <                (map, searchFunction).invoke();
4449 <        }
4450 <
4451 <        /**
4452 <         * Returns the result of accumulating all entries using the
4453 <         * given reducer to combine values, or null if none.
4454 <         *
4455 <         * @param reducer a commutative associative combining function
4456 <         * @return the result of accumulating all entries
4457 <         */
4458 <        public Map.Entry<K,V> reduce(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4459 <            return ForkJoinTasks.reduceEntries
4460 <                (map, reducer).invoke();
4461 <        }
4462 <
4463 <        /**
4464 <         * Returns the result of accumulating the given transformation
4465 <         * of all entries using the given reducer to combine values,
4466 <         * or null if none.
4467 <         *
4468 <         * @param transformer a function returning the transformation
4469 <         * for an element, or null of there is no transformation (in
4470 <         * which case it is not combined).
4471 <         * @param reducer a commutative associative combining function
4472 <         * @return the result of accumulating the given transformation
4473 <         * of all entries
4474 <         */
4475 <        public <U> U reduce(Fun<Map.Entry<K,V>, ? extends U> transformer,
4476 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
4477 <            return ForkJoinTasks.reduceEntries
4478 <                (map, transformer, reducer).invoke();
4658 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4659 >            Node<K,V>[] t;
4660 >            ConcurrentHashMapV8<K,V> m = map;
4661 >            long n = m.sumCount();
4662 >            int f = (t = m.table) == null ? 0 : t.length;
4663 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4664          }
4665  
4666 <        /**
4667 <         * Returns the result of accumulating the given transformation
4668 <         * of all entries using the given reducer to combine values,
4669 <         * and the given basis as an identity value.
4670 <         *
4671 <         * @param transformer a function returning the transformation
4672 <         * for an element
4673 <         * @param basis the identity (initial default value) for the reduction
4489 <         * @param reducer a commutative associative combining function
4490 <         * @return the result of accumulating the given transformation
4491 <         * of all entries
4492 <         */
4493 <        public double reduceToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4494 <                                     double basis,
4495 <                                     DoubleByDoubleToDouble reducer) {
4496 <            return ForkJoinTasks.reduceEntriesToDouble
4497 <                (map, transformer, basis, reducer).invoke();
4498 <        }
4499 <
4500 <        /**
4501 <         * Returns the result of accumulating the given transformation
4502 <         * of all entries using the given reducer to combine values,
4503 <         * and the given basis as an identity value.
4504 <         *
4505 <         * @param transformer a function returning the transformation
4506 <         * for an element
4507 <         * @param basis the identity (initial default value) for the reduction
4508 <         * @param reducer a commutative associative combining function
4509 <         * @return  the result of accumulating the given transformation
4510 <         * of all entries
4511 <         */
4512 <        public long reduceToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4513 <                                 long basis,
4514 <                                 LongByLongToLong reducer) {
4515 <            return ForkJoinTasks.reduceEntriesToLong
4516 <                (map, transformer, basis, reducer).invoke();
4517 <        }
4518 <
4519 <        /**
4520 <         * Returns the result of accumulating the given transformation
4521 <         * of all entries using the given reducer to combine values,
4522 <         * and the given basis as an identity value.
4523 <         *
4524 <         * @param transformer a function returning the transformation
4525 <         * for an element
4526 <         * @param basis the identity (initial default value) for the reduction
4527 <         * @param reducer a commutative associative combining function
4528 <         * @return the result of accumulating the given transformation
4529 <         * of all entries
4530 <         */
4531 <        public int reduceToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4532 <                               int basis,
4533 <                               IntByIntToInt reducer) {
4534 <            return ForkJoinTasks.reduceEntriesToInt
4535 <                (map, transformer, basis, reducer).invoke();
4666 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4667 >            if (action == null) throw new NullPointerException();
4668 >            Node<K,V>[] t;
4669 >            if ((t = map.table) != null) {
4670 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4671 >                for (Node<K,V> p; (p = it.advance()) != null; )
4672 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4673 >            }
4674          }
4675  
4676      }
4677  
4678 <    // ---------------------------------------------------------------------
4678 >    // -------------------------------------------------------
4679  
4680      /**
4681 <     * Predefined tasks for performing bulk parallel operations on
4682 <     * ConcurrentHashMapV8s. These tasks follow the forms and rules used
4545 <     * for bulk operations. Each method has the same name, but returns
4546 <     * a task rather than invoking it. These methods may be useful in
4547 <     * custom applications such as submitting a task without waiting
4548 <     * for completion, using a custom pool, or combining with other
4549 <     * tasks.
4681 >     * Base class for bulk tasks. Repeats some fields and code from
4682 >     * class Traverser, because we need to subclass CountedCompleter.
4683       */
4684 <    public static class ForkJoinTasks {
4685 <        private ForkJoinTasks() {}
4686 <
4687 <        /**
4688 <         * Returns a task that when invoked, performs the given
4689 <         * action for each (key, value)
4690 <         *
4691 <         * @param map the map
4692 <         * @param action the action
4693 <         * @return the task
4694 <         */
4695 <        public static <K,V> ForkJoinTask<Void> forEach
4696 <            (ConcurrentHashMapV8<K,V> map,
4697 <             BiAction<K,V> action) {
4698 <            if (action == null) throw new NullPointerException();
4699 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
4700 <        }
4701 <
4702 <        /**
4703 <         * Returns a task that when invoked, performs the given
4704 <         * action for each non-null transformation of each (key, value)
4572 <         *
4573 <         * @param map the map
4574 <         * @param transformer a function returning the transformation
4575 <         * for an element, or null if there is no transformation (in
4576 <         * which case the action is not applied)
4577 <         * @param action the action
4578 <         * @return the task
4579 <         */
4580 <        public static <K,V,U> ForkJoinTask<Void> forEach
4581 <            (ConcurrentHashMapV8<K,V> map,
4582 <             BiFun<? super K, ? super V, ? extends U> transformer,
4583 <             Action<U> action) {
4584 <            if (transformer == null || action == null)
4585 <                throw new NullPointerException();
4586 <            return new ForEachTransformedMappingTask<K,V,U>
4587 <                (map, null, -1, transformer, action);
4588 <        }
4589 <
4590 <        /**
4591 <         * Returns a task that when invoked, returns a non-null result
4592 <         * from applying the given search function on each (key,
4593 <         * value), or null if none. Upon success, further element
4594 <         * processing is suppressed and the results of any other
4595 <         * parallel invocations of the search function are ignored.
4596 <         *
4597 <         * @param map the map
4598 <         * @param searchFunction a function returning a non-null
4599 <         * result on success, else null
4600 <         * @return the task
4601 <         */
4602 <        public static <K,V,U> ForkJoinTask<U> search
4603 <            (ConcurrentHashMapV8<K,V> map,
4604 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4605 <            if (searchFunction == null) throw new NullPointerException();
4606 <            return new SearchMappingsTask<K,V,U>
4607 <                (map, null, -1, searchFunction,
4608 <                 new AtomicReference<U>());
4609 <        }
4610 <
4611 <        /**
4612 <         * Returns a task that when invoked, returns the result of
4613 <         * accumulating the given transformation of all (key, value) pairs
4614 <         * using the given reducer to combine values, or null if none.
4615 <         *
4616 <         * @param map the map
4617 <         * @param transformer a function returning the transformation
4618 <         * for an element, or null if there is no transformation (in
4619 <         * which case it is not combined).
4620 <         * @param reducer a commutative associative combining function
4621 <         * @return the task
4622 <         */
4623 <        public static <K,V,U> ForkJoinTask<U> reduce
4624 <            (ConcurrentHashMapV8<K,V> map,
4625 <             BiFun<? super K, ? super V, ? extends U> transformer,
4626 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4627 <            if (transformer == null || reducer == null)
4628 <                throw new NullPointerException();
4629 <            return new MapReduceMappingsTask<K,V,U>
4630 <                (map, null, -1, null, transformer, reducer);
4631 <        }
4632 <
4633 <        /**
4634 <         * Returns a task that when invoked, returns the result of
4635 <         * accumulating the given transformation of all (key, value) pairs
4636 <         * using the given reducer to combine values, and the given
4637 <         * basis as an identity value.
4638 <         *
4639 <         * @param map the map
4640 <         * @param transformer a function returning the transformation
4641 <         * for an element
4642 <         * @param basis the identity (initial default value) for the reduction
4643 <         * @param reducer a commutative associative combining function
4644 <         * @return the task
4645 <         */
4646 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4647 <            (ConcurrentHashMapV8<K,V> map,
4648 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4649 <             double basis,
4650 <             DoubleByDoubleToDouble reducer) {
4651 <            if (transformer == null || reducer == null)
4652 <                throw new NullPointerException();
4653 <            return new MapReduceMappingsToDoubleTask<K,V>
4654 <                (map, null, -1, null, transformer, basis, reducer);
4655 <        }
4656 <
4657 <        /**
4658 <         * Returns a task that when invoked, returns the result of
4659 <         * accumulating the given transformation of all (key, value) pairs
4660 <         * using the given reducer to combine values, and the given
4661 <         * basis as an identity value.
4662 <         *
4663 <         * @param map the map
4664 <         * @param transformer a function returning the transformation
4665 <         * for an element
4666 <         * @param basis the identity (initial default value) for the reduction
4667 <         * @param reducer a commutative associative combining function
4668 <         * @return the task
4669 <         */
4670 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4671 <            (ConcurrentHashMapV8<K,V> map,
4672 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4673 <             long basis,
4674 <             LongByLongToLong reducer) {
4675 <            if (transformer == null || reducer == null)
4676 <                throw new NullPointerException();
4677 <            return new MapReduceMappingsToLongTask<K,V>
4678 <                (map, null, -1, null, transformer, basis, reducer);
4679 <        }
4680 <
4681 <        /**
4682 <         * Returns a task that when invoked, returns the result of
4683 <         * accumulating the given transformation of all (key, value) pairs
4684 <         * using the given reducer to combine values, and the given
4685 <         * basis as an identity value.
4686 <         *
4687 <         * @param transformer a function returning the transformation
4688 <         * for an element
4689 <         * @param basis the identity (initial default value) for the reduction
4690 <         * @param reducer a commutative associative combining function
4691 <         * @return the task
4692 <         */
4693 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4694 <            (ConcurrentHashMapV8<K,V> map,
4695 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4696 <             int basis,
4697 <             IntByIntToInt reducer) {
4698 <            if (transformer == null || reducer == null)
4699 <                throw new NullPointerException();
4700 <            return new MapReduceMappingsToIntTask<K,V>
4701 <                (map, null, -1, null, transformer, basis, reducer);
4702 <        }
4703 <
4704 <        /**
4705 <         * Returns a task that when invoked, performs the given action
4706 <         * for each key.
4707 <         *
4708 <         * @param map the map
4709 <         * @param action the action
4710 <         * @return the task
4711 <         */
4712 <        public static <K,V> ForkJoinTask<Void> forEachKey
4713 <            (ConcurrentHashMapV8<K,V> map,
4714 <             Action<K> action) {
4715 <            if (action == null) throw new NullPointerException();
4716 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4717 <        }
4718 <
4719 <        /**
4720 <         * Returns a task that when invoked, performs the given action
4721 <         * for each non-null transformation of each key.
4722 <         *
4723 <         * @param map the map
4724 <         * @param transformer a function returning the transformation
4725 <         * for an element, or null if there is no transformation (in
4726 <         * which case the action is not applied)
4727 <         * @param action the action
4728 <         * @return the task
4729 <         */
4730 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4731 <            (ConcurrentHashMapV8<K,V> map,
4732 <             Fun<? super K, ? extends U> transformer,
4733 <             Action<U> action) {
4734 <            if (transformer == null || action == null)
4735 <                throw new NullPointerException();
4736 <            return new ForEachTransformedKeyTask<K,V,U>
4737 <                (map, null, -1, transformer, action);
4738 <        }
4739 <
4740 <        /**
4741 <         * Returns a task that when invoked, returns a non-null result
4742 <         * from applying the given search function on each key, or
4743 <         * null if none.  Upon success, further element processing is
4744 <         * suppressed and the results of any other parallel
4745 <         * invocations of the search function are ignored.
4746 <         *
4747 <         * @param map the map
4748 <         * @param searchFunction a function returning a non-null
4749 <         * result on success, else null
4750 <         * @return the task
4751 <         */
4752 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4753 <            (ConcurrentHashMapV8<K,V> map,
4754 <             Fun<? super K, ? extends U> searchFunction) {
4755 <            if (searchFunction == null) throw new NullPointerException();
4756 <            return new SearchKeysTask<K,V,U>
4757 <                (map, null, -1, searchFunction,
4758 <                 new AtomicReference<U>());
4759 <        }
4760 <
4761 <        /**
4762 <         * Returns a task that when invoked, returns the result of
4763 <         * accumulating all keys using the given reducer to combine
4764 <         * values, or null if none.
4765 <         *
4766 <         * @param map the map
4767 <         * @param reducer a commutative associative combining function
4768 <         * @return the task
4769 <         */
4770 <        public static <K,V> ForkJoinTask<K> reduceKeys
4771 <            (ConcurrentHashMapV8<K,V> map,
4772 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4773 <            if (reducer == null) throw new NullPointerException();
4774 <            return new ReduceKeysTask<K,V>
4775 <                (map, null, -1, null, reducer);
4776 <        }
4777 <
4778 <        /**
4779 <         * Returns a task that when invoked, returns the result of
4780 <         * accumulating the given transformation of all keys using the given
4781 <         * reducer to combine values, or null if none.
4782 <         *
4783 <         * @param map the map
4784 <         * @param transformer a function returning the transformation
4785 <         * for an element, or null if there is no transformation (in
4786 <         * which case it is not combined).
4787 <         * @param reducer a commutative associative combining function
4788 <         * @return the task
4789 <         */
4790 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4791 <            (ConcurrentHashMapV8<K,V> map,
4792 <             Fun<? super K, ? extends U> transformer,
4793 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4794 <            if (transformer == null || reducer == null)
4795 <                throw new NullPointerException();
4796 <            return new MapReduceKeysTask<K,V,U>
4797 <                (map, null, -1, null, transformer, reducer);
4798 <        }
4799 <
4800 <        /**
4801 <         * Returns a task that when invoked, returns the result of
4802 <         * accumulating the given transformation of all keys using the given
4803 <         * reducer to combine values, and the given basis as an
4804 <         * identity value.
4805 <         *
4806 <         * @param map the map
4807 <         * @param transformer a function returning the transformation
4808 <         * for an element
4809 <         * @param basis the identity (initial default value) for the reduction
4810 <         * @param reducer a commutative associative combining function
4811 <         * @return the task
4812 <         */
4813 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4814 <            (ConcurrentHashMapV8<K,V> map,
4815 <             ObjectToDouble<? super K> transformer,
4816 <             double basis,
4817 <             DoubleByDoubleToDouble reducer) {
4818 <            if (transformer == null || reducer == null)
4819 <                throw new NullPointerException();
4820 <            return new MapReduceKeysToDoubleTask<K,V>
4821 <                (map, null, -1, null, transformer, basis, reducer);
4822 <        }
4823 <
4824 <        /**
4825 <         * Returns a task that when invoked, returns the result of
4826 <         * accumulating the given transformation of all keys using the given
4827 <         * reducer to combine values, and the given basis as an
4828 <         * identity value.
4829 <         *
4830 <         * @param map the map
4831 <         * @param transformer a function returning the transformation
4832 <         * for an element
4833 <         * @param basis the identity (initial default value) for the reduction
4834 <         * @param reducer a commutative associative combining function
4835 <         * @return the task
4836 <         */
4837 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4838 <            (ConcurrentHashMapV8<K,V> map,
4839 <             ObjectToLong<? super K> transformer,
4840 <             long basis,
4841 <             LongByLongToLong reducer) {
4842 <            if (transformer == null || reducer == null)
4843 <                throw new NullPointerException();
4844 <            return new MapReduceKeysToLongTask<K,V>
4845 <                (map, null, -1, null, transformer, basis, reducer);
4846 <        }
4847 <
4848 <        /**
4849 <         * Returns a task that when invoked, returns the result of
4850 <         * accumulating the given transformation of all keys using the given
4851 <         * reducer to combine values, and the given basis as an
4852 <         * identity value.
4853 <         *
4854 <         * @param map the map
4855 <         * @param transformer a function returning the transformation
4856 <         * for an element
4857 <         * @param basis the identity (initial default value) for the reduction
4858 <         * @param reducer a commutative associative combining function
4859 <         * @return the task
4860 <         */
4861 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4862 <            (ConcurrentHashMapV8<K,V> map,
4863 <             ObjectToInt<? super K> transformer,
4864 <             int basis,
4865 <             IntByIntToInt reducer) {
4866 <            if (transformer == null || reducer == null)
4867 <                throw new NullPointerException();
4868 <            return new MapReduceKeysToIntTask<K,V>
4869 <                (map, null, -1, null, transformer, basis, reducer);
4870 <        }
4871 <
4872 <        /**
4873 <         * Returns a task that when invoked, performs the given action
4874 <         * for each value.
4875 <         *
4876 <         * @param map the map
4877 <         * @param action the action
4878 <         */
4879 <        public static <K,V> ForkJoinTask<Void> forEachValue
4880 <            (ConcurrentHashMapV8<K,V> map,
4881 <             Action<V> action) {
4882 <            if (action == null) throw new NullPointerException();
4883 <            return new ForEachValueTask<K,V>(map, null, -1, action);
4884 <        }
4885 <
4886 <        /**
4887 <         * Returns a task that when invoked, performs the given action
4888 <         * for each non-null transformation of each value.
4889 <         *
4890 <         * @param map the map
4891 <         * @param transformer a function returning the transformation
4892 <         * for an element, or null if there is no transformation (in
4893 <         * which case the action is not applied)
4894 <         * @param action the action
4895 <         */
4896 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4897 <            (ConcurrentHashMapV8<K,V> map,
4898 <             Fun<? super V, ? extends U> transformer,
4899 <             Action<U> action) {
4900 <            if (transformer == null || action == null)
4901 <                throw new NullPointerException();
4902 <            return new ForEachTransformedValueTask<K,V,U>
4903 <                (map, null, -1, transformer, action);
4904 <        }
4905 <
4906 <        /**
4907 <         * Returns a task that when invoked, returns a non-null result
4908 <         * from applying the given search function on each value, or
4909 <         * null if none.  Upon success, further element processing is
4910 <         * suppressed and the results of any other parallel
4911 <         * invocations of the search function are ignored.
4912 <         *
4913 <         * @param map the map
4914 <         * @param searchFunction a function returning a non-null
4915 <         * result on success, else null
4916 <         * @return the task
4917 <         */
4918 <        public static <K,V,U> ForkJoinTask<U> searchValues
4919 <            (ConcurrentHashMapV8<K,V> map,
4920 <             Fun<? super V, ? extends U> searchFunction) {
4921 <            if (searchFunction == null) throw new NullPointerException();
4922 <            return new SearchValuesTask<K,V,U>
4923 <                (map, null, -1, searchFunction,
4924 <                 new AtomicReference<U>());
4925 <        }
4926 <
4927 <        /**
4928 <         * Returns a task that when invoked, returns the result of
4929 <         * accumulating all values using the given reducer to combine
4930 <         * values, or null if none.
4931 <         *
4932 <         * @param map the map
4933 <         * @param reducer a commutative associative combining function
4934 <         * @return the task
4935 <         */
4936 <        public static <K,V> ForkJoinTask<V> reduceValues
4937 <            (ConcurrentHashMapV8<K,V> map,
4938 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4939 <            if (reducer == null) throw new NullPointerException();
4940 <            return new ReduceValuesTask<K,V>
4941 <                (map, null, -1, null, reducer);
4942 <        }
4943 <
4944 <        /**
4945 <         * Returns a task that when invoked, returns the result of
4946 <         * accumulating the given transformation of all values using the
4947 <         * given reducer to combine values, or null if none.
4948 <         *
4949 <         * @param map the map
4950 <         * @param transformer a function returning the transformation
4951 <         * for an element, or null if there is no transformation (in
4952 <         * which case it is not combined).
4953 <         * @param reducer a commutative associative combining function
4954 <         * @return the task
4955 <         */
4956 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4957 <            (ConcurrentHashMapV8<K,V> map,
4958 <             Fun<? super V, ? extends U> transformer,
4959 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4960 <            if (transformer == null || reducer == null)
4961 <                throw new NullPointerException();
4962 <            return new MapReduceValuesTask<K,V,U>
4963 <                (map, null, -1, null, transformer, reducer);
4964 <        }
4965 <
4966 <        /**
4967 <         * Returns a task that when invoked, returns the result of
4968 <         * accumulating the given transformation of all values using the
4969 <         * given reducer to combine values, and the given basis as an
4970 <         * identity value.
4971 <         *
4972 <         * @param map the map
4973 <         * @param transformer a function returning the transformation
4974 <         * for an element
4975 <         * @param basis the identity (initial default value) for the reduction
4976 <         * @param reducer a commutative associative combining function
4977 <         * @return the task
4978 <         */
4979 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4980 <            (ConcurrentHashMapV8<K,V> map,
4981 <             ObjectToDouble<? super V> transformer,
4982 <             double basis,
4983 <             DoubleByDoubleToDouble reducer) {
4984 <            if (transformer == null || reducer == null)
4985 <                throw new NullPointerException();
4986 <            return new MapReduceValuesToDoubleTask<K,V>
4987 <                (map, null, -1, null, transformer, basis, reducer);
4988 <        }
4989 <
4990 <        /**
4991 <         * Returns a task that when invoked, returns the result of
4992 <         * accumulating the given transformation of all values using the
4993 <         * given reducer to combine values, and the given basis as an
4994 <         * identity value.
4995 <         *
4996 <         * @param map the map
4997 <         * @param transformer a function returning the transformation
4998 <         * for an element
4999 <         * @param basis the identity (initial default value) for the reduction
5000 <         * @param reducer a commutative associative combining function
5001 <         * @return the task
5002 <         */
5003 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5004 <            (ConcurrentHashMapV8<K,V> map,
5005 <             ObjectToLong<? super V> transformer,
5006 <             long basis,
5007 <             LongByLongToLong reducer) {
5008 <            if (transformer == null || reducer == null)
5009 <                throw new NullPointerException();
5010 <            return new MapReduceValuesToLongTask<K,V>
5011 <                (map, null, -1, null, transformer, basis, reducer);
5012 <        }
5013 <
5014 <        /**
5015 <         * Returns a task that when invoked, returns the result of
5016 <         * accumulating the given transformation of all values using the
5017 <         * given reducer to combine values, and the given basis as an
5018 <         * identity value.
5019 <         *
5020 <         * @param map the map
5021 <         * @param transformer a function returning the transformation
5022 <         * for an element
5023 <         * @param basis the identity (initial default value) for the reduction
5024 <         * @param reducer a commutative associative combining function
5025 <         * @return the task
5026 <         */
5027 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5028 <            (ConcurrentHashMapV8<K,V> map,
5029 <             ObjectToInt<? super V> transformer,
5030 <             int basis,
5031 <             IntByIntToInt reducer) {
5032 <            if (transformer == null || reducer == null)
5033 <                throw new NullPointerException();
5034 <            return new MapReduceValuesToIntTask<K,V>
5035 <                (map, null, -1, null, transformer, basis, reducer);
5036 <        }
5037 <
5038 <        /**
5039 <         * Returns a task that when invoked, perform the given action
5040 <         * for each entry.
5041 <         *
5042 <         * @param map the map
5043 <         * @param action the action
5044 <         */
5045 <        public static <K,V> ForkJoinTask<Void> forEachEntry
5046 <            (ConcurrentHashMapV8<K,V> map,
5047 <             Action<Map.Entry<K,V>> action) {
5048 <            if (action == null) throw new NullPointerException();
5049 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
5050 <        }
5051 <
5052 <        /**
5053 <         * Returns a task that when invoked, perform the given action
5054 <         * for each non-null transformation of each entry.
5055 <         *
5056 <         * @param map the map
5057 <         * @param transformer a function returning the transformation
5058 <         * for an element, or null if there is no transformation (in
5059 <         * which case the action is not applied)
5060 <         * @param action the action
5061 <         */
5062 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5063 <            (ConcurrentHashMapV8<K,V> map,
5064 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5065 <             Action<U> action) {
5066 <            if (transformer == null || action == null)
5067 <                throw new NullPointerException();
5068 <            return new ForEachTransformedEntryTask<K,V,U>
5069 <                (map, null, -1, transformer, action);
5070 <        }
5071 <
5072 <        /**
5073 <         * Returns a task that when invoked, returns a non-null result
5074 <         * from applying the given search function on each entry, or
5075 <         * null if none.  Upon success, further element processing is
5076 <         * suppressed and the results of any other parallel
5077 <         * invocations of the search function are ignored.
5078 <         *
5079 <         * @param map the map
5080 <         * @param searchFunction a function returning a non-null
5081 <         * result on success, else null
5082 <         * @return the task
5083 <         */
5084 <        public static <K,V,U> ForkJoinTask<U> searchEntries
5085 <            (ConcurrentHashMapV8<K,V> map,
5086 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5087 <            if (searchFunction == null) throw new NullPointerException();
5088 <            return new SearchEntriesTask<K,V,U>
5089 <                (map, null, -1, searchFunction,
5090 <                 new AtomicReference<U>());
5091 <        }
5092 <
5093 <        /**
5094 <         * Returns a task that when invoked, returns the result of
5095 <         * accumulating all entries using the given reducer to combine
5096 <         * values, or null if none.
5097 <         *
5098 <         * @param map the map
5099 <         * @param reducer a commutative associative combining function
5100 <         * @return the task
5101 <         */
5102 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5103 <            (ConcurrentHashMapV8<K,V> map,
5104 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5105 <            if (reducer == null) throw new NullPointerException();
5106 <            return new ReduceEntriesTask<K,V>
5107 <                (map, null, -1, null, reducer);
5108 <        }
5109 <
5110 <        /**
5111 <         * Returns a task that when invoked, returns the result of
5112 <         * accumulating the given transformation of all entries using the
5113 <         * given reducer to combine values, or null if none.
5114 <         *
5115 <         * @param map the map
5116 <         * @param transformer a function returning the transformation
5117 <         * for an element, or null if there is no transformation (in
5118 <         * which case it is not combined).
5119 <         * @param reducer a commutative associative combining function
5120 <         * @return the task
5121 <         */
5122 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
5123 <            (ConcurrentHashMapV8<K,V> map,
5124 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5125 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5126 <            if (transformer == null || reducer == null)
5127 <                throw new NullPointerException();
5128 <            return new MapReduceEntriesTask<K,V,U>
5129 <                (map, null, -1, null, transformer, reducer);
5130 <        }
5131 <
5132 <        /**
5133 <         * Returns a task that when invoked, returns the result of
5134 <         * accumulating the given transformation of all entries using the
5135 <         * given reducer to combine values, and the given basis as an
5136 <         * identity value.
5137 <         *
5138 <         * @param map the map
5139 <         * @param transformer a function returning the transformation
5140 <         * for an element
5141 <         * @param basis the identity (initial default value) for the reduction
5142 <         * @param reducer a commutative associative combining function
5143 <         * @return the task
5144 <         */
5145 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5146 <            (ConcurrentHashMapV8<K,V> map,
5147 <             ObjectToDouble<Map.Entry<K,V>> transformer,
5148 <             double basis,
5149 <             DoubleByDoubleToDouble reducer) {
5150 <            if (transformer == null || reducer == null)
5151 <                throw new NullPointerException();
5152 <            return new MapReduceEntriesToDoubleTask<K,V>
5153 <                (map, null, -1, null, transformer, basis, reducer);
5154 <        }
5155 <
5156 <        /**
5157 <         * Returns a task that when invoked, returns the result of
5158 <         * accumulating the given transformation of all entries using the
5159 <         * given 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<Long> reduceEntriesToLong
5170 <            (ConcurrentHashMapV8<K,V> map,
5171 <             ObjectToLong<Map.Entry<K,V>> transformer,
5172 <             long basis,
5173 <             LongByLongToLong reducer) {
5174 <            if (transformer == null || reducer == null)
5175 <                throw new NullPointerException();
5176 <            return new MapReduceEntriesToLongTask<K,V>
5177 <                (map, null, -1, null, transformer, basis, reducer);
4684 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4685 >        Node<K,V>[] tab;        // same as Traverser
4686 >        Node<K,V> next;
4687 >        int index;
4688 >        int baseIndex;
4689 >        int baseLimit;
4690 >        final int baseSize;
4691 >        int batch;              // split control
4692 >
4693 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4694 >            super(par);
4695 >            this.batch = b;
4696 >            this.index = this.baseIndex = i;
4697 >            if ((this.tab = t) == null)
4698 >                this.baseSize = this.baseLimit = 0;
4699 >            else if (par == null)
4700 >                this.baseSize = this.baseLimit = t.length;
4701 >            else {
4702 >                this.baseLimit = f;
4703 >                this.baseSize = par.baseSize;
4704 >            }
4705          }
4706  
4707          /**
4708 <         * Returns a task that when invoked, returns the result of
5182 <         * accumulating the given transformation of all entries using the
5183 <         * given 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
4708 >         * Same as Traverser version
4709           */
4710 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4711 <            (ConcurrentHashMapV8<K,V> map,
4712 <             ObjectToInt<Map.Entry<K,V>> transformer,
4713 <             int basis,
4714 <             IntByIntToInt reducer) {
4715 <            if (transformer == null || reducer == null)
4716 <                throw new NullPointerException();
4717 <            return new MapReduceEntriesToIntTask<K,V>
4718 <                (map, null, -1, null, transformer, basis, reducer);
4710 >        final Node<K,V> advance() {
4711 >            Node<K,V> e;
4712 >            if ((e = next) != null)
4713 >                e = e.next;
4714 >            for (;;) {
4715 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4716 >                if (e != null)
4717 >                    return next = e;
4718 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4719 >                    (n = t.length) <= (i = index) || i < 0)
4720 >                    return next = null;
4721 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4722 >                    if (e instanceof ForwardingNode) {
4723 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4724 >                        e = null;
4725 >                        continue;
4726 >                    }
4727 >                    else if (e instanceof TreeBin)
4728 >                        e = ((TreeBin<K,V>)e).first;
4729 >                    else
4730 >                        e = null;
4731 >                }
4732 >                if ((index += baseSize) >= n)
4733 >                    index = ++baseIndex;    // visit upper slots if present
4734 >            }
4735          }
4736      }
4737  
5205    // -------------------------------------------------------
5206
4738      /*
4739       * Task classes. Coded in a regular but ugly format/style to
4740       * simplify checks that each variant differs in the right way from
# Line 5211 | Line 4742 | public class ConcurrentHashMapV8<K, V>
4742       * that we've already null-checked task arguments, so we force
4743       * simplest hoisted bypass to help avoid convoluted traps.
4744       */
4745 <
4746 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4747 <        extends Traverser<K,V,Void> {
4748 <        final Action<K> action;
4745 >    @SuppressWarnings("serial")
4746 >    static final class ForEachKeyTask<K,V>
4747 >        extends BulkTask<K,V,Void> {
4748 >        final Action<? super K> action;
4749          ForEachKeyTask
4750 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4751 <             Action<K> action) {
4752 <            super(m, p, b);
4750 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4751 >             Action<? super K> action) {
4752 >            super(p, b, i, f, t);
4753              this.action = action;
4754          }
4755 <        @SuppressWarnings("unchecked") public final void compute() {
4756 <            final Action<K> action;
4755 >        public final void compute() {
4756 >            final Action<? super K> action;
4757              if ((action = this.action) != null) {
4758 <                for (int b; (b = preSplit()) > 0;)
4759 <                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
4760 <                while (advance() != null)
4761 <                    action.apply((K)nextKey);
4758 >                for (int i = baseIndex, f, h; batch > 0 &&
4759 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4760 >                    addToPendingCount(1);
4761 >                    new ForEachKeyTask<K,V>
4762 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4763 >                         action).fork();
4764 >                }
4765 >                for (Node<K,V> p; (p = advance()) != null;)
4766 >                    action.apply(p.key);
4767                  propagateCompletion();
4768              }
4769          }
4770      }
4771  
4772 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4773 <        extends Traverser<K,V,Void> {
4774 <        final Action<V> action;
4772 >    @SuppressWarnings("serial")
4773 >    static final class ForEachValueTask<K,V>
4774 >        extends BulkTask<K,V,Void> {
4775 >        final Action<? super V> action;
4776          ForEachValueTask
4777 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4778 <             Action<V> action) {
4779 <            super(m, p, b);
4777 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4778 >             Action<? super V> action) {
4779 >            super(p, b, i, f, t);
4780              this.action = action;
4781          }
4782 <        @SuppressWarnings("unchecked") public final void compute() {
4783 <            final Action<V> action;
4782 >        public final void compute() {
4783 >            final Action<? super V> action;
4784              if ((action = this.action) != null) {
4785 <                for (int b; (b = preSplit()) > 0;)
4786 <                    new ForEachValueTask<K,V>(map, this, b, action).fork();
4787 <                Object v;
4788 <                while ((v = advance()) != null)
4789 <                    action.apply((V)v);
4785 >                for (int i = baseIndex, f, h; batch > 0 &&
4786 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4787 >                    addToPendingCount(1);
4788 >                    new ForEachValueTask<K,V>
4789 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4790 >                         action).fork();
4791 >                }
4792 >                for (Node<K,V> p; (p = advance()) != null;)
4793 >                    action.apply(p.val);
4794                  propagateCompletion();
4795              }
4796          }
4797      }
4798  
4799 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4800 <        extends Traverser<K,V,Void> {
4801 <        final Action<Entry<K,V>> action;
4799 >    @SuppressWarnings("serial")
4800 >    static final class ForEachEntryTask<K,V>
4801 >        extends BulkTask<K,V,Void> {
4802 >        final Action<? super Entry<K,V>> action;
4803          ForEachEntryTask
4804 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4805 <             Action<Entry<K,V>> action) {
4806 <            super(m, p, b);
4804 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4805 >             Action<? super Entry<K,V>> action) {
4806 >            super(p, b, i, f, t);
4807              this.action = action;
4808          }
4809 <        @SuppressWarnings("unchecked") public final void compute() {
4810 <            final Action<Entry<K,V>> action;
4809 >        public final void compute() {
4810 >            final Action<? super Entry<K,V>> action;
4811              if ((action = this.action) != null) {
4812 <                for (int b; (b = preSplit()) > 0;)
4813 <                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
4814 <                Object v;
4815 <                while ((v = advance()) != null)
4816 <                    action.apply(entryFor((K)nextKey, (V)v));
4812 >                for (int i = baseIndex, f, h; batch > 0 &&
4813 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4814 >                    addToPendingCount(1);
4815 >                    new ForEachEntryTask<K,V>
4816 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4817 >                         action).fork();
4818 >                }
4819 >                for (Node<K,V> p; (p = advance()) != null; )
4820 >                    action.apply(p);
4821                  propagateCompletion();
4822              }
4823          }
4824      }
4825  
4826 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4827 <        extends Traverser<K,V,Void> {
4828 <        final BiAction<K,V> action;
4826 >    @SuppressWarnings("serial")
4827 >    static final class ForEachMappingTask<K,V>
4828 >        extends BulkTask<K,V,Void> {
4829 >        final BiAction<? super K, ? super V> action;
4830          ForEachMappingTask
4831 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4832 <             BiAction<K,V> action) {
4833 <            super(m, p, b);
4831 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4832 >             BiAction<? super K,? super V> action) {
4833 >            super(p, b, i, f, t);
4834              this.action = action;
4835          }
4836 <        @SuppressWarnings("unchecked") public final void compute() {
4837 <            final BiAction<K,V> action;
4836 >        public final void compute() {
4837 >            final BiAction<? super K, ? super V> action;
4838              if ((action = this.action) != null) {
4839 <                for (int b; (b = preSplit()) > 0;)
4840 <                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
4841 <                Object v;
4842 <                while ((v = advance()) != null)
4843 <                    action.apply((K)nextKey, (V)v);
4839 >                for (int i = baseIndex, f, h; batch > 0 &&
4840 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4841 >                    addToPendingCount(1);
4842 >                    new ForEachMappingTask<K,V>
4843 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4844 >                         action).fork();
4845 >                }
4846 >                for (Node<K,V> p; (p = advance()) != null; )
4847 >                    action.apply(p.key, p.val);
4848                  propagateCompletion();
4849              }
4850          }
4851      }
4852  
4853 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4854 <        extends Traverser<K,V,Void> {
4853 >    @SuppressWarnings("serial")
4854 >    static final class ForEachTransformedKeyTask<K,V,U>
4855 >        extends BulkTask<K,V,Void> {
4856          final Fun<? super K, ? extends U> transformer;
4857 <        final Action<U> action;
4857 >        final Action<? super U> action;
4858          ForEachTransformedKeyTask
4859 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4860 <             Fun<? super K, ? extends U> transformer, Action<U> action) {
4861 <            super(m, p, b);
4859 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4860 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4861 >            super(p, b, i, f, t);
4862              this.transformer = transformer; this.action = action;
4863          }
4864 <        @SuppressWarnings("unchecked") public final void compute() {
4864 >        public final void compute() {
4865              final Fun<? super K, ? extends U> transformer;
4866 <            final Action<U> action;
4866 >            final Action<? super U> action;
4867              if ((transformer = this.transformer) != null &&
4868                  (action = this.action) != null) {
4869 <                for (int b; (b = preSplit()) > 0;)
4869 >                for (int i = baseIndex, f, h; batch > 0 &&
4870 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4871 >                    addToPendingCount(1);
4872                      new ForEachTransformedKeyTask<K,V,U>
4873 <                        (map, this, b, transformer, action).fork();
4874 <                U u;
4875 <                while (advance() != null) {
4876 <                    if ((u = transformer.apply((K)nextKey)) != null)
4873 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4874 >                         transformer, action).fork();
4875 >                }
4876 >                for (Node<K,V> p; (p = advance()) != null; ) {
4877 >                    U u;
4878 >                    if ((u = transformer.apply(p.key)) != null)
4879                          action.apply(u);
4880                  }
4881                  propagateCompletion();
# Line 5327 | Line 4883 | public class ConcurrentHashMapV8<K, V>
4883          }
4884      }
4885  
4886 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4887 <        extends Traverser<K,V,Void> {
4886 >    @SuppressWarnings("serial")
4887 >    static final class ForEachTransformedValueTask<K,V,U>
4888 >        extends BulkTask<K,V,Void> {
4889          final Fun<? super V, ? extends U> transformer;
4890 <        final Action<U> action;
4890 >        final Action<? super U> action;
4891          ForEachTransformedValueTask
4892 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4893 <             Fun<? super V, ? extends U> transformer, Action<U> action) {
4894 <            super(m, p, b);
4892 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4893 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4894 >            super(p, b, i, f, t);
4895              this.transformer = transformer; this.action = action;
4896          }
4897 <        @SuppressWarnings("unchecked") public final void compute() {
4897 >        public final void compute() {
4898              final Fun<? super V, ? extends U> transformer;
4899 <            final Action<U> action;
4899 >            final Action<? super U> action;
4900              if ((transformer = this.transformer) != null &&
4901                  (action = this.action) != null) {
4902 <                for (int b; (b = preSplit()) > 0;)
4902 >                for (int i = baseIndex, f, h; batch > 0 &&
4903 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4904 >                    addToPendingCount(1);
4905                      new ForEachTransformedValueTask<K,V,U>
4906 <                        (map, this, b, transformer, action).fork();
4907 <                Object v; U u;
4908 <                while ((v = advance()) != null) {
4909 <                    if ((u = transformer.apply((V)v)) != null)
4906 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4907 >                         transformer, action).fork();
4908 >                }
4909 >                for (Node<K,V> p; (p = advance()) != null; ) {
4910 >                    U u;
4911 >                    if ((u = transformer.apply(p.val)) != null)
4912                          action.apply(u);
4913                  }
4914                  propagateCompletion();
# Line 5355 | Line 4916 | public class ConcurrentHashMapV8<K, V>
4916          }
4917      }
4918  
4919 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4920 <        extends Traverser<K,V,Void> {
4919 >    @SuppressWarnings("serial")
4920 >    static final class ForEachTransformedEntryTask<K,V,U>
4921 >        extends BulkTask<K,V,Void> {
4922          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4923 <        final Action<U> action;
4923 >        final Action<? super U> action;
4924          ForEachTransformedEntryTask
4925 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4926 <             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
4927 <            super(m, p, b);
4925 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4926 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4927 >            super(p, b, i, f, t);
4928              this.transformer = transformer; this.action = action;
4929          }
4930 <        @SuppressWarnings("unchecked") public final void compute() {
4930 >        public final void compute() {
4931              final Fun<Map.Entry<K,V>, ? extends U> transformer;
4932 <            final Action<U> action;
4932 >            final Action<? super U> action;
4933              if ((transformer = this.transformer) != null &&
4934                  (action = this.action) != null) {
4935 <                for (int b; (b = preSplit()) > 0;)
4935 >                for (int i = baseIndex, f, h; batch > 0 &&
4936 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4937 >                    addToPendingCount(1);
4938                      new ForEachTransformedEntryTask<K,V,U>
4939 <                        (map, this, b, transformer, action).fork();
4940 <                Object v; U u;
4941 <                while ((v = advance()) != null) {
4942 <                    if ((u = transformer.apply(entryFor((K)nextKey,
4943 <                                                        (V)v))) != null)
4939 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4940 >                         transformer, action).fork();
4941 >                }
4942 >                for (Node<K,V> p; (p = advance()) != null; ) {
4943 >                    U u;
4944 >                    if ((u = transformer.apply(p)) != null)
4945                          action.apply(u);
4946                  }
4947                  propagateCompletion();
# Line 5384 | Line 4949 | public class ConcurrentHashMapV8<K, V>
4949          }
4950      }
4951  
4952 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4953 <        extends Traverser<K,V,Void> {
4952 >    @SuppressWarnings("serial")
4953 >    static final class ForEachTransformedMappingTask<K,V,U>
4954 >        extends BulkTask<K,V,Void> {
4955          final BiFun<? super K, ? super V, ? extends U> transformer;
4956 <        final Action<U> action;
4956 >        final Action<? super U> action;
4957          ForEachTransformedMappingTask
4958 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4958 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4959               BiFun<? super K, ? super V, ? extends U> transformer,
4960 <             Action<U> action) {
4961 <            super(m, p, b);
4960 >             Action<? super U> action) {
4961 >            super(p, b, i, f, t);
4962              this.transformer = transformer; this.action = action;
4963          }
4964 <        @SuppressWarnings("unchecked") public final void compute() {
4964 >        public final void compute() {
4965              final BiFun<? super K, ? super V, ? extends U> transformer;
4966 <            final Action<U> action;
4966 >            final Action<? super U> action;
4967              if ((transformer = this.transformer) != null &&
4968                  (action = this.action) != null) {
4969 <                for (int b; (b = preSplit()) > 0;)
4969 >                for (int i = baseIndex, f, h; batch > 0 &&
4970 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4971 >                    addToPendingCount(1);
4972                      new ForEachTransformedMappingTask<K,V,U>
4973 <                        (map, this, b, transformer, action).fork();
4974 <                Object v; U u;
4975 <                while ((v = advance()) != null) {
4976 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
4973 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4974 >                         transformer, action).fork();
4975 >                }
4976 >                for (Node<K,V> p; (p = advance()) != null; ) {
4977 >                    U u;
4978 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4979                          action.apply(u);
4980                  }
4981                  propagateCompletion();
# Line 5413 | Line 4983 | public class ConcurrentHashMapV8<K, V>
4983          }
4984      }
4985  
4986 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4987 <        extends Traverser<K,V,U> {
4986 >    @SuppressWarnings("serial")
4987 >    static final class SearchKeysTask<K,V,U>
4988 >        extends BulkTask<K,V,U> {
4989          final Fun<? super K, ? extends U> searchFunction;
4990          final AtomicReference<U> result;
4991          SearchKeysTask
4992 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
4992 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4993               Fun<? super K, ? extends U> searchFunction,
4994               AtomicReference<U> result) {
4995 <            super(m, p, b);
4995 >            super(p, b, i, f, t);
4996              this.searchFunction = searchFunction; this.result = result;
4997          }
4998          public final U getRawResult() { return result.get(); }
4999 <        @SuppressWarnings("unchecked") public final void compute() {
4999 >        public final void compute() {
5000              final Fun<? super K, ? extends U> searchFunction;
5001              final AtomicReference<U> result;
5002              if ((searchFunction = this.searchFunction) != null &&
5003                  (result = this.result) != null) {
5004 <                for (int b;;) {
5004 >                for (int i = baseIndex, f, h; batch > 0 &&
5005 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5006                      if (result.get() != null)
5007                          return;
5008 <                    if ((b = preSplit()) <= 0)
5437 <                        break;
5008 >                    addToPendingCount(1);
5009                      new SearchKeysTask<K,V,U>
5010 <                        (map, this, b, searchFunction, result).fork();
5010 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5011 >                         searchFunction, result).fork();
5012                  }
5013                  while (result.get() == null) {
5014                      U u;
5015 <                    if (advance() == null) {
5015 >                    Node<K,V> p;
5016 >                    if ((p = advance()) == null) {
5017                          propagateCompletion();
5018                          break;
5019                      }
5020 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
5020 >                    if ((u = searchFunction.apply(p.key)) != null) {
5021                          if (result.compareAndSet(null, u))
5022                              quietlyCompleteRoot();
5023                          break;
# Line 5454 | Line 5027 | public class ConcurrentHashMapV8<K, V>
5027          }
5028      }
5029  
5030 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5031 <        extends Traverser<K,V,U> {
5030 >    @SuppressWarnings("serial")
5031 >    static final class SearchValuesTask<K,V,U>
5032 >        extends BulkTask<K,V,U> {
5033          final Fun<? super V, ? extends U> searchFunction;
5034          final AtomicReference<U> result;
5035          SearchValuesTask
5036 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5036 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5037               Fun<? super V, ? extends U> searchFunction,
5038               AtomicReference<U> result) {
5039 <            super(m, p, b);
5039 >            super(p, b, i, f, t);
5040              this.searchFunction = searchFunction; this.result = result;
5041          }
5042          public final U getRawResult() { return result.get(); }
5043 <        @SuppressWarnings("unchecked") public final void compute() {
5043 >        public final void compute() {
5044              final Fun<? super V, ? extends U> searchFunction;
5045              final AtomicReference<U> result;
5046              if ((searchFunction = this.searchFunction) != null &&
5047                  (result = this.result) != null) {
5048 <                for (int b;;) {
5048 >                for (int i = baseIndex, f, h; batch > 0 &&
5049 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5050                      if (result.get() != null)
5051                          return;
5052 <                    if ((b = preSplit()) <= 0)
5478 <                        break;
5052 >                    addToPendingCount(1);
5053                      new SearchValuesTask<K,V,U>
5054 <                        (map, this, b, searchFunction, result).fork();
5054 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5055 >                         searchFunction, result).fork();
5056                  }
5057                  while (result.get() == null) {
5058 <                    Object v; U u;
5059 <                    if ((v = advance()) == null) {
5058 >                    U u;
5059 >                    Node<K,V> p;
5060 >                    if ((p = advance()) == null) {
5061                          propagateCompletion();
5062                          break;
5063                      }
5064 <                    if ((u = searchFunction.apply((V)v)) != null) {
5064 >                    if ((u = searchFunction.apply(p.val)) != null) {
5065                          if (result.compareAndSet(null, u))
5066                              quietlyCompleteRoot();
5067                          break;
# Line 5495 | Line 5071 | public class ConcurrentHashMapV8<K, V>
5071          }
5072      }
5073  
5074 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5075 <        extends Traverser<K,V,U> {
5074 >    @SuppressWarnings("serial")
5075 >    static final class SearchEntriesTask<K,V,U>
5076 >        extends BulkTask<K,V,U> {
5077          final Fun<Entry<K,V>, ? extends U> searchFunction;
5078          final AtomicReference<U> result;
5079          SearchEntriesTask
5080 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5080 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5081               Fun<Entry<K,V>, ? extends U> searchFunction,
5082               AtomicReference<U> result) {
5083 <            super(m, p, b);
5083 >            super(p, b, i, f, t);
5084              this.searchFunction = searchFunction; this.result = result;
5085          }
5086          public final U getRawResult() { return result.get(); }
5087 <        @SuppressWarnings("unchecked") public final void compute() {
5087 >        public final void compute() {
5088              final Fun<Entry<K,V>, ? extends U> searchFunction;
5089              final AtomicReference<U> result;
5090              if ((searchFunction = this.searchFunction) != null &&
5091                  (result = this.result) != null) {
5092 <                for (int b;;) {
5092 >                for (int i = baseIndex, f, h; batch > 0 &&
5093 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5094                      if (result.get() != null)
5095                          return;
5096 <                    if ((b = preSplit()) <= 0)
5519 <                        break;
5096 >                    addToPendingCount(1);
5097                      new SearchEntriesTask<K,V,U>
5098 <                        (map, this, b, searchFunction, result).fork();
5098 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5099 >                         searchFunction, result).fork();
5100                  }
5101                  while (result.get() == null) {
5102 <                    Object v; U u;
5103 <                    if ((v = advance()) == null) {
5102 >                    U u;
5103 >                    Node<K,V> p;
5104 >                    if ((p = advance()) == null) {
5105                          propagateCompletion();
5106                          break;
5107                      }
5108 <                    if ((u = searchFunction.apply(entryFor((K)nextKey,
5530 <                                                           (V)v))) != null) {
5108 >                    if ((u = searchFunction.apply(p)) != null) {
5109                          if (result.compareAndSet(null, u))
5110                              quietlyCompleteRoot();
5111                          return;
# Line 5537 | Line 5115 | public class ConcurrentHashMapV8<K, V>
5115          }
5116      }
5117  
5118 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5119 <        extends Traverser<K,V,U> {
5118 >    @SuppressWarnings("serial")
5119 >    static final class SearchMappingsTask<K,V,U>
5120 >        extends BulkTask<K,V,U> {
5121          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5122          final AtomicReference<U> result;
5123          SearchMappingsTask
5124 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5124 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5125               BiFun<? super K, ? super V, ? extends U> searchFunction,
5126               AtomicReference<U> result) {
5127 <            super(m, p, b);
5127 >            super(p, b, i, f, t);
5128              this.searchFunction = searchFunction; this.result = result;
5129          }
5130          public final U getRawResult() { return result.get(); }
5131 <        @SuppressWarnings("unchecked") public final void compute() {
5131 >        public final void compute() {
5132              final BiFun<? super K, ? super V, ? extends U> searchFunction;
5133              final AtomicReference<U> result;
5134              if ((searchFunction = this.searchFunction) != null &&
5135                  (result = this.result) != null) {
5136 <                for (int b;;) {
5136 >                for (int i = baseIndex, f, h; batch > 0 &&
5137 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5138                      if (result.get() != null)
5139                          return;
5140 <                    if ((b = preSplit()) <= 0)
5561 <                        break;
5140 >                    addToPendingCount(1);
5141                      new SearchMappingsTask<K,V,U>
5142 <                        (map, this, b, searchFunction, result).fork();
5142 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5143 >                         searchFunction, result).fork();
5144                  }
5145                  while (result.get() == null) {
5146 <                    Object v; U u;
5147 <                    if ((v = advance()) == null) {
5146 >                    U u;
5147 >                    Node<K,V> p;
5148 >                    if ((p = advance()) == null) {
5149                          propagateCompletion();
5150                          break;
5151                      }
5152 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5152 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5153                          if (result.compareAndSet(null, u))
5154                              quietlyCompleteRoot();
5155                          break;
# Line 5578 | Line 5159 | public class ConcurrentHashMapV8<K, V>
5159          }
5160      }
5161  
5162 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5163 <        extends Traverser<K,V,K> {
5162 >    @SuppressWarnings("serial")
5163 >    static final class ReduceKeysTask<K,V>
5164 >        extends BulkTask<K,V,K> {
5165          final BiFun<? super K, ? super K, ? extends K> reducer;
5166          K result;
5167          ReduceKeysTask<K,V> rights, nextRight;
5168          ReduceKeysTask
5169 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5169 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5170               ReduceKeysTask<K,V> nextRight,
5171               BiFun<? super K, ? super K, ? extends K> reducer) {
5172 <            super(m, p, b); this.nextRight = nextRight;
5172 >            super(p, b, i, f, t); this.nextRight = nextRight;
5173              this.reducer = reducer;
5174          }
5175          public final K getRawResult() { return result; }
5176 <        @SuppressWarnings("unchecked") public final void compute() {
5176 >        public final void compute() {
5177              final BiFun<? super K, ? super K, ? extends K> reducer;
5178              if ((reducer = this.reducer) != null) {
5179 <                for (int b; (b = preSplit()) > 0;)
5179 >                for (int i = baseIndex, f, h; batch > 0 &&
5180 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5181 >                    addToPendingCount(1);
5182                      (rights = new ReduceKeysTask<K,V>
5183 <                     (map, this, b, rights, reducer)).fork();
5183 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5184 >                      rights, reducer)).fork();
5185 >                }
5186                  K r = null;
5187 <                while (advance() != null) {
5188 <                    K u = (K)nextKey;
5189 <                    r = (r == null) ? u : reducer.apply(r, u);
5187 >                for (Node<K,V> p; (p = advance()) != null; ) {
5188 >                    K u = p.key;
5189 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5190                  }
5191                  result = r;
5192                  CountedCompleter<?> c;
5193                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5194 <                    ReduceKeysTask<K,V>
5194 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5195                          t = (ReduceKeysTask<K,V>)c,
5196                          s = t.rights;
5197                      while (s != null) {
# Line 5620 | Line 5206 | public class ConcurrentHashMapV8<K, V>
5206          }
5207      }
5208  
5209 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5210 <        extends Traverser<K,V,V> {
5209 >    @SuppressWarnings("serial")
5210 >    static final class ReduceValuesTask<K,V>
5211 >        extends BulkTask<K,V,V> {
5212          final BiFun<? super V, ? super V, ? extends V> reducer;
5213          V result;
5214          ReduceValuesTask<K,V> rights, nextRight;
5215          ReduceValuesTask
5216 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5216 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5217               ReduceValuesTask<K,V> nextRight,
5218               BiFun<? super V, ? super V, ? extends V> reducer) {
5219 <            super(m, p, b); this.nextRight = nextRight;
5219 >            super(p, b, i, f, t); this.nextRight = nextRight;
5220              this.reducer = reducer;
5221          }
5222          public final V getRawResult() { return result; }
5223 <        @SuppressWarnings("unchecked") public final void compute() {
5223 >        public final void compute() {
5224              final BiFun<? super V, ? super V, ? extends V> reducer;
5225              if ((reducer = this.reducer) != null) {
5226 <                for (int b; (b = preSplit()) > 0;)
5226 >                for (int i = baseIndex, f, h; batch > 0 &&
5227 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5228 >                    addToPendingCount(1);
5229                      (rights = new ReduceValuesTask<K,V>
5230 <                     (map, this, b, rights, reducer)).fork();
5230 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5231 >                      rights, reducer)).fork();
5232 >                }
5233                  V r = null;
5234 <                Object v;
5235 <                while ((v = advance()) != null) {
5236 <                    V u = (V)v;
5646 <                    r = (r == null) ? u : reducer.apply(r, u);
5234 >                for (Node<K,V> p; (p = advance()) != null; ) {
5235 >                    V v = p.val;
5236 >                    r = (r == null) ? v : reducer.apply(r, v);
5237                  }
5238                  result = r;
5239                  CountedCompleter<?> c;
5240                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5241 <                    ReduceValuesTask<K,V>
5241 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5242                          t = (ReduceValuesTask<K,V>)c,
5243                          s = t.rights;
5244                      while (s != null) {
# Line 5663 | Line 5253 | public class ConcurrentHashMapV8<K, V>
5253          }
5254      }
5255  
5256 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5257 <        extends Traverser<K,V,Map.Entry<K,V>> {
5256 >    @SuppressWarnings("serial")
5257 >    static final class ReduceEntriesTask<K,V>
5258 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5259          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5260          Map.Entry<K,V> result;
5261          ReduceEntriesTask<K,V> rights, nextRight;
5262          ReduceEntriesTask
5263 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5263 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5264               ReduceEntriesTask<K,V> nextRight,
5265               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5266 <            super(m, p, b); this.nextRight = nextRight;
5266 >            super(p, b, i, f, t); this.nextRight = nextRight;
5267              this.reducer = reducer;
5268          }
5269          public final Map.Entry<K,V> getRawResult() { return result; }
5270 <        @SuppressWarnings("unchecked") public final void compute() {
5270 >        public final void compute() {
5271              final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5272              if ((reducer = this.reducer) != null) {
5273 <                for (int b; (b = preSplit()) > 0;)
5273 >                for (int i = baseIndex, f, h; batch > 0 &&
5274 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5275 >                    addToPendingCount(1);
5276                      (rights = new ReduceEntriesTask<K,V>
5277 <                     (map, this, b, rights, reducer)).fork();
5278 <                Map.Entry<K,V> r = null;
5686 <                Object v;
5687 <                while ((v = advance()) != null) {
5688 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
5689 <                    r = (r == null) ? u : reducer.apply(r, u);
5277 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5278 >                      rights, reducer)).fork();
5279                  }
5280 +                Map.Entry<K,V> r = null;
5281 +                for (Node<K,V> p; (p = advance()) != null; )
5282 +                    r = (r == null) ? p : reducer.apply(r, p);
5283                  result = r;
5284                  CountedCompleter<?> c;
5285                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5286 <                    ReduceEntriesTask<K,V>
5286 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5287                          t = (ReduceEntriesTask<K,V>)c,
5288                          s = t.rights;
5289                      while (s != null) {
# Line 5706 | Line 5298 | public class ConcurrentHashMapV8<K, V>
5298          }
5299      }
5300  
5301 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5302 <        extends Traverser<K,V,U> {
5301 >    @SuppressWarnings("serial")
5302 >    static final class MapReduceKeysTask<K,V,U>
5303 >        extends BulkTask<K,V,U> {
5304          final Fun<? super K, ? extends U> transformer;
5305          final BiFun<? super U, ? super U, ? extends U> reducer;
5306          U result;
5307          MapReduceKeysTask<K,V,U> rights, nextRight;
5308          MapReduceKeysTask
5309 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5309 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5310               MapReduceKeysTask<K,V,U> nextRight,
5311               Fun<? super K, ? extends U> transformer,
5312               BiFun<? super U, ? super U, ? extends U> reducer) {
5313 <            super(m, p, b); this.nextRight = nextRight;
5313 >            super(p, b, i, f, t); this.nextRight = nextRight;
5314              this.transformer = transformer;
5315              this.reducer = reducer;
5316          }
5317          public final U getRawResult() { return result; }
5318 <        @SuppressWarnings("unchecked") public final void compute() {
5318 >        public final void compute() {
5319              final Fun<? super K, ? extends U> transformer;
5320              final BiFun<? super U, ? super U, ? extends U> reducer;
5321              if ((transformer = this.transformer) != null &&
5322                  (reducer = this.reducer) != null) {
5323 <                for (int b; (b = preSplit()) > 0;)
5323 >                for (int i = baseIndex, f, h; batch > 0 &&
5324 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5325 >                    addToPendingCount(1);
5326                      (rights = new MapReduceKeysTask<K,V,U>
5327 <                     (map, this, b, rights, transformer, reducer)).fork();
5328 <                U r = null, u;
5329 <                while (advance() != null) {
5330 <                    if ((u = transformer.apply((K)nextKey)) != null)
5327 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5328 >                      rights, transformer, reducer)).fork();
5329 >                }
5330 >                U r = null;
5331 >                for (Node<K,V> p; (p = advance()) != null; ) {
5332 >                    U u;
5333 >                    if ((u = transformer.apply(p.key)) != null)
5334                          r = (r == null) ? u : reducer.apply(r, u);
5335                  }
5336                  result = r;
5337                  CountedCompleter<?> c;
5338                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5339 <                    MapReduceKeysTask<K,V,U>
5339 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5340                          t = (MapReduceKeysTask<K,V,U>)c,
5341                          s = t.rights;
5342                      while (s != null) {
# Line 5753 | Line 5351 | public class ConcurrentHashMapV8<K, V>
5351          }
5352      }
5353  
5354 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5355 <        extends Traverser<K,V,U> {
5354 >    @SuppressWarnings("serial")
5355 >    static final class MapReduceValuesTask<K,V,U>
5356 >        extends BulkTask<K,V,U> {
5357          final Fun<? super V, ? extends U> transformer;
5358          final BiFun<? super U, ? super U, ? extends U> reducer;
5359          U result;
5360          MapReduceValuesTask<K,V,U> rights, nextRight;
5361          MapReduceValuesTask
5362 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5362 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5363               MapReduceValuesTask<K,V,U> nextRight,
5364               Fun<? super V, ? extends U> transformer,
5365               BiFun<? super U, ? super U, ? extends U> reducer) {
5366 <            super(m, p, b); this.nextRight = nextRight;
5366 >            super(p, b, i, f, t); this.nextRight = nextRight;
5367              this.transformer = transformer;
5368              this.reducer = reducer;
5369          }
5370          public final U getRawResult() { return result; }
5371 <        @SuppressWarnings("unchecked") public final void compute() {
5371 >        public final void compute() {
5372              final Fun<? super V, ? extends U> transformer;
5373              final BiFun<? super U, ? super U, ? extends U> reducer;
5374              if ((transformer = this.transformer) != null &&
5375                  (reducer = this.reducer) != null) {
5376 <                for (int b; (b = preSplit()) > 0;)
5376 >                for (int i = baseIndex, f, h; batch > 0 &&
5377 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5378 >                    addToPendingCount(1);
5379                      (rights = new MapReduceValuesTask<K,V,U>
5380 <                     (map, this, b, rights, transformer, reducer)).fork();
5381 <                U r = null, u;
5382 <                Object v;
5383 <                while ((v = advance()) != null) {
5384 <                    if ((u = transformer.apply((V)v)) != null)
5380 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5381 >                      rights, transformer, reducer)).fork();
5382 >                }
5383 >                U r = null;
5384 >                for (Node<K,V> p; (p = advance()) != null; ) {
5385 >                    U u;
5386 >                    if ((u = transformer.apply(p.val)) != null)
5387                          r = (r == null) ? u : reducer.apply(r, u);
5388                  }
5389                  result = r;
5390                  CountedCompleter<?> c;
5391                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5392 <                    MapReduceValuesTask<K,V,U>
5392 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5393                          t = (MapReduceValuesTask<K,V,U>)c,
5394                          s = t.rights;
5395                      while (s != null) {
# Line 5801 | Line 5404 | public class ConcurrentHashMapV8<K, V>
5404          }
5405      }
5406  
5407 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5408 <        extends Traverser<K,V,U> {
5407 >    @SuppressWarnings("serial")
5408 >    static final class MapReduceEntriesTask<K,V,U>
5409 >        extends BulkTask<K,V,U> {
5410          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5411          final BiFun<? super U, ? super U, ? extends U> reducer;
5412          U result;
5413          MapReduceEntriesTask<K,V,U> rights, nextRight;
5414          MapReduceEntriesTask
5415 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5415 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5416               MapReduceEntriesTask<K,V,U> nextRight,
5417               Fun<Map.Entry<K,V>, ? extends U> transformer,
5418               BiFun<? super U, ? super U, ? extends U> reducer) {
5419 <            super(m, p, b); this.nextRight = nextRight;
5419 >            super(p, b, i, f, t); this.nextRight = nextRight;
5420              this.transformer = transformer;
5421              this.reducer = reducer;
5422          }
5423          public final U getRawResult() { return result; }
5424 <        @SuppressWarnings("unchecked") public final void compute() {
5424 >        public final void compute() {
5425              final Fun<Map.Entry<K,V>, ? extends U> transformer;
5426              final BiFun<? super U, ? super U, ? extends U> reducer;
5427              if ((transformer = this.transformer) != null &&
5428                  (reducer = this.reducer) != null) {
5429 <                for (int b; (b = preSplit()) > 0;)
5429 >                for (int i = baseIndex, f, h; batch > 0 &&
5430 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5431 >                    addToPendingCount(1);
5432                      (rights = new MapReduceEntriesTask<K,V,U>
5433 <                     (map, this, b, rights, transformer, reducer)).fork();
5434 <                U r = null, u;
5435 <                Object v;
5436 <                while ((v = advance()) != null) {
5437 <                    if ((u = transformer.apply(entryFor((K)nextKey,
5438 <                                                        (V)v))) != null)
5433 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5434 >                      rights, transformer, reducer)).fork();
5435 >                }
5436 >                U r = null;
5437 >                for (Node<K,V> p; (p = advance()) != null; ) {
5438 >                    U u;
5439 >                    if ((u = transformer.apply(p)) != null)
5440                          r = (r == null) ? u : reducer.apply(r, u);
5441                  }
5442                  result = r;
5443                  CountedCompleter<?> c;
5444                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5445 <                    MapReduceEntriesTask<K,V,U>
5445 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5446                          t = (MapReduceEntriesTask<K,V,U>)c,
5447                          s = t.rights;
5448                      while (s != null) {
# Line 5850 | Line 5457 | public class ConcurrentHashMapV8<K, V>
5457          }
5458      }
5459  
5460 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5461 <        extends Traverser<K,V,U> {
5460 >    @SuppressWarnings("serial")
5461 >    static final class MapReduceMappingsTask<K,V,U>
5462 >        extends BulkTask<K,V,U> {
5463          final BiFun<? super K, ? super V, ? extends U> transformer;
5464          final BiFun<? super U, ? super U, ? extends U> reducer;
5465          U result;
5466          MapReduceMappingsTask<K,V,U> rights, nextRight;
5467          MapReduceMappingsTask
5468 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5468 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5469               MapReduceMappingsTask<K,V,U> nextRight,
5470               BiFun<? super K, ? super V, ? extends U> transformer,
5471               BiFun<? super U, ? super U, ? extends U> reducer) {
5472 <            super(m, p, b); this.nextRight = nextRight;
5472 >            super(p, b, i, f, t); this.nextRight = nextRight;
5473              this.transformer = transformer;
5474              this.reducer = reducer;
5475          }
5476          public final U getRawResult() { return result; }
5477 <        @SuppressWarnings("unchecked") public final void compute() {
5477 >        public final void compute() {
5478              final BiFun<? super K, ? super V, ? extends U> transformer;
5479              final BiFun<? super U, ? super U, ? extends U> reducer;
5480              if ((transformer = this.transformer) != null &&
5481                  (reducer = this.reducer) != null) {
5482 <                for (int b; (b = preSplit()) > 0;)
5482 >                for (int i = baseIndex, f, h; batch > 0 &&
5483 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5484 >                    addToPendingCount(1);
5485                      (rights = new MapReduceMappingsTask<K,V,U>
5486 <                     (map, this, b, rights, transformer, reducer)).fork();
5487 <                U r = null, u;
5488 <                Object v;
5489 <                while ((v = advance()) != null) {
5490 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5486 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5487 >                      rights, transformer, reducer)).fork();
5488 >                }
5489 >                U r = null;
5490 >                for (Node<K,V> p; (p = advance()) != null; ) {
5491 >                    U u;
5492 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5493                          r = (r == null) ? u : reducer.apply(r, u);
5494                  }
5495                  result = r;
5496                  CountedCompleter<?> c;
5497                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5498 <                    MapReduceMappingsTask<K,V,U>
5498 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5499                          t = (MapReduceMappingsTask<K,V,U>)c,
5500                          s = t.rights;
5501                      while (s != null) {
# Line 5898 | Line 5510 | public class ConcurrentHashMapV8<K, V>
5510          }
5511      }
5512  
5513 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5514 <        extends Traverser<K,V,Double> {
5513 >    @SuppressWarnings("serial")
5514 >    static final class MapReduceKeysToDoubleTask<K,V>
5515 >        extends BulkTask<K,V,Double> {
5516          final ObjectToDouble<? super K> transformer;
5517          final DoubleByDoubleToDouble reducer;
5518          final double basis;
5519          double result;
5520          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5521          MapReduceKeysToDoubleTask
5522 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5522 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5523               MapReduceKeysToDoubleTask<K,V> nextRight,
5524               ObjectToDouble<? super K> transformer,
5525               double basis,
5526               DoubleByDoubleToDouble reducer) {
5527 <            super(m, p, b); this.nextRight = nextRight;
5527 >            super(p, b, i, f, t); this.nextRight = nextRight;
5528              this.transformer = transformer;
5529              this.basis = basis; this.reducer = reducer;
5530          }
5531          public final Double getRawResult() { return result; }
5532 <        @SuppressWarnings("unchecked") public final void compute() {
5532 >        public final void compute() {
5533              final ObjectToDouble<? super K> transformer;
5534              final DoubleByDoubleToDouble reducer;
5535              if ((transformer = this.transformer) != null &&
5536                  (reducer = this.reducer) != null) {
5537                  double r = this.basis;
5538 <                for (int b; (b = preSplit()) > 0;)
5538 >                for (int i = baseIndex, f, h; batch > 0 &&
5539 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5540 >                    addToPendingCount(1);
5541                      (rights = new MapReduceKeysToDoubleTask<K,V>
5542 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5543 <                while (advance() != null)
5544 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5542 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5543 >                      rights, transformer, r, reducer)).fork();
5544 >                }
5545 >                for (Node<K,V> p; (p = advance()) != null; )
5546 >                    r = reducer.apply(r, transformer.apply(p.key));
5547                  result = r;
5548                  CountedCompleter<?> c;
5549                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5550 <                    MapReduceKeysToDoubleTask<K,V>
5550 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5551                          t = (MapReduceKeysToDoubleTask<K,V>)c,
5552                          s = t.rights;
5553                      while (s != null) {
# Line 5942 | Line 5559 | public class ConcurrentHashMapV8<K, V>
5559          }
5560      }
5561  
5562 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5563 <        extends Traverser<K,V,Double> {
5562 >    @SuppressWarnings("serial")
5563 >    static final class MapReduceValuesToDoubleTask<K,V>
5564 >        extends BulkTask<K,V,Double> {
5565          final ObjectToDouble<? super V> transformer;
5566          final DoubleByDoubleToDouble reducer;
5567          final double basis;
5568          double result;
5569          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5570          MapReduceValuesToDoubleTask
5571 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5571 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5572               MapReduceValuesToDoubleTask<K,V> nextRight,
5573               ObjectToDouble<? super V> transformer,
5574               double basis,
5575               DoubleByDoubleToDouble reducer) {
5576 <            super(m, p, b); this.nextRight = nextRight;
5576 >            super(p, b, i, f, t); this.nextRight = nextRight;
5577              this.transformer = transformer;
5578              this.basis = basis; this.reducer = reducer;
5579          }
5580          public final Double getRawResult() { return result; }
5581 <        @SuppressWarnings("unchecked") public final void compute() {
5581 >        public final void compute() {
5582              final ObjectToDouble<? super V> transformer;
5583              final DoubleByDoubleToDouble reducer;
5584              if ((transformer = this.transformer) != null &&
5585                  (reducer = this.reducer) != null) {
5586                  double r = this.basis;
5587 <                for (int b; (b = preSplit()) > 0;)
5587 >                for (int i = baseIndex, f, h; batch > 0 &&
5588 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5589 >                    addToPendingCount(1);
5590                      (rights = new MapReduceValuesToDoubleTask<K,V>
5591 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5592 <                Object v;
5593 <                while ((v = advance()) != null)
5594 <                    r = reducer.apply(r, transformer.apply((V)v));
5591 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5592 >                      rights, transformer, r, reducer)).fork();
5593 >                }
5594 >                for (Node<K,V> p; (p = advance()) != null; )
5595 >                    r = reducer.apply(r, transformer.apply(p.val));
5596                  result = r;
5597                  CountedCompleter<?> c;
5598                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5599 <                    MapReduceValuesToDoubleTask<K,V>
5599 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5600                          t = (MapReduceValuesToDoubleTask<K,V>)c,
5601                          s = t.rights;
5602                      while (s != null) {
# Line 5987 | Line 5608 | public class ConcurrentHashMapV8<K, V>
5608          }
5609      }
5610  
5611 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5612 <        extends Traverser<K,V,Double> {
5611 >    @SuppressWarnings("serial")
5612 >    static final class MapReduceEntriesToDoubleTask<K,V>
5613 >        extends BulkTask<K,V,Double> {
5614          final ObjectToDouble<Map.Entry<K,V>> transformer;
5615          final DoubleByDoubleToDouble reducer;
5616          final double basis;
5617          double result;
5618          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5619          MapReduceEntriesToDoubleTask
5620 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5620 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5621               MapReduceEntriesToDoubleTask<K,V> nextRight,
5622               ObjectToDouble<Map.Entry<K,V>> transformer,
5623               double basis,
5624               DoubleByDoubleToDouble reducer) {
5625 <            super(m, p, b); this.nextRight = nextRight;
5625 >            super(p, b, i, f, t); this.nextRight = nextRight;
5626              this.transformer = transformer;
5627              this.basis = basis; this.reducer = reducer;
5628          }
5629          public final Double getRawResult() { return result; }
5630 <        @SuppressWarnings("unchecked") public final void compute() {
5630 >        public final void compute() {
5631              final ObjectToDouble<Map.Entry<K,V>> transformer;
5632              final DoubleByDoubleToDouble reducer;
5633              if ((transformer = this.transformer) != null &&
5634                  (reducer = this.reducer) != null) {
5635                  double r = this.basis;
5636 <                for (int b; (b = preSplit()) > 0;)
5636 >                for (int i = baseIndex, f, h; batch > 0 &&
5637 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5638 >                    addToPendingCount(1);
5639                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5640 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5641 <                Object v;
5642 <                while ((v = advance()) != null)
5643 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5644 <                                                                    (V)v)));
5640 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5641 >                      rights, transformer, r, reducer)).fork();
5642 >                }
5643 >                for (Node<K,V> p; (p = advance()) != null; )
5644 >                    r = reducer.apply(r, transformer.apply(p));
5645                  result = r;
5646                  CountedCompleter<?> c;
5647                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5648 <                    MapReduceEntriesToDoubleTask<K,V>
5648 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5649                          t = (MapReduceEntriesToDoubleTask<K,V>)c,
5650                          s = t.rights;
5651                      while (s != null) {
# Line 6033 | Line 5657 | public class ConcurrentHashMapV8<K, V>
5657          }
5658      }
5659  
5660 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5661 <        extends Traverser<K,V,Double> {
5660 >    @SuppressWarnings("serial")
5661 >    static final class MapReduceMappingsToDoubleTask<K,V>
5662 >        extends BulkTask<K,V,Double> {
5663          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5664          final DoubleByDoubleToDouble reducer;
5665          final double basis;
5666          double result;
5667          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5668          MapReduceMappingsToDoubleTask
5669 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5669 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5670               MapReduceMappingsToDoubleTask<K,V> nextRight,
5671               ObjectByObjectToDouble<? super K, ? super V> transformer,
5672               double basis,
5673               DoubleByDoubleToDouble reducer) {
5674 <            super(m, p, b); this.nextRight = nextRight;
5674 >            super(p, b, i, f, t); this.nextRight = nextRight;
5675              this.transformer = transformer;
5676              this.basis = basis; this.reducer = reducer;
5677          }
5678          public final Double getRawResult() { return result; }
5679 <        @SuppressWarnings("unchecked") public final void compute() {
5679 >        public final void compute() {
5680              final ObjectByObjectToDouble<? super K, ? super V> transformer;
5681              final DoubleByDoubleToDouble reducer;
5682              if ((transformer = this.transformer) != null &&
5683                  (reducer = this.reducer) != null) {
5684                  double r = this.basis;
5685 <                for (int b; (b = preSplit()) > 0;)
5685 >                for (int i = baseIndex, f, h; batch > 0 &&
5686 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5687 >                    addToPendingCount(1);
5688                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5689 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5690 <                Object v;
5691 <                while ((v = advance()) != null)
5692 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5689 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5690 >                      rights, transformer, r, reducer)).fork();
5691 >                }
5692 >                for (Node<K,V> p; (p = advance()) != null; )
5693 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5694                  result = r;
5695                  CountedCompleter<?> c;
5696                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5697 <                    MapReduceMappingsToDoubleTask<K,V>
5697 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5698                          t = (MapReduceMappingsToDoubleTask<K,V>)c,
5699                          s = t.rights;
5700                      while (s != null) {
# Line 6078 | Line 5706 | public class ConcurrentHashMapV8<K, V>
5706          }
5707      }
5708  
5709 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5710 <        extends Traverser<K,V,Long> {
5709 >    @SuppressWarnings("serial")
5710 >    static final class MapReduceKeysToLongTask<K,V>
5711 >        extends BulkTask<K,V,Long> {
5712          final ObjectToLong<? super K> transformer;
5713          final LongByLongToLong reducer;
5714          final long basis;
5715          long result;
5716          MapReduceKeysToLongTask<K,V> rights, nextRight;
5717          MapReduceKeysToLongTask
5718 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5718 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5719               MapReduceKeysToLongTask<K,V> nextRight,
5720               ObjectToLong<? super K> transformer,
5721               long basis,
5722               LongByLongToLong reducer) {
5723 <            super(m, p, b); this.nextRight = nextRight;
5723 >            super(p, b, i, f, t); this.nextRight = nextRight;
5724              this.transformer = transformer;
5725              this.basis = basis; this.reducer = reducer;
5726          }
5727          public final Long getRawResult() { return result; }
5728 <        @SuppressWarnings("unchecked") public final void compute() {
5728 >        public final void compute() {
5729              final ObjectToLong<? super K> transformer;
5730              final LongByLongToLong reducer;
5731              if ((transformer = this.transformer) != null &&
5732                  (reducer = this.reducer) != null) {
5733                  long r = this.basis;
5734 <                for (int b; (b = preSplit()) > 0;)
5734 >                for (int i = baseIndex, f, h; batch > 0 &&
5735 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5736 >                    addToPendingCount(1);
5737                      (rights = new MapReduceKeysToLongTask<K,V>
5738 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5739 <                while (advance() != null)
5740 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5738 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5739 >                      rights, transformer, r, reducer)).fork();
5740 >                }
5741 >                for (Node<K,V> p; (p = advance()) != null; )
5742 >                    r = reducer.apply(r, transformer.apply(p.key));
5743                  result = r;
5744                  CountedCompleter<?> c;
5745                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5746 <                    MapReduceKeysToLongTask<K,V>
5746 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5747                          t = (MapReduceKeysToLongTask<K,V>)c,
5748                          s = t.rights;
5749                      while (s != null) {
# Line 6122 | Line 5755 | public class ConcurrentHashMapV8<K, V>
5755          }
5756      }
5757  
5758 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5759 <        extends Traverser<K,V,Long> {
5758 >    @SuppressWarnings("serial")
5759 >    static final class MapReduceValuesToLongTask<K,V>
5760 >        extends BulkTask<K,V,Long> {
5761          final ObjectToLong<? super V> transformer;
5762          final LongByLongToLong reducer;
5763          final long basis;
5764          long result;
5765          MapReduceValuesToLongTask<K,V> rights, nextRight;
5766          MapReduceValuesToLongTask
5767 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5767 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5768               MapReduceValuesToLongTask<K,V> nextRight,
5769               ObjectToLong<? super V> transformer,
5770               long basis,
5771               LongByLongToLong reducer) {
5772 <            super(m, p, b); this.nextRight = nextRight;
5772 >            super(p, b, i, f, t); this.nextRight = nextRight;
5773              this.transformer = transformer;
5774              this.basis = basis; this.reducer = reducer;
5775          }
5776          public final Long getRawResult() { return result; }
5777 <        @SuppressWarnings("unchecked") public final void compute() {
5777 >        public final void compute() {
5778              final ObjectToLong<? super V> transformer;
5779              final LongByLongToLong reducer;
5780              if ((transformer = this.transformer) != null &&
5781                  (reducer = this.reducer) != null) {
5782                  long r = this.basis;
5783 <                for (int b; (b = preSplit()) > 0;)
5783 >                for (int i = baseIndex, f, h; batch > 0 &&
5784 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5785 >                    addToPendingCount(1);
5786                      (rights = new MapReduceValuesToLongTask<K,V>
5787 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5788 <                Object v;
5789 <                while ((v = advance()) != null)
5790 <                    r = reducer.apply(r, transformer.apply((V)v));
5787 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5788 >                      rights, transformer, r, reducer)).fork();
5789 >                }
5790 >                for (Node<K,V> p; (p = advance()) != null; )
5791 >                    r = reducer.apply(r, transformer.apply(p.val));
5792                  result = r;
5793                  CountedCompleter<?> c;
5794                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5795 <                    MapReduceValuesToLongTask<K,V>
5795 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5796                          t = (MapReduceValuesToLongTask<K,V>)c,
5797                          s = t.rights;
5798                      while (s != null) {
# Line 6167 | Line 5804 | public class ConcurrentHashMapV8<K, V>
5804          }
5805      }
5806  
5807 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5808 <        extends Traverser<K,V,Long> {
5807 >    @SuppressWarnings("serial")
5808 >    static final class MapReduceEntriesToLongTask<K,V>
5809 >        extends BulkTask<K,V,Long> {
5810          final ObjectToLong<Map.Entry<K,V>> transformer;
5811          final LongByLongToLong reducer;
5812          final long basis;
5813          long result;
5814          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5815          MapReduceEntriesToLongTask
5816 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5816 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5817               MapReduceEntriesToLongTask<K,V> nextRight,
5818               ObjectToLong<Map.Entry<K,V>> transformer,
5819               long basis,
5820               LongByLongToLong reducer) {
5821 <            super(m, p, b); this.nextRight = nextRight;
5821 >            super(p, b, i, f, t); this.nextRight = nextRight;
5822              this.transformer = transformer;
5823              this.basis = basis; this.reducer = reducer;
5824          }
5825          public final Long getRawResult() { return result; }
5826 <        @SuppressWarnings("unchecked") public final void compute() {
5826 >        public final void compute() {
5827              final ObjectToLong<Map.Entry<K,V>> transformer;
5828              final LongByLongToLong reducer;
5829              if ((transformer = this.transformer) != null &&
5830                  (reducer = this.reducer) != null) {
5831                  long r = this.basis;
5832 <                for (int b; (b = preSplit()) > 0;)
5832 >                for (int i = baseIndex, f, h; batch > 0 &&
5833 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5834 >                    addToPendingCount(1);
5835                      (rights = new MapReduceEntriesToLongTask<K,V>
5836 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5837 <                Object v;
5838 <                while ((v = advance()) != null)
5839 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
5840 <                                                                    (V)v)));
5836 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5837 >                      rights, transformer, r, reducer)).fork();
5838 >                }
5839 >                for (Node<K,V> p; (p = advance()) != null; )
5840 >                    r = reducer.apply(r, transformer.apply(p));
5841                  result = r;
5842                  CountedCompleter<?> c;
5843                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5844 <                    MapReduceEntriesToLongTask<K,V>
5844 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5845                          t = (MapReduceEntriesToLongTask<K,V>)c,
5846                          s = t.rights;
5847                      while (s != null) {
# Line 6213 | Line 5853 | public class ConcurrentHashMapV8<K, V>
5853          }
5854      }
5855  
5856 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5857 <        extends Traverser<K,V,Long> {
5856 >    @SuppressWarnings("serial")
5857 >    static final class MapReduceMappingsToLongTask<K,V>
5858 >        extends BulkTask<K,V,Long> {
5859          final ObjectByObjectToLong<? super K, ? super V> transformer;
5860          final LongByLongToLong reducer;
5861          final long basis;
5862          long result;
5863          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5864          MapReduceMappingsToLongTask
5865 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5865 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5866               MapReduceMappingsToLongTask<K,V> nextRight,
5867               ObjectByObjectToLong<? super K, ? super V> transformer,
5868               long basis,
5869               LongByLongToLong reducer) {
5870 <            super(m, p, b); this.nextRight = nextRight;
5870 >            super(p, b, i, f, t); this.nextRight = nextRight;
5871              this.transformer = transformer;
5872              this.basis = basis; this.reducer = reducer;
5873          }
5874          public final Long getRawResult() { return result; }
5875 <        @SuppressWarnings("unchecked") public final void compute() {
5875 >        public final void compute() {
5876              final ObjectByObjectToLong<? super K, ? super V> transformer;
5877              final LongByLongToLong reducer;
5878              if ((transformer = this.transformer) != null &&
5879                  (reducer = this.reducer) != null) {
5880                  long r = this.basis;
5881 <                for (int b; (b = preSplit()) > 0;)
5881 >                for (int i = baseIndex, f, h; batch > 0 &&
5882 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5883 >                    addToPendingCount(1);
5884                      (rights = new MapReduceMappingsToLongTask<K,V>
5885 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5886 <                Object v;
5887 <                while ((v = advance()) != null)
5888 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5885 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5886 >                      rights, transformer, r, reducer)).fork();
5887 >                }
5888 >                for (Node<K,V> p; (p = advance()) != null; )
5889 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5890                  result = r;
5891                  CountedCompleter<?> c;
5892                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5893 <                    MapReduceMappingsToLongTask<K,V>
5893 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5894                          t = (MapReduceMappingsToLongTask<K,V>)c,
5895                          s = t.rights;
5896                      while (s != null) {
# Line 6258 | Line 5902 | public class ConcurrentHashMapV8<K, V>
5902          }
5903      }
5904  
5905 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5906 <        extends Traverser<K,V,Integer> {
5905 >    @SuppressWarnings("serial")
5906 >    static final class MapReduceKeysToIntTask<K,V>
5907 >        extends BulkTask<K,V,Integer> {
5908          final ObjectToInt<? super K> transformer;
5909          final IntByIntToInt reducer;
5910          final int basis;
5911          int result;
5912          MapReduceKeysToIntTask<K,V> rights, nextRight;
5913          MapReduceKeysToIntTask
5914 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5914 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5915               MapReduceKeysToIntTask<K,V> nextRight,
5916               ObjectToInt<? super K> transformer,
5917               int basis,
5918               IntByIntToInt reducer) {
5919 <            super(m, p, b); this.nextRight = nextRight;
5919 >            super(p, b, i, f, t); this.nextRight = nextRight;
5920              this.transformer = transformer;
5921              this.basis = basis; this.reducer = reducer;
5922          }
5923          public final Integer getRawResult() { return result; }
5924 <        @SuppressWarnings("unchecked") public final void compute() {
5924 >        public final void compute() {
5925              final ObjectToInt<? super K> transformer;
5926              final IntByIntToInt reducer;
5927              if ((transformer = this.transformer) != null &&
5928                  (reducer = this.reducer) != null) {
5929                  int r = this.basis;
5930 <                for (int b; (b = preSplit()) > 0;)
5930 >                for (int i = baseIndex, f, h; batch > 0 &&
5931 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5932 >                    addToPendingCount(1);
5933                      (rights = new MapReduceKeysToIntTask<K,V>
5934 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5935 <                while (advance() != null)
5936 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5934 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5935 >                      rights, transformer, r, reducer)).fork();
5936 >                }
5937 >                for (Node<K,V> p; (p = advance()) != null; )
5938 >                    r = reducer.apply(r, transformer.apply(p.key));
5939                  result = r;
5940                  CountedCompleter<?> c;
5941                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5942 <                    MapReduceKeysToIntTask<K,V>
5942 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5943                          t = (MapReduceKeysToIntTask<K,V>)c,
5944                          s = t.rights;
5945                      while (s != null) {
# Line 6302 | Line 5951 | public class ConcurrentHashMapV8<K, V>
5951          }
5952      }
5953  
5954 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5955 <        extends Traverser<K,V,Integer> {
5954 >    @SuppressWarnings("serial")
5955 >    static final class MapReduceValuesToIntTask<K,V>
5956 >        extends BulkTask<K,V,Integer> {
5957          final ObjectToInt<? super V> transformer;
5958          final IntByIntToInt reducer;
5959          final int basis;
5960          int result;
5961          MapReduceValuesToIntTask<K,V> rights, nextRight;
5962          MapReduceValuesToIntTask
5963 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
5963 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5964               MapReduceValuesToIntTask<K,V> nextRight,
5965               ObjectToInt<? super V> transformer,
5966               int basis,
5967               IntByIntToInt reducer) {
5968 <            super(m, p, b); this.nextRight = nextRight;
5968 >            super(p, b, i, f, t); this.nextRight = nextRight;
5969              this.transformer = transformer;
5970              this.basis = basis; this.reducer = reducer;
5971          }
5972          public final Integer getRawResult() { return result; }
5973 <        @SuppressWarnings("unchecked") public final void compute() {
5973 >        public final void compute() {
5974              final ObjectToInt<? super V> transformer;
5975              final IntByIntToInt reducer;
5976              if ((transformer = this.transformer) != null &&
5977                  (reducer = this.reducer) != null) {
5978                  int r = this.basis;
5979 <                for (int b; (b = preSplit()) > 0;)
5979 >                for (int i = baseIndex, f, h; batch > 0 &&
5980 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5981 >                    addToPendingCount(1);
5982                      (rights = new MapReduceValuesToIntTask<K,V>
5983 <                     (map, this, b, rights, transformer, r, reducer)).fork();
5984 <                Object v;
5985 <                while ((v = advance()) != null)
5986 <                    r = reducer.apply(r, transformer.apply((V)v));
5983 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5984 >                      rights, transformer, r, reducer)).fork();
5985 >                }
5986 >                for (Node<K,V> p; (p = advance()) != null; )
5987 >                    r = reducer.apply(r, transformer.apply(p.val));
5988                  result = r;
5989                  CountedCompleter<?> c;
5990                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
5991 <                    MapReduceValuesToIntTask<K,V>
5991 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5992                          t = (MapReduceValuesToIntTask<K,V>)c,
5993                          s = t.rights;
5994                      while (s != null) {
# Line 6347 | Line 6000 | public class ConcurrentHashMapV8<K, V>
6000          }
6001      }
6002  
6003 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6004 <        extends Traverser<K,V,Integer> {
6003 >    @SuppressWarnings("serial")
6004 >    static final class MapReduceEntriesToIntTask<K,V>
6005 >        extends BulkTask<K,V,Integer> {
6006          final ObjectToInt<Map.Entry<K,V>> transformer;
6007          final IntByIntToInt reducer;
6008          final int basis;
6009          int result;
6010          MapReduceEntriesToIntTask<K,V> rights, nextRight;
6011          MapReduceEntriesToIntTask
6012 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6012 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6013               MapReduceEntriesToIntTask<K,V> nextRight,
6014               ObjectToInt<Map.Entry<K,V>> transformer,
6015               int basis,
6016               IntByIntToInt reducer) {
6017 <            super(m, p, b); this.nextRight = nextRight;
6017 >            super(p, b, i, f, t); this.nextRight = nextRight;
6018              this.transformer = transformer;
6019              this.basis = basis; this.reducer = reducer;
6020          }
6021          public final Integer getRawResult() { return result; }
6022 <        @SuppressWarnings("unchecked") public final void compute() {
6022 >        public final void compute() {
6023              final ObjectToInt<Map.Entry<K,V>> transformer;
6024              final IntByIntToInt reducer;
6025              if ((transformer = this.transformer) != null &&
6026                  (reducer = this.reducer) != null) {
6027                  int r = this.basis;
6028 <                for (int b; (b = preSplit()) > 0;)
6028 >                for (int i = baseIndex, f, h; batch > 0 &&
6029 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6030 >                    addToPendingCount(1);
6031                      (rights = new MapReduceEntriesToIntTask<K,V>
6032 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6033 <                Object v;
6034 <                while ((v = advance()) != null)
6035 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6036 <                                                                    (V)v)));
6032 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6033 >                      rights, transformer, r, reducer)).fork();
6034 >                }
6035 >                for (Node<K,V> p; (p = advance()) != null; )
6036 >                    r = reducer.apply(r, transformer.apply(p));
6037                  result = r;
6038                  CountedCompleter<?> c;
6039                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6040 <                    MapReduceEntriesToIntTask<K,V>
6040 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
6041                          t = (MapReduceEntriesToIntTask<K,V>)c,
6042                          s = t.rights;
6043                      while (s != null) {
# Line 6393 | Line 6049 | public class ConcurrentHashMapV8<K, V>
6049          }
6050      }
6051  
6052 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6053 <        extends Traverser<K,V,Integer> {
6052 >    @SuppressWarnings("serial")
6053 >    static final class MapReduceMappingsToIntTask<K,V>
6054 >        extends BulkTask<K,V,Integer> {
6055          final ObjectByObjectToInt<? super K, ? super V> transformer;
6056          final IntByIntToInt reducer;
6057          final int basis;
6058          int result;
6059          MapReduceMappingsToIntTask<K,V> rights, nextRight;
6060          MapReduceMappingsToIntTask
6061 <            (ConcurrentHashMapV8<K,V> m, Traverser<K,V,?> p, int b,
6061 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6062               MapReduceMappingsToIntTask<K,V> nextRight,
6063               ObjectByObjectToInt<? super K, ? super V> transformer,
6064               int basis,
6065               IntByIntToInt reducer) {
6066 <            super(m, p, b); this.nextRight = nextRight;
6066 >            super(p, b, i, f, t); this.nextRight = nextRight;
6067              this.transformer = transformer;
6068              this.basis = basis; this.reducer = reducer;
6069          }
6070          public final Integer getRawResult() { return result; }
6071 <        @SuppressWarnings("unchecked") public final void compute() {
6071 >        public final void compute() {
6072              final ObjectByObjectToInt<? super K, ? super V> transformer;
6073              final IntByIntToInt reducer;
6074              if ((transformer = this.transformer) != null &&
6075                  (reducer = this.reducer) != null) {
6076                  int r = this.basis;
6077 <                for (int b; (b = preSplit()) > 0;)
6077 >                for (int i = baseIndex, f, h; batch > 0 &&
6078 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6079 >                    addToPendingCount(1);
6080                      (rights = new MapReduceMappingsToIntTask<K,V>
6081 <                     (map, this, b, rights, transformer, r, reducer)).fork();
6082 <                Object v;
6083 <                while ((v = advance()) != null)
6084 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
6081 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6082 >                      rights, transformer, r, reducer)).fork();
6083 >                }
6084 >                for (Node<K,V> p; (p = advance()) != null; )
6085 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
6086                  result = r;
6087                  CountedCompleter<?> c;
6088                  for (c = firstComplete(); c != null; c = c.nextComplete()) {
6089 <                    MapReduceMappingsToIntTask<K,V>
6089 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6090                          t = (MapReduceMappingsToIntTask<K,V>)c,
6091                          s = t.rights;
6092                      while (s != null) {
# Line 6438 | Line 6098 | public class ConcurrentHashMapV8<K, V>
6098          }
6099      }
6100  
6101 +    /* ---------------- Counters -------------- */
6102 +
6103 +    // Adapted from LongAdder and Striped64.
6104 +    // See their internal docs for explanation.
6105 +
6106 +    // A padded cell for distributing counts
6107 +    static final class CounterCell {
6108 +        volatile long p0, p1, p2, p3, p4, p5, p6;
6109 +        volatile long value;
6110 +        volatile long q0, q1, q2, q3, q4, q5, q6;
6111 +        CounterCell(long x) { value = x; }
6112 +    }
6113 +
6114 +    /**
6115 +     * Holder for the thread-local hash code determining which
6116 +     * CounterCell to use. The code is initialized via the
6117 +     * counterHashCodeGenerator, but may be moved upon collisions.
6118 +     */
6119 +    static final class CounterHashCode {
6120 +        int code;
6121 +    }
6122 +
6123 +    /**
6124 +     * Generates initial value for per-thread CounterHashCodes.
6125 +     */
6126 +    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
6127 +
6128 +    /**
6129 +     * Increment for counterHashCodeGenerator. See class ThreadLocal
6130 +     * for explanation.
6131 +     */
6132 +    static final int SEED_INCREMENT = 0x61c88647;
6133 +
6134 +    /**
6135 +     * Per-thread counter hash codes. Shared across all instances.
6136 +     */
6137 +    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6138 +        new ThreadLocal<CounterHashCode>();
6139 +
6140 +
6141 +    final long sumCount() {
6142 +        CounterCell[] as = counterCells; CounterCell a;
6143 +        long sum = baseCount;
6144 +        if (as != null) {
6145 +            for (int i = 0; i < as.length; ++i) {
6146 +                if ((a = as[i]) != null)
6147 +                    sum += a.value;
6148 +            }
6149 +        }
6150 +        return sum;
6151 +    }
6152 +
6153 +    // See LongAdder version for explanation
6154 +    private final void fullAddCount(long x, CounterHashCode hc,
6155 +                                    boolean wasUncontended) {
6156 +        int h;
6157 +        if (hc == null) {
6158 +            hc = new CounterHashCode();
6159 +            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6160 +            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6161 +            threadCounterHashCode.set(hc);
6162 +        }
6163 +        else
6164 +            h = hc.code;
6165 +        boolean collide = false;                // True if last slot nonempty
6166 +        for (;;) {
6167 +            CounterCell[] as; CounterCell a; int n; long v;
6168 +            if ((as = counterCells) != null && (n = as.length) > 0) {
6169 +                if ((a = as[(n - 1) & h]) == null) {
6170 +                    if (cellsBusy == 0) {            // Try to attach new Cell
6171 +                        CounterCell r = new CounterCell(x); // Optimistic create
6172 +                        if (cellsBusy == 0 &&
6173 +                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6174 +                            boolean created = false;
6175 +                            try {               // Recheck under lock
6176 +                                CounterCell[] rs; int m, j;
6177 +                                if ((rs = counterCells) != null &&
6178 +                                    (m = rs.length) > 0 &&
6179 +                                    rs[j = (m - 1) & h] == null) {
6180 +                                    rs[j] = r;
6181 +                                    created = true;
6182 +                                }
6183 +                            } finally {
6184 +                                cellsBusy = 0;
6185 +                            }
6186 +                            if (created)
6187 +                                break;
6188 +                            continue;           // Slot is now non-empty
6189 +                        }
6190 +                    }
6191 +                    collide = false;
6192 +                }
6193 +                else if (!wasUncontended)       // CAS already known to fail
6194 +                    wasUncontended = true;      // Continue after rehash
6195 +                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6196 +                    break;
6197 +                else if (counterCells != as || n >= NCPU)
6198 +                    collide = false;            // At max size or stale
6199 +                else if (!collide)
6200 +                    collide = true;
6201 +                else if (cellsBusy == 0 &&
6202 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6203 +                    try {
6204 +                        if (counterCells == as) {// Expand table unless stale
6205 +                            CounterCell[] rs = new CounterCell[n << 1];
6206 +                            for (int i = 0; i < n; ++i)
6207 +                                rs[i] = as[i];
6208 +                            counterCells = rs;
6209 +                        }
6210 +                    } finally {
6211 +                        cellsBusy = 0;
6212 +                    }
6213 +                    collide = false;
6214 +                    continue;                   // Retry with expanded table
6215 +                }
6216 +                h ^= h << 13;                   // Rehash
6217 +                h ^= h >>> 17;
6218 +                h ^= h << 5;
6219 +            }
6220 +            else if (cellsBusy == 0 && counterCells == as &&
6221 +                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6222 +                boolean init = false;
6223 +                try {                           // Initialize table
6224 +                    if (counterCells == as) {
6225 +                        CounterCell[] rs = new CounterCell[2];
6226 +                        rs[h & 1] = new CounterCell(x);
6227 +                        counterCells = rs;
6228 +                        init = true;
6229 +                    }
6230 +                } finally {
6231 +                    cellsBusy = 0;
6232 +                }
6233 +                if (init)
6234 +                    break;
6235 +            }
6236 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6237 +                break;                          // Fall back on using base
6238 +        }
6239 +        hc.code = h;                            // Record index for next time
6240 +    }
6241 +
6242      // Unsafe mechanics
6243      private static final sun.misc.Unsafe U;
6244      private static final long SIZECTL;
6245      private static final long TRANSFERINDEX;
6445    private static final long TRANSFERORIGIN;
6246      private static final long BASECOUNT;
6247 <    private static final long COUNTERBUSY;
6247 >    private static final long CELLSBUSY;
6248      private static final long CELLVALUE;
6249      private static final long ABASE;
6250      private static final int ASHIFT;
6251  
6252      static {
6453        int ss;
6253          try {
6254              U = getUnsafe();
6255              Class<?> k = ConcurrentHashMapV8.class;
# Line 6458 | Line 6257 | public class ConcurrentHashMapV8<K, V>
6257                  (k.getDeclaredField("sizeCtl"));
6258              TRANSFERINDEX = U.objectFieldOffset
6259                  (k.getDeclaredField("transferIndex"));
6461            TRANSFERORIGIN = U.objectFieldOffset
6462                (k.getDeclaredField("transferOrigin"));
6260              BASECOUNT = U.objectFieldOffset
6261                  (k.getDeclaredField("baseCount"));
6262 <            COUNTERBUSY = U.objectFieldOffset
6263 <                (k.getDeclaredField("counterBusy"));
6262 >            CELLSBUSY = U.objectFieldOffset
6263 >                (k.getDeclaredField("cellsBusy"));
6264              Class<?> ck = CounterCell.class;
6265              CELLVALUE = U.objectFieldOffset
6266                  (ck.getDeclaredField("value"));
6267 <            Class<?> sc = Node[].class;
6268 <            ABASE = U.arrayBaseOffset(sc);
6269 <            ss = U.arrayIndexScale(sc);
6270 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6267 >            Class<?> ak = Node[].class;
6268 >            ABASE = U.arrayBaseOffset(ak);
6269 >            int scale = U.arrayIndexScale(ak);
6270 >            if ((scale & (scale - 1)) != 0)
6271 >                throw new Error("data type scale not a power of two");
6272 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6273          } catch (Exception e) {
6274              throw new Error(e);
6275          }
6477        if ((ss & (ss-1)) != 0)
6478            throw new Error("data type scale not a power of two");
6276      }
6277  
6278      /**
# Line 6488 | Line 6285 | public class ConcurrentHashMapV8<K, V>
6285      private static sun.misc.Unsafe getUnsafe() {
6286          try {
6287              return sun.misc.Unsafe.getUnsafe();
6288 <        } catch (SecurityException se) {
6289 <            try {
6290 <                return java.security.AccessController.doPrivileged
6291 <                    (new java.security
6292 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6293 <                        public sun.misc.Unsafe run() throws Exception {
6294 <                            java.lang.reflect.Field f = sun.misc
6295 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6296 <                            f.setAccessible(true);
6297 <                            return (sun.misc.Unsafe) f.get(null);
6298 <                        }});
6299 <            } catch (java.security.PrivilegedActionException e) {
6300 <                throw new RuntimeException("Could not initialize intrinsics",
6301 <                                           e.getCause());
6302 <            }
6288 >        } catch (SecurityException tryReflectionInstead) {}
6289 >        try {
6290 >            return java.security.AccessController.doPrivileged
6291 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6292 >                public sun.misc.Unsafe run() throws Exception {
6293 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6294 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6295 >                        f.setAccessible(true);
6296 >                        Object x = f.get(null);
6297 >                        if (k.isInstance(x))
6298 >                            return k.cast(x);
6299 >                    }
6300 >                    throw new NoSuchFieldError("the Unsafe");
6301 >                }});
6302 >        } catch (java.security.PrivilegedActionException e) {
6303 >            throw new RuntimeException("Could not initialize intrinsics",
6304 >                                       e.getCause());
6305          }
6306      }
6307   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines