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.69 by jsr166, Sun Oct 21 06:14:11 2012 UTC vs.
Revision 1.109 by dl, Wed Jul 3 18:16:31 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166e;
8 < import jsr166e.LongAdder;
8 >
9   import jsr166e.ForkJoinPool;
10 import jsr166e.ForkJoinTask;
10  
11 < import java.util.Comparator;
11 > import java.io.ObjectStreamField;
12 > import java.io.Serializable;
13 > import java.lang.reflect.ParameterizedType;
14 > import java.lang.reflect.Type;
15   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
16   import java.util.Collection;
17 < import java.util.AbstractMap;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
17 > import java.util.Comparator;
18 > import java.util.ConcurrentModificationException;
19 > import java.util.Enumeration;
20   import java.util.HashMap;
21 + import java.util.Hashtable;
22   import java.util.Iterator;
23 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
23 > import java.util.Map;
24   import java.util.NoSuchElementException;
25 + import java.util.Set;
26   import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ThreadLocalRandom;
28 import java.util.concurrent.locks.LockSupport;
29 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
27   import java.util.concurrent.atomic.AtomicReference;
28 <
29 < import java.io.Serializable;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 > import java.util.concurrent.locks.LockSupport;
30 > import java.util.concurrent.locks.ReentrantLock;
31  
32   /**
33   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 41 | import java.io.Serializable;
41   * interoperable with {@code Hashtable} in programs that rely on its
42   * thread safety but not on its synchronization details.
43   *
44 < * <p> Retrieval operations (including {@code get}) generally do not
44 > * <p>Retrieval operations (including {@code get}) generally do not
45   * block, so may overlap with update operations (including {@code put}
46   * and {@code remove}). Retrievals reflect the results of the most
47   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 62 | import java.io.Serializable;
62   * that may be adequate for monitoring or estimation purposes, but not
63   * for program control.
64   *
65 < * <p> The table is dynamically expanded when there are too many
65 > * <p>The table is dynamically expanded when there are too many
66   * collisions (i.e., keys that have distinct hash codes but fall into
67   * the same slot modulo the table size), with the expected average
68   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 81 | import java.io.Serializable;
81   * expected {@code concurrencyLevel} as an additional hint for
82   * internal sizing.  Note that using many keys with exactly the same
83   * {@code hashCode()} is a sure way to slow down performance of any
84 < * hash table.
84 > * hash table. To ameliorate impact, when keys are {@link Comparable},
85 > * this class may use comparison order among keys to help break ties.
86 > *
87 > * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
88 > * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
89 > * (using {@link #keySet(Object)} when only keys are of interest, and the
90 > * mapped values are (perhaps transiently) not used or all take the
91 > * same mapping value.
92   *
93   * <p>This class and its views and iterators implement all of the
94   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
95   * interfaces.
96   *
97 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
97 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
98   * does <em>not</em> allow {@code null} to be used as a key or value.
99   *
100 + * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
101 + * operations that are designed
102 + * to be safely, and often sensibly, applied even with maps that are
103 + * being concurrently updated by other threads; for example, when
104 + * computing a snapshot summary of the values in a shared registry.
105 + * There are three kinds of operation, each with four forms, accepting
106 + * functions with Keys, Values, Entries, and (Key, Value) arguments
107 + * and/or return values. Because the elements of a ConcurrentHashMapV8
108 + * are not ordered in any particular way, and may be processed in
109 + * different orders in different parallel executions, the correctness
110 + * of supplied functions should not depend on any ordering, or on any
111 + * other objects or values that may transiently change while
112 + * computation is in progress; and except for forEach actions, should
113 + * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
114 + * objects do not support method {@code setValue}.
115 + *
116 + * <ul>
117 + * <li> forEach: Perform a given action on each element.
118 + * A variant form applies a given transformation on each element
119 + * before performing the action.</li>
120 + *
121 + * <li> search: Return the first available non-null result of
122 + * applying a given function on each element; skipping further
123 + * search when a result is found.</li>
124 + *
125 + * <li> reduce: Accumulate each element.  The supplied reduction
126 + * function cannot rely on ordering (more formally, it should be
127 + * both associative and commutative).  There are five variants:
128 + *
129 + * <ul>
130 + *
131 + * <li> Plain reductions. (There is not a form of this method for
132 + * (key, value) function arguments since there is no corresponding
133 + * return type.)</li>
134 + *
135 + * <li> Mapped reductions that accumulate the results of a given
136 + * function applied to each element.</li>
137 + *
138 + * <li> Reductions to scalar doubles, longs, and ints, using a
139 + * given basis value.</li>
140 + *
141 + * </ul>
142 + * </li>
143 + * </ul>
144 + *
145 + * <p>These bulk operations accept a {@code parallelismThreshold}
146 + * argument. Methods proceed sequentially if the current map size is
147 + * estimated to be less than the given threshold. Using a value of
148 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
149 + * of {@code 1} results in maximal parallelism by partitioning into
150 + * enough subtasks to fully utilize the {@link
151 + * ForkJoinPool#commonPool()} that is used for all parallel
152 + * computations. Normally, you would initially choose one of these
153 + * extreme values, and then measure performance of using in-between
154 + * values that trade off overhead versus throughput.
155 + *
156 + * <p>The concurrency properties of bulk operations follow
157 + * from those of ConcurrentHashMapV8: Any non-null result returned
158 + * from {@code get(key)} and related access methods bears a
159 + * happens-before relation with the associated insertion or
160 + * update.  The result of any bulk operation reflects the
161 + * composition of these per-element relations (but is not
162 + * necessarily atomic with respect to the map as a whole unless it
163 + * is somehow known to be quiescent).  Conversely, because keys
164 + * and values in the map are never null, null serves as a reliable
165 + * atomic indicator of the current lack of any result.  To
166 + * maintain this property, null serves as an implicit basis for
167 + * all non-scalar reduction operations. For the double, long, and
168 + * int versions, the basis should be one that, when combined with
169 + * any other value, returns that other value (more formally, it
170 + * should be the identity element for the reduction). Most common
171 + * reductions have these properties; for example, computing a sum
172 + * with basis 0 or a minimum with basis MAX_VALUE.
173 + *
174 + * <p>Search and transformation functions provided as arguments
175 + * should similarly return null to indicate the lack of any result
176 + * (in which case it is not used). In the case of mapped
177 + * reductions, this also enables transformations to serve as
178 + * filters, returning null (or, in the case of primitive
179 + * specializations, the identity basis) if the element should not
180 + * be combined. You can create compound transformations and
181 + * filterings by composing them yourself under this "null means
182 + * there is nothing there now" rule before using them in search or
183 + * reduce operations.
184 + *
185 + * <p>Methods accepting and/or returning Entry arguments maintain
186 + * key-value associations. They may be useful for example when
187 + * finding the key for the greatest value. Note that "plain" Entry
188 + * arguments can be supplied using {@code new
189 + * AbstractMap.SimpleEntry(k,v)}.
190 + *
191 + * <p>Bulk operations may complete abruptly, throwing an
192 + * exception encountered in the application of a supplied
193 + * function. Bear in mind when handling such exceptions that other
194 + * concurrently executing functions could also have thrown
195 + * exceptions, or would have done so if the first exception had
196 + * not occurred.
197 + *
198 + * <p>Speedups for parallel compared to sequential forms are common
199 + * but not guaranteed.  Parallel operations involving brief functions
200 + * on small maps may execute more slowly than sequential forms if the
201 + * underlying work to parallelize the computation is more expensive
202 + * than the computation itself.  Similarly, parallelization may not
203 + * lead to much actual parallelism if all processors are busy
204 + * performing unrelated tasks.
205 + *
206 + * <p>All arguments to all task methods must be non-null.
207 + *
208 + * <p><em>jsr166e note: During transition, this class
209 + * uses nested functional interfaces with different names but the
210 + * same forms as those expected for JDK8.</em>
211 + *
212   * <p>This class is a member of the
213   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
214   * Java Collections Framework</a>.
215   *
99 * <p><em>jsr166e note: This class is a candidate replacement for
100 * java.util.concurrent.ConcurrentHashMap.  During transition, this
101 * class declares and uses nested functional interfaces with different
102 * names but the same forms as those expected for JDK8.<em>
103 *
216   * @since 1.5
217   * @author Doug Lea
218   * @param <K> the type of keys maintained by this map
219   * @param <V> the type of mapped values
220   */
221 < public class ConcurrentHashMapV8<K, V>
222 <    implements ConcurrentMap<K, V>, Serializable {
221 > public class ConcurrentHashMapV8<K,V>
222 >    implements ConcurrentMap<K,V>, Serializable {
223      private static final long serialVersionUID = 7249069246763182397L;
224  
225      /**
226 <     * A partitionable iterator. A Spliterator can be traversed
227 <     * directly, but can also be partitioned (before traversal) by
228 <     * creating another Spliterator that covers a non-overlapping
117 <     * portion of the elements, and so may be amenable to parallel
118 <     * execution.
119 <     *
120 <     * <p> This interface exports a subset of expected JDK8
121 <     * functionality.
122 <     *
123 <     * <p>Sample usage: Here is one (of the several) ways to compute
124 <     * the sum of the values held in a map using the ForkJoin
125 <     * framework. As illustrated here, Spliterators are well suited to
126 <     * designs in which a task repeatedly splits off half its work
127 <     * into forked subtasks until small enough to process directly,
128 <     * and then joins these subtasks. Variants of this style can also
129 <     * be used in completion-based designs.
130 <     *
131 <     * <pre>
132 <     * {@code ConcurrentHashMapV8<String, Long> m = ...
133 <     * // split as if have 8 * parallelism, for load balance
134 <     * int n = m.size();
135 <     * int p = aForkJoinPool.getParallelism() * 8;
136 <     * int split = (n < p)? n : p;
137 <     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
138 <     * // ...
139 <     * static class SumValues extends RecursiveTask<Long> {
140 <     *   final Spliterator<Long> s;
141 <     *   final int split;             // split while > 1
142 <     *   final SumValues nextJoin;    // records forked subtasks to join
143 <     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
144 <     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
145 <     *   }
146 <     *   public Long compute() {
147 <     *     long sum = 0;
148 <     *     SumValues subtasks = null; // fork subtasks
149 <     *     for (int s = split >>> 1; s > 0; s >>>= 1)
150 <     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
151 <     *     while (s.hasNext())        // directly process remaining elements
152 <     *       sum += s.next();
153 <     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
154 <     *       sum += t.join();         // collect subtask results
155 <     *     return sum;
156 <     *   }
157 <     * }
158 <     * }</pre>
226 >     * An object for traversing and partitioning elements of a source.
227 >     * This interface provides a subset of the functionality of JDK8
228 >     * java.util.Spliterator.
229       */
230 <    public static interface Spliterator<T> extends Iterator<T> {
230 >    public static interface ConcurrentHashMapSpliterator<T> {
231          /**
232 <         * Returns a Spliterator covering approximately half of the
233 <         * elements, guaranteed not to overlap with those subsequently
234 <         * returned by this Spliterator.  After invoking this method,
235 <         * the current Spliterator will <em>not</em> produce any of
236 <         * the elements of the returned Spliterator, but the two
237 <         * Spliterators together will produce all of the elements that
238 <         * would have been produced by this Spliterator had this
239 <         * method not been called. The exact number of elements
240 <         * produced by the returned Spliterator is not guaranteed, and
171 <         * may be zero (i.e., with {@code hasNext()} reporting {@code
172 <         * false}) if this Spliterator cannot be further split.
173 <         *
174 <         * @return a Spliterator covering approximately half of the
175 <         * elements
176 <         * @throws IllegalStateException if this Spliterator has
177 <         * already commenced traversing elements
232 >         * If possible, returns a new spliterator covering
233 >         * approximately one half of the elements, which will not be
234 >         * covered by this spliterator. Returns null if cannot be
235 >         * split.
236 >         */
237 >        ConcurrentHashMapSpliterator<T> trySplit();
238 >        /**
239 >         * Returns an estimate of the number of elements covered by
240 >         * this Spliterator.
241           */
242 <        Spliterator<T> split();
242 >        long estimateSize();
243 >
244 >        /** Applies the action to each untraversed element */
245 >        void forEachRemaining(Action<? super T> action);
246 >        /** If an element remains, applies the action and returns true. */
247 >        boolean tryAdvance(Action<? super T> action);
248      }
249  
250 +    // Sams
251 +    /** Interface describing a void action of one argument */
252 +    public interface Action<A> { void apply(A a); }
253 +    /** Interface describing a void action of two arguments */
254 +    public interface BiAction<A,B> { void apply(A a, B b); }
255 +    /** Interface describing a function of one argument */
256 +    public interface Fun<A,T> { T apply(A a); }
257 +    /** Interface describing a function of two arguments */
258 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
259 +    /** Interface describing a function mapping its argument to a double */
260 +    public interface ObjectToDouble<A> { double apply(A a); }
261 +    /** Interface describing a function mapping its argument to a long */
262 +    public interface ObjectToLong<A> { long apply(A a); }
263 +    /** Interface describing a function mapping its argument to an int */
264 +    public interface ObjectToInt<A> {int apply(A a); }
265 +    /** Interface describing a function mapping two arguments to a double */
266 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
267 +    /** Interface describing a function mapping two arguments to a long */
268 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
269 +    /** Interface describing a function mapping two arguments to an int */
270 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
271 +    /** Interface describing a function mapping two doubles to a double */
272 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
273 +    /** Interface describing a function mapping two longs to a long */
274 +    public interface LongByLongToLong { long apply(long a, long b); }
275 +    /** Interface describing a function mapping two ints to an int */
276 +    public interface IntByIntToInt { int apply(int a, int b); }
277 +
278      /*
279       * Overview:
280       *
# Line 189 | Line 285 | public class ConcurrentHashMapV8<K, V>
285       * the same or better than java.util.HashMap, and to support high
286       * initial insertion rates on an empty table by many threads.
287       *
288 <     * Each key-value mapping is held in a Node.  Because Node fields
289 <     * can contain special values, they are defined using plain Object
290 <     * types. Similarly in turn, all internal methods that use them
291 <     * work off Object types. And similarly, so do the internal
292 <     * methods of auxiliary iterator and view classes.  All public
293 <     * generic typed methods relay in/out of these internal methods,
294 <     * supplying null-checks and casts as needed. This also allows
295 <     * many of the public methods to be factored into a smaller number
296 <     * 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.
288 >     * This map usually acts as a binned (bucketed) hash table.  Each
289 >     * key-value mapping is held in a Node.  Most nodes are instances
290 >     * of the basic Node class with hash, key, value, and next
291 >     * fields. However, various subclasses exist: TreeNodes are
292 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
293 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
294 >     * of bins during resizing. ReservationNodes are used as
295 >     * placeholders while establishing values in computeIfAbsent and
296 >     * related methods.  The types TreeBin, ForwardingNode, and
297 >     * ReservationNode do not hold normal user keys, values, or
298 >     * hashes, and are readily distinguishable during search etc
299 >     * because they have negative hash fields and null key and value
300 >     * fields. (These special nodes are either uncommon or transient,
301 >     * so the impact of carrying around some unused fields is
302 >     * insignificant.)
303       *
304       * The table is lazily initialized to a power-of-two size upon the
305       * first insertion.  Each bin in the table normally contains a
# Line 208 | Line 307 | public class ConcurrentHashMapV8<K, V>
307       * Table accesses require volatile/atomic reads, writes, and
308       * CASes.  Because there is no other way to arrange this without
309       * adding further indirections, we use intrinsics
310 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
311 <     * are always accurately traversable under volatile reads, so long
312 <     * as lookups check hash code and non-nullness of value before
313 <     * checking key equality.
314 <     *
315 <     * We use the top two bits of Node hash fields for control
217 <     * purposes -- they are available anyway because of addressing
218 <     * constraints.  As explained further below, these top bits are
219 <     * used as follows:
220 <     *  00 - Normal
221 <     *  01 - Locked
222 <     *  11 - Locked and may have a thread waiting for lock
223 <     *  10 - Node is a forwarding node
224 <     *
225 <     * The lower 30 bits of each Node's hash field contain a
226 <     * transformation of the key's hash code, except for forwarding
227 <     * nodes, for which the lower bits are zero (and so always have
228 <     * hash field == MOVED).
310 >     * (sun.misc.Unsafe) operations.
311 >     *
312 >     * We use the top (sign) bit of Node hash fields for control
313 >     * purposes -- it is available anyway because of addressing
314 >     * constraints.  Nodes with negative hash fields are specially
315 >     * handled or ignored in map methods.
316       *
317       * Insertion (via put or its variants) of the first node in an
318       * empty bin is performed by just CASing it to the bin.  This is
# Line 234 | Line 321 | public class ConcurrentHashMapV8<K, V>
321       * delete, and replace) require locks.  We do not want to waste
322       * the space required to associate a distinct lock object with
323       * each bin, so instead use the first node of a bin list itself as
324 <     * a lock. Blocking support for these locks relies on the builtin
325 <     * "synchronized" monitors.  However, we also need a tryLock
239 <     * construction, so we overlay these by using bits of the Node
240 <     * hash field for lock control (see above), and so normally use
241 <     * builtin monitors only for blocking and signalling using
242 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
324 >     * a lock. Locking support for these locks relies on builtin
325 >     * "synchronized" monitors.
326       *
327       * Using the first node of a list as a lock does not by itself
328       * suffice though: When a node is locked, any update must first
329       * validate that it is still the first node after locking it, and
330       * retry if not. Because new nodes are always appended to lists,
331       * once a node is first in a bin, it remains first until deleted
332 <     * or the bin becomes invalidated (upon resizing).  However,
250 <     * operations that only conditionally update may inspect nodes
251 <     * until the point of update. This is a converse of sorts to the
252 <     * lazy locking technique described by Herlihy & Shavit.
332 >     * or the bin becomes invalidated (upon resizing).
333       *
334       * The main disadvantage of per-bin locks is that other update
335       * operations on other nodes in a bin list protected by the same
# Line 282 | Line 362 | public class ConcurrentHashMapV8<K, V>
362       * sometimes deviate significantly from uniform randomness.  This
363       * includes the case when N > (1<<30), so some keys MUST collide.
364       * Similarly for dumb or hostile usages in which multiple keys are
365 <     * designed to have identical hash codes. Also, although we guard
366 <     * against the worst effects of this (see method spread), sets of
367 <     * hashes may differ only in bits that do not impact their bin
368 <     * index for a given power-of-two mask.  So we use a secondary
369 <     * strategy that applies when the number of nodes in a bin exceeds
370 <     * a threshold, and at least one of the keys implements
291 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
292 <     * (a specialized form of red-black trees), bounding search time
293 <     * to O(log N).  Each search step in a TreeBin is around twice as
365 >     * designed to have identical hash codes or ones that differs only
366 >     * in masked-out high bits. So we use a secondary strategy that
367 >     * applies when the number of nodes in a bin exceeds a
368 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
369 >     * specialized form of red-black trees), bounding search time to
370 >     * O(log N).  Each search step in a TreeBin is at least twice as
371       * slow as in a regular list, but given that N cannot exceed
372       * (1<<64) (before running out of addresses) this bounds search
373       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 301 | Line 378 | public class ConcurrentHashMapV8<K, V>
378       * iterators in the same way.
379       *
380       * The table is resized when occupancy exceeds a percentage
381 <     * threshold (nominally, 0.75, but see below).  Only a single
382 <     * thread performs the resize (using field "sizeCtl", to arrange
383 <     * exclusion), but the table otherwise remains usable for reads
384 <     * and updates. Resizing proceeds by transferring bins, one by
385 <     * one, from the table to the next table.  Because we are using
386 <     * power-of-two expansion, the elements from each bin must either
387 <     * stay at same index, or move with a power of two offset. We
388 <     * eliminate unnecessary node creation by catching cases where old
389 <     * nodes can be reused because their next fields won't change.  On
390 <     * average, only about one-sixth of them need cloning when a table
391 <     * doubles. The nodes they replace will be garbage collectable as
392 <     * soon as they are no longer referenced by any reader thread that
393 <     * may be in the midst of concurrently traversing table.  Upon
394 <     * transfer, the old table bin contains only a special forwarding
395 <     * node (with hash field "MOVED") that contains the next table as
396 <     * its key. On encountering a forwarding node, access and update
397 <     * operations restart, using the new table.
398 <     *
399 <     * Each bin transfer requires its bin lock. However, unlike other
400 <     * cases, a transfer can skip a bin if it fails to acquire its
401 <     * lock, and revisit it later (unless it is a TreeBin). Method
402 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
403 <     * have been skipped because of failure to acquire a lock, and
404 <     * blocks only if none are available (i.e., only very rarely).
405 <     * The transfer operation must also ensure that all accessible
406 <     * bins in both the old and new table are usable by any traversal.
407 <     * When there are no lock acquisition failures, this is arranged
408 <     * simply by proceeding from the last bin (table.length - 1) up
409 <     * towards the first.  Upon seeing a forwarding node, traversals
410 <     * (see class Iter) arrange to move to the new table
411 <     * without revisiting nodes.  However, when any node is skipped
412 <     * during a transfer, all earlier table bins may have become
413 <     * visible, so are initialized with a reverse-forwarding node back
414 <     * to the old table until the new ones are established. (This
415 <     * sometimes requires transiently locking a forwarding node, which
416 <     * is possible under the above encoding.) These more expensive
417 <     * mechanics trigger only when necessary.
381 >     * threshold (nominally, 0.75, but see below).  Any thread
382 >     * noticing an overfull bin may assist in resizing after the
383 >     * initiating thread allocates and sets up the replacement
384 >     * array. However, rather than stalling, these other threads may
385 >     * proceed with insertions etc.  The use of TreeBins shields us
386 >     * from the worst case effects of overfilling while resizes are in
387 >     * progress.  Resizing proceeds by transferring bins, one by one,
388 >     * from the table to the next table. To enable concurrency, the
389 >     * next table must be (incrementally) prefilled with place-holders
390 >     * serving as reverse forwarders to the old table.  Because we are
391 >     * using power-of-two expansion, the elements from each bin must
392 >     * either stay at same index, or move with a power of two
393 >     * offset. We eliminate unnecessary node creation by catching
394 >     * cases where old nodes can be reused because their next fields
395 >     * won't change.  On average, only about one-sixth of them need
396 >     * cloning when a table doubles. The nodes they replace will be
397 >     * garbage collectable as soon as they are no longer referenced by
398 >     * any reader thread that may be in the midst of concurrently
399 >     * traversing table.  Upon transfer, the old table bin contains
400 >     * only a special forwarding node (with hash field "MOVED") that
401 >     * contains the next table as its key. On encountering a
402 >     * forwarding node, access and update operations restart, using
403 >     * the new table.
404 >     *
405 >     * Each bin transfer requires its bin lock, which can stall
406 >     * waiting for locks while resizing. However, because other
407 >     * threads can join in and help resize rather than contend for
408 >     * locks, average aggregate waits become shorter as resizing
409 >     * progresses.  The transfer operation must also ensure that all
410 >     * accessible bins in both the old and new table are usable by any
411 >     * traversal.  This is arranged by proceeding from the last bin
412 >     * (table.length - 1) up towards the first.  Upon seeing a
413 >     * forwarding node, traversals (see class Traverser) arrange to
414 >     * move to the new table without revisiting nodes.  However, to
415 >     * ensure that no intervening nodes are skipped, bin splitting can
416 >     * only begin after the associated reverse-forwarders are in
417 >     * place.
418       *
419       * The traversal scheme also applies to partial traversals of
420       * ranges of bins (via an alternate Traverser constructor)
# Line 352 | Line 429 | public class ConcurrentHashMapV8<K, V>
429       * These cases attempt to override the initial capacity settings,
430       * but harmlessly fail to take effect in cases of races.
431       *
432 <     * The element count is maintained using a LongAdder, which avoids
433 <     * contention on updates but can encounter cache thrashing if read
434 <     * too frequently during concurrent access. To avoid reading so
435 <     * often, resizing is attempted either when a bin lock is
436 <     * contended, or upon adding to a bin already holding two or more
437 <     * nodes (checked before adding in the xIfAbsent methods, after
438 <     * adding in others). Under uniform hash distributions, the
439 <     * probability of this occurring at threshold is around 13%,
440 <     * meaning that only about 1 in 8 puts check threshold (and after
441 <     * resizing, many fewer do so). But this approximation has high
442 <     * variance for small table sizes, so we check on any collision
443 <     * for sizes <= 64. The bulk putAll operation further reduces
444 <     * contention by only committing count updates upon these size
445 <     * checks.
432 >     * The element count is maintained using a specialization of
433 >     * LongAdder. We need to incorporate a specialization rather than
434 >     * just use a LongAdder in order to access implicit
435 >     * contention-sensing that leads to creation of multiple
436 >     * CounterCells.  The counter mechanics avoid contention on
437 >     * updates but can encounter cache thrashing if read too
438 >     * frequently during concurrent access. To avoid reading so often,
439 >     * resizing under contention is attempted only upon adding to a
440 >     * bin already holding two or more nodes. Under uniform hash
441 >     * distributions, the probability of this occurring at threshold
442 >     * is around 13%, meaning that only about 1 in 8 puts check
443 >     * threshold (and after resizing, many fewer do so).
444 >     *
445 >     * TreeBins use a special form of comparison for search and
446 >     * related operations (which is the main reason we cannot use
447 >     * existing collections such as TreeMaps). TreeBins contain
448 >     * Comparable elements, but may contain others, as well as
449 >     * elements that are Comparable but not necessarily Comparable
450 >     * for the same T, so we cannot invoke compareTo among them. To
451 >     * handle this, the tree is ordered primarily by hash value, then
452 >     * by Comparable.compareTo order if applicable.  On lookup at a
453 >     * node, if elements are not comparable or compare as 0 then both
454 >     * left and right children may need to be searched in the case of
455 >     * tied hash values. (This corresponds to the full list search
456 >     * that would be necessary if all elements were non-Comparable and
457 >     * had tied hashes.)  The red-black balancing code is updated from
458 >     * pre-jdk-collections
459 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
460 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
461 >     * Algorithms" (CLR).
462 >     *
463 >     * TreeBins also require an additional locking mechanism.  While
464 >     * list traversal is always possible by readers even during
465 >     * updates, tree traversal is not, mainly because of tree-rotations
466 >     * that may change the root node and/or its linkages.  TreeBins
467 >     * include a simple read-write lock mechanism parasitic on the
468 >     * main bin-synchronization strategy: Structural adjustments
469 >     * associated with an insertion or removal are already bin-locked
470 >     * (and so cannot conflict with other writers) but must wait for
471 >     * ongoing readers to finish. Since there can be only one such
472 >     * waiter, we use a simple scheme using a single "waiter" field to
473 >     * block writers.  However, readers need never block.  If the root
474 >     * lock is held, they proceed along the slow traversal path (via
475 >     * next-pointers) until the lock becomes available or the list is
476 >     * exhausted, whichever comes first. These cases are not fast, but
477 >     * maximize aggregate expected throughput.
478       *
479       * Maintaining API and serialization compatibility with previous
480       * versions of this class introduces several oddities. Mainly: We
# Line 375 | Line 484 | public class ConcurrentHashMapV8<K, V>
484       * time that we can guarantee to honor it.) We also declare an
485       * unused "Segment" class that is instantiated in minimal form
486       * only when serializing.
487 +     *
488 +     * This file is organized to make things a little easier to follow
489 +     * while reading than they might otherwise: First the main static
490 +     * declarations and utilities, then fields, then main public
491 +     * methods (with a few factorings of multiple public methods into
492 +     * internal ones), then sizing methods, trees, traversers, and
493 +     * bulk operations.
494       */
495  
496      /* ---------------- Constants -------------- */
# Line 416 | Line 532 | public class ConcurrentHashMapV8<K, V>
532      private static final float LOAD_FACTOR = 0.75f;
533  
534      /**
419     * The buffer size for skipped bins during transfers. The
420     * value is arbitrary but should be large enough to avoid
421     * most locking stalls during resizes.
422     */
423    private static final int TRANSFER_BUFFER_SIZE = 32;
424
425    /**
535       * The bin count threshold for using a tree rather than list for a
536 <     * bin.  The value reflects the approximate break-even point for
537 <     * using tree-based operations.
536 >     * bin.  Bins are converted to trees when adding an element to a
537 >     * bin with at least this many nodes. The value must be greater
538 >     * than 2, and should be at least 8 to mesh with assumptions in
539 >     * tree removal about conversion back to plain bins upon
540 >     * shrinkage.
541       */
542 <    private static final int TREE_THRESHOLD = 8;
431 <
432 <    /*
433 <     * Encodings for special uses of Node hash fields. See above for
434 <     * explanation.
435 <     */
436 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
437 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
438 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
439 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
440 <
441 <    /* ---------------- Fields -------------- */
542 >    static final int TREEIFY_THRESHOLD = 8;
543  
544      /**
545 <     * The array of bins. Lazily initialized upon first insertion.
546 <     * Size is always a power of two. Accessed directly by iterators.
545 >     * The bin count threshold for untreeifying a (split) bin during a
546 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
547 >     * most 6 to mesh with shrinkage detection under removal.
548       */
549 <    transient volatile Node[] table;
549 >    static final int UNTREEIFY_THRESHOLD = 6;
550  
551      /**
552 <     * The counter maintaining number of elements.
552 >     * The smallest table capacity for which bins may be treeified.
553 >     * (Otherwise the table is resized if too many nodes in a bin.)
554 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
555 >     * conflicts between resizing and treeification thresholds.
556       */
557 <    private transient final LongAdder counter;
557 >    static final int MIN_TREEIFY_CAPACITY = 64;
558  
559      /**
560 <     * Table initialization and resizing control.  When negative, the
561 <     * table is being initialized or resized. Otherwise, when table is
562 <     * null, holds the initial table size to use upon creation, or 0
563 <     * for default. After initialization, holds the next element count
564 <     * value upon which to resize the table.
560 >     * Minimum number of rebinnings per transfer step. Ranges are
561 >     * subdivided to allow multiple resizer threads.  This value
562 >     * serves as a lower bound to avoid resizers encountering
563 >     * excessive memory contention.  The value should be at least
564 >     * DEFAULT_CAPACITY.
565       */
566 <    private transient volatile int sizeCtl;
462 <
463 <    // views
464 <    private transient KeySet<K,V> keySet;
465 <    private transient Values<K,V> values;
466 <    private transient EntrySet<K,V> entrySet;
467 <
468 <    /** For serialization compatibility. Null unless serialized; see below */
469 <    private Segment<K,V>[] segments;
470 <
471 <    /* ---------------- Table element access -------------- */
566 >    private static final int MIN_TRANSFER_STRIDE = 16;
567  
568      /*
569 <     * Volatile access methods are used for table elements as well as
475 <     * elements of in-progress next table while resizing.  Uses are
476 <     * null checked by callers, and implicitly bounds-checked, relying
477 <     * on the invariants that tab arrays have non-zero size, and all
478 <     * indices are masked with (tab.length - 1) which is never
479 <     * negative and always less than length. Note that, to be correct
480 <     * wrt arbitrary concurrency errors by users, bounds checks must
481 <     * operate on local variables, which accounts for some odd-looking
482 <     * inline assignments below.
569 >     * Encodings for Node hash fields. See above for explanation.
570       */
571 <
572 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
573 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
574 <    }
575 <
576 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
577 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
578 <    }
579 <
580 <    private static final void setTabAt(Node[] tab, int i, Node v) {
581 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
582 <    }
571 >    static final int MOVED     = -1; // hash for forwarding nodes
572 >    static final int TREEBIN   = -2; // hash for roots of trees
573 >    static final int RESERVED  = -3; // hash for transient reservations
574 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
575 >
576 >    /** Number of CPUS, to place bounds on some sizings */
577 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
578 >
579 >    /** For serialization compatibility. */
580 >    private static final ObjectStreamField[] serialPersistentFields = {
581 >        new ObjectStreamField("segments", Segment[].class),
582 >        new ObjectStreamField("segmentMask", Integer.TYPE),
583 >        new ObjectStreamField("segmentShift", Integer.TYPE)
584 >    };
585  
586      /* ---------------- Nodes -------------- */
587  
588      /**
589 <     * Key-value entry. Note that this is never exported out as a
590 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
591 <     * field of MOVED are special, and do not contain user keys or
592 <     * values.  Otherwise, keys are never null, and null val fields
593 <     * indicate that a node is in the process of being deleted or
594 <     * created. For purposes of read-only access, a key may be read
595 <     * before a val, but can only be used after checking val to be
596 <     * non-null.
597 <     */
598 <    static class Node {
599 <        volatile int hash;
600 <        final Object key;
512 <        volatile Object val;
513 <        volatile Node next;
589 >     * Key-value entry.  This class is never exported out as a
590 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
591 >     * MapEntry below), but can be used for read-only traversals used
592 >     * in bulk tasks.  Subclasses of Node with a negative hash field
593 >     * are special, and contain null keys and values (but are never
594 >     * exported).  Otherwise, keys and vals are never null.
595 >     */
596 >    static class Node<K,V> implements Map.Entry<K,V> {
597 >        final int hash;
598 >        final K key;
599 >        volatile V val;
600 >        volatile Node<K,V> next;
601  
602 <        Node(int hash, Object key, Object val, Node next) {
602 >        Node(int hash, K key, V val, Node<K,V> next) {
603              this.hash = hash;
604              this.key = key;
605              this.val = val;
606              this.next = next;
607          }
608  
609 <        /** CompareAndSet the hash field */
610 <        final boolean casHash(int cmp, int val) {
611 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
612 <        }
613 <
614 <        /** The number of spins before blocking for a lock */
528 <        static final int MAX_SPINS =
529 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
530 <
531 <        /**
532 <         * Spins a while if LOCKED bit set and this node is the first
533 <         * of its bin, and then sets WAITING bits on hash field and
534 <         * blocks (once) if they are still set.  It is OK for this
535 <         * method to return even if lock is not available upon exit,
536 <         * which enables these simple single-wait mechanics.
537 <         *
538 <         * The corresponding signalling operation is performed within
539 <         * callers: Upon detecting that WAITING has been set when
540 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
541 <         * state), unlockers acquire the sync lock and perform a
542 <         * notifyAll.
543 <         *
544 <         * The initial sanity check on tab and bounds is not currently
545 <         * necessary in the only usages of this method, but enables
546 <         * use in other future contexts.
547 <         */
548 <        final void tryAwaitLock(Node[] tab, int i) {
549 <            if (tab != null && i >= 0 && i < tab.length) { // sanity check
550 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
551 <                int spins = MAX_SPINS, h;
552 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
553 <                    if (spins >= 0) {
554 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
555 <                        if (r >= 0 && --spins == 0)
556 <                            Thread.yield();  // yield before block
557 <                    }
558 <                    else if (casHash(h, h | WAITING)) {
559 <                        synchronized (this) {
560 <                            if (tabAt(tab, i) == this &&
561 <                                (hash & WAITING) == WAITING) {
562 <                                try {
563 <                                    wait();
564 <                                } catch (InterruptedException ie) {
565 <                                    Thread.currentThread().interrupt();
566 <                                }
567 <                            }
568 <                            else
569 <                                notifyAll(); // possibly won race vs signaller
570 <                        }
571 <                        break;
572 <                    }
573 <                }
574 <            }
575 <        }
576 <
577 <        // Unsafe mechanics for casHash
578 <        private static final sun.misc.Unsafe UNSAFE;
579 <        private static final long hashOffset;
580 <
581 <        static {
582 <            try {
583 <                UNSAFE = getUnsafe();
584 <                Class<?> k = Node.class;
585 <                hashOffset = UNSAFE.objectFieldOffset
586 <                    (k.getDeclaredField("hash"));
587 <            } catch (Exception e) {
588 <                throw new Error(e);
589 <            }
590 <        }
591 <    }
592 <
593 <    /* ---------------- TreeBins -------------- */
594 <
595 <    /**
596 <     * Nodes for use in TreeBins
597 <     */
598 <    static final class TreeNode extends Node {
599 <        TreeNode parent;  // red-black tree links
600 <        TreeNode left;
601 <        TreeNode right;
602 <        TreeNode prev;    // needed to unlink next upon deletion
603 <        boolean red;
604 <
605 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
606 <            super(hash, key, val, next);
607 <            this.parent = parent;
608 <        }
609 <    }
610 <
611 <    /**
612 <     * A specialized form of red-black tree for use in bins
613 <     * whose size exceeds a threshold.
614 <     *
615 <     * TreeBins use a special form of comparison for search and
616 <     * related operations (which is the main reason we cannot use
617 <     * existing collections such as TreeMaps). TreeBins contain
618 <     * Comparable elements, but may contain others, as well as
619 <     * elements that are Comparable but not necessarily Comparable<T>
620 <     * for the same T, so we cannot invoke compareTo among them. To
621 <     * handle this, the tree is ordered primarily by hash value, then
622 <     * by getClass().getName() order, and then by Comparator order
623 <     * among elements of the same class.  On lookup at a node, if
624 <     * elements are not comparable or compare as 0, both left and
625 <     * right children may need to be searched in the case of tied hash
626 <     * values. (This corresponds to the full list search that would be
627 <     * necessary if all elements were non-Comparable and had tied
628 <     * hashes.)  The red-black balancing code is updated from
629 <     * pre-jdk-collections
630 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
631 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
632 <     * Algorithms" (CLR).
633 <     *
634 <     * TreeBins also maintain a separate locking discipline than
635 <     * regular bins. Because they are forwarded via special MOVED
636 <     * nodes at bin heads (which can never change once established),
637 <     * we cannot use those nodes as locks. Instead, TreeBin
638 <     * extends AbstractQueuedSynchronizer to support a simple form of
639 <     * read-write lock. For update operations and table validation,
640 <     * the exclusive form of lock behaves in the same way as bin-head
641 <     * locks. However, lookups use shared read-lock mechanics to allow
642 <     * multiple readers in the absence of writers.  Additionally,
643 <     * these lookups do not ever block: While the lock is not
644 <     * available, they proceed along the slow traversal path (via
645 <     * next-pointers) until the lock becomes available or the list is
646 <     * exhausted, whichever comes first. (These cases are not fast,
647 <     * but maximize aggregate expected throughput.)  The AQS mechanics
648 <     * for doing this are straightforward.  The lock state is held as
649 <     * AQS getState().  Read counts are negative; the write count (1)
650 <     * is positive.  There are no signalling preferences among readers
651 <     * and writers. Since we don't need to export full Lock API, we
652 <     * just override the minimal AQS methods and use them directly.
653 <     */
654 <    static final class TreeBin extends AbstractQueuedSynchronizer {
655 <        private static final long serialVersionUID = 2249069246763182397L;
656 <        transient TreeNode root;  // root of tree
657 <        transient TreeNode first; // head of next-pointer list
658 <
659 <        /* AQS overrides */
660 <        public final boolean isHeldExclusively() { return getState() > 0; }
661 <        public final boolean tryAcquire(int ignore) {
662 <            if (compareAndSetState(0, 1)) {
663 <                setExclusiveOwnerThread(Thread.currentThread());
664 <                return true;
665 <            }
666 <            return false;
667 <        }
668 <        public final boolean tryRelease(int ignore) {
669 <            setExclusiveOwnerThread(null);
670 <            setState(0);
671 <            return true;
672 <        }
673 <        public final int tryAcquireShared(int ignore) {
674 <            for (int c;;) {
675 <                if ((c = getState()) > 0)
676 <                    return -1;
677 <                if (compareAndSetState(c, c -1))
678 <                    return 1;
679 <            }
680 <        }
681 <        public final boolean tryReleaseShared(int ignore) {
682 <            int c;
683 <            do {} while (!compareAndSetState(c = getState(), c + 1));
684 <            return c == -1;
685 <        }
686 <
687 <        /** From CLR */
688 <        private void rotateLeft(TreeNode p) {
689 <            if (p != null) {
690 <                TreeNode r = p.right, pp, rl;
691 <                if ((rl = p.right = r.left) != null)
692 <                    rl.parent = p;
693 <                if ((pp = r.parent = p.parent) == null)
694 <                    root = r;
695 <                else if (pp.left == p)
696 <                    pp.left = r;
697 <                else
698 <                    pp.right = r;
699 <                r.left = p;
700 <                p.parent = r;
701 <            }
702 <        }
703 <
704 <        /** From CLR */
705 <        private void rotateRight(TreeNode p) {
706 <            if (p != null) {
707 <                TreeNode l = p.left, pp, lr;
708 <                if ((lr = p.left = l.right) != null)
709 <                    lr.parent = p;
710 <                if ((pp = l.parent = p.parent) == null)
711 <                    root = l;
712 <                else if (pp.right == p)
713 <                    pp.right = l;
714 <                else
715 <                    pp.left = l;
716 <                l.right = p;
717 <                p.parent = l;
718 <            }
719 <        }
720 <
721 <        /**
722 <         * Returns the TreeNode (or null if not found) for the given key
723 <         * starting at given root.
724 <         */
725 <        @SuppressWarnings("unchecked") final TreeNode getTreeNode
726 <            (int h, Object k, TreeNode p) {
727 <            Class<?> c = k.getClass();
728 <            while (p != null) {
729 <                int dir, ph;  Object pk; Class<?> pc;
730 <                if ((ph = p.hash) == h) {
731 <                    if ((pk = p.key) == k || k.equals(pk))
732 <                        return p;
733 <                    if (c != (pc = pk.getClass()) ||
734 <                        !(k instanceof Comparable) ||
735 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
736 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
737 <                        TreeNode r = null, s = null, pl, pr;
738 <                        if (dir >= 0) {
739 <                            if ((pl = p.left) != null && h <= pl.hash)
740 <                                s = pl;
741 <                        }
742 <                        else if ((pr = p.right) != null && h >= pr.hash)
743 <                            s = pr;
744 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
745 <                            return r;
746 <                    }
747 <                }
748 <                else
749 <                    dir = (h < ph) ? -1 : 1;
750 <                p = (dir > 0) ? p.right : p.left;
751 <            }
752 <            return null;
609 >        public final K getKey()       { return key; }
610 >        public final V getValue()     { return val; }
611 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
612 >        public final String toString(){ return key + "=" + val; }
613 >        public final V setValue(V value) {
614 >            throw new UnsupportedOperationException();
615          }
616  
617 <        /**
618 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
619 <         * read-lock to call getTreeNode, but during failure to get
620 <         * lock, searches along next links.
621 <         */
622 <        final Object getValue(int h, Object k) {
623 <            Node r = null;
762 <            int c = getState(); // Must read lock state first
763 <            for (Node e = first; e != null; e = e.next) {
764 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
765 <                    try {
766 <                        r = getTreeNode(h, k, root);
767 <                    } finally {
768 <                        releaseShared(0);
769 <                    }
770 <                    break;
771 <                }
772 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
773 <                    r = e;
774 <                    break;
775 <                }
776 <                else
777 <                    c = getState();
778 <            }
779 <            return r == null ? null : r.val;
617 >        public final boolean equals(Object o) {
618 >            Object k, v, u; Map.Entry<?,?> e;
619 >            return ((o instanceof Map.Entry) &&
620 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
621 >                    (v = e.getValue()) != null &&
622 >                    (k == key || k.equals(key)) &&
623 >                    (v == (u = val) || v.equals(u)));
624          }
625  
626          /**
627 <         * Finds or adds a node.
784 <         * @return null if added
627 >         * Virtualized support for map.get(); overridden in subclasses.
628           */
629 <        @SuppressWarnings("unchecked") final TreeNode putTreeNode
630 <            (int h, Object k, Object v) {
631 <            Class<?> c = k.getClass();
632 <            TreeNode pp = root, p = null;
633 <            int dir = 0;
634 <            while (pp != null) { // find existing node or leaf to insert at
635 <                int ph;  Object pk; Class<?> pc;
636 <                p = pp;
637 <                if ((ph = p.hash) == h) {
795 <                    if ((pk = p.key) == k || k.equals(pk))
796 <                        return p;
797 <                    if (c != (pc = pk.getClass()) ||
798 <                        !(k instanceof Comparable) ||
799 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
800 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
801 <                        TreeNode r = null, s = null, pl, pr;
802 <                        if (dir >= 0) {
803 <                            if ((pl = p.left) != null && h <= pl.hash)
804 <                                s = pl;
805 <                        }
806 <                        else if ((pr = p.right) != null && h >= pr.hash)
807 <                            s = pr;
808 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
809 <                            return r;
810 <                    }
811 <                }
812 <                else
813 <                    dir = (h < ph) ? -1 : 1;
814 <                pp = (dir > 0) ? p.right : p.left;
815 <            }
816 <
817 <            TreeNode f = first;
818 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
819 <            if (p == null)
820 <                root = x;
821 <            else { // attach and rebalance; adapted from CLR
822 <                TreeNode xp, xpp;
823 <                if (f != null)
824 <                    f.prev = x;
825 <                if (dir <= 0)
826 <                    p.left = x;
827 <                else
828 <                    p.right = x;
829 <                x.red = true;
830 <                while (x != null && (xp = x.parent) != null && xp.red &&
831 <                       (xpp = xp.parent) != null) {
832 <                    TreeNode xppl = xpp.left;
833 <                    if (xp == xppl) {
834 <                        TreeNode y = xpp.right;
835 <                        if (y != null && y.red) {
836 <                            y.red = false;
837 <                            xp.red = false;
838 <                            xpp.red = true;
839 <                            x = xpp;
840 <                        }
841 <                        else {
842 <                            if (x == xp.right) {
843 <                                rotateLeft(x = xp);
844 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
845 <                            }
846 <                            if (xp != null) {
847 <                                xp.red = false;
848 <                                if (xpp != null) {
849 <                                    xpp.red = true;
850 <                                    rotateRight(xpp);
851 <                                }
852 <                            }
853 <                        }
854 <                    }
855 <                    else {
856 <                        TreeNode y = xppl;
857 <                        if (y != null && y.red) {
858 <                            y.red = false;
859 <                            xp.red = false;
860 <                            xpp.red = true;
861 <                            x = xpp;
862 <                        }
863 <                        else {
864 <                            if (x == xp.left) {
865 <                                rotateRight(x = xp);
866 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
867 <                            }
868 <                            if (xp != null) {
869 <                                xp.red = false;
870 <                                if (xpp != null) {
871 <                                    xpp.red = true;
872 <                                    rotateLeft(xpp);
873 <                                }
874 <                            }
875 <                        }
876 <                    }
877 <                }
878 <                TreeNode r = root;
879 <                if (r != null && r.red)
880 <                    r.red = false;
629 >        Node<K,V> find(int h, Object k) {
630 >            Node<K,V> e = this;
631 >            if (k != null) {
632 >                do {
633 >                    K ek;
634 >                    if (e.hash == h &&
635 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
636 >                        return e;
637 >                } while ((e = e.next) != null);
638              }
639              return null;
640          }
884
885        /**
886         * Removes the given node, that must be present before this
887         * call.  This is messier than typical red-black deletion code
888         * because we cannot swap the contents of an interior node
889         * with a leaf successor that is pinned by "next" pointers
890         * that are accessible independently of lock. So instead we
891         * swap the tree linkages.
892         */
893        final void deleteTreeNode(TreeNode p) {
894            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
895            TreeNode pred = p.prev;
896            if (pred == null)
897                first = next;
898            else
899                pred.next = next;
900            if (next != null)
901                next.prev = pred;
902            TreeNode replacement;
903            TreeNode pl = p.left;
904            TreeNode pr = p.right;
905            if (pl != null && pr != null) {
906                TreeNode s = pr, sl;
907                while ((sl = s.left) != null) // find successor
908                    s = sl;
909                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
910                TreeNode sr = s.right;
911                TreeNode pp = p.parent;
912                if (s == pr) { // p was s's direct parent
913                    p.parent = s;
914                    s.right = p;
915                }
916                else {
917                    TreeNode sp = s.parent;
918                    if ((p.parent = sp) != null) {
919                        if (s == sp.left)
920                            sp.left = p;
921                        else
922                            sp.right = p;
923                    }
924                    if ((s.right = pr) != null)
925                        pr.parent = s;
926                }
927                p.left = null;
928                if ((p.right = sr) != null)
929                    sr.parent = p;
930                if ((s.left = pl) != null)
931                    pl.parent = s;
932                if ((s.parent = pp) == null)
933                    root = s;
934                else if (p == pp.left)
935                    pp.left = s;
936                else
937                    pp.right = s;
938                replacement = sr;
939            }
940            else
941                replacement = (pl != null) ? pl : pr;
942            TreeNode pp = p.parent;
943            if (replacement == null) {
944                if (pp == null) {
945                    root = null;
946                    return;
947                }
948                replacement = p;
949            }
950            else {
951                replacement.parent = pp;
952                if (pp == null)
953                    root = replacement;
954                else if (p == pp.left)
955                    pp.left = replacement;
956                else
957                    pp.right = replacement;
958                p.left = p.right = p.parent = null;
959            }
960            if (!p.red) { // rebalance, from CLR
961                TreeNode x = replacement;
962                while (x != null) {
963                    TreeNode xp, xpl;
964                    if (x.red || (xp = x.parent) == null) {
965                        x.red = false;
966                        break;
967                    }
968                    if (x == (xpl = xp.left)) {
969                        TreeNode sib = xp.right;
970                        if (sib != null && sib.red) {
971                            sib.red = false;
972                            xp.red = true;
973                            rotateLeft(xp);
974                            sib = (xp = x.parent) == null ? null : xp.right;
975                        }
976                        if (sib == null)
977                            x = xp;
978                        else {
979                            TreeNode sl = sib.left, sr = sib.right;
980                            if ((sr == null || !sr.red) &&
981                                (sl == null || !sl.red)) {
982                                sib.red = true;
983                                x = xp;
984                            }
985                            else {
986                                if (sr == null || !sr.red) {
987                                    if (sl != null)
988                                        sl.red = false;
989                                    sib.red = true;
990                                    rotateRight(sib);
991                                    sib = (xp = x.parent) == null ? null : xp.right;
992                                }
993                                if (sib != null) {
994                                    sib.red = (xp == null) ? false : xp.red;
995                                    if ((sr = sib.right) != null)
996                                        sr.red = false;
997                                }
998                                if (xp != null) {
999                                    xp.red = false;
1000                                    rotateLeft(xp);
1001                                }
1002                                x = root;
1003                            }
1004                        }
1005                    }
1006                    else { // symmetric
1007                        TreeNode sib = xpl;
1008                        if (sib != null && sib.red) {
1009                            sib.red = false;
1010                            xp.red = true;
1011                            rotateRight(xp);
1012                            sib = (xp = x.parent) == null ? null : xp.left;
1013                        }
1014                        if (sib == null)
1015                            x = xp;
1016                        else {
1017                            TreeNode sl = sib.left, sr = sib.right;
1018                            if ((sl == null || !sl.red) &&
1019                                (sr == null || !sr.red)) {
1020                                sib.red = true;
1021                                x = xp;
1022                            }
1023                            else {
1024                                if (sl == null || !sl.red) {
1025                                    if (sr != null)
1026                                        sr.red = false;
1027                                    sib.red = true;
1028                                    rotateLeft(sib);
1029                                    sib = (xp = x.parent) == null ? null : xp.left;
1030                                }
1031                                if (sib != null) {
1032                                    sib.red = (xp == null) ? false : xp.red;
1033                                    if ((sl = sib.left) != null)
1034                                        sl.red = false;
1035                                }
1036                                if (xp != null) {
1037                                    xp.red = false;
1038                                    rotateRight(xp);
1039                                }
1040                                x = root;
1041                            }
1042                        }
1043                    }
1044                }
1045            }
1046            if (p == replacement && (pp = p.parent) != null) {
1047                if (p == pp.left) // detach pointers
1048                    pp.left = null;
1049                else if (p == pp.right)
1050                    pp.right = null;
1051                p.parent = null;
1052            }
1053        }
641      }
642  
643 <    /* ---------------- Collision reduction methods -------------- */
643 >    /* ---------------- Static utilities -------------- */
644  
645      /**
646 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
647 <     * Because the table uses power-of-two masking, sets of hashes
648 <     * that vary only in bits above the current mask will always
649 <     * collide. (Among known examples are sets of Float keys holding
650 <     * consecutive whole numbers in small tables.)  To counter this,
651 <     * we apply a transform that spreads the impact of higher bits
646 >     * Spreads (XORs) higher bits of hash to lower and also forces top
647 >     * bit to 0. Because the table uses power-of-two masking, sets of
648 >     * hashes that vary only in bits above the current mask will
649 >     * always collide. (Among known examples are sets of Float keys
650 >     * holding consecutive whole numbers in small tables.)  So we
651 >     * apply a transform that spreads the impact of higher bits
652       * downward. There is a tradeoff between speed, utility, and
653       * quality of bit-spreading. Because many common sets of hashes
654 <     * are already reasonably distributed across bits (so don't benefit
655 <     * from spreading), and because we use trees to handle large sets
656 <     * of collisions in bins, we don't need excessively high quality.
657 <     */
658 <    private static final int spread(int h) {
659 <        h ^= (h >>> 18) ^ (h >>> 12);
1073 <        return (h ^ (h >>> 10)) & HASH_BITS;
1074 <    }
1075 <
1076 <    /**
1077 <     * Replaces a list bin with a tree bin. Call only when locked.
1078 <     * Fails to replace if the given key is non-comparable or table
1079 <     * is, or needs, resizing.
1080 <     */
1081 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1082 <        if ((key instanceof Comparable) &&
1083 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1084 <            TreeBin t = new TreeBin();
1085 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
1086 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1087 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
1088 <        }
1089 <    }
1090 <
1091 <    /* ---------------- Internal access and update methods -------------- */
1092 <
1093 <    /** Implementation for get and containsKey */
1094 <    private final Object internalGet(Object k) {
1095 <        int h = spread(k.hashCode());
1096 <        retry: for (Node[] tab = table; tab != null;) {
1097 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1098 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1099 <                if ((eh = e.hash) == MOVED) {
1100 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1101 <                        return ((TreeBin)ek).getValue(h, k);
1102 <                    else {                        // restart with new table
1103 <                        tab = (Node[])ek;
1104 <                        continue retry;
1105 <                    }
1106 <                }
1107 <                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1108 <                         ((ek = e.key) == k || k.equals(ek)))
1109 <                    return ev;
1110 <            }
1111 <            break;
1112 <        }
1113 <        return null;
1114 <    }
1115 <
1116 <    /**
1117 <     * Implementation for the four public remove/replace methods:
1118 <     * Replaces node value with v, conditional upon match of cv if
1119 <     * non-null.  If resulting value is null, delete.
654 >     * are already reasonably distributed (so don't benefit from
655 >     * spreading), and because we use trees to handle large sets of
656 >     * collisions in bins, we just XOR some shifted bits in the
657 >     * cheapest possible way to reduce systematic lossage, as well as
658 >     * to incorporate impact of the highest bits that would otherwise
659 >     * never be used in index calculations because of table bounds.
660       */
661 <    private final Object internalReplace(Object k, Object v, Object cv) {
662 <        int h = spread(k.hashCode());
1123 <        Object oldVal = null;
1124 <        for (Node[] tab = table;;) {
1125 <            Node f; int i, fh; Object fk;
1126 <            if (tab == null ||
1127 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1128 <                break;
1129 <            else if ((fh = f.hash) == MOVED) {
1130 <                if ((fk = f.key) instanceof TreeBin) {
1131 <                    TreeBin t = (TreeBin)fk;
1132 <                    boolean validated = false;
1133 <                    boolean deleted = false;
1134 <                    t.acquire(0);
1135 <                    try {
1136 <                        if (tabAt(tab, i) == f) {
1137 <                            validated = true;
1138 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1139 <                            if (p != null) {
1140 <                                Object pv = p.val;
1141 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1142 <                                    oldVal = pv;
1143 <                                    if ((p.val = v) == null) {
1144 <                                        deleted = true;
1145 <                                        t.deleteTreeNode(p);
1146 <                                    }
1147 <                                }
1148 <                            }
1149 <                        }
1150 <                    } finally {
1151 <                        t.release(0);
1152 <                    }
1153 <                    if (validated) {
1154 <                        if (deleted)
1155 <                            counter.add(-1L);
1156 <                        break;
1157 <                    }
1158 <                }
1159 <                else
1160 <                    tab = (Node[])fk;
1161 <            }
1162 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1163 <                break;                          // rules out possible existence
1164 <            else if ((fh & LOCKED) != 0) {
1165 <                checkForResize();               // try resizing if can't get lock
1166 <                f.tryAwaitLock(tab, i);
1167 <            }
1168 <            else if (f.casHash(fh, fh | LOCKED)) {
1169 <                boolean validated = false;
1170 <                boolean deleted = false;
1171 <                try {
1172 <                    if (tabAt(tab, i) == f) {
1173 <                        validated = true;
1174 <                        for (Node e = f, pred = null;;) {
1175 <                            Object ek, ev;
1176 <                            if ((e.hash & HASH_BITS) == h &&
1177 <                                ((ev = e.val) != null) &&
1178 <                                ((ek = e.key) == k || k.equals(ek))) {
1179 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1180 <                                    oldVal = ev;
1181 <                                    if ((e.val = v) == null) {
1182 <                                        deleted = true;
1183 <                                        Node en = e.next;
1184 <                                        if (pred != null)
1185 <                                            pred.next = en;
1186 <                                        else
1187 <                                            setTabAt(tab, i, en);
1188 <                                    }
1189 <                                }
1190 <                                break;
1191 <                            }
1192 <                            pred = e;
1193 <                            if ((e = e.next) == null)
1194 <                                break;
1195 <                        }
1196 <                    }
1197 <                } finally {
1198 <                    if (!f.casHash(fh | LOCKED, fh)) {
1199 <                        f.hash = fh;
1200 <                        synchronized (f) { f.notifyAll(); };
1201 <                    }
1202 <                }
1203 <                if (validated) {
1204 <                    if (deleted)
1205 <                        counter.add(-1L);
1206 <                    break;
1207 <                }
1208 <            }
1209 <        }
1210 <        return oldVal;
661 >    static final int spread(int h) {
662 >        return (h ^ (h >>> 16)) & HASH_BITS;
663      }
664  
1213    /*
1214     * Internal versions of the six insertion methods, each a
1215     * little more complicated than the last. All have
1216     * the same basic structure as the first (internalPut):
1217     *  1. If table uninitialized, create
1218     *  2. If bin empty, try to CAS new node
1219     *  3. If bin stale, use new table
1220     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1221     *  5. Lock and validate; if valid, scan and add or update
1222     *
1223     * The others interweave other checks and/or alternative actions:
1224     *  * Plain put checks for and performs resize after insertion.
1225     *  * putIfAbsent prescans for mapping without lock (and fails to add
1226     *    if present), which also makes pre-emptive resize checks worthwhile.
1227     *  * computeIfAbsent extends form used in putIfAbsent with additional
1228     *    mechanics to deal with, calls, potential exceptions and null
1229     *    returns from function call.
1230     *  * compute uses the same function-call mechanics, but without
1231     *    the prescans
1232     *  * merge acts as putIfAbsent in the absent case, but invokes the
1233     *    update function if present
1234     *  * putAll attempts to pre-allocate enough table space
1235     *    and more lazily performs count updates and checks.
1236     *
1237     * Someday when details settle down a bit more, it might be worth
1238     * some factoring to reduce sprawl.
1239     */
1240
1241    /** Implementation for put */
1242    private final Object internalPut(Object k, Object v) {
1243        int h = spread(k.hashCode());
1244        int count = 0;
1245        for (Node[] tab = table;;) {
1246            int i; Node f; int fh; Object fk;
1247            if (tab == null)
1248                tab = initTable();
1249            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1250                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1251                    break;                   // no lock when adding to empty bin
1252            }
1253            else if ((fh = f.hash) == MOVED) {
1254                if ((fk = f.key) instanceof TreeBin) {
1255                    TreeBin t = (TreeBin)fk;
1256                    Object oldVal = null;
1257                    t.acquire(0);
1258                    try {
1259                        if (tabAt(tab, i) == f) {
1260                            count = 2;
1261                            TreeNode p = t.putTreeNode(h, k, v);
1262                            if (p != null) {
1263                                oldVal = p.val;
1264                                p.val = v;
1265                            }
1266                        }
1267                    } finally {
1268                        t.release(0);
1269                    }
1270                    if (count != 0) {
1271                        if (oldVal != null)
1272                            return oldVal;
1273                        break;
1274                    }
1275                }
1276                else
1277                    tab = (Node[])fk;
1278            }
1279            else if ((fh & LOCKED) != 0) {
1280                checkForResize();
1281                f.tryAwaitLock(tab, i);
1282            }
1283            else if (f.casHash(fh, fh | LOCKED)) {
1284                Object oldVal = null;
1285                try {                        // needed in case equals() throws
1286                    if (tabAt(tab, i) == f) {
1287                        count = 1;
1288                        for (Node e = f;; ++count) {
1289                            Object ek, ev;
1290                            if ((e.hash & HASH_BITS) == h &&
1291                                (ev = e.val) != null &&
1292                                ((ek = e.key) == k || k.equals(ek))) {
1293                                oldVal = ev;
1294                                e.val = v;
1295                                break;
1296                            }
1297                            Node last = e;
1298                            if ((e = e.next) == null) {
1299                                last.next = new Node(h, k, v, null);
1300                                if (count >= TREE_THRESHOLD)
1301                                    replaceWithTreeBin(tab, i, k);
1302                                break;
1303                            }
1304                        }
1305                    }
1306                } finally {                  // unlock and signal if needed
1307                    if (!f.casHash(fh | LOCKED, fh)) {
1308                        f.hash = fh;
1309                        synchronized (f) { f.notifyAll(); };
1310                    }
1311                }
1312                if (count != 0) {
1313                    if (oldVal != null)
1314                        return oldVal;
1315                    if (tab.length <= 64)
1316                        count = 2;
1317                    break;
1318                }
1319            }
1320        }
1321        counter.add(1L);
1322        if (count > 1)
1323            checkForResize();
1324        return null;
1325    }
1326
1327    /** Implementation for putIfAbsent */
1328    private final Object internalPutIfAbsent(Object k, Object v) {
1329        int h = spread(k.hashCode());
1330        int count = 0;
1331        for (Node[] tab = table;;) {
1332            int i; Node f; int fh; Object fk, fv;
1333            if (tab == null)
1334                tab = initTable();
1335            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1336                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1337                    break;
1338            }
1339            else if ((fh = f.hash) == MOVED) {
1340                if ((fk = f.key) instanceof TreeBin) {
1341                    TreeBin t = (TreeBin)fk;
1342                    Object oldVal = null;
1343                    t.acquire(0);
1344                    try {
1345                        if (tabAt(tab, i) == f) {
1346                            count = 2;
1347                            TreeNode p = t.putTreeNode(h, k, v);
1348                            if (p != null)
1349                                oldVal = p.val;
1350                        }
1351                    } finally {
1352                        t.release(0);
1353                    }
1354                    if (count != 0) {
1355                        if (oldVal != null)
1356                            return oldVal;
1357                        break;
1358                    }
1359                }
1360                else
1361                    tab = (Node[])fk;
1362            }
1363            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1364                     ((fk = f.key) == k || k.equals(fk)))
1365                return fv;
1366            else {
1367                Node g = f.next;
1368                if (g != null) { // at least 2 nodes -- search and maybe resize
1369                    for (Node e = g;;) {
1370                        Object ek, ev;
1371                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1372                            ((ek = e.key) == k || k.equals(ek)))
1373                            return ev;
1374                        if ((e = e.next) == null) {
1375                            checkForResize();
1376                            break;
1377                        }
1378                    }
1379                }
1380                if (((fh = f.hash) & LOCKED) != 0) {
1381                    checkForResize();
1382                    f.tryAwaitLock(tab, i);
1383                }
1384                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1385                    Object oldVal = null;
1386                    try {
1387                        if (tabAt(tab, i) == f) {
1388                            count = 1;
1389                            for (Node e = f;; ++count) {
1390                                Object ek, ev;
1391                                if ((e.hash & HASH_BITS) == h &&
1392                                    (ev = e.val) != null &&
1393                                    ((ek = e.key) == k || k.equals(ek))) {
1394                                    oldVal = ev;
1395                                    break;
1396                                }
1397                                Node last = e;
1398                                if ((e = e.next) == null) {
1399                                    last.next = new Node(h, k, v, null);
1400                                    if (count >= TREE_THRESHOLD)
1401                                        replaceWithTreeBin(tab, i, k);
1402                                    break;
1403                                }
1404                            }
1405                        }
1406                    } finally {
1407                        if (!f.casHash(fh | LOCKED, fh)) {
1408                            f.hash = fh;
1409                            synchronized (f) { f.notifyAll(); };
1410                        }
1411                    }
1412                    if (count != 0) {
1413                        if (oldVal != null)
1414                            return oldVal;
1415                        if (tab.length <= 64)
1416                            count = 2;
1417                        break;
1418                    }
1419                }
1420            }
1421        }
1422        counter.add(1L);
1423        if (count > 1)
1424            checkForResize();
1425        return null;
1426    }
1427
1428    /** Implementation for computeIfAbsent */
1429    private final Object internalComputeIfAbsent(K k,
1430                                                 Fun<? super K, ?> mf) {
1431        int h = spread(k.hashCode());
1432        Object val = null;
1433        int count = 0;
1434        for (Node[] tab = table;;) {
1435            Node f; int i, fh; Object fk, fv;
1436            if (tab == null)
1437                tab = initTable();
1438            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1439                Node node = new Node(fh = h | LOCKED, k, null, null);
1440                if (casTabAt(tab, i, null, node)) {
1441                    count = 1;
1442                    try {
1443                        if ((val = mf.apply(k)) != null)
1444                            node.val = val;
1445                    } finally {
1446                        if (val == null)
1447                            setTabAt(tab, i, null);
1448                        if (!node.casHash(fh, h)) {
1449                            node.hash = h;
1450                            synchronized (node) { node.notifyAll(); };
1451                        }
1452                    }
1453                }
1454                if (count != 0)
1455                    break;
1456            }
1457            else if ((fh = f.hash) == MOVED) {
1458                if ((fk = f.key) instanceof TreeBin) {
1459                    TreeBin t = (TreeBin)fk;
1460                    boolean added = false;
1461                    t.acquire(0);
1462                    try {
1463                        if (tabAt(tab, i) == f) {
1464                            count = 1;
1465                            TreeNode p = t.getTreeNode(h, k, t.root);
1466                            if (p != null)
1467                                val = p.val;
1468                            else if ((val = mf.apply(k)) != null) {
1469                                added = true;
1470                                count = 2;
1471                                t.putTreeNode(h, k, val);
1472                            }
1473                        }
1474                    } finally {
1475                        t.release(0);
1476                    }
1477                    if (count != 0) {
1478                        if (!added)
1479                            return val;
1480                        break;
1481                    }
1482                }
1483                else
1484                    tab = (Node[])fk;
1485            }
1486            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1487                     ((fk = f.key) == k || k.equals(fk)))
1488                return fv;
1489            else {
1490                Node g = f.next;
1491                if (g != null) {
1492                    for (Node e = g;;) {
1493                        Object ek, ev;
1494                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1495                            ((ek = e.key) == k || k.equals(ek)))
1496                            return ev;
1497                        if ((e = e.next) == null) {
1498                            checkForResize();
1499                            break;
1500                        }
1501                    }
1502                }
1503                if (((fh = f.hash) & LOCKED) != 0) {
1504                    checkForResize();
1505                    f.tryAwaitLock(tab, i);
1506                }
1507                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1508                    boolean added = false;
1509                    try {
1510                        if (tabAt(tab, i) == f) {
1511                            count = 1;
1512                            for (Node e = f;; ++count) {
1513                                Object ek, ev;
1514                                if ((e.hash & HASH_BITS) == h &&
1515                                    (ev = e.val) != null &&
1516                                    ((ek = e.key) == k || k.equals(ek))) {
1517                                    val = ev;
1518                                    break;
1519                                }
1520                                Node last = e;
1521                                if ((e = e.next) == null) {
1522                                    if ((val = mf.apply(k)) != null) {
1523                                        added = true;
1524                                        last.next = new Node(h, k, val, null);
1525                                        if (count >= TREE_THRESHOLD)
1526                                            replaceWithTreeBin(tab, i, k);
1527                                    }
1528                                    break;
1529                                }
1530                            }
1531                        }
1532                    } finally {
1533                        if (!f.casHash(fh | LOCKED, fh)) {
1534                            f.hash = fh;
1535                            synchronized (f) { f.notifyAll(); };
1536                        }
1537                    }
1538                    if (count != 0) {
1539                        if (!added)
1540                            return val;
1541                        if (tab.length <= 64)
1542                            count = 2;
1543                        break;
1544                    }
1545                }
1546            }
1547        }
1548        if (val != null) {
1549            counter.add(1L);
1550            if (count > 1)
1551                checkForResize();
1552        }
1553        return val;
1554    }
1555
1556    /** Implementation for compute */
1557    @SuppressWarnings("unchecked") private final Object internalCompute
1558        (K k, boolean onlyIfPresent, BiFun<? super K, ? super V, ? extends V> mf) {
1559        int h = spread(k.hashCode());
1560        Object val = null;
1561        int delta = 0;
1562        int count = 0;
1563        for (Node[] tab = table;;) {
1564            Node f; int i, fh; Object fk;
1565            if (tab == null)
1566                tab = initTable();
1567            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1568                if (onlyIfPresent)
1569                    break;
1570                Node node = new Node(fh = h | LOCKED, k, null, null);
1571                if (casTabAt(tab, i, null, node)) {
1572                    try {
1573                        count = 1;
1574                        if ((val = mf.apply(k, null)) != null) {
1575                            node.val = val;
1576                            delta = 1;
1577                        }
1578                    } finally {
1579                        if (delta == 0)
1580                            setTabAt(tab, i, null);
1581                        if (!node.casHash(fh, h)) {
1582                            node.hash = h;
1583                            synchronized (node) { node.notifyAll(); };
1584                        }
1585                    }
1586                }
1587                if (count != 0)
1588                    break;
1589            }
1590            else if ((fh = f.hash) == MOVED) {
1591                if ((fk = f.key) instanceof TreeBin) {
1592                    TreeBin t = (TreeBin)fk;
1593                    t.acquire(0);
1594                    try {
1595                        if (tabAt(tab, i) == f) {
1596                            count = 1;
1597                            TreeNode p = t.getTreeNode(h, k, t.root);
1598                            Object pv = (p == null) ? null : p.val;
1599                            if ((val = mf.apply(k, (V)pv)) != null) {
1600                                if (p != null)
1601                                    p.val = val;
1602                                else {
1603                                    count = 2;
1604                                    delta = 1;
1605                                    t.putTreeNode(h, k, val);
1606                                }
1607                            }
1608                            else if (p != null) {
1609                                delta = -1;
1610                                t.deleteTreeNode(p);
1611                            }
1612                        }
1613                    } finally {
1614                        t.release(0);
1615                    }
1616                    if (count != 0)
1617                        break;
1618                }
1619                else
1620                    tab = (Node[])fk;
1621            }
1622            else if ((fh & LOCKED) != 0) {
1623                checkForResize();
1624                f.tryAwaitLock(tab, i);
1625            }
1626            else if (f.casHash(fh, fh | LOCKED)) {
1627                try {
1628                    if (tabAt(tab, i) == f) {
1629                        count = 1;
1630                        for (Node e = f, pred = null;; ++count) {
1631                            Object ek, ev;
1632                            if ((e.hash & HASH_BITS) == h &&
1633                                (ev = e.val) != null &&
1634                                ((ek = e.key) == k || k.equals(ek))) {
1635                                val = mf.apply(k, (V)ev);
1636                                if (val != null)
1637                                    e.val = val;
1638                                else {
1639                                    delta = -1;
1640                                    Node en = e.next;
1641                                    if (pred != null)
1642                                        pred.next = en;
1643                                    else
1644                                        setTabAt(tab, i, en);
1645                                }
1646                                break;
1647                            }
1648                            pred = e;
1649                            if ((e = e.next) == null) {
1650                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1651                                    pred.next = new Node(h, k, val, null);
1652                                    delta = 1;
1653                                    if (count >= TREE_THRESHOLD)
1654                                        replaceWithTreeBin(tab, i, k);
1655                                }
1656                                break;
1657                            }
1658                        }
1659                    }
1660                } finally {
1661                    if (!f.casHash(fh | LOCKED, fh)) {
1662                        f.hash = fh;
1663                        synchronized (f) { f.notifyAll(); };
1664                    }
1665                }
1666                if (count != 0) {
1667                    if (tab.length <= 64)
1668                        count = 2;
1669                    break;
1670                }
1671            }
1672        }
1673        if (delta != 0) {
1674            counter.add((long)delta);
1675            if (count > 1)
1676                checkForResize();
1677        }
1678        return val;
1679    }
1680
1681    /** Implementation for merge */
1682    @SuppressWarnings("unchecked") private final Object internalMerge
1683        (K k, V v, BiFun<? super V, ? super V, ? extends V> mf) {
1684        int h = spread(k.hashCode());
1685        Object val = null;
1686        int delta = 0;
1687        int count = 0;
1688        for (Node[] tab = table;;) {
1689            int i; Node f; int fh; Object fk, fv;
1690            if (tab == null)
1691                tab = initTable();
1692            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1693                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1694                    delta = 1;
1695                    val = v;
1696                    break;
1697                }
1698            }
1699            else if ((fh = f.hash) == MOVED) {
1700                if ((fk = f.key) instanceof TreeBin) {
1701                    TreeBin t = (TreeBin)fk;
1702                    t.acquire(0);
1703                    try {
1704                        if (tabAt(tab, i) == f) {
1705                            count = 1;
1706                            TreeNode p = t.getTreeNode(h, k, t.root);
1707                            val = (p == null) ? v : mf.apply((V)p.val, v);
1708                            if (val != null) {
1709                                if (p != null)
1710                                    p.val = val;
1711                                else {
1712                                    count = 2;
1713                                    delta = 1;
1714                                    t.putTreeNode(h, k, val);
1715                                }
1716                            }
1717                            else if (p != null) {
1718                                delta = -1;
1719                                t.deleteTreeNode(p);
1720                            }
1721                        }
1722                    } finally {
1723                        t.release(0);
1724                    }
1725                    if (count != 0)
1726                        break;
1727                }
1728                else
1729                    tab = (Node[])fk;
1730            }
1731            else if ((fh & LOCKED) != 0) {
1732                checkForResize();
1733                f.tryAwaitLock(tab, i);
1734            }
1735            else if (f.casHash(fh, fh | LOCKED)) {
1736                try {
1737                    if (tabAt(tab, i) == f) {
1738                        count = 1;
1739                        for (Node e = f, pred = null;; ++count) {
1740                            Object ek, ev;
1741                            if ((e.hash & HASH_BITS) == h &&
1742                                (ev = e.val) != null &&
1743                                ((ek = e.key) == k || k.equals(ek))) {
1744                                val = mf.apply(v, (V)ev);
1745                                if (val != null)
1746                                    e.val = val;
1747                                else {
1748                                    delta = -1;
1749                                    Node en = e.next;
1750                                    if (pred != null)
1751                                        pred.next = en;
1752                                    else
1753                                        setTabAt(tab, i, en);
1754                                }
1755                                break;
1756                            }
1757                            pred = e;
1758                            if ((e = e.next) == null) {
1759                                val = v;
1760                                pred.next = new Node(h, k, val, null);
1761                                delta = 1;
1762                                if (count >= TREE_THRESHOLD)
1763                                    replaceWithTreeBin(tab, i, k);
1764                                break;
1765                            }
1766                        }
1767                    }
1768                } finally {
1769                    if (!f.casHash(fh | LOCKED, fh)) {
1770                        f.hash = fh;
1771                        synchronized (f) { f.notifyAll(); };
1772                    }
1773                }
1774                if (count != 0) {
1775                    if (tab.length <= 64)
1776                        count = 2;
1777                    break;
1778                }
1779            }
1780        }
1781        if (delta != 0) {
1782            counter.add((long)delta);
1783            if (count > 1)
1784                checkForResize();
1785        }
1786        return val;
1787    }
1788
1789    /** Implementation for putAll */
1790    private final void internalPutAll(Map<?, ?> m) {
1791        tryPresize(m.size());
1792        long delta = 0L;     // number of uncommitted additions
1793        boolean npe = false; // to throw exception on exit for nulls
1794        try {                // to clean up counts on other exceptions
1795            for (Map.Entry<?, ?> entry : m.entrySet()) {
1796                Object k, v;
1797                if (entry == null || (k = entry.getKey()) == null ||
1798                    (v = entry.getValue()) == null) {
1799                    npe = true;
1800                    break;
1801                }
1802                int h = spread(k.hashCode());
1803                for (Node[] tab = table;;) {
1804                    int i; Node f; int fh; Object fk;
1805                    if (tab == null)
1806                        tab = initTable();
1807                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1808                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1809                            ++delta;
1810                            break;
1811                        }
1812                    }
1813                    else if ((fh = f.hash) == MOVED) {
1814                        if ((fk = f.key) instanceof TreeBin) {
1815                            TreeBin t = (TreeBin)fk;
1816                            boolean validated = false;
1817                            t.acquire(0);
1818                            try {
1819                                if (tabAt(tab, i) == f) {
1820                                    validated = true;
1821                                    TreeNode p = t.getTreeNode(h, k, t.root);
1822                                    if (p != null)
1823                                        p.val = v;
1824                                    else {
1825                                        t.putTreeNode(h, k, v);
1826                                        ++delta;
1827                                    }
1828                                }
1829                            } finally {
1830                                t.release(0);
1831                            }
1832                            if (validated)
1833                                break;
1834                        }
1835                        else
1836                            tab = (Node[])fk;
1837                    }
1838                    else if ((fh & LOCKED) != 0) {
1839                        counter.add(delta);
1840                        delta = 0L;
1841                        checkForResize();
1842                        f.tryAwaitLock(tab, i);
1843                    }
1844                    else if (f.casHash(fh, fh | LOCKED)) {
1845                        int count = 0;
1846                        try {
1847                            if (tabAt(tab, i) == f) {
1848                                count = 1;
1849                                for (Node e = f;; ++count) {
1850                                    Object ek, ev;
1851                                    if ((e.hash & HASH_BITS) == h &&
1852                                        (ev = e.val) != null &&
1853                                        ((ek = e.key) == k || k.equals(ek))) {
1854                                        e.val = v;
1855                                        break;
1856                                    }
1857                                    Node last = e;
1858                                    if ((e = e.next) == null) {
1859                                        ++delta;
1860                                        last.next = new Node(h, k, v, null);
1861                                        if (count >= TREE_THRESHOLD)
1862                                            replaceWithTreeBin(tab, i, k);
1863                                        break;
1864                                    }
1865                                }
1866                            }
1867                        } finally {
1868                            if (!f.casHash(fh | LOCKED, fh)) {
1869                                f.hash = fh;
1870                                synchronized (f) { f.notifyAll(); };
1871                            }
1872                        }
1873                        if (count != 0) {
1874                            if (count > 1) {
1875                                counter.add(delta);
1876                                delta = 0L;
1877                                checkForResize();
1878                            }
1879                            break;
1880                        }
1881                    }
1882                }
1883            }
1884        } finally {
1885            if (delta != 0)
1886                counter.add(delta);
1887        }
1888        if (npe)
1889            throw new NullPointerException();
1890    }
1891
1892    /* ---------------- Table Initialization and Resizing -------------- */
1893
665      /**
666       * Returns a power of two table size for the given desired capacity.
667       * See Hackers Delight, sec 3.2
# Line 1906 | Line 677 | public class ConcurrentHashMapV8<K, V>
677      }
678  
679      /**
680 <     * Initializes table, using the size recorded in sizeCtl.
680 >     * Returns x's Class if it is of the form "class C implements
681 >     * Comparable<C>", else null.
682       */
683 <    private final Node[] initTable() {
684 <        Node[] tab; int sc;
685 <        while ((tab = table) == null) {
686 <            if ((sc = sizeCtl) < 0)
687 <                Thread.yield(); // lost initialization race; just spin
688 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
689 <                try {
690 <                    if ((tab = table) == null) {
691 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
692 <                        tab = table = new Node[n];
693 <                        sc = n - (n >>> 2);
694 <                    }
695 <                } finally {
1924 <                    sizeCtl = sc;
1925 <                }
1926 <                break;
1927 <            }
1928 <        }
1929 <        return tab;
1930 <    }
1931 <
1932 <    /**
1933 <     * If table is too small and not already resizing, creates next
1934 <     * table and transfers bins.  Rechecks occupancy after a transfer
1935 <     * to see if another resize is already needed because resizings
1936 <     * are lagging additions.
1937 <     */
1938 <    private final void checkForResize() {
1939 <        Node[] tab; int n, sc;
1940 <        while ((tab = table) != null &&
1941 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1942 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1943 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1944 <            try {
1945 <                if (tab == table) {
1946 <                    table = rebuild(tab);
1947 <                    sc = (n << 1) - (n >>> 1);
683 >    static Class<?> comparableClassFor(Object x) {
684 >        if (x instanceof Comparable) {
685 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
686 >            if ((c = x.getClass()) == String.class) // bypass checks
687 >                return c;
688 >            if ((ts = c.getGenericInterfaces()) != null) {
689 >                for (int i = 0; i < ts.length; ++i) {
690 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
691 >                        ((p = (ParameterizedType)t).getRawType() ==
692 >                         Comparable.class) &&
693 >                        (as = p.getActualTypeArguments()) != null &&
694 >                        as.length == 1 && as[0] == c) // type arg is c
695 >                        return c;
696                  }
1949            } finally {
1950                sizeCtl = sc;
697              }
698          }
699 +        return null;
700      }
701  
702      /**
703 <     * Tries to presize table to accommodate the given number of elements.
704 <     *
1958 <     * @param size number of elements (doesn't need to be perfectly accurate)
703 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
704 >     * class), else 0.
705       */
706 <    private final void tryPresize(int size) {
707 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
708 <            tableSizeFor(size + (size >>> 1) + 1);
709 <        int sc;
1964 <        while ((sc = sizeCtl) >= 0) {
1965 <            Node[] tab = table; int n;
1966 <            if (tab == null || (n = tab.length) == 0) {
1967 <                n = (sc > c) ? sc : c;
1968 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1969 <                    try {
1970 <                        if (table == tab) {
1971 <                            table = new Node[n];
1972 <                            sc = n - (n >>> 2);
1973 <                        }
1974 <                    } finally {
1975 <                        sizeCtl = sc;
1976 <                    }
1977 <                }
1978 <            }
1979 <            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1980 <                break;
1981 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1982 <                try {
1983 <                    if (table == tab) {
1984 <                        table = rebuild(tab);
1985 <                        sc = (n << 1) - (n >>> 1);
1986 <                    }
1987 <                } finally {
1988 <                    sizeCtl = sc;
1989 <                }
1990 <            }
1991 <        }
706 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
707 >    static int compareComparables(Class<?> kc, Object k, Object x) {
708 >        return (x == null || x.getClass() != kc ? 0 :
709 >                ((Comparable)k).compareTo(x));
710      }
711  
712 +    /* ---------------- Table element access -------------- */
713 +
714      /*
715 <     * Moves and/or copies the nodes in each bin to new table. See
716 <     * above for explanation.
717 <     *
718 <     * @return the new table
719 <     */
720 <    private static final Node[] rebuild(Node[] tab) {
721 <        int n = tab.length;
722 <        Node[] nextTab = new Node[n << 1];
723 <        Node fwd = new Node(MOVED, nextTab, null, null);
724 <        int[] buffer = null;       // holds bins to revisit; null until needed
725 <        Node rev = null;           // reverse forwarder; null until needed
726 <        int nbuffered = 0;         // the number of bins in buffer list
727 <        int bufferIndex = 0;       // buffer index of current buffered bin
728 <        int bin = n - 1;           // current non-buffered bin or -1 if none
729 <
730 <        for (int i = bin;;) {      // start upwards sweep
731 <            int fh; Node f;
732 <            if ((f = tabAt(tab, i)) == null) {
733 <                if (bin >= 0) {    // Unbuffered; no lock needed (or available)
734 <                    if (!casTabAt(tab, i, f, fwd))
735 <                        continue;
736 <                }
737 <                else {             // transiently use a locked forwarding node
2018 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2019 <                    if (!casTabAt(tab, i, f, g))
2020 <                        continue;
2021 <                    setTabAt(nextTab, i, null);
2022 <                    setTabAt(nextTab, i + n, null);
2023 <                    setTabAt(tab, i, fwd);
2024 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2025 <                        g.hash = MOVED;
2026 <                        synchronized (g) { g.notifyAll(); }
2027 <                    }
2028 <                }
2029 <            }
2030 <            else if ((fh = f.hash) == MOVED) {
2031 <                Object fk = f.key;
2032 <                if (fk instanceof TreeBin) {
2033 <                    TreeBin t = (TreeBin)fk;
2034 <                    boolean validated = false;
2035 <                    t.acquire(0);
2036 <                    try {
2037 <                        if (tabAt(tab, i) == f) {
2038 <                            validated = true;
2039 <                            splitTreeBin(nextTab, i, t);
2040 <                            setTabAt(tab, i, fwd);
2041 <                        }
2042 <                    } finally {
2043 <                        t.release(0);
2044 <                    }
2045 <                    if (!validated)
2046 <                        continue;
2047 <                }
2048 <            }
2049 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2050 <                boolean validated = false;
2051 <                try {              // split to lo and hi lists; copying as needed
2052 <                    if (tabAt(tab, i) == f) {
2053 <                        validated = true;
2054 <                        splitBin(nextTab, i, f);
2055 <                        setTabAt(tab, i, fwd);
2056 <                    }
2057 <                } finally {
2058 <                    if (!f.casHash(fh | LOCKED, fh)) {
2059 <                        f.hash = fh;
2060 <                        synchronized (f) { f.notifyAll(); };
2061 <                    }
2062 <                }
2063 <                if (!validated)
2064 <                    continue;
2065 <            }
2066 <            else {
2067 <                if (buffer == null) // initialize buffer for revisits
2068 <                    buffer = new int[TRANSFER_BUFFER_SIZE];
2069 <                if (bin < 0 && bufferIndex > 0) {
2070 <                    int j = buffer[--bufferIndex];
2071 <                    buffer[bufferIndex] = i;
2072 <                    i = j;         // swap with another bin
2073 <                    continue;
2074 <                }
2075 <                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2076 <                    f.tryAwaitLock(tab, i);
2077 <                    continue;      // no other options -- block
2078 <                }
2079 <                if (rev == null)   // initialize reverse-forwarder
2080 <                    rev = new Node(MOVED, tab, null, null);
2081 <                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2082 <                    continue;      // recheck before adding to list
2083 <                buffer[nbuffered++] = i;
2084 <                setTabAt(nextTab, i, rev);     // install place-holders
2085 <                setTabAt(nextTab, i + n, rev);
2086 <            }
2087 <
2088 <            if (bin > 0)
2089 <                i = --bin;
2090 <            else if (buffer != null && nbuffered > 0) {
2091 <                bin = -1;
2092 <                i = buffer[bufferIndex = --nbuffered];
2093 <            }
2094 <            else
2095 <                return nextTab;
2096 <        }
715 >     * Volatile access methods are used for table elements as well as
716 >     * elements of in-progress next table while resizing.  All uses of
717 >     * the tab arguments must be null checked by callers.  All callers
718 >     * also paranoically precheck that tab's length is not zero (or an
719 >     * equivalent check), thus ensuring that any index argument taking
720 >     * the form of a hash value anded with (length - 1) is a valid
721 >     * index.  Note that, to be correct wrt arbitrary concurrency
722 >     * errors by users, these checks must operate on local variables,
723 >     * which accounts for some odd-looking inline assignments below.
724 >     * Note that calls to setTabAt always occur within locked regions,
725 >     * and so in principle require only release ordering, not need
726 >     * full volatile semantics, but are currently coded as volatile
727 >     * writes to be conservative.
728 >     */
729 >
730 >    @SuppressWarnings("unchecked")
731 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
732 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
733 >    }
734 >
735 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
736 >                                        Node<K,V> c, Node<K,V> v) {
737 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
738      }
739  
740 <    /**
741 <     * Splits a normal bin with list headed by e into lo and hi parts;
2101 <     * installs in given table.
2102 <     */
2103 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2104 <        int bit = nextTab.length >>> 1; // bit to split on
2105 <        int runBit = e.hash & bit;
2106 <        Node lastRun = e, lo = null, hi = null;
2107 <        for (Node p = e.next; p != null; p = p.next) {
2108 <            int b = p.hash & bit;
2109 <            if (b != runBit) {
2110 <                runBit = b;
2111 <                lastRun = p;
2112 <            }
2113 <        }
2114 <        if (runBit == 0)
2115 <            lo = lastRun;
2116 <        else
2117 <            hi = lastRun;
2118 <        for (Node p = e; p != lastRun; p = p.next) {
2119 <            int ph = p.hash & HASH_BITS;
2120 <            Object pk = p.key, pv = p.val;
2121 <            if ((ph & bit) == 0)
2122 <                lo = new Node(ph, pk, pv, lo);
2123 <            else
2124 <                hi = new Node(ph, pk, pv, hi);
2125 <        }
2126 <        setTabAt(nextTab, i, lo);
2127 <        setTabAt(nextTab, i + bit, hi);
740 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
741 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
742      }
743  
744 +    /* ---------------- Fields -------------- */
745 +
746      /**
747 <     * Splits a tree bin into lo and hi parts; installs in given table.
747 >     * The array of bins. Lazily initialized upon first insertion.
748 >     * Size is always a power of two. Accessed directly by iterators.
749       */
750 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2134 <        int bit = nextTab.length >>> 1;
2135 <        TreeBin lt = new TreeBin();
2136 <        TreeBin ht = new TreeBin();
2137 <        int lc = 0, hc = 0;
2138 <        for (Node e = t.first; e != null; e = e.next) {
2139 <            int h = e.hash & HASH_BITS;
2140 <            Object k = e.key, v = e.val;
2141 <            if ((h & bit) == 0) {
2142 <                ++lc;
2143 <                lt.putTreeNode(h, k, v);
2144 <            }
2145 <            else {
2146 <                ++hc;
2147 <                ht.putTreeNode(h, k, v);
2148 <            }
2149 <        }
2150 <        Node ln, hn; // throw away trees if too small
2151 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2152 <            ln = null;
2153 <            for (Node p = lt.first; p != null; p = p.next)
2154 <                ln = new Node(p.hash, p.key, p.val, ln);
2155 <        }
2156 <        else
2157 <            ln = new Node(MOVED, lt, null, null);
2158 <        setTabAt(nextTab, i, ln);
2159 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2160 <            hn = null;
2161 <            for (Node p = ht.first; p != null; p = p.next)
2162 <                hn = new Node(p.hash, p.key, p.val, hn);
2163 <        }
2164 <        else
2165 <            hn = new Node(MOVED, ht, null, null);
2166 <        setTabAt(nextTab, i + bit, hn);
2167 <    }
750 >    transient volatile Node<K,V>[] table;
751  
752      /**
753 <     * Implementation for clear. Steps through each bin, removing all
2171 <     * nodes.
753 >     * The next table to use; non-null only while resizing.
754       */
755 <    private final void internalClear() {
2174 <        long delta = 0L; // negative number of deletions
2175 <        int i = 0;
2176 <        Node[] tab = table;
2177 <        while (tab != null && i < tab.length) {
2178 <            int fh; Object fk;
2179 <            Node f = tabAt(tab, i);
2180 <            if (f == null)
2181 <                ++i;
2182 <            else if ((fh = f.hash) == MOVED) {
2183 <                if ((fk = f.key) instanceof TreeBin) {
2184 <                    TreeBin t = (TreeBin)fk;
2185 <                    t.acquire(0);
2186 <                    try {
2187 <                        if (tabAt(tab, i) == f) {
2188 <                            for (Node p = t.first; p != null; p = p.next) {
2189 <                                if (p.val != null) { // (currently always true)
2190 <                                    p.val = null;
2191 <                                    --delta;
2192 <                                }
2193 <                            }
2194 <                            t.first = null;
2195 <                            t.root = null;
2196 <                            ++i;
2197 <                        }
2198 <                    } finally {
2199 <                        t.release(0);
2200 <                    }
2201 <                }
2202 <                else
2203 <                    tab = (Node[])fk;
2204 <            }
2205 <            else if ((fh & LOCKED) != 0) {
2206 <                counter.add(delta); // opportunistically update count
2207 <                delta = 0L;
2208 <                f.tryAwaitLock(tab, i);
2209 <            }
2210 <            else if (f.casHash(fh, fh | LOCKED)) {
2211 <                try {
2212 <                    if (tabAt(tab, i) == f) {
2213 <                        for (Node e = f; e != null; e = e.next) {
2214 <                            if (e.val != null) {  // (currently always true)
2215 <                                e.val = null;
2216 <                                --delta;
2217 <                            }
2218 <                        }
2219 <                        setTabAt(tab, i, null);
2220 <                        ++i;
2221 <                    }
2222 <                } finally {
2223 <                    if (!f.casHash(fh | LOCKED, fh)) {
2224 <                        f.hash = fh;
2225 <                        synchronized (f) { f.notifyAll(); };
2226 <                    }
2227 <                }
2228 <            }
2229 <        }
2230 <        if (delta != 0)
2231 <            counter.add(delta);
2232 <    }
755 >    private transient volatile Node<K,V>[] nextTable;
756  
757 <    /* ----------------Table Traversal -------------- */
757 >    /**
758 >     * Base counter value, used mainly when there is no contention,
759 >     * but also as a fallback during table initialization
760 >     * races. Updated via CAS.
761 >     */
762 >    private transient volatile long baseCount;
763  
764      /**
765 <     * Encapsulates traversal for methods such as containsValue; also
766 <     * serves as a base class for other iterators and bulk tasks.
767 <     *
768 <     * At each step, the iterator snapshots the key ("nextKey") and
769 <     * value ("nextVal") of a valid node (i.e., one that, at point of
770 <     * snapshot, has a non-null user value). Because val fields can
771 <     * change (including to null, indicating deletion), field nextVal
772 <     * might not be accurate at point of use, but still maintains the
2245 <     * weak consistency property of holding a value that was once
2246 <     * valid.
2247 <     *
2248 <     * Internal traversals directly access these fields, as in:
2249 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2250 <     *
2251 <     * Exported iterators must track whether the iterator has advanced
2252 <     * (in hasNext vs next) (by setting/checking/nulling field
2253 <     * nextVal), and then extract key, value, or key-value pairs as
2254 <     * return values of next().
2255 <     *
2256 <     * The iterator visits once each still-valid node that was
2257 <     * reachable upon iterator construction. It might miss some that
2258 <     * were added to a bin after the bin was visited, which is OK wrt
2259 <     * consistency guarantees. Maintaining this property in the face
2260 <     * of possible ongoing resizes requires a fair amount of
2261 <     * bookkeeping state that is difficult to optimize away amidst
2262 <     * volatile accesses.  Even so, traversal maintains reasonable
2263 <     * throughput.
2264 <     *
2265 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2266 <     * However, if the table has been resized, then all future steps
2267 <     * must traverse both the bin at the current index as well as at
2268 <     * (index + baseSize); and so on for further resizings. To
2269 <     * paranoically cope with potential sharing by users of iterators
2270 <     * across threads, iteration terminates if a bounds checks fails
2271 <     * for a table read.
2272 <     *
2273 <     * This class extends ForkJoinTask to streamline parallel
2274 <     * iteration in bulk operations (see BulkTask). This adds only an
2275 <     * int of space overhead, which is close enough to negligible in
2276 <     * cases where it is not needed to not worry about it.  Because
2277 <     * ForkJoinTask is Serializable, but iterators need not be, we
2278 <     * need to add warning suppressions.
2279 <     */
2280 <    @SuppressWarnings("serial") static class Traverser<K,V,R> extends ForkJoinTask<R> {
2281 <        final ConcurrentHashMapV8<K, V> map;
2282 <        Node next;           // the next entry to use
2283 <        Node last;           // the last entry used
2284 <        Object nextKey;      // cached key field of next
2285 <        Object nextVal;      // cached val field of next
2286 <        Node[] tab;          // current table; updated if resized
2287 <        int index;           // index of bin to use next
2288 <        int baseIndex;       // current index of initial table
2289 <        int baseLimit;       // index bound for initial table
2290 <        int baseSize;        // initial table size
765 >     * Table initialization and resizing control.  When negative, the
766 >     * table is being initialized or resized: -1 for initialization,
767 >     * else -(1 + the number of active resizing threads).  Otherwise,
768 >     * when table is null, holds the initial table size to use upon
769 >     * creation, or 0 for default. After initialization, holds the
770 >     * next element count value upon which to resize the table.
771 >     */
772 >    private transient volatile int sizeCtl;
773  
774 <        /** Creates iterator for all entries in the table. */
775 <        Traverser(ConcurrentHashMapV8<K, V> map) {
776 <            this.map = map;
777 <        }
774 >    /**
775 >     * The next table index (plus one) to split while resizing.
776 >     */
777 >    private transient volatile int transferIndex;
778  
779 <        /** Creates iterator for split() methods */
780 <        Traverser(Traverser<K,V,?> it) {
781 <            ConcurrentHashMapV8<K, V> m; Node[] t;
782 <            if ((m = this.map = it.map) == null)
2301 <                t = null;
2302 <            else if ((t = it.tab) == null && // force parent tab initialization
2303 <                     (t = it.tab = m.table) != null)
2304 <                it.baseLimit = it.baseSize = t.length;
2305 <            this.tab = t;
2306 <            this.baseSize = it.baseSize;
2307 <            it.baseLimit = this.index = this.baseIndex =
2308 <                ((this.baseLimit = it.baseLimit) + it.baseIndex + 1) >>> 1;
2309 <        }
779 >    /**
780 >     * The least available table index to split while resizing.
781 >     */
782 >    private transient volatile int transferOrigin;
783  
784 <        /**
785 <         * Advances next; returns nextVal or null if terminated.
786 <         * See above for explanation.
787 <         */
2315 <        final Object advance() {
2316 <            Node e = last = next;
2317 <            Object ev = null;
2318 <            outer: do {
2319 <                if (e != null)                  // advance past used/skipped node
2320 <                    e = e.next;
2321 <                while (e == null) {             // get to next non-null bin
2322 <                    ConcurrentHashMapV8<K, V> m;
2323 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2324 <                    if ((t = tab) != null)
2325 <                        n = t.length;
2326 <                    else if ((m = map) != null && (t = tab = m.table) != null)
2327 <                        n = baseLimit = baseSize = t.length;
2328 <                    else
2329 <                        break outer;
2330 <                    if ((b = baseIndex) >= baseLimit ||
2331 <                        (i = index) < 0 || i >= n)
2332 <                        break outer;
2333 <                    if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2334 <                        if ((ek = e.key) instanceof TreeBin)
2335 <                            e = ((TreeBin)ek).first;
2336 <                        else {
2337 <                            tab = (Node[])ek;
2338 <                            continue;           // restarts due to null val
2339 <                        }
2340 <                    }                           // visit upper slots if present
2341 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2342 <                }
2343 <                nextKey = e.key;
2344 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2345 <            next = e;
2346 <            return nextVal = ev;
2347 <        }
784 >    /**
785 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
786 >     */
787 >    private transient volatile int cellsBusy;
788  
789 <        public final void remove() {
790 <            if (nextVal == null && last == null)
791 <                advance();
792 <            Node e = last;
2353 <            if (e == null)
2354 <                throw new IllegalStateException();
2355 <            last = null;
2356 <            map.remove(e.key);
2357 <        }
789 >    /**
790 >     * Table of counter cells. When non-null, size is a power of 2.
791 >     */
792 >    private transient volatile CounterCell[] counterCells;
793  
794 <        public final boolean hasNext() {
795 <            return nextVal != null || advance() != null;
796 <        }
794 >    // views
795 >    private transient KeySetView<K,V> keySet;
796 >    private transient ValuesView<K,V> values;
797 >    private transient EntrySetView<K,V> entrySet;
798  
2363        public final boolean hasMoreElements() { return hasNext(); }
2364        public final void setRawResult(Object x) { }
2365        public R getRawResult() { return null; }
2366        public boolean exec() { return true; }
2367    }
799  
800      /* ---------------- Public operations -------------- */
801  
# Line 2372 | Line 803 | public class ConcurrentHashMapV8<K, V>
803       * Creates a new, empty map with the default initial table size (16).
804       */
805      public ConcurrentHashMapV8() {
2375        this.counter = new LongAdder();
806      }
807  
808      /**
# Line 2391 | Line 821 | public class ConcurrentHashMapV8<K, V>
821          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
822                     MAXIMUM_CAPACITY :
823                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2394        this.counter = new LongAdder();
824          this.sizeCtl = cap;
825      }
826  
# Line 2401 | Line 830 | public class ConcurrentHashMapV8<K, V>
830       * @param m the map
831       */
832      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2404        this.counter = new LongAdder();
833          this.sizeCtl = DEFAULT_CAPACITY;
834 <        internalPutAll(m);
834 >        putAll(m);
835      }
836  
837      /**
# Line 2444 | Line 872 | public class ConcurrentHashMapV8<K, V>
872       * nonpositive
873       */
874      public ConcurrentHashMapV8(int initialCapacity,
875 <                               float loadFactor, int concurrencyLevel) {
875 >                             float loadFactor, int concurrencyLevel) {
876          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
877              throw new IllegalArgumentException();
878          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2452 | Line 880 | public class ConcurrentHashMapV8<K, V>
880          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
881          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
882              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2455        this.counter = new LongAdder();
883          this.sizeCtl = cap;
884      }
885  
886 <    /**
2460 <     * {@inheritDoc}
2461 <     */
2462 <    public boolean isEmpty() {
2463 <        return counter.sum() <= 0L; // ignore transient negative values
2464 <    }
886 >    // Original (since JDK1.2) Map methods
887  
888      /**
889       * {@inheritDoc}
890       */
891      public int size() {
892 <        long n = counter.sum();
892 >        long n = sumCount();
893          return ((n < 0L) ? 0 :
894                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
895                  (int)n);
896      }
897  
898      /**
899 <     * Returns the number of mappings. This method should be used
2478 <     * instead of {@link #size} because a ConcurrentHashMap may
2479 <     * contain more mappings than can be represented as an int. The
2480 <     * value returned is a snapshot; the actual count may differ if
2481 <     * there are ongoing concurrent insertions or removals.
2482 <     *
2483 <     * @return the number of mappings
899 >     * {@inheritDoc}
900       */
901 <    public long mappingCount() {
902 <        long n = counter.sum();
2487 <        return (n < 0L) ? 0L : n; // ignore transient negative values
901 >    public boolean isEmpty() {
902 >        return sumCount() <= 0L; // ignore transient negative values
903      }
904  
905      /**
# Line 2498 | Line 913 | public class ConcurrentHashMapV8<K, V>
913       *
914       * @throws NullPointerException if the specified key is null
915       */
916 <    @SuppressWarnings("unchecked") public V get(Object key) {
917 <        if (key == null)
918 <            throw new NullPointerException();
919 <        return (V)internalGet(key);
920 <    }
921 <
922 <    /**
923 <     * Returns the value to which the specified key is mapped,
924 <     * or the given defaultValue if this map contains no mapping for the key.
925 <     *
926 <     * @param key the key
927 <     * @param defaultValue the value to return if this map contains
928 <     * no mapping for the given key
929 <     * @return the mapping for the key, if present; else the defaultValue
930 <     * @throws NullPointerException if the specified key is null
931 <     */
932 <    @SuppressWarnings("unchecked") public V getValueOrDefault(Object key, V defaultValue) {
933 <        if (key == null)
2519 <            throw new NullPointerException();
2520 <        V v = (V) internalGet(key);
2521 <        return v == null ? defaultValue : v;
916 >    public V get(Object key) {
917 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
918 >        int h = spread(key.hashCode());
919 >        if ((tab = table) != null && (n = tab.length) > 0 &&
920 >            (e = tabAt(tab, (n - 1) & h)) != null) {
921 >            if ((eh = e.hash) == h) {
922 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
923 >                    return e.val;
924 >            }
925 >            else if (eh < 0)
926 >                return (p = e.find(h, key)) != null ? p.val : null;
927 >            while ((e = e.next) != null) {
928 >                if (e.hash == h &&
929 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
930 >                    return e.val;
931 >            }
932 >        }
933 >        return null;
934      }
935  
936      /**
937       * Tests if the specified object is a key in this table.
938       *
939 <     * @param  key   possible key
939 >     * @param  key possible key
940       * @return {@code true} if and only if the specified object
941       *         is a key in this table, as determined by the
942       *         {@code equals} method; {@code false} otherwise
943       * @throws NullPointerException if the specified key is null
944       */
945      public boolean containsKey(Object key) {
946 <        if (key == null)
2535 <            throw new NullPointerException();
2536 <        return internalGet(key) != null;
946 >        return get(key) != null;
947      }
948  
949      /**
# Line 2549 | Line 959 | public class ConcurrentHashMapV8<K, V>
959      public boolean containsValue(Object value) {
960          if (value == null)
961              throw new NullPointerException();
962 <        Object v;
963 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
964 <        while ((v = it.advance()) != null) {
965 <            if (v == value || value.equals(v))
966 <                return true;
962 >        Node<K,V>[] t;
963 >        if ((t = table) != null) {
964 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
965 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
966 >                V v;
967 >                if ((v = p.val) == value || (v != null && value.equals(v)))
968 >                    return true;
969 >            }
970          }
971          return false;
972      }
973  
974      /**
2562     * Legacy method testing if some key maps into the specified value
2563     * in this table.  This method is identical in functionality to
2564     * {@link #containsValue}, and exists solely to ensure
2565     * full compatibility with class {@link java.util.Hashtable},
2566     * which supported this method prior to introduction of the
2567     * Java Collections framework.
2568     *
2569     * @param  value a value to search for
2570     * @return {@code true} if and only if some key maps to the
2571     *         {@code value} argument in this table as
2572     *         determined by the {@code equals} method;
2573     *         {@code false} otherwise
2574     * @throws NullPointerException if the specified value is null
2575     */
2576    public boolean contains(Object value) {
2577        return containsValue(value);
2578    }
2579
2580    /**
975       * Maps the specified key to the specified value in this table.
976       * Neither the key nor the value can be null.
977       *
978 <     * <p> The value can be retrieved by calling the {@code get} method
978 >     * <p>The value can be retrieved by calling the {@code get} method
979       * with a key that is equal to the original key.
980       *
981       * @param key key with which the specified value is to be associated
# Line 2590 | Line 984 | public class ConcurrentHashMapV8<K, V>
984       *         {@code null} if there was no mapping for {@code key}
985       * @throws NullPointerException if the specified key or value is null
986       */
987 <    @SuppressWarnings("unchecked") public V put(K key, V value) {
988 <        if (key == null || value == null)
2595 <            throw new NullPointerException();
2596 <        return (V)internalPut(key, value);
987 >    public V put(K key, V value) {
988 >        return putVal(key, value, false);
989      }
990  
991 <    /**
992 <     * {@inheritDoc}
993 <     *
994 <     * @return the previous value associated with the specified key,
995 <     *         or {@code null} if there was no mapping for the key
996 <     * @throws NullPointerException if the specified key or value is null
997 <     */
998 <    @SuppressWarnings("unchecked") public V putIfAbsent(K key, V value) {
999 <        if (key == null || value == null)
1000 <            throw new NullPointerException();
1001 <        return (V)internalPutIfAbsent(key, value);
991 >    /** Implementation for put and putIfAbsent */
992 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
993 >        if (key == null || value == null) throw new NullPointerException();
994 >        int hash = spread(key.hashCode());
995 >        int binCount = 0;
996 >        for (Node<K,V>[] tab = table;;) {
997 >            Node<K,V> f; int n, i, fh;
998 >            if (tab == null || (n = tab.length) == 0)
999 >                tab = initTable();
1000 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1001 >                if (casTabAt(tab, i, null,
1002 >                             new Node<K,V>(hash, key, value, null)))
1003 >                    break;                   // no lock when adding to empty bin
1004 >            }
1005 >            else if ((fh = f.hash) == MOVED)
1006 >                tab = helpTransfer(tab, f);
1007 >            else {
1008 >                V oldVal = null;
1009 >                synchronized (f) {
1010 >                    if (tabAt(tab, i) == f) {
1011 >                        if (fh >= 0) {
1012 >                            binCount = 1;
1013 >                            for (Node<K,V> e = f;; ++binCount) {
1014 >                                K ek;
1015 >                                if (e.hash == hash &&
1016 >                                    ((ek = e.key) == key ||
1017 >                                     (ek != null && key.equals(ek)))) {
1018 >                                    oldVal = e.val;
1019 >                                    if (!onlyIfAbsent)
1020 >                                        e.val = value;
1021 >                                    break;
1022 >                                }
1023 >                                Node<K,V> pred = e;
1024 >                                if ((e = e.next) == null) {
1025 >                                    pred.next = new Node<K,V>(hash, key,
1026 >                                                              value, null);
1027 >                                    break;
1028 >                                }
1029 >                            }
1030 >                        }
1031 >                        else if (f instanceof TreeBin) {
1032 >                            Node<K,V> p;
1033 >                            binCount = 2;
1034 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1035 >                                                           value)) != null) {
1036 >                                oldVal = p.val;
1037 >                                if (!onlyIfAbsent)
1038 >                                    p.val = value;
1039 >                            }
1040 >                        }
1041 >                    }
1042 >                }
1043 >                if (binCount != 0) {
1044 >                    if (binCount >= TREEIFY_THRESHOLD)
1045 >                        treeifyBin(tab, i);
1046 >                    if (oldVal != null)
1047 >                        return oldVal;
1048 >                    break;
1049 >                }
1050 >            }
1051 >        }
1052 >        addCount(1L, binCount);
1053 >        return null;
1054      }
1055  
1056      /**
# Line 2617 | Line 1061 | public class ConcurrentHashMapV8<K, V>
1061       * @param m mappings to be stored in this map
1062       */
1063      public void putAll(Map<? extends K, ? extends V> m) {
1064 <        internalPutAll(m);
1065 <    }
1066 <
2623 <    /**
2624 <     * If the specified key is not already associated with a value,
2625 <     * computes its value using the given mappingFunction and enters
2626 <     * it into the map unless null.  This is equivalent to
2627 <     * <pre> {@code
2628 <     * if (map.containsKey(key))
2629 <     *   return map.get(key);
2630 <     * value = mappingFunction.apply(key);
2631 <     * if (value != null)
2632 <     *   map.put(key, value);
2633 <     * return value;}</pre>
2634 <     *
2635 <     * except that the action is performed atomically.  If the
2636 <     * function returns {@code null} no mapping is recorded. If the
2637 <     * function itself throws an (unchecked) exception, the exception
2638 <     * is rethrown to its caller, and no mapping is recorded.  Some
2639 <     * attempted update operations on this map by other threads may be
2640 <     * blocked while computation is in progress, so the computation
2641 <     * should be short and simple, and must not attempt to update any
2642 <     * other mappings of this Map. The most appropriate usage is to
2643 <     * construct a new object serving as an initial mapped value, or
2644 <     * memoized result, as in:
2645 <     *
2646 <     *  <pre> {@code
2647 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2648 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2649 <     *
2650 <     * @param key key with which the specified value is to be associated
2651 <     * @param mappingFunction the function to compute a value
2652 <     * @return the current (existing or computed) value associated with
2653 <     *         the specified key, or null if the computed value is null
2654 <     * @throws NullPointerException if the specified key or mappingFunction
2655 <     *         is null
2656 <     * @throws IllegalStateException if the computation detectably
2657 <     *         attempts a recursive update to this map that would
2658 <     *         otherwise never complete
2659 <     * @throws RuntimeException or Error if the mappingFunction does so,
2660 <     *         in which case the mapping is left unestablished
2661 <     */
2662 <    @SuppressWarnings("unchecked") public V computeIfAbsent
2663 <        (K key, Fun<? super K, ? extends V> mappingFunction) {
2664 <        if (key == null || mappingFunction == null)
2665 <            throw new NullPointerException();
2666 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2667 <    }
2668 <
2669 <    /**
2670 <     * If the given key is present, computes a new mapping value given a key and
2671 <     * its current mapped value. This is equivalent to
2672 <     *  <pre> {@code
2673 <     *   if (map.containsKey(key)) {
2674 <     *     value = remappingFunction.apply(key, map.get(key));
2675 <     *     if (value != null)
2676 <     *       map.put(key, value);
2677 <     *     else
2678 <     *       map.remove(key);
2679 <     *   }
2680 <     * }</pre>
2681 <     *
2682 <     * except that the action is performed atomically.  If the
2683 <     * function returns {@code null}, the mapping is removed.  If the
2684 <     * function itself throws an (unchecked) exception, the exception
2685 <     * is rethrown to its caller, and the current mapping is left
2686 <     * unchanged.  Some attempted update operations on this map by
2687 <     * other threads may be blocked while computation is in progress,
2688 <     * so the computation should be short and simple, and must not
2689 <     * attempt to update any other mappings of this Map. For example,
2690 <     * to either create or append new messages to a value mapping:
2691 <     *
2692 <     * @param key key with which the specified value is to be associated
2693 <     * @param remappingFunction the function to compute a value
2694 <     * @return the new value associated with the specified key, or null if none
2695 <     * @throws NullPointerException if the specified key or remappingFunction
2696 <     *         is null
2697 <     * @throws IllegalStateException if the computation detectably
2698 <     *         attempts a recursive update to this map that would
2699 <     *         otherwise never complete
2700 <     * @throws RuntimeException or Error if the remappingFunction does so,
2701 <     *         in which case the mapping is unchanged
2702 <     */
2703 <    @SuppressWarnings("unchecked") public V computeIfPresent
2704 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2705 <        if (key == null || remappingFunction == null)
2706 <            throw new NullPointerException();
2707 <        return (V)internalCompute(key, true, remappingFunction);
2708 <    }
2709 <
2710 <    /**
2711 <     * Computes a new mapping value given a key and
2712 <     * its current mapped value (or {@code null} if there is no current
2713 <     * mapping). This is equivalent to
2714 <     *  <pre> {@code
2715 <     *   value = remappingFunction.apply(key, map.get(key));
2716 <     *   if (value != null)
2717 <     *     map.put(key, value);
2718 <     *   else
2719 <     *     map.remove(key);
2720 <     * }</pre>
2721 <     *
2722 <     * except that the action is performed atomically.  If the
2723 <     * function returns {@code null}, the mapping is removed.  If the
2724 <     * function itself throws an (unchecked) exception, the exception
2725 <     * is rethrown to its caller, and the current mapping is left
2726 <     * unchanged.  Some attempted update operations on this map by
2727 <     * other threads may be blocked while computation is in progress,
2728 <     * so the computation should be short and simple, and must not
2729 <     * attempt to update any other mappings of this Map. For example,
2730 <     * to either create or append new messages to a value mapping:
2731 <     *
2732 <     * <pre> {@code
2733 <     * Map<Key, String> map = ...;
2734 <     * final String msg = ...;
2735 <     * map.compute(key, new BiFun<Key, String, String>() {
2736 <     *   public String apply(Key k, String v) {
2737 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2738 <     *
2739 <     * @param key key with which the specified value is to be associated
2740 <     * @param remappingFunction the function to compute a value
2741 <     * @return the new value associated with the specified key, or null if none
2742 <     * @throws NullPointerException if the specified key or remappingFunction
2743 <     *         is null
2744 <     * @throws IllegalStateException if the computation detectably
2745 <     *         attempts a recursive update to this map that would
2746 <     *         otherwise never complete
2747 <     * @throws RuntimeException or Error if the remappingFunction does so,
2748 <     *         in which case the mapping is unchanged
2749 <     */
2750 <    @SuppressWarnings("unchecked") public V compute
2751 <        (K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2752 <        if (key == null || remappingFunction == null)
2753 <            throw new NullPointerException();
2754 <        return (V)internalCompute(key, false, remappingFunction);
2755 <    }
2756 <
2757 <    /**
2758 <     * If the specified key is not already associated
2759 <     * with a value, associate it with the given value.
2760 <     * Otherwise, replace the value with the results of
2761 <     * the given remapping function. This is equivalent to:
2762 <     *  <pre> {@code
2763 <     *   if (!map.containsKey(key))
2764 <     *     map.put(value);
2765 <     *   else {
2766 <     *     newValue = remappingFunction.apply(map.get(key), value);
2767 <     *     if (value != null)
2768 <     *       map.put(key, value);
2769 <     *     else
2770 <     *       map.remove(key);
2771 <     *   }
2772 <     * }</pre>
2773 <     * except that the action is performed atomically.  If the
2774 <     * function returns {@code null}, the mapping is removed.  If the
2775 <     * function itself throws an (unchecked) exception, the exception
2776 <     * is rethrown to its caller, and the current mapping is left
2777 <     * unchanged.  Some attempted update operations on this map by
2778 <     * other threads may be blocked while computation is in progress,
2779 <     * so the computation should be short and simple, and must not
2780 <     * attempt to update any other mappings of this Map.
2781 <     */
2782 <    @SuppressWarnings("unchecked") public V merge
2783 <        (K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2784 <        if (key == null || value == null || remappingFunction == null)
2785 <            throw new NullPointerException();
2786 <        return (V)internalMerge(key, value, remappingFunction);
1064 >        tryPresize(m.size());
1065 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1066 >            putVal(e.getKey(), e.getValue(), false);
1067      }
1068  
1069      /**
# Line 2795 | Line 1075 | public class ConcurrentHashMapV8<K, V>
1075       *         {@code null} if there was no mapping for {@code key}
1076       * @throws NullPointerException if the specified key is null
1077       */
1078 <    @SuppressWarnings("unchecked") public V remove(Object key) {
1079 <        if (key == null)
2800 <            throw new NullPointerException();
2801 <        return (V)internalReplace(key, null, null);
2802 <    }
2803 <
2804 <    /**
2805 <     * {@inheritDoc}
2806 <     *
2807 <     * @throws NullPointerException if the specified key is null
2808 <     */
2809 <    public boolean remove(Object key, Object value) {
2810 <        if (key == null)
2811 <            throw new NullPointerException();
2812 <        if (value == null)
2813 <            return false;
2814 <        return internalReplace(key, null, value) != null;
2815 <    }
2816 <
2817 <    /**
2818 <     * {@inheritDoc}
2819 <     *
2820 <     * @throws NullPointerException if any of the arguments are null
2821 <     */
2822 <    public boolean replace(K key, V oldValue, V newValue) {
2823 <        if (key == null || oldValue == null || newValue == null)
2824 <            throw new NullPointerException();
2825 <        return internalReplace(key, newValue, oldValue) != null;
1078 >    public V remove(Object key) {
1079 >        return replaceNode(key, null, null);
1080      }
1081  
1082      /**
1083 <     * {@inheritDoc}
1084 <     *
1085 <     * @return the previous value associated with the specified key,
2832 <     *         or {@code null} if there was no mapping for the key
2833 <     * @throws NullPointerException if the specified key or value is null
1083 >     * Implementation for the four public remove/replace methods:
1084 >     * Replaces node value with v, conditional upon match of cv if
1085 >     * non-null.  If resulting value is null, delete.
1086       */
1087 <    @SuppressWarnings("unchecked") public V replace(K key, V value) {
1088 <        if (key == null || value == null)
1089 <            throw new NullPointerException();
1090 <        return (V)internalReplace(key, value, null);
1087 >    final V replaceNode(Object key, V value, Object cv) {
1088 >        int hash = spread(key.hashCode());
1089 >        for (Node<K,V>[] tab = table;;) {
1090 >            Node<K,V> f; int n, i, fh;
1091 >            if (tab == null || (n = tab.length) == 0 ||
1092 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1093 >                break;
1094 >            else if ((fh = f.hash) == MOVED)
1095 >                tab = helpTransfer(tab, f);
1096 >            else {
1097 >                V oldVal = null;
1098 >                boolean validated = false;
1099 >                synchronized (f) {
1100 >                    if (tabAt(tab, i) == f) {
1101 >                        if (fh >= 0) {
1102 >                            validated = true;
1103 >                            for (Node<K,V> e = f, pred = null;;) {
1104 >                                K ek;
1105 >                                if (e.hash == hash &&
1106 >                                    ((ek = e.key) == key ||
1107 >                                     (ek != null && key.equals(ek)))) {
1108 >                                    V ev = e.val;
1109 >                                    if (cv == null || cv == ev ||
1110 >                                        (ev != null && cv.equals(ev))) {
1111 >                                        oldVal = ev;
1112 >                                        if (value != null)
1113 >                                            e.val = value;
1114 >                                        else if (pred != null)
1115 >                                            pred.next = e.next;
1116 >                                        else
1117 >                                            setTabAt(tab, i, e.next);
1118 >                                    }
1119 >                                    break;
1120 >                                }
1121 >                                pred = e;
1122 >                                if ((e = e.next) == null)
1123 >                                    break;
1124 >                            }
1125 >                        }
1126 >                        else if (f instanceof TreeBin) {
1127 >                            validated = true;
1128 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1129 >                            TreeNode<K,V> r, p;
1130 >                            if ((r = t.root) != null &&
1131 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1132 >                                V pv = p.val;
1133 >                                if (cv == null || cv == pv ||
1134 >                                    (pv != null && cv.equals(pv))) {
1135 >                                    oldVal = pv;
1136 >                                    if (value != null)
1137 >                                        p.val = value;
1138 >                                    else if (t.removeTreeNode(p))
1139 >                                        setTabAt(tab, i, untreeify(t.first));
1140 >                                }
1141 >                            }
1142 >                        }
1143 >                    }
1144 >                }
1145 >                if (validated) {
1146 >                    if (oldVal != null) {
1147 >                        if (value == null)
1148 >                            addCount(-1L, -1);
1149 >                        return oldVal;
1150 >                    }
1151 >                    break;
1152 >                }
1153 >            }
1154 >        }
1155 >        return null;
1156      }
1157  
1158      /**
1159       * Removes all of the mappings from this map.
1160       */
1161      public void clear() {
1162 <        internalClear();
1162 >        long delta = 0L; // negative number of deletions
1163 >        int i = 0;
1164 >        Node<K,V>[] tab = table;
1165 >        while (tab != null && i < tab.length) {
1166 >            int fh;
1167 >            Node<K,V> f = tabAt(tab, i);
1168 >            if (f == null)
1169 >                ++i;
1170 >            else if ((fh = f.hash) == MOVED) {
1171 >                tab = helpTransfer(tab, f);
1172 >                i = 0; // restart
1173 >            }
1174 >            else {
1175 >                synchronized (f) {
1176 >                    if (tabAt(tab, i) == f) {
1177 >                        Node<K,V> p = (fh >= 0 ? f :
1178 >                                       (f instanceof TreeBin) ?
1179 >                                       ((TreeBin<K,V>)f).first : null);
1180 >                        while (p != null) {
1181 >                            --delta;
1182 >                            p = p.next;
1183 >                        }
1184 >                        setTabAt(tab, i++, null);
1185 >                    }
1186 >                }
1187 >            }
1188 >        }
1189 >        if (delta != 0L)
1190 >            addCount(delta, -1);
1191      }
1192  
1193      /**
1194       * Returns a {@link Set} view of the keys contained in this map.
1195       * The set is backed by the map, so changes to the map are
1196 <     * reflected in the set, and vice-versa.  The set supports element
1196 >     * reflected in the set, and vice-versa. The set supports element
1197       * removal, which removes the corresponding mapping from this map,
1198       * via the {@code Iterator.remove}, {@code Set.remove},
1199       * {@code removeAll}, {@code retainAll}, and {@code clear}
# Line 2860 | Line 1205 | public class ConcurrentHashMapV8<K, V>
1205       * and guarantees to traverse elements as they existed upon
1206       * construction of the iterator, and may (but is not guaranteed to)
1207       * reflect any modifications subsequent to construction.
1208 +     *
1209 +     * @return the set view
1210       */
1211 <    public Set<K> keySet() {
1212 <        KeySet<K,V> ks = keySet;
1213 <        return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
1211 >    public KeySetView<K,V> keySet() {
1212 >        KeySetView<K,V> ks;
1213 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1214      }
1215  
1216      /**
# Line 2881 | Line 1228 | public class ConcurrentHashMapV8<K, V>
1228       * and guarantees to traverse elements as they existed upon
1229       * construction of the iterator, and may (but is not guaranteed to)
1230       * reflect any modifications subsequent to construction.
1231 +     *
1232 +     * @return the collection view
1233       */
1234      public Collection<V> values() {
1235 <        Values<K,V> vs = values;
1236 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
1235 >        ValuesView<K,V> vs;
1236 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1237      }
1238  
1239      /**
# Line 2894 | Line 1243 | public class ConcurrentHashMapV8<K, V>
1243       * removal, which removes the corresponding mapping from the map,
1244       * via the {@code Iterator.remove}, {@code Set.remove},
1245       * {@code removeAll}, {@code retainAll}, and {@code clear}
1246 <     * operations.  It does not support the {@code add} or
2898 <     * {@code addAll} operations.
1246 >     * operations.
1247       *
1248       * <p>The view's {@code iterator} is a "weakly consistent" iterator
1249       * that will never throw {@link ConcurrentModificationException},
1250       * and guarantees to traverse elements as they existed upon
1251       * construction of the iterator, and may (but is not guaranteed to)
1252       * reflect any modifications subsequent to construction.
2905     */
2906    public Set<Map.Entry<K,V>> entrySet() {
2907        EntrySet<K,V> es = entrySet;
2908        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2909    }
2910
2911    /**
2912     * Returns an enumeration of the keys in this table.
1253       *
1254 <     * @return an enumeration of the keys in this table
2915 <     * @see #keySet()
1254 >     * @return the set view
1255       */
1256 <    public Enumeration<K> keys() {
1257 <        return new KeyIterator<K,V>(this);
1258 <    }
2920 <
2921 <    /**
2922 <     * Returns an enumeration of the values in this table.
2923 <     *
2924 <     * @return an enumeration of the values in this table
2925 <     * @see #values()
2926 <     */
2927 <    public Enumeration<V> elements() {
2928 <        return new ValueIterator<K,V>(this);
2929 <    }
2930 <
2931 <    /**
2932 <     * Returns a partitionable iterator of the keys in this map.
2933 <     *
2934 <     * @return a partitionable iterator of the keys in this map
2935 <     */
2936 <    public Spliterator<K> keySpliterator() {
2937 <        return new KeyIterator<K,V>(this);
2938 <    }
2939 <
2940 <    /**
2941 <     * Returns a partitionable iterator of the values in this map.
2942 <     *
2943 <     * @return a partitionable iterator of the values in this map
2944 <     */
2945 <    public Spliterator<V> valueSpliterator() {
2946 <        return new ValueIterator<K,V>(this);
2947 <    }
2948 <
2949 <    /**
2950 <     * Returns a partitionable iterator of the entries in this map.
2951 <     *
2952 <     * @return a partitionable iterator of the entries in this map
2953 <     */
2954 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2955 <        return new EntryIterator<K,V>(this);
1256 >    public Set<Map.Entry<K,V>> entrySet() {
1257 >        EntrySetView<K,V> es;
1258 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1259      }
1260  
1261      /**
# Line 2964 | Line 1267 | public class ConcurrentHashMapV8<K, V>
1267       */
1268      public int hashCode() {
1269          int h = 0;
1270 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1271 <        Object v;
1272 <        while ((v = it.advance()) != null) {
1273 <            h += it.nextKey.hashCode() ^ v.hashCode();
1270 >        Node<K,V>[] t;
1271 >        if ((t = table) != null) {
1272 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1273 >            for (Node<K,V> p; (p = it.advance()) != null; )
1274 >                h += p.key.hashCode() ^ p.val.hashCode();
1275          }
1276          return h;
1277      }
# Line 2984 | Line 1288 | public class ConcurrentHashMapV8<K, V>
1288       * @return a string representation of this map
1289       */
1290      public String toString() {
1291 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1291 >        Node<K,V>[] t;
1292 >        int f = (t = table) == null ? 0 : t.length;
1293 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1294          StringBuilder sb = new StringBuilder();
1295          sb.append('{');
1296 <        Object v;
1297 <        if ((v = it.advance()) != null) {
1296 >        Node<K,V> p;
1297 >        if ((p = it.advance()) != null) {
1298              for (;;) {
1299 <                Object k = it.nextKey;
1299 >                K k = p.key;
1300 >                V v = p.val;
1301                  sb.append(k == this ? "(this Map)" : k);
1302                  sb.append('=');
1303                  sb.append(v == this ? "(this Map)" : v);
1304 <                if ((v = it.advance()) == null)
1304 >                if ((p = it.advance()) == null)
1305                      break;
1306                  sb.append(',').append(' ');
1307              }
# Line 3017 | Line 1324 | public class ConcurrentHashMapV8<K, V>
1324              if (!(o instanceof Map))
1325                  return false;
1326              Map<?,?> m = (Map<?,?>) o;
1327 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1328 <            Object val;
1329 <            while ((val = it.advance()) != null) {
1330 <                Object v = m.get(it.nextKey);
1327 >            Node<K,V>[] t;
1328 >            int f = (t = table) == null ? 0 : t.length;
1329 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1330 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1331 >                V val = p.val;
1332 >                Object v = m.get(p.key);
1333                  if (v == null || (v != val && !v.equals(val)))
1334                      return false;
1335              }
# Line 3028 | Line 1337 | public class ConcurrentHashMapV8<K, V>
1337                  Object mk, mv, v;
1338                  if ((mk = e.getKey()) == null ||
1339                      (mv = e.getValue()) == null ||
1340 <                    (v = internalGet(mk)) == null ||
1340 >                    (v = get(mk)) == null ||
1341                      (mv != v && !mv.equals(v)))
1342                      return false;
1343              }
# Line 3036 | Line 1345 | public class ConcurrentHashMapV8<K, V>
1345          return true;
1346      }
1347  
1348 <    /* ----------------Iterators -------------- */
1348 >    /**
1349 >     * Stripped-down version of helper class used in previous version,
1350 >     * declared for the sake of serialization compatibility
1351 >     */
1352 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1353 >        private static final long serialVersionUID = 2249069246763182397L;
1354 >        final float loadFactor;
1355 >        Segment(float lf) { this.loadFactor = lf; }
1356 >    }
1357  
1358 <    @SuppressWarnings("serial") static final class KeyIterator<K,V> extends Traverser<K,V,Object>
1359 <        implements Spliterator<K>, Enumeration<K> {
1360 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1361 <        KeyIterator(Traverser<K,V,Object> it) {
1362 <            super(it);
1363 <        }
1364 <        public KeyIterator<K,V> split() {
1365 <            if (last != null || (next != null && nextVal == null))
1366 <                throw new IllegalStateException();
1367 <            return new KeyIterator<K,V>(this);
1368 <        }
1369 <        @SuppressWarnings("unchecked") public final K next() {
1370 <            if (nextVal == null && advance() == null)
1371 <                throw new NoSuchElementException();
1372 <            Object k = nextKey;
1373 <            nextVal = null;
1374 <            return (K) k;
1358 >    /**
1359 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1360 >     * stream (i.e., serializes it).
1361 >     * @param s the stream
1362 >     * @serialData
1363 >     * the key (Object) and value (Object)
1364 >     * for each key-value mapping, followed by a null pair.
1365 >     * The key-value mappings are emitted in no particular order.
1366 >     */
1367 >    private void writeObject(java.io.ObjectOutputStream s)
1368 >        throws java.io.IOException {
1369 >        // For serialization compatibility
1370 >        // Emulate segment calculation from previous version of this class
1371 >        int sshift = 0;
1372 >        int ssize = 1;
1373 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1374 >            ++sshift;
1375 >            ssize <<= 1;
1376 >        }
1377 >        int segmentShift = 32 - sshift;
1378 >        int segmentMask = ssize - 1;
1379 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1380 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1381 >        for (int i = 0; i < segments.length; ++i)
1382 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1383 >        s.putFields().put("segments", segments);
1384 >        s.putFields().put("segmentShift", segmentShift);
1385 >        s.putFields().put("segmentMask", segmentMask);
1386 >        s.writeFields();
1387 >
1388 >        Node<K,V>[] t;
1389 >        if ((t = table) != null) {
1390 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1391 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1392 >                s.writeObject(p.key);
1393 >                s.writeObject(p.val);
1394 >            }
1395          }
1396 <
1397 <        public final K nextElement() { return next(); }
1396 >        s.writeObject(null);
1397 >        s.writeObject(null);
1398 >        segments = null; // throw away
1399      }
1400  
1401 <    @SuppressWarnings("serial") static final class ValueIterator<K,V> extends Traverser<K,V,Object>
1402 <        implements Spliterator<V>, Enumeration<V> {
1403 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1404 <        ValueIterator(Traverser<K,V,Object> it) {
1405 <            super(it);
1406 <        }
1407 <        public ValueIterator<K,V> split() {
1408 <            if (last != null || (next != null && nextVal == null))
1409 <                throw new IllegalStateException();
1410 <            return new ValueIterator<K,V>(this);
1401 >    /**
1402 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1403 >     * @param s the stream
1404 >     */
1405 >    private void readObject(java.io.ObjectInputStream s)
1406 >        throws java.io.IOException, ClassNotFoundException {
1407 >        /*
1408 >         * To improve performance in typical cases, we create nodes
1409 >         * while reading, then place in table once size is known.
1410 >         * However, we must also validate uniqueness and deal with
1411 >         * overpopulated bins while doing so, which requires
1412 >         * specialized versions of putVal mechanics.
1413 >         */
1414 >        sizeCtl = -1; // force exclusion for table construction
1415 >        s.defaultReadObject();
1416 >        long size = 0L;
1417 >        Node<K,V> p = null;
1418 >        for (;;) {
1419 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1420 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1421 >            if (k != null && v != null) {
1422 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1423 >                ++size;
1424 >            }
1425 >            else
1426 >                break;
1427          }
1428 <
1429 <        @SuppressWarnings("unchecked") public final V next() {
1430 <            Object v;
1431 <            if ((v = nextVal) == null && (v = advance()) == null)
1432 <                throw new NoSuchElementException();
1433 <            nextVal = null;
1434 <            return (V) v;
1428 >        if (size == 0L)
1429 >            sizeCtl = 0;
1430 >        else {
1431 >            int n;
1432 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1433 >                n = MAXIMUM_CAPACITY;
1434 >            else {
1435 >                int sz = (int)size;
1436 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1437 >            }
1438 >            @SuppressWarnings({"rawtypes","unchecked"})
1439 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1440 >            int mask = n - 1;
1441 >            long added = 0L;
1442 >            while (p != null) {
1443 >                boolean insertAtFront;
1444 >                Node<K,V> next = p.next, first;
1445 >                int h = p.hash, j = h & mask;
1446 >                if ((first = tabAt(tab, j)) == null)
1447 >                    insertAtFront = true;
1448 >                else {
1449 >                    K k = p.key;
1450 >                    if (first.hash < 0) {
1451 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1452 >                        if (t.putTreeVal(h, k, p.val) == null)
1453 >                            ++added;
1454 >                        insertAtFront = false;
1455 >                    }
1456 >                    else {
1457 >                        int binCount = 0;
1458 >                        insertAtFront = true;
1459 >                        Node<K,V> q; K qk;
1460 >                        for (q = first; q != null; q = q.next) {
1461 >                            if (q.hash == h &&
1462 >                                ((qk = q.key) == k ||
1463 >                                 (qk != null && k.equals(qk)))) {
1464 >                                insertAtFront = false;
1465 >                                break;
1466 >                            }
1467 >                            ++binCount;
1468 >                        }
1469 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1470 >                            insertAtFront = false;
1471 >                            ++added;
1472 >                            p.next = first;
1473 >                            TreeNode<K,V> hd = null, tl = null;
1474 >                            for (q = p; q != null; q = q.next) {
1475 >                                TreeNode<K,V> t = new TreeNode<K,V>
1476 >                                    (q.hash, q.key, q.val, null, null);
1477 >                                if ((t.prev = tl) == null)
1478 >                                    hd = t;
1479 >                                else
1480 >                                    tl.next = t;
1481 >                                tl = t;
1482 >                            }
1483 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1484 >                        }
1485 >                    }
1486 >                }
1487 >                if (insertAtFront) {
1488 >                    ++added;
1489 >                    p.next = first;
1490 >                    setTabAt(tab, j, p);
1491 >                }
1492 >                p = next;
1493 >            }
1494 >            table = tab;
1495 >            sizeCtl = n - (n >>> 2);
1496 >            baseCount = added;
1497          }
3082
3083        public final V nextElement() { return next(); }
1498      }
1499  
1500 <    @SuppressWarnings("serial") static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3087 <        implements Spliterator<Map.Entry<K,V>> {
3088 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3089 <        EntryIterator(Traverser<K,V,Object> it) {
3090 <            super(it);
3091 <        }
3092 <        public EntryIterator<K,V> split() {
3093 <            if (last != null || (next != null && nextVal == null))
3094 <                throw new IllegalStateException();
3095 <            return new EntryIterator<K,V>(this);
3096 <        }
1500 >    // ConcurrentMap methods
1501  
1502 <        @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
1503 <            Object v;
1504 <            if ((v = nextVal) == null && (v = advance()) == null)
1505 <                throw new NoSuchElementException();
1506 <            Object k = nextKey;
1507 <            nextVal = null;
1508 <            return new MapEntry<K,V>((K)k, (V)v, map);
1509 <        }
1502 >    /**
1503 >     * {@inheritDoc}
1504 >     *
1505 >     * @return the previous value associated with the specified key,
1506 >     *         or {@code null} if there was no mapping for the key
1507 >     * @throws NullPointerException if the specified key or value is null
1508 >     */
1509 >    public V putIfAbsent(K key, V value) {
1510 >        return putVal(key, value, true);
1511      }
1512  
1513      /**
1514 <     * Exported Entry for iterators
1514 >     * {@inheritDoc}
1515 >     *
1516 >     * @throws NullPointerException if the specified key is null
1517       */
1518 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
1519 <        final K key; // non-null
1520 <        V val;       // non-null
1521 <        final ConcurrentHashMapV8<K, V> map;
3115 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3116 <            this.key = key;
3117 <            this.val = val;
3118 <            this.map = map;
3119 <        }
3120 <        public final K getKey()       { return key; }
3121 <        public final V getValue()     { return val; }
3122 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3123 <        public final String toString(){ return key + "=" + val; }
3124 <
3125 <        public final boolean equals(Object o) {
3126 <            Object k, v; Map.Entry<?,?> e;
3127 <            return ((o instanceof Map.Entry) &&
3128 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3129 <                    (v = e.getValue()) != null &&
3130 <                    (k == key || k.equals(key)) &&
3131 <                    (v == val || v.equals(val)));
3132 <        }
3133 <
3134 <        /**
3135 <         * Sets our entry's value and writes through to the map. The
3136 <         * value to return is somewhat arbitrary here. Since we do not
3137 <         * necessarily track asynchronous changes, the most recent
3138 <         * "previous" value could be different from what we return (or
3139 <         * could even have been removed in which case the put will
3140 <         * re-establish). We do not and cannot guarantee more.
3141 <         */
3142 <        public final V setValue(V value) {
3143 <            if (value == null) throw new NullPointerException();
3144 <            V v = val;
3145 <            val = value;
3146 <            map.put(key, value);
3147 <            return v;
3148 <        }
1518 >    public boolean remove(Object key, Object value) {
1519 >        if (key == null)
1520 >            throw new NullPointerException();
1521 >        return value != null && replaceNode(key, null, value) != null;
1522      }
1523  
1524 <    /* ----------------Views -------------- */
1524 >    /**
1525 >     * {@inheritDoc}
1526 >     *
1527 >     * @throws NullPointerException if any of the arguments are null
1528 >     */
1529 >    public boolean replace(K key, V oldValue, V newValue) {
1530 >        if (key == null || oldValue == null || newValue == null)
1531 >            throw new NullPointerException();
1532 >        return replaceNode(key, newValue, oldValue) != null;
1533 >    }
1534  
1535      /**
1536 <     * Base class for views.
1536 >     * {@inheritDoc}
1537 >     *
1538 >     * @return the previous value associated with the specified key,
1539 >     *         or {@code null} if there was no mapping for the key
1540 >     * @throws NullPointerException if the specified key or value is null
1541       */
1542 <    static abstract class CHMView<K, V> {
1543 <        final ConcurrentHashMapV8<K, V> map;
1544 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
1545 <        public final int size()                 { return map.size(); }
1546 <        public final boolean isEmpty()          { return map.isEmpty(); }
3161 <        public final void clear()               { map.clear(); }
1542 >    public V replace(K key, V value) {
1543 >        if (key == null || value == null)
1544 >            throw new NullPointerException();
1545 >        return replaceNode(key, value, null);
1546 >    }
1547  
1548 <        // implementations below rely on concrete classes supplying these
3164 <        abstract public Iterator<?> iterator();
3165 <        abstract public boolean contains(Object o);
3166 <        abstract public boolean remove(Object o);
1548 >    // Overrides of JDK8+ Map extension method defaults
1549  
1550 <        private static final String oomeMsg = "Required array size too large";
1550 >    /**
1551 >     * Returns the value to which the specified key is mapped, or the
1552 >     * given default value if this map contains no mapping for the
1553 >     * key.
1554 >     *
1555 >     * @param key the key whose associated value is to be returned
1556 >     * @param defaultValue the value to return if this map contains
1557 >     * no mapping for the given key
1558 >     * @return the mapping for the key, if present; else the default value
1559 >     * @throws NullPointerException if the specified key is null
1560 >     */
1561 >    public V getOrDefault(Object key, V defaultValue) {
1562 >        V v;
1563 >        return (v = get(key)) == null ? defaultValue : v;
1564 >    }
1565 >
1566 >    public void forEach(BiAction<? super K, ? super V> action) {
1567 >        if (action == null) throw new NullPointerException();
1568 >        Node<K,V>[] t;
1569 >        if ((t = table) != null) {
1570 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1571 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1572 >                action.apply(p.key, p.val);
1573 >            }
1574 >        }
1575 >    }
1576  
1577 <        public final Object[] toArray() {
1578 <            long sz = map.mappingCount();
1579 <            if (sz > (long)(MAX_ARRAY_SIZE))
1580 <                throw new OutOfMemoryError(oomeMsg);
1581 <            int n = (int)sz;
1582 <            Object[] r = new Object[n];
1583 <            int i = 0;
1584 <            Iterator<?> it = iterator();
1585 <            while (it.hasNext()) {
1586 <                if (i == n) {
1587 <                    if (n >= MAX_ARRAY_SIZE)
1588 <                        throw new OutOfMemoryError(oomeMsg);
1589 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1590 <                        n = MAX_ARRAY_SIZE;
3184 <                    else
3185 <                        n += (n >>> 1) + 1;
3186 <                    r = Arrays.copyOf(r, n);
1577 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1578 >        if (function == null) throw new NullPointerException();
1579 >        Node<K,V>[] t;
1580 >        if ((t = table) != null) {
1581 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1582 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1583 >                V oldValue = p.val;
1584 >                for (K key = p.key;;) {
1585 >                    V newValue = function.apply(key, oldValue);
1586 >                    if (newValue == null)
1587 >                        throw new NullPointerException();
1588 >                    if (replaceNode(key, newValue, oldValue) != null ||
1589 >                        (oldValue = get(key)) == null)
1590 >                        break;
1591                  }
3188                r[i++] = it.next();
1592              }
3190            return (i == n) ? r : Arrays.copyOf(r, i);
1593          }
1594 +    }
1595  
1596 <        @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
1597 <            long sz = map.mappingCount();
1598 <            if (sz > (long)(MAX_ARRAY_SIZE))
1599 <                throw new OutOfMemoryError(oomeMsg);
1600 <            int m = (int)sz;
1601 <            T[] r = (a.length >= m) ? a :
1602 <                (T[])java.lang.reflect.Array
1603 <                .newInstance(a.getClass().getComponentType(), m);
1604 <            int n = r.length;
1605 <            int i = 0;
1606 <            Iterator<?> it = iterator();
1607 <            while (it.hasNext()) {
1608 <                if (i == n) {
1609 <                    if (n >= MAX_ARRAY_SIZE)
1610 <                        throw new OutOfMemoryError(oomeMsg);
1611 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1612 <                        n = MAX_ARRAY_SIZE;
1613 <                    else
1614 <                        n += (n >>> 1) + 1;
1615 <                    r = Arrays.copyOf(r, n);
1596 >    /**
1597 >     * If the specified key is not already associated with a value,
1598 >     * attempts to compute its value using the given mapping function
1599 >     * and enters it into this map unless {@code null}.  The entire
1600 >     * method invocation is performed atomically, so the function is
1601 >     * applied at most once per key.  Some attempted update operations
1602 >     * on this map by other threads may be blocked while computation
1603 >     * is in progress, so the computation should be short and simple,
1604 >     * and must not attempt to update any other mappings of this map.
1605 >     *
1606 >     * @param key key with which the specified value is to be associated
1607 >     * @param mappingFunction the function to compute a value
1608 >     * @return the current (existing or computed) value associated with
1609 >     *         the specified key, or null if the computed value is null
1610 >     * @throws NullPointerException if the specified key or mappingFunction
1611 >     *         is null
1612 >     * @throws IllegalStateException if the computation detectably
1613 >     *         attempts a recursive update to this map that would
1614 >     *         otherwise never complete
1615 >     * @throws RuntimeException or Error if the mappingFunction does so,
1616 >     *         in which case the mapping is left unestablished
1617 >     */
1618 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1619 >        if (key == null || mappingFunction == null)
1620 >            throw new NullPointerException();
1621 >        int h = spread(key.hashCode());
1622 >        V val = null;
1623 >        int binCount = 0;
1624 >        for (Node<K,V>[] tab = table;;) {
1625 >            Node<K,V> f; int n, i, fh;
1626 >            if (tab == null || (n = tab.length) == 0)
1627 >                tab = initTable();
1628 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1629 >                Node<K,V> r = new ReservationNode<K,V>();
1630 >                synchronized (r) {
1631 >                    if (casTabAt(tab, i, null, r)) {
1632 >                        binCount = 1;
1633 >                        Node<K,V> node = null;
1634 >                        try {
1635 >                            if ((val = mappingFunction.apply(key)) != null)
1636 >                                node = new Node<K,V>(h, key, val, null);
1637 >                        } finally {
1638 >                            setTabAt(tab, i, node);
1639 >                        }
1640 >                    }
1641                  }
1642 <                r[i++] = (T)it.next();
1642 >                if (binCount != 0)
1643 >                    break;
1644              }
1645 <            if (a == r && i < n) {
1646 <                r[i] = null; // null-terminate
1647 <                return r;
1645 >            else if ((fh = f.hash) == MOVED)
1646 >                tab = helpTransfer(tab, f);
1647 >            else {
1648 >                boolean added = false;
1649 >                synchronized (f) {
1650 >                    if (tabAt(tab, i) == f) {
1651 >                        if (fh >= 0) {
1652 >                            binCount = 1;
1653 >                            for (Node<K,V> e = f;; ++binCount) {
1654 >                                K ek; V ev;
1655 >                                if (e.hash == h &&
1656 >                                    ((ek = e.key) == key ||
1657 >                                     (ek != null && key.equals(ek)))) {
1658 >                                    val = e.val;
1659 >                                    break;
1660 >                                }
1661 >                                Node<K,V> pred = e;
1662 >                                if ((e = e.next) == null) {
1663 >                                    if ((val = mappingFunction.apply(key)) != null) {
1664 >                                        added = true;
1665 >                                        pred.next = new Node<K,V>(h, key, val, null);
1666 >                                    }
1667 >                                    break;
1668 >                                }
1669 >                            }
1670 >                        }
1671 >                        else if (f instanceof TreeBin) {
1672 >                            binCount = 2;
1673 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1674 >                            TreeNode<K,V> r, p;
1675 >                            if ((r = t.root) != null &&
1676 >                                (p = r.findTreeNode(h, key, null)) != null)
1677 >                                val = p.val;
1678 >                            else if ((val = mappingFunction.apply(key)) != null) {
1679 >                                added = true;
1680 >                                t.putTreeVal(h, key, val);
1681 >                            }
1682 >                        }
1683 >                    }
1684 >                }
1685 >                if (binCount != 0) {
1686 >                    if (binCount >= TREEIFY_THRESHOLD)
1687 >                        treeifyBin(tab, i);
1688 >                    if (!added)
1689 >                        return val;
1690 >                    break;
1691 >                }
1692              }
3220            return (i == n) ? r : Arrays.copyOf(r, i);
3221        }
3222
3223        public final int hashCode() {
3224            int h = 0;
3225            for (Iterator<?> it = iterator(); it.hasNext();)
3226                h += it.next().hashCode();
3227            return h;
1693          }
1694 +        if (val != null)
1695 +            addCount(1L, binCount);
1696 +        return val;
1697 +    }
1698  
1699 <        public final String toString() {
1700 <            StringBuilder sb = new StringBuilder();
1701 <            sb.append('[');
1702 <            Iterator<?> it = iterator();
1703 <            if (it.hasNext()) {
1704 <                for (;;) {
1705 <                    Object e = it.next();
1706 <                    sb.append(e == this ? "(this Collection)" : e);
1707 <                    if (!it.hasNext())
1708 <                        break;
1709 <                    sb.append(',').append(' ');
1699 >    /**
1700 >     * If the value for the specified key is present, attempts to
1701 >     * compute a new mapping given the key and its current mapped
1702 >     * value.  The entire method invocation is performed atomically.
1703 >     * Some attempted update operations on this map by other threads
1704 >     * may be blocked while computation is in progress, so the
1705 >     * computation should be short and simple, and must not attempt to
1706 >     * update any other mappings of this map.
1707 >     *
1708 >     * @param key key with which a value may be associated
1709 >     * @param remappingFunction the function to compute a value
1710 >     * @return the new value associated with the specified key, or null if none
1711 >     * @throws NullPointerException if the specified key or remappingFunction
1712 >     *         is null
1713 >     * @throws IllegalStateException if the computation detectably
1714 >     *         attempts a recursive update to this map that would
1715 >     *         otherwise never complete
1716 >     * @throws RuntimeException or Error if the remappingFunction does so,
1717 >     *         in which case the mapping is unchanged
1718 >     */
1719 >    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1720 >        if (key == null || remappingFunction == null)
1721 >            throw new NullPointerException();
1722 >        int h = spread(key.hashCode());
1723 >        V val = null;
1724 >        int delta = 0;
1725 >        int binCount = 0;
1726 >        for (Node<K,V>[] tab = table;;) {
1727 >            Node<K,V> f; int n, i, fh;
1728 >            if (tab == null || (n = tab.length) == 0)
1729 >                tab = initTable();
1730 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1731 >                break;
1732 >            else if ((fh = f.hash) == MOVED)
1733 >                tab = helpTransfer(tab, f);
1734 >            else {
1735 >                synchronized (f) {
1736 >                    if (tabAt(tab, i) == f) {
1737 >                        if (fh >= 0) {
1738 >                            binCount = 1;
1739 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1740 >                                K ek;
1741 >                                if (e.hash == h &&
1742 >                                    ((ek = e.key) == key ||
1743 >                                     (ek != null && key.equals(ek)))) {
1744 >                                    val = remappingFunction.apply(key, e.val);
1745 >                                    if (val != null)
1746 >                                        e.val = val;
1747 >                                    else {
1748 >                                        delta = -1;
1749 >                                        Node<K,V> en = e.next;
1750 >                                        if (pred != null)
1751 >                                            pred.next = en;
1752 >                                        else
1753 >                                            setTabAt(tab, i, en);
1754 >                                    }
1755 >                                    break;
1756 >                                }
1757 >                                pred = e;
1758 >                                if ((e = e.next) == null)
1759 >                                    break;
1760 >                            }
1761 >                        }
1762 >                        else if (f instanceof TreeBin) {
1763 >                            binCount = 2;
1764 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1765 >                            TreeNode<K,V> r, p;
1766 >                            if ((r = t.root) != null &&
1767 >                                (p = r.findTreeNode(h, key, null)) != null) {
1768 >                                val = remappingFunction.apply(key, p.val);
1769 >                                if (val != null)
1770 >                                    p.val = val;
1771 >                                else {
1772 >                                    delta = -1;
1773 >                                    if (t.removeTreeNode(p))
1774 >                                        setTabAt(tab, i, untreeify(t.first));
1775 >                                }
1776 >                            }
1777 >                        }
1778 >                    }
1779                  }
1780 +                if (binCount != 0)
1781 +                    break;
1782              }
3243            return sb.append(']').toString();
1783          }
1784 +        if (delta != 0)
1785 +            addCount((long)delta, binCount);
1786 +        return val;
1787 +    }
1788  
1789 <        public final boolean containsAll(Collection<?> c) {
1790 <            if (c != this) {
1791 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
1792 <                    Object e = it.next();
1793 <                    if (e == null || !contains(e))
1794 <                        return false;
1789 >    /**
1790 >     * Attempts to compute a mapping for the specified key and its
1791 >     * current mapped value (or {@code null} if there is no current
1792 >     * mapping). The entire method invocation is performed atomically.
1793 >     * Some attempted update operations on this map by other threads
1794 >     * may be blocked while computation is in progress, so the
1795 >     * computation should be short and simple, and must not attempt to
1796 >     * update any other mappings of this Map.
1797 >     *
1798 >     * @param key key with which the specified value is to be associated
1799 >     * @param remappingFunction the function to compute a value
1800 >     * @return the new value associated with the specified key, or null if none
1801 >     * @throws NullPointerException if the specified key or remappingFunction
1802 >     *         is null
1803 >     * @throws IllegalStateException if the computation detectably
1804 >     *         attempts a recursive update to this map that would
1805 >     *         otherwise never complete
1806 >     * @throws RuntimeException or Error if the remappingFunction does so,
1807 >     *         in which case the mapping is unchanged
1808 >     */
1809 >    public V compute(K key,
1810 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1811 >        if (key == null || remappingFunction == null)
1812 >            throw new NullPointerException();
1813 >        int h = spread(key.hashCode());
1814 >        V val = null;
1815 >        int delta = 0;
1816 >        int binCount = 0;
1817 >        for (Node<K,V>[] tab = table;;) {
1818 >            Node<K,V> f; int n, i, fh;
1819 >            if (tab == null || (n = tab.length) == 0)
1820 >                tab = initTable();
1821 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1822 >                Node<K,V> r = new ReservationNode<K,V>();
1823 >                synchronized (r) {
1824 >                    if (casTabAt(tab, i, null, r)) {
1825 >                        binCount = 1;
1826 >                        Node<K,V> node = null;
1827 >                        try {
1828 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1829 >                                delta = 1;
1830 >                                node = new Node<K,V>(h, key, val, null);
1831 >                            }
1832 >                        } finally {
1833 >                            setTabAt(tab, i, node);
1834 >                        }
1835 >                    }
1836                  }
1837 +                if (binCount != 0)
1838 +                    break;
1839              }
1840 <            return true;
1841 <        }
1842 <
1843 <        public final boolean removeAll(Collection<?> c) {
1844 <            boolean modified = false;
1845 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1846 <                if (c.contains(it.next())) {
1847 <                    it.remove();
1848 <                    modified = true;
1840 >            else if ((fh = f.hash) == MOVED)
1841 >                tab = helpTransfer(tab, f);
1842 >            else {
1843 >                synchronized (f) {
1844 >                    if (tabAt(tab, i) == f) {
1845 >                        if (fh >= 0) {
1846 >                            binCount = 1;
1847 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1848 >                                K ek;
1849 >                                if (e.hash == h &&
1850 >                                    ((ek = e.key) == key ||
1851 >                                     (ek != null && key.equals(ek)))) {
1852 >                                    val = remappingFunction.apply(key, e.val);
1853 >                                    if (val != null)
1854 >                                        e.val = val;
1855 >                                    else {
1856 >                                        delta = -1;
1857 >                                        Node<K,V> en = e.next;
1858 >                                        if (pred != null)
1859 >                                            pred.next = en;
1860 >                                        else
1861 >                                            setTabAt(tab, i, en);
1862 >                                    }
1863 >                                    break;
1864 >                                }
1865 >                                pred = e;
1866 >                                if ((e = e.next) == null) {
1867 >                                    val = remappingFunction.apply(key, null);
1868 >                                    if (val != null) {
1869 >                                        delta = 1;
1870 >                                        pred.next =
1871 >                                            new Node<K,V>(h, key, val, null);
1872 >                                    }
1873 >                                    break;
1874 >                                }
1875 >                            }
1876 >                        }
1877 >                        else if (f instanceof TreeBin) {
1878 >                            binCount = 1;
1879 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1880 >                            TreeNode<K,V> r, p;
1881 >                            if ((r = t.root) != null)
1882 >                                p = r.findTreeNode(h, key, null);
1883 >                            else
1884 >                                p = null;
1885 >                            V pv = (p == null) ? null : p.val;
1886 >                            val = remappingFunction.apply(key, pv);
1887 >                            if (val != null) {
1888 >                                if (p != null)
1889 >                                    p.val = val;
1890 >                                else {
1891 >                                    delta = 1;
1892 >                                    t.putTreeVal(h, key, val);
1893 >                                }
1894 >                            }
1895 >                            else if (p != null) {
1896 >                                delta = -1;
1897 >                                if (t.removeTreeNode(p))
1898 >                                    setTabAt(tab, i, untreeify(t.first));
1899 >                            }
1900 >                        }
1901 >                    }
1902 >                }
1903 >                if (binCount != 0) {
1904 >                    if (binCount >= TREEIFY_THRESHOLD)
1905 >                        treeifyBin(tab, i);
1906 >                    break;
1907                  }
1908              }
3265            return modified;
1909          }
1910 +        if (delta != 0)
1911 +            addCount((long)delta, binCount);
1912 +        return val;
1913 +    }
1914  
1915 <        public final boolean retainAll(Collection<?> c) {
1916 <            boolean modified = false;
1917 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1918 <                if (!c.contains(it.next())) {
1919 <                    it.remove();
1920 <                    modified = true;
1915 >    /**
1916 >     * If the specified key is not already associated with a
1917 >     * (non-null) value, associates it with the given value.
1918 >     * Otherwise, replaces the value with the results of the given
1919 >     * remapping function, or removes if {@code null}. The entire
1920 >     * method invocation is performed atomically.  Some attempted
1921 >     * update operations on this map by other threads may be blocked
1922 >     * while computation is in progress, so the computation should be
1923 >     * short and simple, and must not attempt to update any other
1924 >     * mappings of this Map.
1925 >     *
1926 >     * @param key key with which the specified value is to be associated
1927 >     * @param value the value to use if absent
1928 >     * @param remappingFunction the function to recompute a value if present
1929 >     * @return the new value associated with the specified key, or null if none
1930 >     * @throws NullPointerException if the specified key or the
1931 >     *         remappingFunction is null
1932 >     * @throws RuntimeException or Error if the remappingFunction does so,
1933 >     *         in which case the mapping is unchanged
1934 >     */
1935 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1936 >        if (key == null || value == null || remappingFunction == null)
1937 >            throw new NullPointerException();
1938 >        int h = spread(key.hashCode());
1939 >        V val = null;
1940 >        int delta = 0;
1941 >        int binCount = 0;
1942 >        for (Node<K,V>[] tab = table;;) {
1943 >            Node<K,V> f; int n, i, fh;
1944 >            if (tab == null || (n = tab.length) == 0)
1945 >                tab = initTable();
1946 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1947 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1948 >                    delta = 1;
1949 >                    val = value;
1950 >                    break;
1951 >                }
1952 >            }
1953 >            else if ((fh = f.hash) == MOVED)
1954 >                tab = helpTransfer(tab, f);
1955 >            else {
1956 >                synchronized (f) {
1957 >                    if (tabAt(tab, i) == f) {
1958 >                        if (fh >= 0) {
1959 >                            binCount = 1;
1960 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1961 >                                K ek;
1962 >                                if (e.hash == h &&
1963 >                                    ((ek = e.key) == key ||
1964 >                                     (ek != null && key.equals(ek)))) {
1965 >                                    val = remappingFunction.apply(e.val, value);
1966 >                                    if (val != null)
1967 >                                        e.val = val;
1968 >                                    else {
1969 >                                        delta = -1;
1970 >                                        Node<K,V> en = e.next;
1971 >                                        if (pred != null)
1972 >                                            pred.next = en;
1973 >                                        else
1974 >                                            setTabAt(tab, i, en);
1975 >                                    }
1976 >                                    break;
1977 >                                }
1978 >                                pred = e;
1979 >                                if ((e = e.next) == null) {
1980 >                                    delta = 1;
1981 >                                    val = value;
1982 >                                    pred.next =
1983 >                                        new Node<K,V>(h, key, val, null);
1984 >                                    break;
1985 >                                }
1986 >                            }
1987 >                        }
1988 >                        else if (f instanceof TreeBin) {
1989 >                            binCount = 2;
1990 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1991 >                            TreeNode<K,V> r = t.root;
1992 >                            TreeNode<K,V> p = (r == null) ? null :
1993 >                                r.findTreeNode(h, key, null);
1994 >                            val = (p == null) ? value :
1995 >                                remappingFunction.apply(p.val, value);
1996 >                            if (val != null) {
1997 >                                if (p != null)
1998 >                                    p.val = val;
1999 >                                else {
2000 >                                    delta = 1;
2001 >                                    t.putTreeVal(h, key, val);
2002 >                                }
2003 >                            }
2004 >                            else if (p != null) {
2005 >                                delta = -1;
2006 >                                if (t.removeTreeNode(p))
2007 >                                    setTabAt(tab, i, untreeify(t.first));
2008 >                            }
2009 >                        }
2010 >                    }
2011 >                }
2012 >                if (binCount != 0) {
2013 >                    if (binCount >= TREEIFY_THRESHOLD)
2014 >                        treeifyBin(tab, i);
2015 >                    break;
2016                  }
2017              }
3276            return modified;
2018          }
2019 +        if (delta != 0)
2020 +            addCount((long)delta, binCount);
2021 +        return val;
2022 +    }
2023  
2024 +    // Hashtable legacy methods
2025 +
2026 +    /**
2027 +     * Legacy method testing if some key maps into the specified value
2028 +     * in this table.  This method is identical in functionality to
2029 +     * {@link #containsValue(Object)}, and exists solely to ensure
2030 +     * full compatibility with class {@link java.util.Hashtable},
2031 +     * which supported this method prior to introduction of the
2032 +     * Java Collections framework.
2033 +     *
2034 +     * @param  value a value to search for
2035 +     * @return {@code true} if and only if some key maps to the
2036 +     *         {@code value} argument in this table as
2037 +     *         determined by the {@code equals} method;
2038 +     *         {@code false} otherwise
2039 +     * @throws NullPointerException if the specified value is null
2040 +     */
2041 +    @Deprecated public boolean contains(Object value) {
2042 +        return containsValue(value);
2043      }
2044  
2045 <    static final class KeySet<K,V> extends CHMView<K,V> implements Set<K> {
2046 <        KeySet(ConcurrentHashMapV8<K, V> map)  {
2047 <            super(map);
2048 <        }
2049 <        public final boolean contains(Object o) { return map.containsKey(o); }
2050 <        public final boolean remove(Object o)   { return map.remove(o) != null; }
2051 <        public final Iterator<K> iterator() {
2052 <            return new KeyIterator<K,V>(map);
2053 <        }
2054 <        public final boolean add(K e) {
3291 <            throw new UnsupportedOperationException();
3292 <        }
3293 <        public final boolean addAll(Collection<? extends K> c) {
3294 <            throw new UnsupportedOperationException();
3295 <        }
3296 <        public boolean equals(Object o) {
3297 <            Set<?> c;
3298 <            return ((o instanceof Set) &&
3299 <                    ((c = (Set<?>)o) == this ||
3300 <                     (containsAll(c) && c.containsAll(this))));
3301 <        }
2045 >    /**
2046 >     * Returns an enumeration of the keys in this table.
2047 >     *
2048 >     * @return an enumeration of the keys in this table
2049 >     * @see #keySet()
2050 >     */
2051 >    public Enumeration<K> keys() {
2052 >        Node<K,V>[] t;
2053 >        int f = (t = table) == null ? 0 : t.length;
2054 >        return new KeyIterator<K,V>(t, f, 0, f, this);
2055      }
2056  
2057 +    /**
2058 +     * Returns an enumeration of the values in this table.
2059 +     *
2060 +     * @return an enumeration of the values in this table
2061 +     * @see #values()
2062 +     */
2063 +    public Enumeration<V> elements() {
2064 +        Node<K,V>[] t;
2065 +        int f = (t = table) == null ? 0 : t.length;
2066 +        return new ValueIterator<K,V>(t, f, 0, f, this);
2067 +    }
2068  
2069 <    static final class Values<K,V> extends CHMView<K,V>
3306 <        implements Collection<V> {
3307 <        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
3308 <        public final boolean contains(Object o) { return map.containsValue(o); }
3309 <        public final boolean remove(Object o) {
3310 <            if (o != null) {
3311 <                Iterator<V> it = new ValueIterator<K,V>(map);
3312 <                while (it.hasNext()) {
3313 <                    if (o.equals(it.next())) {
3314 <                        it.remove();
3315 <                        return true;
3316 <                    }
3317 <                }
3318 <            }
3319 <            return false;
3320 <        }
3321 <        public final Iterator<V> iterator() {
3322 <            return new ValueIterator<K,V>(map);
3323 <        }
3324 <        public final boolean add(V e) {
3325 <            throw new UnsupportedOperationException();
3326 <        }
3327 <        public final boolean addAll(Collection<? extends V> c) {
3328 <            throw new UnsupportedOperationException();
3329 <        }
2069 >    // ConcurrentHashMapV8-only methods
2070  
2071 +    /**
2072 +     * Returns the number of mappings. This method should be used
2073 +     * instead of {@link #size} because a ConcurrentHashMapV8 may
2074 +     * contain more mappings than can be represented as an int. The
2075 +     * value returned is an estimate; the actual count may differ if
2076 +     * there are concurrent insertions or removals.
2077 +     *
2078 +     * @return the number of mappings
2079 +     * @since 1.8
2080 +     */
2081 +    public long mappingCount() {
2082 +        long n = sumCount();
2083 +        return (n < 0L) ? 0L : n; // ignore transient negative values
2084      }
2085  
2086 <    static final class EntrySet<K,V> extends CHMView<K,V>
2087 <        implements Set<Map.Entry<K,V>> {
2088 <        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2089 <        public final boolean contains(Object o) {
2090 <            Object k, v, r; Map.Entry<?,?> e;
2091 <            return ((o instanceof Map.Entry) &&
2092 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2093 <                    (r = map.get(k)) != null &&
2094 <                    (v = e.getValue()) != null &&
2095 <                    (v == r || v.equals(r)));
3343 <        }
3344 <        public final boolean remove(Object o) {
3345 <            Object k, v; Map.Entry<?,?> e;
3346 <            return ((o instanceof Map.Entry) &&
3347 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3348 <                    (v = e.getValue()) != null &&
3349 <                    map.remove(k, v));
3350 <        }
3351 <        public final Iterator<Map.Entry<K,V>> iterator() {
3352 <            return new EntryIterator<K,V>(map);
3353 <        }
3354 <        public final boolean add(Entry<K,V> e) {
3355 <            throw new UnsupportedOperationException();
3356 <        }
3357 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3358 <            throw new UnsupportedOperationException();
3359 <        }
3360 <        public boolean equals(Object o) {
3361 <            Set<?> c;
3362 <            return ((o instanceof Set) &&
3363 <                    ((c = (Set<?>)o) == this ||
3364 <                     (containsAll(c) && c.containsAll(this))));
3365 <        }
2086 >    /**
2087 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2088 >     * from the given type to {@code Boolean.TRUE}.
2089 >     *
2090 >     * @return the new set
2091 >     * @since 1.8
2092 >     */
2093 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2094 >        return new KeySetView<K,Boolean>
2095 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2096      }
2097  
2098 <    /* ---------------- Serialization Support -------------- */
2098 >    /**
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2100 >     * from the given type to {@code Boolean.TRUE}.
2101 >     *
2102 >     * @param initialCapacity The implementation performs internal
2103 >     * sizing to accommodate this many elements.
2104 >     * @throws IllegalArgumentException if the initial capacity of
2105 >     * elements is negative
2106 >     * @return the new set
2107 >     * @since 1.8
2108 >     */
2109 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2110 >        return new KeySetView<K,Boolean>
2111 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2112 >    }
2113  
2114      /**
2115 <     * Stripped-down version of helper class used in previous version,
2116 <     * declared for the sake of serialization compatibility
2115 >     * Returns a {@link Set} view of the keys in this map, using the
2116 >     * given common mapped value for any additions (i.e., {@link
2117 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2118 >     * This is of course only appropriate if it is acceptable to use
2119 >     * the same value for all additions from this view.
2120 >     *
2121 >     * @param mappedValue the mapped value to use for any additions
2122 >     * @return the set view
2123 >     * @throws NullPointerException if the mappedValue is null
2124       */
2125 <    static class Segment<K,V> implements Serializable {
2126 <        private static final long serialVersionUID = 2249069246763182397L;
2127 <        final float loadFactor;
2128 <        Segment(float lf) { this.loadFactor = lf; }
2125 >    public KeySetView<K,V> keySet(V mappedValue) {
2126 >        if (mappedValue == null)
2127 >            throw new NullPointerException();
2128 >        return new KeySetView<K,V>(this, mappedValue);
2129      }
2130  
2131 +    /* ---------------- Special Nodes -------------- */
2132 +
2133      /**
2134 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
3382 <     * stream (i.e., serializes it).
3383 <     * @param s the stream
3384 <     * @serialData
3385 <     * the key (Object) and value (Object)
3386 <     * for each key-value mapping, followed by a null pair.
3387 <     * The key-value mappings are emitted in no particular order.
2134 >     * A node inserted at head of bins during transfer operations.
2135       */
2136 <    @SuppressWarnings("unchecked") private void writeObject(java.io.ObjectOutputStream s)
2137 <        throws java.io.IOException {
2138 <        if (segments == null) { // for serialization compatibility
2139 <            segments = (Segment<K,V>[])
2140 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
2141 <            for (int i = 0; i < segments.length; ++i)
2142 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
2143 <        }
2144 <        s.defaultWriteObject();
2145 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2146 <        Object v;
2147 <        while ((v = it.advance()) != null) {
2148 <            s.writeObject(it.nextKey);
2149 <            s.writeObject(v);
2136 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2137 >        final Node<K,V>[] nextTable;
2138 >        ForwardingNode(Node<K,V>[] tab) {
2139 >            super(MOVED, null, null, null);
2140 >            this.nextTable = tab;
2141 >        }
2142 >
2143 >        Node<K,V> find(int h, Object k) {
2144 >            Node<K,V> e; int n;
2145 >            Node<K,V>[] tab = nextTable;
2146 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2147 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2148 >                do {
2149 >                    int eh; K ek;
2150 >                    if ((eh = e.hash) == h &&
2151 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2152 >                        return e;
2153 >                    if (eh < 0)
2154 >                        return e.find(h, k);
2155 >                } while ((e = e.next) != null);
2156 >            }
2157 >            return null;
2158          }
3404        s.writeObject(null);
3405        s.writeObject(null);
3406        segments = null; // throw away
2159      }
2160  
2161      /**
2162 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3411 <     * @param s the stream
2162 >     * A place-holder node used in computeIfAbsent and compute
2163       */
2164 <    @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s)
2165 <        throws java.io.IOException, ClassNotFoundException {
2166 <        s.defaultReadObject();
2167 <        this.segments = null; // unneeded
3417 <        // initialize transient final field
3418 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
2164 >    static final class ReservationNode<K,V> extends Node<K,V> {
2165 >        ReservationNode() {
2166 >            super(RESERVED, null, null, null);
2167 >        }
2168  
2169 <        // Create all nodes, then place in table once size is known
2170 <        long size = 0L;
3422 <        Node p = null;
3423 <        for (;;) {
3424 <            K k = (K) s.readObject();
3425 <            V v = (V) s.readObject();
3426 <            if (k != null && v != null) {
3427 <                int h = spread(k.hashCode());
3428 <                p = new Node(h, k, v, p);
3429 <                ++size;
3430 <            }
3431 <            else
3432 <                break;
2169 >        Node<K,V> find(int h, Object k) {
2170 >            return null;
2171          }
2172 <        if (p != null) {
2173 <            boolean init = false;
2174 <            int n;
2175 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
2176 <                n = MAXIMUM_CAPACITY;
2177 <            else {
2178 <                int sz = (int)size;
2179 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
2180 <            }
2181 <            int sc = sizeCtl;
2182 <            boolean collide = false;
2183 <            if (n > sc &&
2184 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2172 >    }
2173 >
2174 >    /* ---------------- Table Initialization and Resizing -------------- */
2175 >
2176 >    /**
2177 >     * Initializes table, using the size recorded in sizeCtl.
2178 >     */
2179 >    private final Node<K,V>[] initTable() {
2180 >        Node<K,V>[] tab; int sc;
2181 >        while ((tab = table) == null || tab.length == 0) {
2182 >            if ((sc = sizeCtl) < 0)
2183 >                Thread.yield(); // lost initialization race; just spin
2184 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2185                  try {
2186 <                    if (table == null) {
2187 <                        init = true;
2188 <                        Node[] tab = new Node[n];
2189 <                        int mask = n - 1;
2190 <                        while (p != null) {
3453 <                            int j = p.hash & mask;
3454 <                            Node next = p.next;
3455 <                            Node q = p.next = tabAt(tab, j);
3456 <                            setTabAt(tab, j, p);
3457 <                            if (!collide && q != null && q.hash == p.hash)
3458 <                                collide = true;
3459 <                            p = next;
3460 <                        }
3461 <                        table = tab;
3462 <                        counter.add(size);
2186 >                    if ((tab = table) == null || tab.length == 0) {
2187 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2188 >                        @SuppressWarnings({"rawtypes","unchecked"})
2189 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2190 >                        table = tab = nt;
2191                          sc = n - (n >>> 2);
2192                      }
2193                  } finally {
2194                      sizeCtl = sc;
2195                  }
2196 <                if (collide) { // rescan and convert to TreeBins
3469 <                    Node[] tab = table;
3470 <                    for (int i = 0; i < tab.length; ++i) {
3471 <                        int c = 0;
3472 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3473 <                            if (++c > TREE_THRESHOLD &&
3474 <                                (e.key instanceof Comparable)) {
3475 <                                replaceWithTreeBin(tab, i, e.key);
3476 <                                break;
3477 <                            }
3478 <                        }
3479 <                    }
3480 <                }
2196 >                break;
2197              }
2198 <            if (!init) { // Can only happen if unsafely published.
2199 <                while (p != null) {
2200 <                    internalPut(p.key, p.val);
2201 <                    p = p.next;
2198 >        }
2199 >        return tab;
2200 >    }
2201 >
2202 >    /**
2203 >     * Adds to count, and if table is too small and not already
2204 >     * resizing, initiates transfer. If already resizing, helps
2205 >     * perform transfer if work is available.  Rechecks occupancy
2206 >     * after a transfer to see if another resize is already needed
2207 >     * because resizings are lagging additions.
2208 >     *
2209 >     * @param x the count to add
2210 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2211 >     */
2212 >    private final void addCount(long x, int check) {
2213 >        CounterCell[] as; long b, s;
2214 >        if ((as = counterCells) != null ||
2215 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2216 >            CounterHashCode hc; CounterCell a; long v; int m;
2217 >            boolean uncontended = true;
2218 >            if ((hc = threadCounterHashCode.get()) == null ||
2219 >                as == null || (m = as.length - 1) < 0 ||
2220 >                (a = as[m & hc.code]) == null ||
2221 >                !(uncontended =
2222 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2223 >                fullAddCount(x, hc, uncontended);
2224 >                return;
2225 >            }
2226 >            if (check <= 1)
2227 >                return;
2228 >            s = sumCount();
2229 >        }
2230 >        if (check >= 0) {
2231 >            Node<K,V>[] tab, nt; int sc;
2232 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2233 >                   tab.length < MAXIMUM_CAPACITY) {
2234 >                if (sc < 0) {
2235 >                    if (sc == -1 || transferIndex <= transferOrigin ||
2236 >                        (nt = nextTable) == null)
2237 >                        break;
2238 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2239 >                        transfer(tab, nt);
2240                  }
2241 +                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2242 +                    transfer(tab, null);
2243 +                s = sumCount();
2244              }
2245          }
2246      }
2247  
2248 +    /**
2249 +     * Helps transfer if a resize is in progress.
2250 +     */
2251 +    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2252 +        Node<K,V>[] nextTab; int sc;
2253 +        if ((f instanceof ForwardingNode) &&
2254 +            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2255 +            if (nextTab == nextTable && tab == table &&
2256 +                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2257 +                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2258 +                transfer(tab, nextTab);
2259 +            return nextTab;
2260 +        }
2261 +        return table;
2262 +    }
2263  
2264 <    // -------------------------------------------------------
2264 >    /**
2265 >     * Tries to presize table to accommodate the given number of elements.
2266 >     *
2267 >     * @param size number of elements (doesn't need to be perfectly accurate)
2268 >     */
2269 >    private final void tryPresize(int size) {
2270 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2271 >            tableSizeFor(size + (size >>> 1) + 1);
2272 >        int sc;
2273 >        while ((sc = sizeCtl) >= 0) {
2274 >            Node<K,V>[] tab = table; int n;
2275 >            if (tab == null || (n = tab.length) == 0) {
2276 >                n = (sc > c) ? sc : c;
2277 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2278 >                    try {
2279 >                        if (table == tab) {
2280 >                            @SuppressWarnings({"rawtypes","unchecked"})
2281 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2282 >                            table = nt;
2283 >                            sc = n - (n >>> 2);
2284 >                        }
2285 >                    } finally {
2286 >                        sizeCtl = sc;
2287 >                    }
2288 >                }
2289 >            }
2290 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2291 >                break;
2292 >            else if (tab == table &&
2293 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2294 >                transfer(tab, null);
2295 >        }
2296 >    }
2297  
2298 <    // Sams
2299 <    /** Interface describing a void action of one argument */
2300 <    public interface Action<A> { void apply(A a); }
2301 <    /** Interface describing a void action of two arguments */
2302 <    public interface BiAction<A,B> { void apply(A a, B b); }
2303 <    /** Interface describing a function of one argument */
2304 <    public interface Fun<A,T> { T apply(A a); }
2305 <    /** Interface describing a function of two arguments */
2306 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
2307 <    /** Interface describing a function of no arguments */
2308 <    public interface Generator<T> { T apply(); }
2309 <    /** Interface describing a function mapping its argument to a double */
2310 <    public interface ObjectToDouble<A> { double apply(A a); }
2311 <    /** Interface describing a function mapping its argument to a long */
2312 <    public interface ObjectToLong<A> { long apply(A a); }
2313 <    /** Interface describing a function mapping its argument to an int */
2314 <    public interface ObjectToInt<A> {int apply(A a); }
2315 <    /** Interface describing a function mapping two arguments to a double */
2316 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
2317 <    /** Interface describing a function mapping two arguments to a long */
2318 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
2319 <    /** Interface describing a function mapping two arguments to an int */
2320 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
2321 <    /** Interface describing a function mapping a double to a double */
2322 <    public interface DoubleToDouble { double apply(double a); }
2323 <    /** Interface describing a function mapping a long to a long */
2324 <    public interface LongToLong { long apply(long a); }
2325 <    /** Interface describing a function mapping an int to an int */
2326 <    public interface IntToInt { int apply(int a); }
2327 <    /** Interface describing a function mapping two doubles to a double */
2328 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
2329 <    /** Interface describing a function mapping two longs to a long */
2330 <    public interface LongByLongToLong { long apply(long a, long b); }
2331 <    /** Interface describing a function mapping two ints to an int */
2332 <    public interface IntByIntToInt { int apply(int a, int b); }
2298 >    /**
2299 >     * Moves and/or copies the nodes in each bin to new table. See
2300 >     * above for explanation.
2301 >     */
2302 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2303 >        int n = tab.length, stride;
2304 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2305 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2306 >        if (nextTab == null) {            // initiating
2307 >            try {
2308 >                @SuppressWarnings({"rawtypes","unchecked"})
2309 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2310 >                nextTab = nt;
2311 >            } catch (Throwable ex) {      // try to cope with OOME
2312 >                sizeCtl = Integer.MAX_VALUE;
2313 >                return;
2314 >            }
2315 >            nextTable = nextTab;
2316 >            transferOrigin = n;
2317 >            transferIndex = n;
2318 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2319 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2320 >                int nextk = (k > stride) ? k - stride : 0;
2321 >                for (int m = nextk; m < k; ++m)
2322 >                    nextTab[m] = rev;
2323 >                for (int m = n + nextk; m < n + k; ++m)
2324 >                    nextTab[m] = rev;
2325 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2326 >            }
2327 >        }
2328 >        int nextn = nextTab.length;
2329 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2330 >        boolean advance = true;
2331 >        for (int i = 0, bound = 0;;) {
2332 >            int nextIndex, nextBound, fh; Node<K,V> f;
2333 >            while (advance) {
2334 >                if (--i >= bound)
2335 >                    advance = false;
2336 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2337 >                    i = -1;
2338 >                    advance = false;
2339 >                }
2340 >                else if (U.compareAndSwapInt
2341 >                         (this, TRANSFERINDEX, nextIndex,
2342 >                          nextBound = (nextIndex > stride ?
2343 >                                       nextIndex - stride : 0))) {
2344 >                    bound = nextBound;
2345 >                    i = nextIndex - 1;
2346 >                    advance = false;
2347 >                }
2348 >            }
2349 >            if (i < 0 || i >= n || i + n >= nextn) {
2350 >                for (int sc;;) {
2351 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2352 >                        if (sc == -1) {
2353 >                            nextTable = null;
2354 >                            table = nextTab;
2355 >                            sizeCtl = (n << 1) - (n >>> 1);
2356 >                        }
2357 >                        return;
2358 >                    }
2359 >                }
2360 >            }
2361 >            else if ((f = tabAt(tab, i)) == null) {
2362 >                if (casTabAt(tab, i, null, fwd)) {
2363 >                    setTabAt(nextTab, i, null);
2364 >                    setTabAt(nextTab, i + n, null);
2365 >                    advance = true;
2366 >                }
2367 >            }
2368 >            else if ((fh = f.hash) == MOVED)
2369 >                advance = true; // already processed
2370 >            else {
2371 >                synchronized (f) {
2372 >                    if (tabAt(tab, i) == f) {
2373 >                        Node<K,V> ln, hn;
2374 >                        if (fh >= 0) {
2375 >                            int runBit = fh & n;
2376 >                            Node<K,V> lastRun = f;
2377 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2378 >                                int b = p.hash & n;
2379 >                                if (b != runBit) {
2380 >                                    runBit = b;
2381 >                                    lastRun = p;
2382 >                                }
2383 >                            }
2384 >                            if (runBit == 0) {
2385 >                                ln = lastRun;
2386 >                                hn = null;
2387 >                            }
2388 >                            else {
2389 >                                hn = lastRun;
2390 >                                ln = null;
2391 >                            }
2392 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2393 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2394 >                                if ((ph & n) == 0)
2395 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2396 >                                else
2397 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2398 >                            }
2399 >                            setTabAt(nextTab, i, ln);
2400 >                            setTabAt(nextTab, i + n, hn);
2401 >                            setTabAt(tab, i, fwd);
2402 >                            advance = true;
2403 >                        }
2404 >                        else if (f instanceof TreeBin) {
2405 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2406 >                            TreeNode<K,V> lo = null, loTail = null;
2407 >                            TreeNode<K,V> hi = null, hiTail = null;
2408 >                            int lc = 0, hc = 0;
2409 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2410 >                                int h = e.hash;
2411 >                                TreeNode<K,V> p = new TreeNode<K,V>
2412 >                                    (h, e.key, e.val, null, null);
2413 >                                if ((h & n) == 0) {
2414 >                                    if ((p.prev = loTail) == null)
2415 >                                        lo = p;
2416 >                                    else
2417 >                                        loTail.next = p;
2418 >                                    loTail = p;
2419 >                                    ++lc;
2420 >                                }
2421 >                                else {
2422 >                                    if ((p.prev = hiTail) == null)
2423 >                                        hi = p;
2424 >                                    else
2425 >                                        hiTail.next = p;
2426 >                                    hiTail = p;
2427 >                                    ++hc;
2428 >                                }
2429 >                            }
2430 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2431 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2432 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2433 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2434 >                            setTabAt(nextTab, i, ln);
2435 >                            setTabAt(nextTab, i + n, hn);
2436 >                            setTabAt(tab, i, fwd);
2437 >                            advance = true;
2438 >                        }
2439 >                    }
2440 >                }
2441 >            }
2442 >        }
2443 >    }
2444  
2445 +    /* ---------------- Conversion from/to TreeBins -------------- */
2446  
2447 <    // -------------------------------------------------------
2447 >    /**
2448 >     * Replaces all linked nodes in bin at given index unless table is
2449 >     * too small, in which case resizes instead.
2450 >     */
2451 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2452 >        Node<K,V> b; int n, sc;
2453 >        if (tab != null) {
2454 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2455 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2456 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2457 >                    transfer(tab, null);
2458 >            }
2459 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2460 >                synchronized (b) {
2461 >                    if (tabAt(tab, index) == b) {
2462 >                        TreeNode<K,V> hd = null, tl = null;
2463 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2464 >                            TreeNode<K,V> p =
2465 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2466 >                                                  null, null);
2467 >                            if ((p.prev = tl) == null)
2468 >                                hd = p;
2469 >                            else
2470 >                                tl.next = p;
2471 >                            tl = p;
2472 >                        }
2473 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2474 >                    }
2475 >                }
2476 >            }
2477 >        }
2478 >    }
2479  
2480      /**
2481 <     * Returns an extended {@link Parallel} view of this map using the
3535 <     * given executor for bulk parallel operations.
3536 <     *
3537 <     * @param executor the executor
3538 <     * @return a parallel view
2481 >     * Returns a list on non-TreeNodes replacing those in given list.
2482       */
2483 <    public Parallel parallel(ForkJoinPool executor)  {
2484 <        return new Parallel(executor);
2483 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2484 >        Node<K,V> hd = null, tl = null;
2485 >        for (Node<K,V> q = b; q != null; q = q.next) {
2486 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2487 >            if (tl == null)
2488 >                hd = p;
2489 >            else
2490 >                tl.next = p;
2491 >            tl = p;
2492 >        }
2493 >        return hd;
2494      }
2495  
2496 +    /* ---------------- TreeNodes -------------- */
2497 +
2498      /**
2499 <     * An extended view of a ConcurrentHashMap supporting bulk
3546 <     * parallel operations. These operations are designed to be
3547 <     * safely, and often sensibly, applied even with maps that are
3548 <     * being concurrently updated by other threads; for example, when
3549 <     * computing a snapshot summary of the values in a shared
3550 <     * registry.  There are three kinds of operation, each with four
3551 <     * forms, accepting functions with Keys, Values, Entries, and
3552 <     * (Key, Value) arguments and/or return values. Because the
3553 <     * elements of a ConcurrentHashMap are not ordered in any
3554 <     * particular way, and may be processed in different orders in
3555 <     * different parallel executions, the correctness of supplied
3556 <     * functions should not depend on any ordering, or on any other
3557 <     * objects or values that may transiently change while computation
3558 <     * is in progress; and except for forEach actions, should ideally
3559 <     * be side-effect-free.
3560 <     *
3561 <     * <ul>
3562 <     * <li> forEach: Perform a given action on each element.
3563 <     * A variant form applies a given transformation on each element
3564 <     * before performing the action.</li>
3565 <     *
3566 <     * <li> search: Return the first available non-null result of
3567 <     * applying a given function on each element; skipping further
3568 <     * search when a result is found.</li>
3569 <     *
3570 <     * <li> reduce: Accumulate each element.  The supplied reduction
3571 <     * function cannot rely on ordering (more formally, it should be
3572 <     * both associative and commutative).  There are five variants:
3573 <     *
3574 <     * <ul>
3575 <     *
3576 <     * <li> Plain reductions. (There is not a form of this method for
3577 <     * (key, value) function arguments since there is no corresponding
3578 <     * return type.)</li>
3579 <     *
3580 <     * <li> Mapped reductions that accumulate the results of a given
3581 <     * function applied to each element.</li>
3582 <     *
3583 <     * <li> Reductions to scalar doubles, longs, and ints, using a
3584 <     * given basis value.</li>
3585 <     *
3586 <     * </li>
3587 <     * </ul>
3588 <     * </ul>
3589 <     *
3590 <     * <p>The concurrency properties of the bulk operations follow
3591 <     * from those of ConcurrentHashMap: Any non-null result returned
3592 <     * from {@code get(key)} and related access methods bears a
3593 <     * happens-before relation with the associated insertion or
3594 <     * update.  The result of any bulk operation reflects the
3595 <     * composition of these per-element relations (but is not
3596 <     * necessarily atomic with respect to the map as a whole unless it
3597 <     * is somehow known to be quiescent).  Conversely, because keys
3598 <     * and values in the map are never null, null serves as a reliable
3599 <     * atomic indicator of the current lack of any result.  To
3600 <     * maintain this property, null serves as an implicit basis for
3601 <     * all non-scalar reduction operations. For the double, long, and
3602 <     * int versions, the basis should be one that, when combined with
3603 <     * any other value, returns that other value (more formally, it
3604 <     * should be the identity element for the reduction). Most common
3605 <     * reductions have these properties; for example, computing a sum
3606 <     * with basis 0 or a minimum with basis MAX_VALUE.
3607 <     *
3608 <     * <p>Search and transformation functions provided as arguments
3609 <     * should similarly return null to indicate the lack of any result
3610 <     * (in which case it is not used). In the case of mapped
3611 <     * reductions, this also enables transformations to serve as
3612 <     * filters, returning null (or, in the case of primitive
3613 <     * specializations, the identity basis) if the element should not
3614 <     * be combined. You can create compound transformations and
3615 <     * filterings by composing them yourself under this "null means
3616 <     * there is nothing there now" rule before using them in search or
3617 <     * reduce operations.
3618 <     *
3619 <     * <p>Methods accepting and/or returning Entry arguments maintain
3620 <     * key-value associations. They may be useful for example when
3621 <     * finding the key for the greatest value. Note that "plain" Entry
3622 <     * arguments can be supplied using {@code new
3623 <     * AbstractMap.SimpleEntry(k,v)}.
3624 <     *
3625 <     * <p> Bulk operations may complete abruptly, throwing an
3626 <     * exception encountered in the application of a supplied
3627 <     * function. Bear in mind when handling such exceptions that other
3628 <     * concurrently executing functions could also have thrown
3629 <     * exceptions, or would have done so if the first exception had
3630 <     * not occurred.
3631 <     *
3632 <     * <p>Parallel speedups compared to sequential processing are
3633 <     * common but not guaranteed.  Operations involving brief
3634 <     * functions on small maps may execute more slowly than sequential
3635 <     * loops if the underlying work to parallelize the computation is
3636 <     * more expensive than the computation itself. Similarly,
3637 <     * parallelization may not lead to much actual parallelism if all
3638 <     * processors are busy performing unrelated tasks.
3639 <     *
3640 <     * <p> All arguments to all task methods must be non-null.
3641 <     *
3642 <     * <p><em>jsr166e note: During transition, this class
3643 <     * uses nested functional interfaces with different names but the
3644 <     * same forms as those expected for JDK8.<em>
2499 >     * Nodes for use in TreeBins
2500       */
2501 <    public class Parallel {
2502 <        final ForkJoinPool fjp;
2501 >    static final class TreeNode<K,V> extends Node<K,V> {
2502 >        TreeNode<K,V> parent;  // red-black tree links
2503 >        TreeNode<K,V> left;
2504 >        TreeNode<K,V> right;
2505 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2506 >        boolean red;
2507  
2508 <        /**
2509 <         * Returns an extended view of this map using the given
2510 <         * executor for bulk parallel operations.
2511 <         *
3653 <         * @param executor the executor
3654 <         */
3655 <        public Parallel(ForkJoinPool executor)  {
3656 <            this.fjp = executor;
2508 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2509 >                 TreeNode<K,V> parent) {
2510 >            super(hash, key, val, next);
2511 >            this.parent = parent;
2512          }
2513  
2514 <        /**
2515 <         * Performs the given action for each (key, value).
3661 <         *
3662 <         * @param action the action
3663 <         */
3664 <        public void forEach(BiAction<K,V> action) {
3665 <            fjp.invoke(ForkJoinTasks.forEach
3666 <                       (ConcurrentHashMapV8.this, action));
2514 >        Node<K,V> find(int h, Object k) {
2515 >            return findTreeNode(h, k, null);
2516          }
2517  
2518          /**
2519 <         * Performs the given action for each non-null transformation
2520 <         * of each (key, value).
3672 <         *
3673 <         * @param transformer a function returning the transformation
3674 <         * for an element, or null if there is no transformation (in
3675 <         * which case the action is not applied)
3676 <         * @param action the action
2519 >         * Returns the TreeNode (or null if not found) for the given key
2520 >         * starting at given root.
2521           */
2522 <        public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
2523 <                                Action<U> action) {
2524 <            fjp.invoke(ForkJoinTasks.forEach
2525 <                       (ConcurrentHashMapV8.this, transformer, action));
2522 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2523 >            if (k != null) {
2524 >                TreeNode<K,V> p = this;
2525 >                do  {
2526 >                    int ph, dir; K pk; TreeNode<K,V> q;
2527 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2528 >                    if ((ph = p.hash) > h)
2529 >                        p = pl;
2530 >                    else if (ph < h)
2531 >                        p = pr;
2532 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2533 >                        return p;
2534 >                    else if (pl == null && pr == null)
2535 >                        break;
2536 >                    else if ((kc != null ||
2537 >                              (kc = comparableClassFor(k)) != null) &&
2538 >                             (dir = compareComparables(kc, k, pk)) != 0)
2539 >                        p = (dir < 0) ? pl : pr;
2540 >                    else if (pl == null)
2541 >                        p = pr;
2542 >                    else if (pr == null ||
2543 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2544 >                        p = pl;
2545 >                    else
2546 >                        return q;
2547 >                } while (p != null);
2548 >            }
2549 >            return null;
2550          }
2551 +    }
2552  
2553 <        /**
2554 <         * Returns a non-null result from applying the given search
2555 <         * function on each (key, value), or null if none.  Upon
2556 <         * success, further element processing is suppressed and the
2557 <         * results of any other parallel invocations of the search
2558 <         * function are ignored.
2559 <         *
2560 <         * @param searchFunction a function returning a non-null
2561 <         * result on success, else null
2562 <         * @return a non-null result from applying the given search
2563 <         * function on each (key, value), or null if none
2564 <         */
2565 <        public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
2566 <            return fjp.invoke(ForkJoinTasks.search
2567 <                              (ConcurrentHashMapV8.this, searchFunction));
2553 >    /* ---------------- TreeBins -------------- */
2554 >
2555 >    /**
2556 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2557 >     * keys or values, but instead point to list of TreeNodes and
2558 >     * their root. They also maintain a parasitic read-write lock
2559 >     * forcing writers (who hold bin lock) to wait for readers (who do
2560 >     * not) to complete before tree restructuring operations.
2561 >     */
2562 >    static final class TreeBin<K,V> extends Node<K,V> {
2563 >        TreeNode<K,V> root;
2564 >        volatile TreeNode<K,V> first;
2565 >        volatile Thread waiter;
2566 >        volatile int lockState;
2567 >        // values for lockState
2568 >        static final int WRITER = 1; // set while holding write lock
2569 >        static final int WAITER = 2; // set when waiting for write lock
2570 >        static final int READER = 4; // increment value for setting read lock
2571 >
2572 >        /**
2573 >         * Creates bin with initial set of nodes headed by b.
2574 >         */
2575 >        TreeBin(TreeNode<K,V> b) {
2576 >            super(TREEBIN, null, null, null);
2577 >            this.first = b;
2578 >            TreeNode<K,V> r = null;
2579 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2580 >                next = (TreeNode<K,V>)x.next;
2581 >                x.left = x.right = null;
2582 >                if (r == null) {
2583 >                    x.parent = null;
2584 >                    x.red = false;
2585 >                    r = x;
2586 >                }
2587 >                else {
2588 >                    Object key = x.key;
2589 >                    int hash = x.hash;
2590 >                    Class<?> kc = null;
2591 >                    for (TreeNode<K,V> p = r;;) {
2592 >                        int dir, ph;
2593 >                        if ((ph = p.hash) > hash)
2594 >                            dir = -1;
2595 >                        else if (ph < hash)
2596 >                            dir = 1;
2597 >                        else if ((kc != null ||
2598 >                                  (kc = comparableClassFor(key)) != null))
2599 >                            dir = compareComparables(kc, key, p.key);
2600 >                        else
2601 >                            dir = 0;
2602 >                        TreeNode<K,V> xp = p;
2603 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2604 >                            x.parent = xp;
2605 >                            if (dir <= 0)
2606 >                                xp.left = x;
2607 >                            else
2608 >                                xp.right = x;
2609 >                            r = balanceInsertion(r, x);
2610 >                            break;
2611 >                        }
2612 >                    }
2613 >                }
2614 >            }
2615 >            this.root = r;
2616          }
2617  
2618          /**
2619 <         * Returns the result of accumulating the given transformation
3703 <         * of all (key, value) pairs using the given reducer to
3704 <         * combine values, or null if none.
3705 <         *
3706 <         * @param transformer a function returning the transformation
3707 <         * for an element, or null if there is no transformation (in
3708 <         * which case it is not combined)
3709 <         * @param reducer a commutative associative combining function
3710 <         * @return the result of accumulating the given transformation
3711 <         * of all (key, value) pairs
2619 >         * Acquires write lock for tree restructuring.
2620           */
2621 <        public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
2622 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
2623 <            return fjp.invoke(ForkJoinTasks.reduce
3716 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2621 >        private final void lockRoot() {
2622 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2623 >                contendedLock(); // offload to separate method
2624          }
2625  
2626          /**
2627 <         * Returns the result of accumulating the given transformation
3721 <         * of all (key, value) pairs using the given reducer to
3722 <         * combine values, and the given basis as an identity value.
3723 <         *
3724 <         * @param transformer a function returning the transformation
3725 <         * for an element
3726 <         * @param basis the identity (initial default value) for the reduction
3727 <         * @param reducer a commutative associative combining function
3728 <         * @return the result of accumulating the given transformation
3729 <         * of all (key, value) pairs
2627 >         * Releases write lock for tree restructuring.
2628           */
2629 <        public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
2630 <                                     double basis,
3733 <                                     DoubleByDoubleToDouble reducer) {
3734 <            return fjp.invoke(ForkJoinTasks.reduceToDouble
3735 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2629 >        private final void unlockRoot() {
2630 >            lockState = 0;
2631          }
2632  
2633          /**
2634 <         * Returns the result of accumulating the given transformation
3740 <         * of all (key, value) pairs using the given reducer to
3741 <         * combine values, and the given basis as an identity value.
3742 <         *
3743 <         * @param transformer a function returning the transformation
3744 <         * for an element
3745 <         * @param basis the identity (initial default value) for the reduction
3746 <         * @param reducer a commutative associative combining function
3747 <         * @return the result of accumulating the given transformation
3748 <         * of all (key, value) pairs
2634 >         * Possibly blocks awaiting root lock.
2635           */
2636 <        public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
2637 <                                 long basis,
2638 <                                 LongByLongToLong reducer) {
2639 <            return fjp.invoke(ForkJoinTasks.reduceToLong
2640 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2636 >        private final void contendedLock() {
2637 >            boolean waiting = false;
2638 >            for (int s;;) {
2639 >                if (((s = lockState) & WRITER) == 0) {
2640 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2641 >                        if (waiting)
2642 >                            waiter = null;
2643 >                        return;
2644 >                    }
2645 >                }
2646 >                else if ((s | WAITER) == 0) {
2647 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2648 >                        waiting = true;
2649 >                        waiter = Thread.currentThread();
2650 >                    }
2651 >                }
2652 >                else if (waiting)
2653 >                    LockSupport.park(this);
2654 >            }
2655          }
2656  
2657          /**
2658 <         * Returns the result of accumulating the given transformation
2659 <         * of all (key, value) pairs using the given reducer to
2660 <         * combine values, and the given basis as an identity value.
3761 <         *
3762 <         * @param transformer a function returning the transformation
3763 <         * for an element
3764 <         * @param basis the identity (initial default value) for the reduction
3765 <         * @param reducer a commutative associative combining function
3766 <         * @return the result of accumulating the given transformation
3767 <         * of all (key, value) pairs
2658 >         * Returns matching node or null if none. Tries to search
2659 >         * using tree comparisons from root, but continues linear
2660 >         * search when lock not available.
2661           */
2662 <        public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
2663 <                               int basis,
2664 <                               IntByIntToInt reducer) {
2665 <            return fjp.invoke(ForkJoinTasks.reduceToInt
2666 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2662 >        final Node<K,V> find(int h, Object k) {
2663 >            if (k != null) {
2664 >                for (Node<K,V> e = first; e != null; e = e.next) {
2665 >                    int s; K ek;
2666 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2667 >                        if (e.hash == h &&
2668 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2669 >                            return e;
2670 >                    }
2671 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2672 >                                                 s + READER)) {
2673 >                        TreeNode<K,V> r, p;
2674 >                        try {
2675 >                            p = ((r = root) == null ? null :
2676 >                                 r.findTreeNode(h, k, null));
2677 >                        } finally {
2678 >                            Thread w;
2679 >                            int ls;
2680 >                            do {} while (!U.compareAndSwapInt
2681 >                                         (this, LOCKSTATE,
2682 >                                          ls = lockState, ls - READER));
2683 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2684 >                                LockSupport.unpark(w);
2685 >                        }
2686 >                        return p;
2687 >                    }
2688 >                }
2689 >            }
2690 >            return null;
2691          }
2692  
2693          /**
2694 <         * Performs the given action for each key.
2695 <         *
3779 <         * @param action the action
2694 >         * Finds or adds a node.
2695 >         * @return null if added
2696           */
2697 <        public void forEachKey(Action<K> action) {
2698 <            fjp.invoke(ForkJoinTasks.forEachKey
2699 <                       (ConcurrentHashMapV8.this, action));
2697 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2698 >            Class<?> kc = null;
2699 >            for (TreeNode<K,V> p = root;;) {
2700 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2701 >                if (p == null) {
2702 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2703 >                    break;
2704 >                }
2705 >                else if ((ph = p.hash) > h)
2706 >                    dir = -1;
2707 >                else if (ph < h)
2708 >                    dir = 1;
2709 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2710 >                    return p;
2711 >                else if ((kc == null &&
2712 >                          (kc = comparableClassFor(k)) == null) ||
2713 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2714 >                    if (p.left == null)
2715 >                        dir = 1;
2716 >                    else if ((pr = p.right) == null ||
2717 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2718 >                        dir = -1;
2719 >                    else
2720 >                        return q;
2721 >                }
2722 >                TreeNode<K,V> xp = p;
2723 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2724 >                    TreeNode<K,V> x, f = first;
2725 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2726 >                    if (f != null)
2727 >                        f.prev = x;
2728 >                    if (dir < 0)
2729 >                        xp.left = x;
2730 >                    else
2731 >                        xp.right = x;
2732 >                    if (!xp.red)
2733 >                        x.red = true;
2734 >                    else {
2735 >                        lockRoot();
2736 >                        try {
2737 >                            root = balanceInsertion(root, x);
2738 >                        } finally {
2739 >                            unlockRoot();
2740 >                        }
2741 >                    }
2742 >                    break;
2743 >                }
2744 >            }
2745 >            assert checkInvariants(root);
2746 >            return null;
2747          }
2748  
2749          /**
2750 <         * Performs the given action for each non-null transformation
2751 <         * of each key.
2750 >         * Removes the given node, that must be present before this
2751 >         * call.  This is messier than typical red-black deletion code
2752 >         * because we cannot swap the contents of an interior node
2753 >         * with a leaf successor that is pinned by "next" pointers
2754 >         * that are accessible independently of lock. So instead we
2755 >         * swap the tree linkages.
2756           *
2757 <         * @param transformer a function returning the transformation
3791 <         * for an element, or null if there is no transformation (in
3792 <         * which case the action is not applied)
3793 <         * @param action the action
2757 >         * @return true if now too small, so should be untreeified
2758           */
2759 <        public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
2760 <                                   Action<U> action) {
2761 <            fjp.invoke(ForkJoinTasks.forEachKey
2762 <                       (ConcurrentHashMapV8.this, transformer, action));
2759 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2760 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2761 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2762 >            TreeNode<K,V> r, rl;
2763 >            if (pred == null)
2764 >                first = next;
2765 >            else
2766 >                pred.next = next;
2767 >            if (next != null)
2768 >                next.prev = pred;
2769 >            if (first == null) {
2770 >                root = null;
2771 >                return true;
2772 >            }
2773 >            if ((r = root) == null || r.right == null || // too small
2774 >                (rl = r.left) == null || rl.left == null)
2775 >                return true;
2776 >            lockRoot();
2777 >            try {
2778 >                TreeNode<K,V> replacement;
2779 >                TreeNode<K,V> pl = p.left;
2780 >                TreeNode<K,V> pr = p.right;
2781 >                if (pl != null && pr != null) {
2782 >                    TreeNode<K,V> s = pr, sl;
2783 >                    while ((sl = s.left) != null) // find successor
2784 >                        s = sl;
2785 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2786 >                    TreeNode<K,V> sr = s.right;
2787 >                    TreeNode<K,V> pp = p.parent;
2788 >                    if (s == pr) { // p was s's direct parent
2789 >                        p.parent = s;
2790 >                        s.right = p;
2791 >                    }
2792 >                    else {
2793 >                        TreeNode<K,V> sp = s.parent;
2794 >                        if ((p.parent = sp) != null) {
2795 >                            if (s == sp.left)
2796 >                                sp.left = p;
2797 >                            else
2798 >                                sp.right = p;
2799 >                        }
2800 >                        if ((s.right = pr) != null)
2801 >                            pr.parent = s;
2802 >                    }
2803 >                    p.left = null;
2804 >                    if ((p.right = sr) != null)
2805 >                        sr.parent = p;
2806 >                    if ((s.left = pl) != null)
2807 >                        pl.parent = s;
2808 >                    if ((s.parent = pp) == null)
2809 >                        r = s;
2810 >                    else if (p == pp.left)
2811 >                        pp.left = s;
2812 >                    else
2813 >                        pp.right = s;
2814 >                    if (sr != null)
2815 >                        replacement = sr;
2816 >                    else
2817 >                        replacement = p;
2818 >                }
2819 >                else if (pl != null)
2820 >                    replacement = pl;
2821 >                else if (pr != null)
2822 >                    replacement = pr;
2823 >                else
2824 >                    replacement = p;
2825 >                if (replacement != p) {
2826 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2827 >                    if (pp == null)
2828 >                        r = replacement;
2829 >                    else if (p == pp.left)
2830 >                        pp.left = replacement;
2831 >                    else
2832 >                        pp.right = replacement;
2833 >                    p.left = p.right = p.parent = null;
2834 >                }
2835 >
2836 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2837 >
2838 >                if (p == replacement) {  // detach pointers
2839 >                    TreeNode<K,V> pp;
2840 >                    if ((pp = p.parent) != null) {
2841 >                        if (p == pp.left)
2842 >                            pp.left = null;
2843 >                        else if (p == pp.right)
2844 >                            pp.right = null;
2845 >                        p.parent = null;
2846 >                    }
2847 >                }
2848 >            } finally {
2849 >                unlockRoot();
2850 >            }
2851 >            assert checkInvariants(root);
2852 >            return false;
2853          }
2854  
2855 <        /**
2856 <         * Returns a non-null result from applying the given search
2857 <         * function on each key, or null if none. Upon success,
2858 <         * further element processing is suppressed and the results of
2859 <         * any other parallel invocations of the search function are
2860 <         * ignored.
2861 <         *
2862 <         * @param searchFunction a function returning a non-null
2863 <         * result on success, else null
2864 <         * @return a non-null result from applying the given search
2865 <         * function on each key, or null if none
2866 <         */
2867 <        public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
2868 <            return fjp.invoke(ForkJoinTasks.searchKeys
2869 <                              (ConcurrentHashMapV8.this, searchFunction));
2855 >        /* ------------------------------------------------------------ */
2856 >        // Red-black tree methods, all adapted from CLR
2857 >
2858 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2859 >                                              TreeNode<K,V> p) {
2860 >            TreeNode<K,V> r, pp, rl;
2861 >            if (p != null && (r = p.right) != null) {
2862 >                if ((rl = p.right = r.left) != null)
2863 >                    rl.parent = p;
2864 >                if ((pp = r.parent = p.parent) == null)
2865 >                    (root = r).red = false;
2866 >                else if (pp.left == p)
2867 >                    pp.left = r;
2868 >                else
2869 >                    pp.right = r;
2870 >                r.left = p;
2871 >                p.parent = r;
2872 >            }
2873 >            return root;
2874          }
2875  
2876 <        /**
2877 <         * Returns the result of accumulating all keys using the given
2878 <         * reducer to combine values, or null if none.
2879 <         *
2880 <         * @param reducer a commutative associative combining function
2881 <         * @return the result of accumulating all keys using the given
2882 <         * reducer to combine values, or null if none
2883 <         */
2884 <        public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
2885 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2886 <                              (ConcurrentHashMapV8.this, reducer));
2876 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2877 >                                               TreeNode<K,V> p) {
2878 >            TreeNode<K,V> l, pp, lr;
2879 >            if (p != null && (l = p.left) != null) {
2880 >                if ((lr = p.left = l.right) != null)
2881 >                    lr.parent = p;
2882 >                if ((pp = l.parent = p.parent) == null)
2883 >                    (root = l).red = false;
2884 >                else if (pp.right == p)
2885 >                    pp.right = l;
2886 >                else
2887 >                    pp.left = l;
2888 >                l.right = p;
2889 >                p.parent = l;
2890 >            }
2891 >            return root;
2892          }
2893  
2894 <        /**
2895 <         * Returns the result of accumulating the given transformation
2896 <         * of all keys using the given reducer to combine values, or
2897 <         * null if none.
2898 <         *
2899 <         * @param transformer a function returning the transformation
2900 <         * for an element, or null if there is no transformation (in
2901 <         * which case it is not combined)
2902 <         * @param reducer a commutative associative combining function
2903 <         * @return the result of accumulating the given transformation
2904 <         * of all keys
2905 <         */
2906 <        public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
2907 <                                BiFun<? super U, ? super U, ? extends U> reducer) {
2908 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2909 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2894 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2895 >                                                    TreeNode<K,V> x) {
2896 >            x.red = true;
2897 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2898 >                if ((xp = x.parent) == null) {
2899 >                    x.red = false;
2900 >                    return x;
2901 >                }
2902 >                else if (!xp.red || (xpp = xp.parent) == null)
2903 >                    return root;
2904 >                if (xp == (xppl = xpp.left)) {
2905 >                    if ((xppr = xpp.right) != null && xppr.red) {
2906 >                        xppr.red = false;
2907 >                        xp.red = false;
2908 >                        xpp.red = true;
2909 >                        x = xpp;
2910 >                    }
2911 >                    else {
2912 >                        if (x == xp.right) {
2913 >                            root = rotateLeft(root, x = xp);
2914 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2915 >                        }
2916 >                        if (xp != null) {
2917 >                            xp.red = false;
2918 >                            if (xpp != null) {
2919 >                                xpp.red = true;
2920 >                                root = rotateRight(root, xpp);
2921 >                            }
2922 >                        }
2923 >                    }
2924 >                }
2925 >                else {
2926 >                    if (xppl != null && xppl.red) {
2927 >                        xppl.red = false;
2928 >                        xp.red = false;
2929 >                        xpp.red = true;
2930 >                        x = xpp;
2931 >                    }
2932 >                    else {
2933 >                        if (x == xp.left) {
2934 >                            root = rotateRight(root, x = xp);
2935 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2936 >                        }
2937 >                        if (xp != null) {
2938 >                            xp.red = false;
2939 >                            if (xpp != null) {
2940 >                                xpp.red = true;
2941 >                                root = rotateLeft(root, xpp);
2942 >                            }
2943 >                        }
2944 >                    }
2945 >                }
2946 >            }
2947          }
2948  
2949 <        /**
2950 <         * Returns the result of accumulating the given transformation
2951 <         * of all keys using the given reducer to combine values, and
2952 <         * the given basis as an identity value.
2953 <         *
2954 <         * @param transformer a function returning the transformation
2955 <         * for an element
2956 <         * @param basis the identity (initial default value) for the reduction
2957 <         * @param reducer a commutative associative combining function
2958 <         * @return  the result of accumulating the given transformation
2959 <         * of all keys
2960 <         */
2961 <        public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
2962 <                                         double basis,
2963 <                                         DoubleByDoubleToDouble reducer) {
2964 <            return fjp.invoke(ForkJoinTasks.reduceKeysToDouble
2965 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2949 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2950 >                                                   TreeNode<K,V> x) {
2951 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2952 >                if (x == null || x == root)
2953 >                    return root;
2954 >                else if ((xp = x.parent) == null) {
2955 >                    x.red = false;
2956 >                    return x;
2957 >                }
2958 >                else if (x.red) {
2959 >                    x.red = false;
2960 >                    return root;
2961 >                }
2962 >                else if ((xpl = xp.left) == x) {
2963 >                    if ((xpr = xp.right) != null && xpr.red) {
2964 >                        xpr.red = false;
2965 >                        xp.red = true;
2966 >                        root = rotateLeft(root, xp);
2967 >                        xpr = (xp = x.parent) == null ? null : xp.right;
2968 >                    }
2969 >                    if (xpr == null)
2970 >                        x = xp;
2971 >                    else {
2972 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2973 >                        if ((sr == null || !sr.red) &&
2974 >                            (sl == null || !sl.red)) {
2975 >                            xpr.red = true;
2976 >                            x = xp;
2977 >                        }
2978 >                        else {
2979 >                            if (sr == null || !sr.red) {
2980 >                                if (sl != null)
2981 >                                    sl.red = false;
2982 >                                xpr.red = true;
2983 >                                root = rotateRight(root, xpr);
2984 >                                xpr = (xp = x.parent) == null ?
2985 >                                    null : xp.right;
2986 >                            }
2987 >                            if (xpr != null) {
2988 >                                xpr.red = (xp == null) ? false : xp.red;
2989 >                                if ((sr = xpr.right) != null)
2990 >                                    sr.red = false;
2991 >                            }
2992 >                            if (xp != null) {
2993 >                                xp.red = false;
2994 >                                root = rotateLeft(root, xp);
2995 >                            }
2996 >                            x = root;
2997 >                        }
2998 >                    }
2999 >                }
3000 >                else { // symmetric
3001 >                    if (xpl != null && xpl.red) {
3002 >                        xpl.red = false;
3003 >                        xp.red = true;
3004 >                        root = rotateRight(root, xp);
3005 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3006 >                    }
3007 >                    if (xpl == null)
3008 >                        x = xp;
3009 >                    else {
3010 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3011 >                        if ((sl == null || !sl.red) &&
3012 >                            (sr == null || !sr.red)) {
3013 >                            xpl.red = true;
3014 >                            x = xp;
3015 >                        }
3016 >                        else {
3017 >                            if (sl == null || !sl.red) {
3018 >                                if (sr != null)
3019 >                                    sr.red = false;
3020 >                                xpl.red = true;
3021 >                                root = rotateLeft(root, xpl);
3022 >                                xpl = (xp = x.parent) == null ?
3023 >                                    null : xp.left;
3024 >                            }
3025 >                            if (xpl != null) {
3026 >                                xpl.red = (xp == null) ? false : xp.red;
3027 >                                if ((sl = xpl.left) != null)
3028 >                                    sl.red = false;
3029 >                            }
3030 >                            if (xp != null) {
3031 >                                xp.red = false;
3032 >                                root = rotateRight(root, xp);
3033 >                            }
3034 >                            x = root;
3035 >                        }
3036 >                    }
3037 >                }
3038 >            }
3039          }
3040  
3041          /**
3042 <         * Returns the result of accumulating the given transformation
3870 <         * of all keys using the given reducer to combine values, and
3871 <         * the given basis as an identity value.
3872 <         *
3873 <         * @param transformer a function returning the transformation
3874 <         * for an element
3875 <         * @param basis the identity (initial default value) for the reduction
3876 <         * @param reducer a commutative associative combining function
3877 <         * @return the result of accumulating the given transformation
3878 <         * of all keys
3042 >         * Recursive invariant check
3043           */
3044 <        public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3045 <                                     long basis,
3046 <                                     LongByLongToLong reducer) {
3047 <            return fjp.invoke(ForkJoinTasks.reduceKeysToLong
3048 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3044 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3045 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3046 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3047 >            if (tb != null && tb.next != t)
3048 >                return false;
3049 >            if (tn != null && tn.prev != t)
3050 >                return false;
3051 >            if (tp != null && t != tp.left && t != tp.right)
3052 >                return false;
3053 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3054 >                return false;
3055 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3056 >                return false;
3057 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3058 >                return false;
3059 >            if (tl != null && !checkInvariants(tl))
3060 >                return false;
3061 >            if (tr != null && !checkInvariants(tr))
3062 >                return false;
3063 >            return true;
3064          }
3065  
3066 <        /**
3067 <         * Returns the result of accumulating the given transformation
3068 <         * of all keys using the given reducer to combine values, and
3069 <         * the given basis as an identity value.
3070 <         *
3071 <         * @param transformer a function returning the transformation
3072 <         * for an element
3073 <         * @param basis the identity (initial default value) for the reduction
3074 <         * @param reducer a commutative associative combining function
3075 <         * @return the result of accumulating the given transformation
3076 <         * of all keys
3898 <         */
3899 <        public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3900 <                                   int basis,
3901 <                                   IntByIntToInt reducer) {
3902 <            return fjp.invoke(ForkJoinTasks.reduceKeysToInt
3903 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3066 >        private static final sun.misc.Unsafe U;
3067 >        private static final long LOCKSTATE;
3068 >        static {
3069 >            try {
3070 >                U = getUnsafe();
3071 >                Class<?> k = TreeBin.class;
3072 >                LOCKSTATE = U.objectFieldOffset
3073 >                    (k.getDeclaredField("lockState"));
3074 >            } catch (Exception e) {
3075 >                throw new Error(e);
3076 >            }
3077          }
3078 +    }
3079  
3080 <        /**
3081 <         * Performs the given action for each value.
3082 <         *
3083 <         * @param action the action
3084 <         */
3085 <        public void forEachValue(Action<V> action) {
3086 <            fjp.invoke(ForkJoinTasks.forEachValue
3087 <                       (ConcurrentHashMapV8.this, action));
3080 >    /* ----------------Table Traversal -------------- */
3081 >
3082 >    /**
3083 >     * Encapsulates traversal for methods such as containsValue; also
3084 >     * serves as a base class for other iterators and spliterators.
3085 >     *
3086 >     * Method advance visits once each still-valid node that was
3087 >     * reachable upon iterator construction. It might miss some that
3088 >     * were added to a bin after the bin was visited, which is OK wrt
3089 >     * consistency guarantees. Maintaining this property in the face
3090 >     * of possible ongoing resizes requires a fair amount of
3091 >     * bookkeeping state that is difficult to optimize away amidst
3092 >     * volatile accesses.  Even so, traversal maintains reasonable
3093 >     * throughput.
3094 >     *
3095 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3096 >     * However, if the table has been resized, then all future steps
3097 >     * must traverse both the bin at the current index as well as at
3098 >     * (index + baseSize); and so on for further resizings. To
3099 >     * paranoically cope with potential sharing by users of iterators
3100 >     * across threads, iteration terminates if a bounds checks fails
3101 >     * for a table read.
3102 >     */
3103 >    static class Traverser<K,V> {
3104 >        Node<K,V>[] tab;        // current table; updated if resized
3105 >        Node<K,V> next;         // the next entry to use
3106 >        int index;              // index of bin to use next
3107 >        int baseIndex;          // current index of initial table
3108 >        int baseLimit;          // index bound for initial table
3109 >        final int baseSize;     // initial table size
3110 >
3111 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3112 >            this.tab = tab;
3113 >            this.baseSize = size;
3114 >            this.baseIndex = this.index = index;
3115 >            this.baseLimit = limit;
3116 >            this.next = null;
3117          }
3118  
3119          /**
3120 <         * Performs the given action for each non-null transformation
3121 <         * of each value.
3122 <         *
3123 <         * @param transformer a function returning the transformation
3124 <         * for an element, or null if there is no transformation (in
3125 <         * which case the action is not applied)
3126 <         */
3127 <        public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3128 <                                     Action<U> action) {
3129 <            fjp.invoke(ForkJoinTasks.forEachValue
3130 <                       (ConcurrentHashMapV8.this, transformer, action));
3120 >         * Advances if possible, returning next valid node, or null if none.
3121 >         */
3122 >        final Node<K,V> advance() {
3123 >            Node<K,V> e;
3124 >            if ((e = next) != null)
3125 >                e = e.next;
3126 >            for (;;) {
3127 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3128 >                if (e != null)
3129 >                    return next = e;
3130 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3131 >                    (n = t.length) <= (i = index) || i < 0)
3132 >                    return next = null;
3133 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3134 >                    if (e instanceof ForwardingNode) {
3135 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3136 >                        e = null;
3137 >                        continue;
3138 >                    }
3139 >                    else if (e instanceof TreeBin)
3140 >                        e = ((TreeBin<K,V>)e).first;
3141 >                    else
3142 >                        e = null;
3143 >                }
3144 >                if ((index += baseSize) >= n)
3145 >                    index = ++baseIndex;    // visit upper slots if present
3146 >            }
3147          }
3148 +    }
3149  
3150 <        /**
3151 <         * Returns a non-null result from applying the given search
3152 <         * function on each value, or null if none.  Upon success,
3153 <         * further element processing is suppressed and the results of
3154 <         * any other parallel invocations of the search function are
3155 <         * ignored.
3156 <         *
3157 <         * @param searchFunction a function returning a non-null
3158 <         * result on success, else null
3159 <         * @return a non-null result from applying the given search
3160 <         * function on each value, or null if none
3161 <         */
3942 <        public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3943 <            return fjp.invoke(ForkJoinTasks.searchValues
3944 <                              (ConcurrentHashMapV8.this, searchFunction));
3150 >    /**
3151 >     * Base of key, value, and entry Iterators. Adds fields to
3152 >     * Traverser to support iterator.remove.
3153 >     */
3154 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3155 >        final ConcurrentHashMapV8<K,V> map;
3156 >        Node<K,V> lastReturned;
3157 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3158 >                    ConcurrentHashMapV8<K,V> map) {
3159 >            super(tab, size, index, limit);
3160 >            this.map = map;
3161 >            advance();
3162          }
3163  
3164 <        /**
3165 <         * Returns the result of accumulating all values using the
3166 <         * given reducer to combine values, or null if none.
3167 <         *
3168 <         * @param reducer a commutative associative combining function
3169 <         * @return  the result of accumulating all values
3170 <         */
3171 <        public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3172 <            return fjp.invoke(ForkJoinTasks.reduceValues
3956 <                              (ConcurrentHashMapV8.this, reducer));
3164 >        public final boolean hasNext() { return next != null; }
3165 >        public final boolean hasMoreElements() { return next != null; }
3166 >
3167 >        public final void remove() {
3168 >            Node<K,V> p;
3169 >            if ((p = lastReturned) == null)
3170 >                throw new IllegalStateException();
3171 >            lastReturned = null;
3172 >            map.replaceNode(p.key, null, null);
3173          }
3174 +    }
3175  
3176 <        /**
3177 <         * Returns the result of accumulating the given transformation
3178 <         * of all values using the given reducer to combine values, or
3179 <         * null if none.
3180 <         *
3964 <         * @param transformer a function returning the transformation
3965 <         * for an element, or null if there is no transformation (in
3966 <         * which case it is not combined)
3967 <         * @param reducer a commutative associative combining function
3968 <         * @return the result of accumulating the given transformation
3969 <         * of all values
3970 <         */
3971 <        public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3972 <                                  BiFun<? super U, ? super U, ? extends U> reducer) {
3973 <            return fjp.invoke(ForkJoinTasks.reduceValues
3974 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3176 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3177 >        implements Iterator<K>, Enumeration<K> {
3178 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3179 >                    ConcurrentHashMapV8<K,V> map) {
3180 >            super(tab, index, size, limit, map);
3181          }
3182  
3183 <        /**
3184 <         * Returns the result of accumulating the given transformation
3185 <         * of all values using the given reducer to combine values,
3186 <         * and the given basis as an identity value.
3187 <         *
3188 <         * @param transformer a function returning the transformation
3189 <         * for an element
3190 <         * @param basis the identity (initial default value) for the reduction
3985 <         * @param reducer a commutative associative combining function
3986 <         * @return the result of accumulating the given transformation
3987 <         * of all values
3988 <         */
3989 <        public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3990 <                                           double basis,
3991 <                                           DoubleByDoubleToDouble reducer) {
3992 <            return fjp.invoke(ForkJoinTasks.reduceValuesToDouble
3993 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3183 >        public final K next() {
3184 >            Node<K,V> p;
3185 >            if ((p = next) == null)
3186 >                throw new NoSuchElementException();
3187 >            K k = p.key;
3188 >            lastReturned = p;
3189 >            advance();
3190 >            return k;
3191          }
3192  
3193 <        /**
3194 <         * Returns the result of accumulating the given transformation
3195 <         * of all values using the given reducer to combine values,
3196 <         * and the given basis as an identity value.
3197 <         *
3198 <         * @param transformer a function returning the transformation
3199 <         * for an element
3200 <         * @param basis the identity (initial default value) for the reduction
4004 <         * @param reducer a commutative associative combining function
4005 <         * @return the result of accumulating the given transformation
4006 <         * of all values
4007 <         */
4008 <        public long reduceValuesToLong(ObjectToLong<? super V> transformer,
4009 <                                       long basis,
4010 <                                       LongByLongToLong reducer) {
4011 <            return fjp.invoke(ForkJoinTasks.reduceValuesToLong
4012 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3193 >        public final K nextElement() { return next(); }
3194 >    }
3195 >
3196 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3197 >        implements Iterator<V>, Enumeration<V> {
3198 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3199 >                      ConcurrentHashMapV8<K,V> map) {
3200 >            super(tab, index, size, limit, map);
3201          }
3202  
3203 <        /**
3204 <         * Returns the result of accumulating the given transformation
3205 <         * of all values using the given reducer to combine values,
3206 <         * and the given basis as an identity value.
3207 <         *
3208 <         * @param transformer a function returning the transformation
3209 <         * for an element
3210 <         * @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 <         */
4027 <        public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4028 <                                     int basis,
4029 <                                     IntByIntToInt reducer) {
4030 <            return fjp.invoke(ForkJoinTasks.reduceValuesToInt
4031 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3203 >        public final V next() {
3204 >            Node<K,V> p;
3205 >            if ((p = next) == null)
3206 >                throw new NoSuchElementException();
3207 >            V v = p.val;
3208 >            lastReturned = p;
3209 >            advance();
3210 >            return v;
3211          }
3212  
3213 <        /**
3214 <         * Performs the given action for each entry.
3215 <         *
3216 <         * @param action the action
3217 <         */
3218 <        public void forEachEntry(Action<Map.Entry<K,V>> action) {
3219 <            fjp.invoke(ForkJoinTasks.forEachEntry
3220 <                       (ConcurrentHashMapV8.this, action));
3213 >        public final V nextElement() { return next(); }
3214 >    }
3215 >
3216 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3217 >        implements Iterator<Map.Entry<K,V>> {
3218 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3219 >                      ConcurrentHashMapV8<K,V> map) {
3220 >            super(tab, index, size, limit, map);
3221          }
3222  
3223 <        /**
3224 <         * Performs the given action for each non-null transformation
3225 <         * of each entry.
3226 <         *
3227 <         * @param transformer a function returning the transformation
3228 <         * for an element, or null if there is no transformation (in
3229 <         * which case the action is not applied)
3230 <         * @param action the action
3231 <         */
4053 <        public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4054 <                                     Action<U> action) {
4055 <            fjp.invoke(ForkJoinTasks.forEachEntry
4056 <                       (ConcurrentHashMapV8.this, transformer, action));
3223 >        public final Map.Entry<K,V> next() {
3224 >            Node<K,V> p;
3225 >            if ((p = next) == null)
3226 >                throw new NoSuchElementException();
3227 >            K k = p.key;
3228 >            V v = p.val;
3229 >            lastReturned = p;
3230 >            advance();
3231 >            return new MapEntry<K,V>(k, v, map);
3232          }
3233 +    }
3234  
3235 <        /**
3236 <         * Returns a non-null result from applying the given search
3237 <         * function on each entry, or null if none.  Upon success,
3238 <         * further element processing is suppressed and the results of
3239 <         * any other parallel invocations of the search function are
3240 <         * ignored.
3241 <         *
3242 <         * @param searchFunction a function returning a non-null
3243 <         * result on success, else null
3244 <         * @return a non-null result from applying the given search
3245 <         * function on each entry, or null if none
4070 <         */
4071 <        public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4072 <            return fjp.invoke(ForkJoinTasks.searchEntries
4073 <                              (ConcurrentHashMapV8.this, searchFunction));
3235 >    /**
3236 >     * Exported Entry for EntryIterator
3237 >     */
3238 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3239 >        final K key; // non-null
3240 >        V val;       // non-null
3241 >        final ConcurrentHashMapV8<K,V> map;
3242 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3243 >            this.key = key;
3244 >            this.val = val;
3245 >            this.map = map;
3246          }
3247 +        public K getKey()        { return key; }
3248 +        public V getValue()      { return val; }
3249 +        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3250 +        public String toString() { return key + "=" + val; }
3251  
3252 <        /**
3253 <         * Returns the result of accumulating all entries using the
3254 <         * given reducer to combine values, or null if none.
3255 <         *
3256 <         * @param reducer a commutative associative combining function
3257 <         * @return the result of accumulating all entries
3258 <         */
4083 <        public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4084 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4085 <                              (ConcurrentHashMapV8.this, reducer));
3252 >        public boolean equals(Object o) {
3253 >            Object k, v; Map.Entry<?,?> e;
3254 >            return ((o instanceof Map.Entry) &&
3255 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3256 >                    (v = e.getValue()) != null &&
3257 >                    (k == key || k.equals(key)) &&
3258 >                    (v == val || v.equals(val)));
3259          }
3260  
3261          /**
3262 <         * Returns the result of accumulating the given transformation
3263 <         * of all entries using the given reducer to combine values,
3264 <         * or null if none.
3265 <         *
3266 <         * @param transformer a function returning the transformation
3267 <         * for an element, or null if there is no transformation (in
4095 <         * which case it is not combined).
4096 <         * @param reducer a commutative associative combining function
4097 <         * @return the result of accumulating the given transformation
4098 <         * of all entries
3262 >         * Sets our entry's value and writes through to the map. The
3263 >         * value to return is somewhat arbitrary here. Since we do not
3264 >         * necessarily track asynchronous changes, the most recent
3265 >         * "previous" value could be different from what we return (or
3266 >         * could even have been removed, in which case the put will
3267 >         * re-establish). We do not and cannot guarantee more.
3268           */
3269 <        public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
3270 <                                   BiFun<? super U, ? super U, ? extends U> reducer) {
3271 <            return fjp.invoke(ForkJoinTasks.reduceEntries
3272 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3269 >        public V setValue(V value) {
3270 >            if (value == null) throw new NullPointerException();
3271 >            V v = val;
3272 >            val = value;
3273 >            map.put(key, value);
3274 >            return v;
3275          }
3276 +    }
3277  
3278 <        /**
3279 <         * Returns the result of accumulating the given transformation
3280 <         * of all entries using the given reducer to combine values,
3281 <         * and the given basis as an identity value.
3282 <         *
3283 <         * @param transformer a function returning the transformation
3284 <         * for an element
3285 <         * @param basis the identity (initial default value) for the reduction
3286 <         * @param reducer a commutative associative combining function
3287 <         * @return the result of accumulating the given transformation
3288 <         * of all entries
3289 <         */
3290 <        public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
3291 <                                            double basis,
4120 <                                            DoubleByDoubleToDouble reducer) {
4121 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToDouble
4122 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3278 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3279 >        implements ConcurrentHashMapSpliterator<K> {
3280 >        long est;               // size estimate
3281 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3282 >                       long est) {
3283 >            super(tab, size, index, limit);
3284 >            this.est = est;
3285 >        }
3286 >
3287 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3288 >            int i, f, h;
3289 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3290 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3291 >                                        f, est >>>= 1);
3292          }
3293  
3294 <        /**
3295 <         * Returns the result of accumulating the given transformation
3296 <         * of all entries using the given reducer to combine values,
3297 <         * and the given basis as an identity value.
4129 <         *
4130 <         * @param transformer a function returning the transformation
4131 <         * for an element
4132 <         * @param basis the identity (initial default value) for the reduction
4133 <         * @param reducer a commutative associative combining function
4134 <         * @return  the result of accumulating the given transformation
4135 <         * of all entries
4136 <         */
4137 <        public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4138 <                                        long basis,
4139 <                                        LongByLongToLong reducer) {
4140 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToLong
4141 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3294 >        public void forEachRemaining(Action<? super K> action) {
3295 >            if (action == null) throw new NullPointerException();
3296 >            for (Node<K,V> p; (p = advance()) != null;)
3297 >                action.apply(p.key);
3298          }
3299  
3300 <        /**
3301 <         * Returns the result of accumulating the given transformation
3302 <         * of all entries using the given reducer to combine values,
3303 <         * and the given basis as an identity value.
3304 <         *
3305 <         * @param transformer a function returning the transformation
3306 <         * for an element
4151 <         * @param basis the identity (initial default value) for the reduction
4152 <         * @param reducer a commutative associative combining function
4153 <         * @return the result of accumulating the given transformation
4154 <         * of all entries
4155 <         */
4156 <        public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4157 <                                      int basis,
4158 <                                      IntByIntToInt reducer) {
4159 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToInt
4160 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3300 >        public boolean tryAdvance(Action<? super K> action) {
3301 >            if (action == null) throw new NullPointerException();
3302 >            Node<K,V> p;
3303 >            if ((p = advance()) == null)
3304 >                return false;
3305 >            action.apply(p.key);
3306 >            return true;
3307          }
3308 +
3309 +        public long estimateSize() { return est; }
3310 +
3311      }
3312  
3313 <    // ---------------------------------------------------------------------
3313 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3314 >        implements ConcurrentHashMapSpliterator<V> {
3315 >        long est;               // size estimate
3316 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3317 >                         long est) {
3318 >            super(tab, size, index, limit);
3319 >            this.est = est;
3320 >        }
3321  
3322 <    /**
3323 <     * Predefined tasks for performing bulk parallel operations on
3324 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
3325 <     * in class {@link Parallel}. Each method has the same name, but
3326 <     * returns a task rather than invoking it. These methods may be
3327 <     * useful in custom applications such as submitting a task without
4172 <     * waiting for completion, or combining with other tasks.
4173 <     */
4174 <    public static class ForkJoinTasks {
4175 <        private ForkJoinTasks() {}
3322 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3323 >            int i, f, h;
3324 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3325 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3326 >                                          f, est >>>= 1);
3327 >        }
3328  
3329 <        /**
4178 <         * Returns a task that when invoked, performs the given
4179 <         * action for each (key, value)
4180 <         *
4181 <         * @param map the map
4182 <         * @param action the action
4183 <         * @return the task
4184 <         */
4185 <        public static <K,V> ForkJoinTask<Void> forEach
4186 <            (ConcurrentHashMapV8<K,V> map,
4187 <             BiAction<K,V> action) {
3329 >        public void forEachRemaining(Action<? super V> action) {
3330              if (action == null) throw new NullPointerException();
3331 <            return new ForEachMappingTask<K,V>(map, null, -1, action);
3331 >            for (Node<K,V> p; (p = advance()) != null;)
3332 >                action.apply(p.val);
3333          }
3334  
3335 <        /**
3336 <         * Returns a task that when invoked, performs the given
3337 <         * action for each non-null transformation of each (key, value)
3338 <         *
3339 <         * @param map the map
3340 <         * @param transformer a function returning the transformation
3341 <         * for an element, or null if there is no transformation (in
4199 <         * which case the action is not applied)
4200 <         * @param action the action
4201 <         * @return the task
4202 <         */
4203 <        public static <K,V,U> ForkJoinTask<Void> forEach
4204 <            (ConcurrentHashMapV8<K,V> map,
4205 <             BiFun<? super K, ? super V, ? extends U> transformer,
4206 <             Action<U> action) {
4207 <            if (transformer == null || action == null)
4208 <                throw new NullPointerException();
4209 <            return new ForEachTransformedMappingTask<K,V,U>
4210 <                (map, null, -1, transformer, action);
3335 >        public boolean tryAdvance(Action<? super V> action) {
3336 >            if (action == null) throw new NullPointerException();
3337 >            Node<K,V> p;
3338 >            if ((p = advance()) == null)
3339 >                return false;
3340 >            action.apply(p.val);
3341 >            return true;
3342          }
3343  
3344 <        /**
3345 <         * Returns a task that when invoked, returns a non-null result
3346 <         * from applying the given search function on each (key,
3347 <         * value), or null if none. Upon success, further element
3348 <         * processing is suppressed and the results of any other
3349 <         * parallel invocations of the search function are ignored.
3350 <         *
3351 <         * @param map the map
3352 <         * @param searchFunction a function returning a non-null
3353 <         * result on success, else null
3354 <         * @return the task
3355 <         */
3356 <        public static <K,V,U> ForkJoinTask<U> search
4226 <            (ConcurrentHashMapV8<K,V> map,
4227 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4228 <            if (searchFunction == null) throw new NullPointerException();
4229 <            return new SearchMappingsTask<K,V,U>
4230 <                (map, null, -1, searchFunction,
4231 <                 new AtomicReference<U>());
3344 >        public long estimateSize() { return est; }
3345 >
3346 >    }
3347 >
3348 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3349 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3350 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3351 >        long est;               // size estimate
3352 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3353 >                         long est, ConcurrentHashMapV8<K,V> map) {
3354 >            super(tab, size, index, limit);
3355 >            this.map = map;
3356 >            this.est = est;
3357          }
3358  
3359 <        /**
3360 <         * Returns a task that when invoked, returns the result of
3361 <         * accumulating the given transformation of all (key, value) pairs
3362 <         * using the given reducer to combine values, or null if none.
3363 <         *
4239 <         * @param map the map
4240 <         * @param transformer a function returning the transformation
4241 <         * for an element, or null if there is no transformation (in
4242 <         * which case it is not combined).
4243 <         * @param reducer a commutative associative combining function
4244 <         * @return the task
4245 <         */
4246 <        public static <K,V,U> ForkJoinTask<U> reduce
4247 <            (ConcurrentHashMapV8<K,V> map,
4248 <             BiFun<? super K, ? super V, ? extends U> transformer,
4249 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4250 <            if (transformer == null || reducer == null)
4251 <                throw new NullPointerException();
4252 <            return new MapReduceMappingsTask<K,V,U>
4253 <                (map, null, -1, null, transformer, reducer);
3359 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3360 >            int i, f, h;
3361 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3362 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3363 >                                          f, est >>>= 1, map);
3364          }
3365  
3366 <        /**
3367 <         * Returns a task that when invoked, returns the result of
3368 <         * accumulating the given transformation of all (key, value) pairs
3369 <         * using the given reducer to combine values, and the given
4260 <         * basis as an identity value.
4261 <         *
4262 <         * @param map the map
4263 <         * @param transformer a function returning the transformation
4264 <         * for an element
4265 <         * @param basis the identity (initial default value) for the reduction
4266 <         * @param reducer a commutative associative combining function
4267 <         * @return the task
4268 <         */
4269 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4270 <            (ConcurrentHashMapV8<K,V> map,
4271 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4272 <             double basis,
4273 <             DoubleByDoubleToDouble reducer) {
4274 <            if (transformer == null || reducer == null)
4275 <                throw new NullPointerException();
4276 <            return new MapReduceMappingsToDoubleTask<K,V>
4277 <                (map, null, -1, null, transformer, basis, reducer);
3366 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3367 >            if (action == null) throw new NullPointerException();
3368 >            for (Node<K,V> p; (p = advance()) != null; )
3369 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3370          }
3371  
3372 <        /**
3373 <         * Returns a task that when invoked, returns the result of
3374 <         * accumulating the given transformation of all (key, value) pairs
3375 <         * using the given reducer to combine values, and the given
3376 <         * basis as an identity value.
3377 <         *
3378 <         * @param map the map
4287 <         * @param transformer a function returning the transformation
4288 <         * for an element
4289 <         * @param basis the identity (initial default value) for the reduction
4290 <         * @param reducer a commutative associative combining function
4291 <         * @return the task
4292 <         */
4293 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4294 <            (ConcurrentHashMapV8<K,V> map,
4295 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4296 <             long basis,
4297 <             LongByLongToLong reducer) {
4298 <            if (transformer == null || reducer == null)
4299 <                throw new NullPointerException();
4300 <            return new MapReduceMappingsToLongTask<K,V>
4301 <                (map, null, -1, null, transformer, basis, reducer);
3372 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3373 >            if (action == null) throw new NullPointerException();
3374 >            Node<K,V> p;
3375 >            if ((p = advance()) == null)
3376 >                return false;
3377 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3378 >            return true;
3379          }
3380  
3381 +        public long estimateSize() { return est; }
3382 +
3383 +    }
3384 +
3385 +    // Parallel bulk operations
3386 +
3387 +    /**
3388 +     * Computes initial batch value for bulk tasks. The returned value
3389 +     * is approximately exp2 of the number of times (minus one) to
3390 +     * split task by two before executing leaf action. This value is
3391 +     * faster to compute and more convenient to use as a guide to
3392 +     * splitting than is the depth, since it is used while dividing by
3393 +     * two anyway.
3394 +     */
3395 +    final int batchFor(long b) {
3396 +        long n;
3397 +        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3398 +            return 0;
3399 +        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3400 +        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3401 +    }
3402 +
3403 +    /**
3404 +     * Performs the given action for each (key, value).
3405 +     *
3406 +     * @param parallelismThreshold the (estimated) number of elements
3407 +     * needed for this operation to be executed in parallel
3408 +     * @param action the action
3409 +     * @since 1.8
3410 +     */
3411 +    public void forEach(long parallelismThreshold,
3412 +                        BiAction<? super K,? super V> action) {
3413 +        if (action == null) throw new NullPointerException();
3414 +        new ForEachMappingTask<K,V>
3415 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3416 +             action).invoke();
3417 +    }
3418 +
3419 +    /**
3420 +     * Performs the given action for each non-null transformation
3421 +     * of each (key, value).
3422 +     *
3423 +     * @param parallelismThreshold the (estimated) number of elements
3424 +     * needed for this operation to be executed in parallel
3425 +     * @param transformer a function returning the transformation
3426 +     * for an element, or null if there is no transformation (in
3427 +     * which case the action is not applied)
3428 +     * @param action the action
3429 +     * @since 1.8
3430 +     */
3431 +    public <U> void forEach(long parallelismThreshold,
3432 +                            BiFun<? super K, ? super V, ? extends U> transformer,
3433 +                            Action<? super U> action) {
3434 +        if (transformer == null || action == null)
3435 +            throw new NullPointerException();
3436 +        new ForEachTransformedMappingTask<K,V,U>
3437 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3438 +             transformer, action).invoke();
3439 +    }
3440 +
3441 +    /**
3442 +     * Returns a non-null result from applying the given search
3443 +     * function on each (key, value), or null if none.  Upon
3444 +     * success, further element processing is suppressed and the
3445 +     * results of any other parallel invocations of the search
3446 +     * function are ignored.
3447 +     *
3448 +     * @param parallelismThreshold the (estimated) number of elements
3449 +     * needed for this operation to be executed in parallel
3450 +     * @param searchFunction a function returning a non-null
3451 +     * result on success, else null
3452 +     * @return a non-null result from applying the given search
3453 +     * function on each (key, value), or null if none
3454 +     * @since 1.8
3455 +     */
3456 +    public <U> U search(long parallelismThreshold,
3457 +                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3458 +        if (searchFunction == null) throw new NullPointerException();
3459 +        return new SearchMappingsTask<K,V,U>
3460 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3461 +             searchFunction, new AtomicReference<U>()).invoke();
3462 +    }
3463 +
3464 +    /**
3465 +     * Returns the result of accumulating the given transformation
3466 +     * of all (key, value) pairs using the given reducer to
3467 +     * combine values, or null if none.
3468 +     *
3469 +     * @param parallelismThreshold the (estimated) number of elements
3470 +     * needed for this operation to be executed in parallel
3471 +     * @param transformer a function returning the transformation
3472 +     * for an element, or null if there is no transformation (in
3473 +     * which case it is not combined)
3474 +     * @param reducer a commutative associative combining function
3475 +     * @return the result of accumulating the given transformation
3476 +     * of all (key, value) pairs
3477 +     * @since 1.8
3478 +     */
3479 +    public <U> U reduce(long parallelismThreshold,
3480 +                        BiFun<? super K, ? super V, ? extends U> transformer,
3481 +                        BiFun<? super U, ? super U, ? extends U> reducer) {
3482 +        if (transformer == null || reducer == null)
3483 +            throw new NullPointerException();
3484 +        return new MapReduceMappingsTask<K,V,U>
3485 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3486 +             null, transformer, reducer).invoke();
3487 +    }
3488 +
3489 +    /**
3490 +     * Returns the result of accumulating the given transformation
3491 +     * of all (key, value) pairs using the given reducer to
3492 +     * combine values, and the given basis as an identity value.
3493 +     *
3494 +     * @param parallelismThreshold the (estimated) number of elements
3495 +     * needed for this operation to be executed in parallel
3496 +     * @param transformer a function returning the transformation
3497 +     * for an element
3498 +     * @param basis the identity (initial default value) for the reduction
3499 +     * @param reducer a commutative associative combining function
3500 +     * @return the result of accumulating the given transformation
3501 +     * of all (key, value) pairs
3502 +     * @since 1.8
3503 +     */
3504 +    public double reduceToDouble(long parallelismThreshold,
3505 +                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3506 +                                 double basis,
3507 +                                 DoubleByDoubleToDouble reducer) {
3508 +        if (transformer == null || reducer == null)
3509 +            throw new NullPointerException();
3510 +        return new MapReduceMappingsToDoubleTask<K,V>
3511 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3512 +             null, transformer, basis, reducer).invoke();
3513 +    }
3514 +
3515 +    /**
3516 +     * Returns the result of accumulating the given transformation
3517 +     * of all (key, value) pairs using the given reducer to
3518 +     * combine values, and the given basis as an identity value.
3519 +     *
3520 +     * @param parallelismThreshold the (estimated) number of elements
3521 +     * needed for this operation to be executed in parallel
3522 +     * @param transformer a function returning the transformation
3523 +     * for an element
3524 +     * @param basis the identity (initial default value) for the reduction
3525 +     * @param reducer a commutative associative combining function
3526 +     * @return the result of accumulating the given transformation
3527 +     * of all (key, value) pairs
3528 +     * @since 1.8
3529 +     */
3530 +    public long reduceToLong(long parallelismThreshold,
3531 +                             ObjectByObjectToLong<? super K, ? super V> transformer,
3532 +                             long basis,
3533 +                             LongByLongToLong reducer) {
3534 +        if (transformer == null || reducer == null)
3535 +            throw new NullPointerException();
3536 +        return new MapReduceMappingsToLongTask<K,V>
3537 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3538 +             null, transformer, basis, reducer).invoke();
3539 +    }
3540 +
3541 +    /**
3542 +     * Returns the result of accumulating the given transformation
3543 +     * of all (key, value) pairs using the given reducer to
3544 +     * combine values, and the given basis as an identity value.
3545 +     *
3546 +     * @param parallelismThreshold the (estimated) number of elements
3547 +     * needed for this operation to be executed in parallel
3548 +     * @param transformer a function returning the transformation
3549 +     * for an element
3550 +     * @param basis the identity (initial default value) for the reduction
3551 +     * @param reducer a commutative associative combining function
3552 +     * @return the result of accumulating the given transformation
3553 +     * of all (key, value) pairs
3554 +     * @since 1.8
3555 +     */
3556 +    public int reduceToInt(long parallelismThreshold,
3557 +                           ObjectByObjectToInt<? super K, ? super V> transformer,
3558 +                           int basis,
3559 +                           IntByIntToInt reducer) {
3560 +        if (transformer == null || reducer == null)
3561 +            throw new NullPointerException();
3562 +        return new MapReduceMappingsToIntTask<K,V>
3563 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3564 +             null, transformer, basis, reducer).invoke();
3565 +    }
3566 +
3567 +    /**
3568 +     * Performs the given action for each key.
3569 +     *
3570 +     * @param parallelismThreshold the (estimated) number of elements
3571 +     * needed for this operation to be executed in parallel
3572 +     * @param action the action
3573 +     * @since 1.8
3574 +     */
3575 +    public void forEachKey(long parallelismThreshold,
3576 +                           Action<? super K> action) {
3577 +        if (action == null) throw new NullPointerException();
3578 +        new ForEachKeyTask<K,V>
3579 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3580 +             action).invoke();
3581 +    }
3582 +
3583 +    /**
3584 +     * Performs the given action for each non-null transformation
3585 +     * of each key.
3586 +     *
3587 +     * @param parallelismThreshold the (estimated) number of elements
3588 +     * needed for this operation to be executed in parallel
3589 +     * @param transformer a function returning the transformation
3590 +     * for an element, or null if there is no transformation (in
3591 +     * which case the action is not applied)
3592 +     * @param action the action
3593 +     * @since 1.8
3594 +     */
3595 +    public <U> void forEachKey(long parallelismThreshold,
3596 +                               Fun<? super K, ? extends U> transformer,
3597 +                               Action<? super U> action) {
3598 +        if (transformer == null || action == null)
3599 +            throw new NullPointerException();
3600 +        new ForEachTransformedKeyTask<K,V,U>
3601 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3602 +             transformer, action).invoke();
3603 +    }
3604 +
3605 +    /**
3606 +     * Returns a non-null result from applying the given search
3607 +     * function on each key, or null if none. Upon success,
3608 +     * further element processing is suppressed and the results of
3609 +     * any other parallel invocations of the search function are
3610 +     * ignored.
3611 +     *
3612 +     * @param parallelismThreshold the (estimated) number of elements
3613 +     * needed for this operation to be executed in parallel
3614 +     * @param searchFunction a function returning a non-null
3615 +     * result on success, else null
3616 +     * @return a non-null result from applying the given search
3617 +     * function on each key, or null if none
3618 +     * @since 1.8
3619 +     */
3620 +    public <U> U searchKeys(long parallelismThreshold,
3621 +                            Fun<? super K, ? extends U> searchFunction) {
3622 +        if (searchFunction == null) throw new NullPointerException();
3623 +        return new SearchKeysTask<K,V,U>
3624 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3625 +             searchFunction, new AtomicReference<U>()).invoke();
3626 +    }
3627 +
3628 +    /**
3629 +     * Returns the result of accumulating all keys using the given
3630 +     * reducer to combine values, or null if none.
3631 +     *
3632 +     * @param parallelismThreshold the (estimated) number of elements
3633 +     * needed for this operation to be executed in parallel
3634 +     * @param reducer a commutative associative combining function
3635 +     * @return the result of accumulating all keys using the given
3636 +     * reducer to combine values, or null if none
3637 +     * @since 1.8
3638 +     */
3639 +    public K reduceKeys(long parallelismThreshold,
3640 +                        BiFun<? super K, ? super K, ? extends K> reducer) {
3641 +        if (reducer == null) throw new NullPointerException();
3642 +        return new ReduceKeysTask<K,V>
3643 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3644 +             null, reducer).invoke();
3645 +    }
3646 +
3647 +    /**
3648 +     * Returns the result of accumulating the given transformation
3649 +     * of all keys using the given reducer to combine values, or
3650 +     * null if none.
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, or null if there is no transformation (in
3656 +     * which case it is not combined)
3657 +     * @param reducer a commutative associative combining function
3658 +     * @return the result of accumulating the given transformation
3659 +     * of all keys
3660 +     * @since 1.8
3661 +     */
3662 +    public <U> U reduceKeys(long parallelismThreshold,
3663 +                            Fun<? super K, ? extends U> transformer,
3664 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3665 +        if (transformer == null || reducer == null)
3666 +            throw new NullPointerException();
3667 +        return new MapReduceKeysTask<K,V,U>
3668 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3669 +             null, transformer, reducer).invoke();
3670 +    }
3671 +
3672 +    /**
3673 +     * Returns the result of accumulating the given transformation
3674 +     * of all keys using the given reducer to combine values, and
3675 +     * the given basis as an identity value.
3676 +     *
3677 +     * @param parallelismThreshold the (estimated) number of elements
3678 +     * needed for this operation to be executed in parallel
3679 +     * @param transformer a function returning the transformation
3680 +     * for an element
3681 +     * @param basis the identity (initial default value) for the reduction
3682 +     * @param reducer a commutative associative combining function
3683 +     * @return the result of accumulating the given transformation
3684 +     * of all keys
3685 +     * @since 1.8
3686 +     */
3687 +    public double reduceKeysToDouble(long parallelismThreshold,
3688 +                                     ObjectToDouble<? super K> transformer,
3689 +                                     double basis,
3690 +                                     DoubleByDoubleToDouble reducer) {
3691 +        if (transformer == null || reducer == null)
3692 +            throw new NullPointerException();
3693 +        return new MapReduceKeysToDoubleTask<K,V>
3694 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3695 +             null, transformer, basis, reducer).invoke();
3696 +    }
3697 +
3698 +    /**
3699 +     * Returns the result of accumulating the given transformation
3700 +     * of all keys using the given reducer to combine values, and
3701 +     * the given basis as an identity value.
3702 +     *
3703 +     * @param parallelismThreshold the (estimated) number of elements
3704 +     * needed for this operation to be executed in parallel
3705 +     * @param transformer a function returning the transformation
3706 +     * for an element
3707 +     * @param basis the identity (initial default value) for the reduction
3708 +     * @param reducer a commutative associative combining function
3709 +     * @return the result of accumulating the given transformation
3710 +     * of all keys
3711 +     * @since 1.8
3712 +     */
3713 +    public long reduceKeysToLong(long parallelismThreshold,
3714 +                                 ObjectToLong<? super K> transformer,
3715 +                                 long basis,
3716 +                                 LongByLongToLong reducer) {
3717 +        if (transformer == null || reducer == null)
3718 +            throw new NullPointerException();
3719 +        return new MapReduceKeysToLongTask<K,V>
3720 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3721 +             null, transformer, basis, reducer).invoke();
3722 +    }
3723 +
3724 +    /**
3725 +     * Returns the result of accumulating the given transformation
3726 +     * of all keys using the given reducer to combine values, and
3727 +     * the given basis as an identity value.
3728 +     *
3729 +     * @param parallelismThreshold the (estimated) number of elements
3730 +     * needed for this operation to be executed in parallel
3731 +     * @param transformer a function returning the transformation
3732 +     * for an element
3733 +     * @param basis the identity (initial default value) for the reduction
3734 +     * @param reducer a commutative associative combining function
3735 +     * @return the result of accumulating the given transformation
3736 +     * of all keys
3737 +     * @since 1.8
3738 +     */
3739 +    public int reduceKeysToInt(long parallelismThreshold,
3740 +                               ObjectToInt<? super K> transformer,
3741 +                               int basis,
3742 +                               IntByIntToInt reducer) {
3743 +        if (transformer == null || reducer == null)
3744 +            throw new NullPointerException();
3745 +        return new MapReduceKeysToIntTask<K,V>
3746 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3747 +             null, transformer, basis, reducer).invoke();
3748 +    }
3749 +
3750 +    /**
3751 +     * Performs the given action for each value.
3752 +     *
3753 +     * @param parallelismThreshold the (estimated) number of elements
3754 +     * needed for this operation to be executed in parallel
3755 +     * @param action the action
3756 +     * @since 1.8
3757 +     */
3758 +    public void forEachValue(long parallelismThreshold,
3759 +                             Action<? super V> action) {
3760 +        if (action == null)
3761 +            throw new NullPointerException();
3762 +        new ForEachValueTask<K,V>
3763 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3764 +             action).invoke();
3765 +    }
3766 +
3767 +    /**
3768 +     * Performs the given action for each non-null transformation
3769 +     * of each value.
3770 +     *
3771 +     * @param parallelismThreshold the (estimated) number of elements
3772 +     * needed for this operation to be executed in parallel
3773 +     * @param transformer a function returning the transformation
3774 +     * for an element, or null if there is no transformation (in
3775 +     * which case the action is not applied)
3776 +     * @param action the action
3777 +     * @since 1.8
3778 +     */
3779 +    public <U> void forEachValue(long parallelismThreshold,
3780 +                                 Fun<? super V, ? extends U> transformer,
3781 +                                 Action<? super U> action) {
3782 +        if (transformer == null || action == null)
3783 +            throw new NullPointerException();
3784 +        new ForEachTransformedValueTask<K,V,U>
3785 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3786 +             transformer, action).invoke();
3787 +    }
3788 +
3789 +    /**
3790 +     * Returns a non-null result from applying the given search
3791 +     * function on each value, or null if none.  Upon success,
3792 +     * further element processing is suppressed and the results of
3793 +     * any other parallel invocations of the search function are
3794 +     * ignored.
3795 +     *
3796 +     * @param parallelismThreshold the (estimated) number of elements
3797 +     * needed for this operation to be executed in parallel
3798 +     * @param searchFunction a function returning a non-null
3799 +     * result on success, else null
3800 +     * @return a non-null result from applying the given search
3801 +     * function on each value, or null if none
3802 +     * @since 1.8
3803 +     */
3804 +    public <U> U searchValues(long parallelismThreshold,
3805 +                              Fun<? super V, ? extends U> searchFunction) {
3806 +        if (searchFunction == null) throw new NullPointerException();
3807 +        return new SearchValuesTask<K,V,U>
3808 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3809 +             searchFunction, new AtomicReference<U>()).invoke();
3810 +    }
3811 +
3812 +    /**
3813 +     * Returns the result of accumulating all values using the
3814 +     * given reducer to combine values, or null if none.
3815 +     *
3816 +     * @param parallelismThreshold the (estimated) number of elements
3817 +     * needed for this operation to be executed in parallel
3818 +     * @param reducer a commutative associative combining function
3819 +     * @return the result of accumulating all values
3820 +     * @since 1.8
3821 +     */
3822 +    public V reduceValues(long parallelismThreshold,
3823 +                          BiFun<? super V, ? super V, ? extends V> reducer) {
3824 +        if (reducer == null) throw new NullPointerException();
3825 +        return new ReduceValuesTask<K,V>
3826 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3827 +             null, reducer).invoke();
3828 +    }
3829 +
3830 +    /**
3831 +     * Returns the result of accumulating the given transformation
3832 +     * of all values using the given reducer to combine values, or
3833 +     * null if none.
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, or null if there is no transformation (in
3839 +     * which case it is not combined)
3840 +     * @param reducer a commutative associative combining function
3841 +     * @return the result of accumulating the given transformation
3842 +     * of all values
3843 +     * @since 1.8
3844 +     */
3845 +    public <U> U reduceValues(long parallelismThreshold,
3846 +                              Fun<? super V, ? extends U> transformer,
3847 +                              BiFun<? super U, ? super U, ? extends U> reducer) {
3848 +        if (transformer == null || reducer == null)
3849 +            throw new NullPointerException();
3850 +        return new MapReduceValuesTask<K,V,U>
3851 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3852 +             null, transformer, reducer).invoke();
3853 +    }
3854 +
3855 +    /**
3856 +     * Returns the result of accumulating the given transformation
3857 +     * of all values using the given reducer to combine values,
3858 +     * and the given basis as an identity value.
3859 +     *
3860 +     * @param parallelismThreshold the (estimated) number of elements
3861 +     * needed for this operation to be executed in parallel
3862 +     * @param transformer a function returning the transformation
3863 +     * for an element
3864 +     * @param basis the identity (initial default value) for the reduction
3865 +     * @param reducer a commutative associative combining function
3866 +     * @return the result of accumulating the given transformation
3867 +     * of all values
3868 +     * @since 1.8
3869 +     */
3870 +    public double reduceValuesToDouble(long parallelismThreshold,
3871 +                                       ObjectToDouble<? super V> transformer,
3872 +                                       double basis,
3873 +                                       DoubleByDoubleToDouble reducer) {
3874 +        if (transformer == null || reducer == null)
3875 +            throw new NullPointerException();
3876 +        return new MapReduceValuesToDoubleTask<K,V>
3877 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3878 +             null, transformer, basis, reducer).invoke();
3879 +    }
3880 +
3881 +    /**
3882 +     * Returns the result of accumulating the given transformation
3883 +     * of all values using the given reducer to combine values,
3884 +     * and the given basis as an identity value.
3885 +     *
3886 +     * @param parallelismThreshold the (estimated) number of elements
3887 +     * needed for this operation to be executed in parallel
3888 +     * @param transformer a function returning the transformation
3889 +     * for an element
3890 +     * @param basis the identity (initial default value) for the reduction
3891 +     * @param reducer a commutative associative combining function
3892 +     * @return the result of accumulating the given transformation
3893 +     * of all values
3894 +     * @since 1.8
3895 +     */
3896 +    public long reduceValuesToLong(long parallelismThreshold,
3897 +                                   ObjectToLong<? super V> transformer,
3898 +                                   long basis,
3899 +                                   LongByLongToLong reducer) {
3900 +        if (transformer == null || reducer == null)
3901 +            throw new NullPointerException();
3902 +        return new MapReduceValuesToLongTask<K,V>
3903 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3904 +             null, transformer, basis, reducer).invoke();
3905 +    }
3906 +
3907 +    /**
3908 +     * Returns the result of accumulating the given transformation
3909 +     * of all values using the given reducer to combine values,
3910 +     * and the given basis as an identity value.
3911 +     *
3912 +     * @param parallelismThreshold the (estimated) number of elements
3913 +     * needed for this operation to be executed in parallel
3914 +     * @param transformer a function returning the transformation
3915 +     * for an element
3916 +     * @param basis the identity (initial default value) for the reduction
3917 +     * @param reducer a commutative associative combining function
3918 +     * @return the result of accumulating the given transformation
3919 +     * of all values
3920 +     * @since 1.8
3921 +     */
3922 +    public int reduceValuesToInt(long parallelismThreshold,
3923 +                                 ObjectToInt<? super V> transformer,
3924 +                                 int basis,
3925 +                                 IntByIntToInt reducer) {
3926 +        if (transformer == null || reducer == null)
3927 +            throw new NullPointerException();
3928 +        return new MapReduceValuesToIntTask<K,V>
3929 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3930 +             null, transformer, basis, reducer).invoke();
3931 +    }
3932 +
3933 +    /**
3934 +     * Performs the given action for each entry.
3935 +     *
3936 +     * @param parallelismThreshold the (estimated) number of elements
3937 +     * needed for this operation to be executed in parallel
3938 +     * @param action the action
3939 +     * @since 1.8
3940 +     */
3941 +    public void forEachEntry(long parallelismThreshold,
3942 +                             Action<? super Map.Entry<K,V>> action) {
3943 +        if (action == null) throw new NullPointerException();
3944 +        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3945 +                                  action).invoke();
3946 +    }
3947 +
3948 +    /**
3949 +     * Performs the given action for each non-null transformation
3950 +     * of each entry.
3951 +     *
3952 +     * @param parallelismThreshold the (estimated) number of elements
3953 +     * needed for this operation to be executed in parallel
3954 +     * @param transformer a function returning the transformation
3955 +     * for an element, or null if there is no transformation (in
3956 +     * which case the action is not applied)
3957 +     * @param action the action
3958 +     * @since 1.8
3959 +     */
3960 +    public <U> void forEachEntry(long parallelismThreshold,
3961 +                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
3962 +                                 Action<? super U> action) {
3963 +        if (transformer == null || action == null)
3964 +            throw new NullPointerException();
3965 +        new ForEachTransformedEntryTask<K,V,U>
3966 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3967 +             transformer, action).invoke();
3968 +    }
3969 +
3970 +    /**
3971 +     * Returns a non-null result from applying the given search
3972 +     * function on each entry, or null if none.  Upon success,
3973 +     * further element processing is suppressed and the results of
3974 +     * any other parallel invocations of the search function are
3975 +     * ignored.
3976 +     *
3977 +     * @param parallelismThreshold the (estimated) number of elements
3978 +     * needed for this operation to be executed in parallel
3979 +     * @param searchFunction a function returning a non-null
3980 +     * result on success, else null
3981 +     * @return a non-null result from applying the given search
3982 +     * function on each entry, or null if none
3983 +     * @since 1.8
3984 +     */
3985 +    public <U> U searchEntries(long parallelismThreshold,
3986 +                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3987 +        if (searchFunction == null) throw new NullPointerException();
3988 +        return new SearchEntriesTask<K,V,U>
3989 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3990 +             searchFunction, new AtomicReference<U>()).invoke();
3991 +    }
3992 +
3993 +    /**
3994 +     * Returns the result of accumulating all entries using the
3995 +     * given reducer to combine values, or null if none.
3996 +     *
3997 +     * @param parallelismThreshold the (estimated) number of elements
3998 +     * needed for this operation to be executed in parallel
3999 +     * @param reducer a commutative associative combining function
4000 +     * @return the result of accumulating all entries
4001 +     * @since 1.8
4002 +     */
4003 +    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4004 +                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4005 +        if (reducer == null) throw new NullPointerException();
4006 +        return new ReduceEntriesTask<K,V>
4007 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4008 +             null, reducer).invoke();
4009 +    }
4010 +
4011 +    /**
4012 +     * Returns the result of accumulating the given transformation
4013 +     * of all entries using the given reducer to combine values,
4014 +     * or null if none.
4015 +     *
4016 +     * @param parallelismThreshold the (estimated) number of elements
4017 +     * needed for this operation to be executed in parallel
4018 +     * @param transformer a function returning the transformation
4019 +     * for an element, or null if there is no transformation (in
4020 +     * which case it is not combined)
4021 +     * @param reducer a commutative associative combining function
4022 +     * @return the result of accumulating the given transformation
4023 +     * of all entries
4024 +     * @since 1.8
4025 +     */
4026 +    public <U> U reduceEntries(long parallelismThreshold,
4027 +                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4028 +                               BiFun<? super U, ? super U, ? extends U> reducer) {
4029 +        if (transformer == null || reducer == null)
4030 +            throw new NullPointerException();
4031 +        return new MapReduceEntriesTask<K,V,U>
4032 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4033 +             null, transformer, reducer).invoke();
4034 +    }
4035 +
4036 +    /**
4037 +     * Returns the result of accumulating the given transformation
4038 +     * of all entries using the given reducer to combine values,
4039 +     * and the given basis as an identity value.
4040 +     *
4041 +     * @param parallelismThreshold the (estimated) number of elements
4042 +     * needed for this operation to be executed in parallel
4043 +     * @param transformer a function returning the transformation
4044 +     * for an element
4045 +     * @param basis the identity (initial default value) for the reduction
4046 +     * @param reducer a commutative associative combining function
4047 +     * @return the result of accumulating the given transformation
4048 +     * of all entries
4049 +     * @since 1.8
4050 +     */
4051 +    public double reduceEntriesToDouble(long parallelismThreshold,
4052 +                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4053 +                                        double basis,
4054 +                                        DoubleByDoubleToDouble reducer) {
4055 +        if (transformer == null || reducer == null)
4056 +            throw new NullPointerException();
4057 +        return new MapReduceEntriesToDoubleTask<K,V>
4058 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4059 +             null, transformer, basis, reducer).invoke();
4060 +    }
4061 +
4062 +    /**
4063 +     * Returns the result of accumulating the given transformation
4064 +     * of all entries using the given reducer to combine values,
4065 +     * and the given basis as an identity value.
4066 +     *
4067 +     * @param parallelismThreshold the (estimated) number of elements
4068 +     * needed for this operation to be executed in parallel
4069 +     * @param transformer a function returning the transformation
4070 +     * for an element
4071 +     * @param basis the identity (initial default value) for the reduction
4072 +     * @param reducer a commutative associative combining function
4073 +     * @return the result of accumulating the given transformation
4074 +     * of all entries
4075 +     * @since 1.8
4076 +     */
4077 +    public long reduceEntriesToLong(long parallelismThreshold,
4078 +                                    ObjectToLong<Map.Entry<K,V>> transformer,
4079 +                                    long basis,
4080 +                                    LongByLongToLong reducer) {
4081 +        if (transformer == null || reducer == null)
4082 +            throw new NullPointerException();
4083 +        return new MapReduceEntriesToLongTask<K,V>
4084 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4085 +             null, transformer, basis, reducer).invoke();
4086 +    }
4087 +
4088 +    /**
4089 +     * Returns the result of accumulating the given transformation
4090 +     * of all entries using the given reducer to combine values,
4091 +     * and the given basis as an identity value.
4092 +     *
4093 +     * @param parallelismThreshold the (estimated) number of elements
4094 +     * needed for this operation to be executed in parallel
4095 +     * @param transformer a function returning the transformation
4096 +     * for an element
4097 +     * @param basis the identity (initial default value) for the reduction
4098 +     * @param reducer a commutative associative combining function
4099 +     * @return the result of accumulating the given transformation
4100 +     * of all entries
4101 +     * @since 1.8
4102 +     */
4103 +    public int reduceEntriesToInt(long parallelismThreshold,
4104 +                                  ObjectToInt<Map.Entry<K,V>> transformer,
4105 +                                  int basis,
4106 +                                  IntByIntToInt reducer) {
4107 +        if (transformer == null || reducer == null)
4108 +            throw new NullPointerException();
4109 +        return new MapReduceEntriesToIntTask<K,V>
4110 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4111 +             null, transformer, basis, reducer).invoke();
4112 +    }
4113 +
4114 +
4115 +    /* ----------------Views -------------- */
4116 +
4117 +    /**
4118 +     * Base class for views.
4119 +     */
4120 +    abstract static class CollectionView<K,V,E>
4121 +        implements Collection<E>, java.io.Serializable {
4122 +        private static final long serialVersionUID = 7249069246763182397L;
4123 +        final ConcurrentHashMapV8<K,V> map;
4124 +        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4125 +
4126          /**
4127 <         * Returns a task that when invoked, returns the result of
4306 <         * accumulating the given transformation of all (key, value) pairs
4307 <         * using the given reducer to combine values, and the given
4308 <         * basis as an identity value.
4127 >         * Returns the map backing this view.
4128           *
4129 <         * @param transformer a function returning the transformation
4311 <         * for an element
4312 <         * @param basis the identity (initial default value) for the reduction
4313 <         * @param reducer a commutative associative combining function
4314 <         * @return the task
4129 >         * @return the map backing this view
4130           */
4131 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4317 <            (ConcurrentHashMapV8<K,V> map,
4318 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4319 <             int basis,
4320 <             IntByIntToInt reducer) {
4321 <            if (transformer == null || reducer == null)
4322 <                throw new NullPointerException();
4323 <            return new MapReduceMappingsToIntTask<K,V>
4324 <                (map, null, -1, null, transformer, basis, reducer);
4325 <        }
4131 >        public ConcurrentHashMapV8<K,V> getMap() { return map; }
4132  
4133          /**
4134 <         * Returns a task that when invoked, performs the given action
4135 <         * for each key.
4330 <         *
4331 <         * @param map the map
4332 <         * @param action the action
4333 <         * @return the task
4134 >         * Removes all of the elements from this view, by removing all
4135 >         * the mappings from the map backing this view.
4136           */
4137 <        public static <K,V> ForkJoinTask<Void> forEachKey
4138 <            (ConcurrentHashMapV8<K,V> map,
4139 <             Action<K> action) {
4338 <            if (action == null) throw new NullPointerException();
4339 <            return new ForEachKeyTask<K,V>(map, null, -1, action);
4340 <        }
4137 >        public final void clear()      { map.clear(); }
4138 >        public final int size()        { return map.size(); }
4139 >        public final boolean isEmpty() { return map.isEmpty(); }
4140  
4141 +        // implementations below rely on concrete classes supplying these
4142 +        // abstract methods
4143          /**
4144 <         * Returns a task that when invoked, performs the given action
4145 <         * for each non-null transformation of each key.
4146 <         *
4147 <         * @param map the map
4148 <         * @param transformer a function returning the transformation
4149 <         * for an element, or null if there is no transformation (in
4150 <         * which case the action is not applied)
4151 <         * @param action the action
4152 <         * @return the task
4153 <         */
4154 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4155 <            (ConcurrentHashMapV8<K,V> map,
4156 <             Fun<? super K, ? extends U> transformer,
4157 <             Action<U> action) {
4158 <            if (transformer == null || action == null)
4159 <                throw new NullPointerException();
4160 <            return new ForEachTransformedKeyTask<K,V,U>
4161 <                (map, null, -1, transformer, action);
4144 >         * Returns a "weakly consistent" iterator that will never
4145 >         * throw {@link ConcurrentModificationException}, and
4146 >         * guarantees to traverse elements as they existed upon
4147 >         * construction of the iterator, and may (but is not
4148 >         * guaranteed to) reflect any modifications subsequent to
4149 >         * construction.
4150 >         */
4151 >        public abstract Iterator<E> iterator();
4152 >        public abstract boolean contains(Object o);
4153 >        public abstract boolean remove(Object o);
4154 >
4155 >        private static final String oomeMsg = "Required array size too large";
4156 >
4157 >        public final Object[] toArray() {
4158 >            long sz = map.mappingCount();
4159 >            if (sz > MAX_ARRAY_SIZE)
4160 >                throw new OutOfMemoryError(oomeMsg);
4161 >            int n = (int)sz;
4162 >            Object[] r = new Object[n];
4163 >            int i = 0;
4164 >            for (E e : this) {
4165 >                if (i == n) {
4166 >                    if (n >= MAX_ARRAY_SIZE)
4167 >                        throw new OutOfMemoryError(oomeMsg);
4168 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4169 >                        n = MAX_ARRAY_SIZE;
4170 >                    else
4171 >                        n += (n >>> 1) + 1;
4172 >                    r = Arrays.copyOf(r, n);
4173 >                }
4174 >                r[i++] = e;
4175 >            }
4176 >            return (i == n) ? r : Arrays.copyOf(r, i);
4177          }
4178  
4179 <        /**
4180 <         * Returns a task that when invoked, returns a non-null result
4181 <         * from applying the given search function on each key, or
4182 <         * null if none.  Upon success, further element processing is
4183 <         * suppressed and the results of any other parallel
4184 <         * invocations of the search function are ignored.
4185 <         *
4186 <         * @param map the map
4187 <         * @param searchFunction a function returning a non-null
4188 <         * result on success, else null
4189 <         * @return the task
4190 <         */
4191 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4192 <            (ConcurrentHashMapV8<K,V> map,
4193 <             Fun<? super K, ? extends U> searchFunction) {
4194 <            if (searchFunction == null) throw new NullPointerException();
4195 <            return new SearchKeysTask<K,V,U>
4196 <                (map, null, -1, searchFunction,
4197 <                 new AtomicReference<U>());
4179 >        @SuppressWarnings("unchecked")
4180 >        public final <T> T[] toArray(T[] a) {
4181 >            long sz = map.mappingCount();
4182 >            if (sz > MAX_ARRAY_SIZE)
4183 >                throw new OutOfMemoryError(oomeMsg);
4184 >            int m = (int)sz;
4185 >            T[] r = (a.length >= m) ? a :
4186 >                (T[])java.lang.reflect.Array
4187 >                .newInstance(a.getClass().getComponentType(), m);
4188 >            int n = r.length;
4189 >            int i = 0;
4190 >            for (E e : this) {
4191 >                if (i == n) {
4192 >                    if (n >= MAX_ARRAY_SIZE)
4193 >                        throw new OutOfMemoryError(oomeMsg);
4194 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4195 >                        n = MAX_ARRAY_SIZE;
4196 >                    else
4197 >                        n += (n >>> 1) + 1;
4198 >                    r = Arrays.copyOf(r, n);
4199 >                }
4200 >                r[i++] = (T)e;
4201 >            }
4202 >            if (a == r && i < n) {
4203 >                r[i] = null; // null-terminate
4204 >                return r;
4205 >            }
4206 >            return (i == n) ? r : Arrays.copyOf(r, i);
4207          }
4208  
4209          /**
4210 <         * Returns a task that when invoked, returns the result of
4211 <         * accumulating all keys using the given reducer to combine
4212 <         * values, or null if none.
4210 >         * Returns a string representation of this collection.
4211 >         * The string representation consists of the string representations
4212 >         * of the collection's elements in the order they are returned by
4213 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4214 >         * Adjacent elements are separated by the characters {@code ", "}
4215 >         * (comma and space).  Elements are converted to strings as by
4216 >         * {@link String#valueOf(Object)}.
4217           *
4218 <         * @param map the map
4390 <         * @param reducer a commutative associative combining function
4391 <         * @return the task
4218 >         * @return a string representation of this collection
4219           */
4220 <        public static <K,V> ForkJoinTask<K> reduceKeys
4221 <            (ConcurrentHashMapV8<K,V> map,
4222 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4223 <            if (reducer == null) throw new NullPointerException();
4224 <            return new ReduceKeysTask<K,V>
4225 <                (map, null, -1, null, reducer);
4220 >        public final String toString() {
4221 >            StringBuilder sb = new StringBuilder();
4222 >            sb.append('[');
4223 >            Iterator<E> it = iterator();
4224 >            if (it.hasNext()) {
4225 >                for (;;) {
4226 >                    Object e = it.next();
4227 >                    sb.append(e == this ? "(this Collection)" : e);
4228 >                    if (!it.hasNext())
4229 >                        break;
4230 >                    sb.append(',').append(' ');
4231 >                }
4232 >            }
4233 >            return sb.append(']').toString();
4234          }
4235  
4236 <        /**
4237 <         * Returns a task that when invoked, returns the result of
4238 <         * accumulating the given transformation of all keys using the given
4239 <         * reducer to combine values, or null if none.
4240 <         *
4241 <         * @param map the map
4242 <         * @param transformer a function returning the transformation
4243 <         * for an element, or null if there is no transformation (in
4409 <         * which case it is not combined).
4410 <         * @param reducer a commutative associative combining function
4411 <         * @return the task
4412 <         */
4413 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4414 <            (ConcurrentHashMapV8<K,V> map,
4415 <             Fun<? super K, ? extends U> transformer,
4416 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4417 <            if (transformer == null || reducer == null)
4418 <                throw new NullPointerException();
4419 <            return new MapReduceKeysTask<K,V,U>
4420 <                (map, null, -1, null, transformer, reducer);
4236 >        public final boolean containsAll(Collection<?> c) {
4237 >            if (c != this) {
4238 >                for (Object e : c) {
4239 >                    if (e == null || !contains(e))
4240 >                        return false;
4241 >                }
4242 >            }
4243 >            return true;
4244          }
4245  
4246 <        /**
4247 <         * Returns a task that when invoked, returns the result of
4248 <         * accumulating the given transformation of all keys using the given
4249 <         * reducer to combine values, and the given basis as an
4250 <         * identity value.
4251 <         *
4252 <         * @param map the map
4253 <         * @param transformer a function returning the transformation
4254 <         * for an element
4432 <         * @param basis the identity (initial default value) for the reduction
4433 <         * @param reducer a commutative associative combining function
4434 <         * @return the task
4435 <         */
4436 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4437 <            (ConcurrentHashMapV8<K,V> map,
4438 <             ObjectToDouble<? super K> transformer,
4439 <             double basis,
4440 <             DoubleByDoubleToDouble reducer) {
4441 <            if (transformer == null || reducer == null)
4442 <                throw new NullPointerException();
4443 <            return new MapReduceKeysToDoubleTask<K,V>
4444 <                (map, null, -1, null, transformer, basis, reducer);
4246 >        public final boolean removeAll(Collection<?> c) {
4247 >            boolean modified = false;
4248 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4249 >                if (c.contains(it.next())) {
4250 >                    it.remove();
4251 >                    modified = true;
4252 >                }
4253 >            }
4254 >            return modified;
4255          }
4256  
4257 <        /**
4258 <         * Returns a task that when invoked, returns the result of
4259 <         * accumulating the given transformation of all keys using the given
4260 <         * reducer to combine values, and the given basis as an
4261 <         * identity value.
4262 <         *
4263 <         * @param map the map
4264 <         * @param transformer a function returning the transformation
4265 <         * for an element
4456 <         * @param basis the identity (initial default value) for the reduction
4457 <         * @param reducer a commutative associative combining function
4458 <         * @return the task
4459 <         */
4460 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4461 <            (ConcurrentHashMapV8<K,V> map,
4462 <             ObjectToLong<? super K> transformer,
4463 <             long basis,
4464 <             LongByLongToLong reducer) {
4465 <            if (transformer == null || reducer == null)
4466 <                throw new NullPointerException();
4467 <            return new MapReduceKeysToLongTask<K,V>
4468 <                (map, null, -1, null, transformer, basis, reducer);
4257 >        public final boolean retainAll(Collection<?> c) {
4258 >            boolean modified = false;
4259 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4260 >                if (!c.contains(it.next())) {
4261 >                    it.remove();
4262 >                    modified = true;
4263 >                }
4264 >            }
4265 >            return modified;
4266          }
4267  
4268 <        /**
4269 <         * Returns a task that when invoked, returns the result of
4270 <         * accumulating the given transformation of all keys using the given
4271 <         * reducer to combine values, and the given basis as an
4272 <         * identity value.
4273 <         *
4274 <         * @param map the map
4275 <         * @param transformer a function returning the transformation
4276 <         * for an element
4277 <         * @param basis the identity (initial default value) for the reduction
4278 <         * @param reducer a commutative associative combining function
4279 <         * @return the task
4280 <         */
4281 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4282 <            (ConcurrentHashMapV8<K,V> map,
4283 <             ObjectToInt<? super K> transformer,
4284 <             int basis,
4285 <             IntByIntToInt reducer) {
4286 <            if (transformer == null || reducer == null)
4287 <                throw new NullPointerException();
4491 <            return new MapReduceKeysToIntTask<K,V>
4492 <                (map, null, -1, null, transformer, basis, reducer);
4268 >    }
4269 >
4270 >    /**
4271 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4272 >     * which additions may optionally be enabled by mapping to a
4273 >     * common value.  This class cannot be directly instantiated.
4274 >     * See {@link #keySet() keySet()},
4275 >     * {@link #keySet(Object) keySet(V)},
4276 >     * {@link #newKeySet() newKeySet()},
4277 >     * {@link #newKeySet(int) newKeySet(int)}.
4278 >     *
4279 >     * @since 1.8
4280 >     */
4281 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4282 >        implements Set<K>, java.io.Serializable {
4283 >        private static final long serialVersionUID = 7249069246763182397L;
4284 >        private final V value;
4285 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4286 >            super(map);
4287 >            this.value = value;
4288          }
4289  
4290          /**
4291 <         * Returns a task that when invoked, performs the given action
4292 <         * for each value.
4291 >         * Returns the default mapped value for additions,
4292 >         * or {@code null} if additions are not supported.
4293           *
4294 <         * @param map the map
4295 <         * @param action the action
4294 >         * @return the default mapped value for additions, or {@code null}
4295 >         * if not supported
4296           */
4297 <        public static <K,V> ForkJoinTask<Void> forEachValue
4503 <            (ConcurrentHashMapV8<K,V> map,
4504 <             Action<V> action) {
4505 <            if (action == null) throw new NullPointerException();
4506 <            return new ForEachValueTask<K,V>(map, null, -1, action);
4507 <        }
4297 >        public V getMappedValue() { return value; }
4298  
4299          /**
4300 <         * Returns a task that when invoked, performs the given action
4301 <         * for each non-null transformation of each value.
4512 <         *
4513 <         * @param map the map
4514 <         * @param transformer a function returning the transformation
4515 <         * for an element, or null if there is no transformation (in
4516 <         * which case the action is not applied)
4517 <         * @param action the action
4300 >         * {@inheritDoc}
4301 >         * @throws NullPointerException if the specified key is null
4302           */
4303 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4520 <            (ConcurrentHashMapV8<K,V> map,
4521 <             Fun<? super V, ? extends U> transformer,
4522 <             Action<U> action) {
4523 <            if (transformer == null || action == null)
4524 <                throw new NullPointerException();
4525 <            return new ForEachTransformedValueTask<K,V,U>
4526 <                (map, null, -1, transformer, action);
4527 <        }
4303 >        public boolean contains(Object o) { return map.containsKey(o); }
4304  
4305          /**
4306 <         * Returns a task that when invoked, returns a non-null result
4307 <         * from applying the given search function on each value, or
4308 <         * null if none.  Upon success, further element processing is
4533 <         * suppressed and the results of any other parallel
4534 <         * invocations of the search function are ignored.
4306 >         * Removes the key from this map view, by removing the key (and its
4307 >         * corresponding value) from the backing map.  This method does
4308 >         * nothing if the key is not in the map.
4309           *
4310 <         * @param map the map
4311 <         * @param searchFunction a function returning a non-null
4312 <         * result on success, else null
4539 <         * @return the task
4310 >         * @param  o the key to be removed from the backing map
4311 >         * @return {@code true} if the backing map contained the specified key
4312 >         * @throws NullPointerException if the specified key is null
4313           */
4314 <        public static <K,V,U> ForkJoinTask<U> searchValues
4542 <            (ConcurrentHashMapV8<K,V> map,
4543 <             Fun<? super V, ? extends U> searchFunction) {
4544 <            if (searchFunction == null) throw new NullPointerException();
4545 <            return new SearchValuesTask<K,V,U>
4546 <                (map, null, -1, searchFunction,
4547 <                 new AtomicReference<U>());
4548 <        }
4314 >        public boolean remove(Object o) { return map.remove(o) != null; }
4315  
4316          /**
4317 <         * Returns a task that when invoked, returns the result of
4552 <         * accumulating all values using the given reducer to combine
4553 <         * values, or null if none.
4554 <         *
4555 <         * @param map the map
4556 <         * @param reducer a commutative associative combining function
4557 <         * @return the task
4317 >         * @return an iterator over the keys of the backing map
4318           */
4319 <        public static <K,V> ForkJoinTask<V> reduceValues
4320 <            (ConcurrentHashMapV8<K,V> map,
4321 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4322 <            if (reducer == null) throw new NullPointerException();
4323 <            return new ReduceValuesTask<K,V>
4564 <                (map, null, -1, null, reducer);
4319 >        public Iterator<K> iterator() {
4320 >            Node<K,V>[] t;
4321 >            ConcurrentHashMapV8<K,V> m = map;
4322 >            int f = (t = m.table) == null ? 0 : t.length;
4323 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4324          }
4325  
4326          /**
4327 <         * Returns a task that when invoked, returns the result of
4328 <         * accumulating the given transformation of all values using the
4570 <         * given reducer to combine values, or null if none.
4327 >         * Adds the specified key to this set view by mapping the key to
4328 >         * the default mapped value in the backing map, if defined.
4329           *
4330 <         * @param map the map
4331 <         * @param transformer a function returning the transformation
4332 <         * for an element, or null if there is no transformation (in
4333 <         * which case it is not combined).
4334 <         * @param reducer a commutative associative combining function
4577 <         * @return the task
4330 >         * @param e key to be added
4331 >         * @return {@code true} if this set changed as a result of the call
4332 >         * @throws NullPointerException if the specified key is null
4333 >         * @throws UnsupportedOperationException if no default mapped value
4334 >         * for additions was provided
4335           */
4336 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4337 <            (ConcurrentHashMapV8<K,V> map,
4338 <             Fun<? super V, ? extends U> transformer,
4339 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4340 <            if (transformer == null || reducer == null)
4584 <                throw new NullPointerException();
4585 <            return new MapReduceValuesTask<K,V,U>
4586 <                (map, null, -1, null, transformer, reducer);
4336 >        public boolean add(K e) {
4337 >            V v;
4338 >            if ((v = value) == null)
4339 >                throw new UnsupportedOperationException();
4340 >            return map.putVal(e, v, true) == null;
4341          }
4342  
4343          /**
4344 <         * Returns a task that when invoked, returns the result of
4345 <         * accumulating the given transformation of all values using the
4592 <         * given reducer to combine values, and the given basis as an
4593 <         * identity value.
4344 >         * Adds all of the elements in the specified collection to this set,
4345 >         * as if by calling {@link #add} on each one.
4346           *
4347 <         * @param map the map
4348 <         * @param transformer a function returning the transformation
4349 <         * for an element
4350 <         * @param basis the identity (initial default value) for the reduction
4351 <         * @param reducer a commutative associative combining function
4352 <         * @return the task
4347 >         * @param c the elements to be inserted into this set
4348 >         * @return {@code true} if this set changed as a result of the call
4349 >         * @throws NullPointerException if the collection or any of its
4350 >         * elements are {@code null}
4351 >         * @throws UnsupportedOperationException if no default mapped value
4352 >         * for additions was provided
4353           */
4354 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4355 <            (ConcurrentHashMapV8<K,V> map,
4356 <             ObjectToDouble<? super V> transformer,
4357 <             double basis,
4358 <             DoubleByDoubleToDouble reducer) {
4359 <            if (transformer == null || reducer == null)
4360 <                throw new NullPointerException();
4361 <            return new MapReduceValuesToDoubleTask<K,V>
4362 <                (map, null, -1, null, transformer, basis, reducer);
4354 >        public boolean addAll(Collection<? extends K> c) {
4355 >            boolean added = false;
4356 >            V v;
4357 >            if ((v = value) == null)
4358 >                throw new UnsupportedOperationException();
4359 >            for (K e : c) {
4360 >                if (map.putVal(e, v, true) == null)
4361 >                    added = true;
4362 >            }
4363 >            return added;
4364          }
4365  
4366 <        /**
4367 <         * Returns a task that when invoked, returns the result of
4368 <         * accumulating the given transformation of all values using the
4369 <         * given reducer to combine values, and the given basis as an
4370 <         * identity value.
4618 <         *
4619 <         * @param map the map
4620 <         * @param transformer a function returning the transformation
4621 <         * for an element
4622 <         * @param basis the identity (initial default value) for the reduction
4623 <         * @param reducer a commutative associative combining function
4624 <         * @return the task
4625 <         */
4626 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
4627 <            (ConcurrentHashMapV8<K,V> map,
4628 <             ObjectToLong<? super V> transformer,
4629 <             long basis,
4630 <             LongByLongToLong reducer) {
4631 <            if (transformer == null || reducer == null)
4632 <                throw new NullPointerException();
4633 <            return new MapReduceValuesToLongTask<K,V>
4634 <                (map, null, -1, null, transformer, basis, reducer);
4366 >        public int hashCode() {
4367 >            int h = 0;
4368 >            for (K e : this)
4369 >                h += e.hashCode();
4370 >            return h;
4371          }
4372  
4373 <        /**
4374 <         * Returns a task that when invoked, returns the result of
4375 <         * accumulating the given transformation of all values using the
4376 <         * given reducer to combine values, and the given basis as an
4377 <         * identity value.
4642 <         *
4643 <         * @param map the map
4644 <         * @param transformer a function returning the transformation
4645 <         * for an element
4646 <         * @param basis the identity (initial default value) for the reduction
4647 <         * @param reducer a commutative associative combining function
4648 <         * @return the task
4649 <         */
4650 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
4651 <            (ConcurrentHashMapV8<K,V> map,
4652 <             ObjectToInt<? super V> transformer,
4653 <             int basis,
4654 <             IntByIntToInt reducer) {
4655 <            if (transformer == null || reducer == null)
4656 <                throw new NullPointerException();
4657 <            return new MapReduceValuesToIntTask<K,V>
4658 <                (map, null, -1, null, transformer, basis, reducer);
4373 >        public boolean equals(Object o) {
4374 >            Set<?> c;
4375 >            return ((o instanceof Set) &&
4376 >                    ((c = (Set<?>)o) == this ||
4377 >                     (containsAll(c) && c.containsAll(this))));
4378          }
4379  
4380 <        /**
4381 <         * Returns a task that when invoked, perform the given action
4382 <         * for each entry.
4383 <         *
4384 <         * @param map the map
4385 <         * @param action the action
4667 <         */
4668 <        public static <K,V> ForkJoinTask<Void> forEachEntry
4669 <            (ConcurrentHashMapV8<K,V> map,
4670 <             Action<Map.Entry<K,V>> action) {
4671 <            if (action == null) throw new NullPointerException();
4672 <            return new ForEachEntryTask<K,V>(map, null, -1, action);
4380 >        public ConcurrentHashMapSpliterator<K> spliterator() {
4381 >            Node<K,V>[] t;
4382 >            ConcurrentHashMapV8<K,V> m = map;
4383 >            long n = m.sumCount();
4384 >            int f = (t = m.table) == null ? 0 : t.length;
4385 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4386          }
4387  
4388 <        /**
4389 <         * Returns a task that when invoked, perform the given action
4390 <         * for each non-null transformation of each entry.
4391 <         *
4392 <         * @param map the map
4393 <         * @param transformer a function returning the transformation
4394 <         * for an element, or null if there is no transformation (in
4395 <         * which case the action is not applied)
4683 <         * @param action the action
4684 <         */
4685 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
4686 <            (ConcurrentHashMapV8<K,V> map,
4687 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4688 <             Action<U> action) {
4689 <            if (transformer == null || action == null)
4690 <                throw new NullPointerException();
4691 <            return new ForEachTransformedEntryTask<K,V,U>
4692 <                (map, null, -1, transformer, action);
4388 >        public void forEach(Action<? super K> action) {
4389 >            if (action == null) throw new NullPointerException();
4390 >            Node<K,V>[] t;
4391 >            if ((t = map.table) != null) {
4392 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4393 >                for (Node<K,V> p; (p = it.advance()) != null; )
4394 >                    action.apply(p.key);
4395 >            }
4396          }
4397 +    }
4398  
4399 <        /**
4400 <         * Returns a task that when invoked, returns a non-null result
4401 <         * from applying the given search function on each entry, or
4402 <         * null if none.  Upon success, further element processing is
4403 <         * suppressed and the results of any other parallel
4404 <         * invocations of the search function are ignored.
4405 <         *
4406 <         * @param map the map
4407 <         * @param searchFunction a function returning a non-null
4408 <         * result on success, else null
4409 <         * @return the task
4706 <         */
4707 <        public static <K,V,U> ForkJoinTask<U> searchEntries
4708 <            (ConcurrentHashMapV8<K,V> map,
4709 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4710 <            if (searchFunction == null) throw new NullPointerException();
4711 <            return new SearchEntriesTask<K,V,U>
4712 <                (map, null, -1, searchFunction,
4713 <                 new AtomicReference<U>());
4399 >    /**
4400 >     * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4401 >     * values, in which additions are disabled. This class cannot be
4402 >     * directly instantiated. See {@link #values()}.
4403 >     */
4404 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4405 >        implements Collection<V>, java.io.Serializable {
4406 >        private static final long serialVersionUID = 2249069246763182397L;
4407 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4408 >        public final boolean contains(Object o) {
4409 >            return map.containsValue(o);
4410          }
4411  
4412 <        /**
4413 <         * Returns a task that when invoked, returns the result of
4414 <         * accumulating all entries using the given reducer to combine
4415 <         * values, or null if none.
4416 <         *
4417 <         * @param map the map
4418 <         * @param reducer a commutative associative combining function
4419 <         * @return the task
4420 <         */
4421 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
4726 <            (ConcurrentHashMapV8<K,V> map,
4727 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4728 <            if (reducer == null) throw new NullPointerException();
4729 <            return new ReduceEntriesTask<K,V>
4730 <                (map, null, -1, null, reducer);
4412 >        public final boolean remove(Object o) {
4413 >            if (o != null) {
4414 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4415 >                    if (o.equals(it.next())) {
4416 >                        it.remove();
4417 >                        return true;
4418 >                    }
4419 >                }
4420 >            }
4421 >            return false;
4422          }
4423  
4424 <        /**
4425 <         * Returns a task that when invoked, returns the result of
4426 <         * accumulating the given transformation of all entries using the
4427 <         * given reducer to combine values, or null if none.
4428 <         *
4738 <         * @param map the map
4739 <         * @param transformer a function returning the transformation
4740 <         * for an element, or null if there is no transformation (in
4741 <         * which case it is not combined).
4742 <         * @param reducer a commutative associative combining function
4743 <         * @return the task
4744 <         */
4745 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
4746 <            (ConcurrentHashMapV8<K,V> map,
4747 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4748 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4749 <            if (transformer == null || reducer == null)
4750 <                throw new NullPointerException();
4751 <            return new MapReduceEntriesTask<K,V,U>
4752 <                (map, null, -1, null, transformer, reducer);
4424 >        public final Iterator<V> iterator() {
4425 >            ConcurrentHashMapV8<K,V> m = map;
4426 >            Node<K,V>[] t;
4427 >            int f = (t = m.table) == null ? 0 : t.length;
4428 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4429          }
4430  
4431 <        /**
4432 <         * Returns a task that when invoked, returns the result of
4433 <         * accumulating the given transformation of all entries using the
4434 <         * given reducer to combine values, and the given basis as an
4435 <         * identity value.
4760 <         *
4761 <         * @param map the map
4762 <         * @param transformer a function returning the transformation
4763 <         * for an element
4764 <         * @param basis the identity (initial default value) for the reduction
4765 <         * @param reducer a commutative associative combining function
4766 <         * @return the task
4767 <         */
4768 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4769 <            (ConcurrentHashMapV8<K,V> map,
4770 <             ObjectToDouble<Map.Entry<K,V>> transformer,
4771 <             double basis,
4772 <             DoubleByDoubleToDouble reducer) {
4773 <            if (transformer == null || reducer == null)
4774 <                throw new NullPointerException();
4775 <            return new MapReduceEntriesToDoubleTask<K,V>
4776 <                (map, null, -1, null, transformer, basis, reducer);
4431 >        public final boolean add(V e) {
4432 >            throw new UnsupportedOperationException();
4433 >        }
4434 >        public final boolean addAll(Collection<? extends V> c) {
4435 >            throw new UnsupportedOperationException();
4436          }
4437  
4438 <        /**
4439 <         * Returns a task that when invoked, returns the result of
4440 <         * accumulating the given transformation of all entries using the
4441 <         * given reducer to combine values, and the given basis as an
4442 <         * identity value.
4443 <         *
4785 <         * @param map the map
4786 <         * @param transformer a function returning the transformation
4787 <         * for an element
4788 <         * @param basis the identity (initial default value) for the reduction
4789 <         * @param reducer a commutative associative combining function
4790 <         * @return the task
4791 <         */
4792 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4793 <            (ConcurrentHashMapV8<K,V> map,
4794 <             ObjectToLong<Map.Entry<K,V>> transformer,
4795 <             long basis,
4796 <             LongByLongToLong reducer) {
4797 <            if (transformer == null || reducer == null)
4798 <                throw new NullPointerException();
4799 <            return new MapReduceEntriesToLongTask<K,V>
4800 <                (map, null, -1, null, transformer, basis, reducer);
4438 >        public ConcurrentHashMapSpliterator<V> spliterator() {
4439 >            Node<K,V>[] t;
4440 >            ConcurrentHashMapV8<K,V> m = map;
4441 >            long n = m.sumCount();
4442 >            int f = (t = m.table) == null ? 0 : t.length;
4443 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4444          }
4445  
4446 <        /**
4447 <         * Returns a task that when invoked, returns the result of
4448 <         * accumulating the given transformation of all entries using the
4449 <         * given reducer to combine values, and the given basis as an
4450 <         * identity value.
4451 <         *
4452 <         * @param map the map
4453 <         * @param transformer a function returning the transformation
4811 <         * for an element
4812 <         * @param basis the identity (initial default value) for the reduction
4813 <         * @param reducer a commutative associative combining function
4814 <         * @return the task
4815 <         */
4816 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4817 <            (ConcurrentHashMapV8<K,V> map,
4818 <             ObjectToInt<Map.Entry<K,V>> transformer,
4819 <             int basis,
4820 <             IntByIntToInt reducer) {
4821 <            if (transformer == null || reducer == null)
4822 <                throw new NullPointerException();
4823 <            return new MapReduceEntriesToIntTask<K,V>
4824 <                (map, null, -1, null, transformer, basis, reducer);
4446 >        public void forEach(Action<? super V> action) {
4447 >            if (action == null) throw new NullPointerException();
4448 >            Node<K,V>[] t;
4449 >            if ((t = map.table) != null) {
4450 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4451 >                for (Node<K,V> p; (p = it.advance()) != null; )
4452 >                    action.apply(p.val);
4453 >            }
4454          }
4455      }
4456  
4828    // -------------------------------------------------------
4829
4457      /**
4458 <     * Base for FJ tasks for bulk operations. This adds a variant of
4459 <     * CountedCompleters and some split and merge bookkeeping to
4460 <     * iterator functionality. The forEach and reduce methods are
4461 <     * similar to those illustrated in CountedCompleter documentation,
4462 <     * except that bottom-up reduction completions perform them within
4463 <     * their compute methods. The search methods are like forEach
4464 <     * except they continually poll for success and exit early.  Also,
4465 <     * exceptions are handled in a simpler manner, by just trying to
4839 <     * complete root task exceptionally.
4840 <     */
4841 <    @SuppressWarnings("serial") static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4842 <        final BulkTask<K,V,?> parent;  // completion target
4843 <        int batch;                     // split control; -1 for unknown
4844 <        int pending;                   // completion control
4458 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4459 >     * entries.  This class cannot be directly instantiated. See
4460 >     * {@link #entrySet()}.
4461 >     */
4462 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4463 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4464 >        private static final long serialVersionUID = 2249069246763182397L;
4465 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4466  
4467 <        BulkTask(ConcurrentHashMapV8<K,V> map, BulkTask<K,V,?> parent,
4468 <                 int batch) {
4469 <            super(map);
4470 <            this.parent = parent;
4471 <            this.batch = batch;
4472 <            if (parent != null && map != null) { // split parent
4473 <                Node[] t;
4853 <                if ((t = parent.tab) == null &&
4854 <                    (t = parent.tab = map.table) != null)
4855 <                    parent.baseLimit = parent.baseSize = t.length;
4856 <                this.tab = t;
4857 <                this.baseSize = parent.baseSize;
4858 <                int hi = this.baseLimit = parent.baseLimit;
4859 <                parent.baseLimit = this.index = this.baseIndex =
4860 <                    (hi + parent.baseIndex + 1) >>> 1;
4861 <            }
4467 >        public boolean contains(Object o) {
4468 >            Object k, v, r; Map.Entry<?,?> e;
4469 >            return ((o instanceof Map.Entry) &&
4470 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4471 >                    (r = map.get(k)) != null &&
4472 >                    (v = e.getValue()) != null &&
4473 >                    (v == r || v.equals(r)));
4474          }
4475  
4476 <        // FJ methods
4476 >        public boolean remove(Object o) {
4477 >            Object k, v; Map.Entry<?,?> e;
4478 >            return ((o instanceof Map.Entry) &&
4479 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4480 >                    (v = e.getValue()) != null &&
4481 >                    map.remove(k, v));
4482 >        }
4483  
4484          /**
4485 <         * Propagates completion. Note that all reduce actions
4868 <         * bypass this method to combine while completing.
4485 >         * @return an iterator over the entries of the backing map
4486           */
4487 <        final void tryComplete() {
4488 <            BulkTask<K,V,?> a = this, s = a;
4489 <            for (int c;;) {
4490 <                if ((c = a.pending) == 0) {
4491 <                    if ((a = (s = a).parent) == null) {
4492 <                        s.quietlyComplete();
4493 <                        break;
4494 <                    }
4495 <                }
4496 <                else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
4497 <                    break;
4487 >        public Iterator<Map.Entry<K,V>> iterator() {
4488 >            ConcurrentHashMapV8<K,V> m = map;
4489 >            Node<K,V>[] t;
4490 >            int f = (t = m.table) == null ? 0 : t.length;
4491 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4492 >        }
4493 >
4494 >        public boolean add(Entry<K,V> e) {
4495 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4496 >        }
4497 >
4498 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4499 >            boolean added = false;
4500 >            for (Entry<K,V> e : c) {
4501 >                if (add(e))
4502 >                    added = true;
4503              }
4504 +            return added;
4505          }
4506  
4507 <        /**
4508 <         * Forces root task to complete.
4509 <         * @param ex if null, complete normally, else exceptionally
4510 <         * @return false to simplify use
4511 <         */
4512 <        final boolean tryCompleteComputation(Throwable ex) {
4513 <            for (BulkTask<K,V,?> a = this;;) {
4891 <                BulkTask<K,V,?> p = a.parent;
4892 <                if (p == null) {
4893 <                    if (ex != null)
4894 <                        a.completeExceptionally(ex);
4895 <                    else
4896 <                        a.quietlyComplete();
4897 <                    return false;
4507 >        public final int hashCode() {
4508 >            int h = 0;
4509 >            Node<K,V>[] t;
4510 >            if ((t = map.table) != null) {
4511 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4512 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4513 >                    h += p.hashCode();
4514                  }
4899                a = p;
4515              }
4516 +            return h;
4517          }
4518  
4519 <        /**
4520 <         * Version of tryCompleteComputation for function screening checks
4521 <         */
4522 <        final boolean abortOnNullFunction() {
4523 <            return tryCompleteComputation(new Error("Unexpected null function"));
4519 >        public final boolean equals(Object o) {
4520 >            Set<?> c;
4521 >            return ((o instanceof Set) &&
4522 >                    ((c = (Set<?>)o) == this ||
4523 >                     (containsAll(c) && c.containsAll(this))));
4524          }
4525  
4526 <        // utilities
4526 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4527 >            Node<K,V>[] t;
4528 >            ConcurrentHashMapV8<K,V> m = map;
4529 >            long n = m.sumCount();
4530 >            int f = (t = m.table) == null ? 0 : t.length;
4531 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4532 >        }
4533  
4534 <        /** CompareAndSet pending count */
4535 <        final boolean casPending(int cmp, int val) {
4536 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4534 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4535 >            if (action == null) throw new NullPointerException();
4536 >            Node<K,V>[] t;
4537 >            if ((t = map.table) != null) {
4538 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4539 >                for (Node<K,V> p; (p = it.advance()) != null; )
4540 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4541 >            }
4542          }
4543  
4544 <        /**
4545 <         * Returns approx exp2 of the number of times (minus one) to
4546 <         * split task by two before executing leaf action. This value
4547 <         * is faster to compute and more convenient to use as a guide
4548 <         * to splitting than is the depth, since it is used while
4549 <         * dividing by two anyway.
4550 <         */
4551 <        final int batch() {
4552 <            ConcurrentHashMapV8<K, V> m; int b; Node[] t;
4553 <            if ((b = batch) < 0 && (m = map) != null) { // force initialization
4554 <                if ((t = tab) == null && (t = tab = m.table) != null)
4555 <                    baseLimit = baseSize = t.length;
4556 <                if (t != null) {
4557 <                    long n = m.counter.sum();
4558 <                    int sp = getPool().getParallelism() << 3; // slack of 8
4559 <                    b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4560 <                }
4544 >    }
4545 >
4546 >    // -------------------------------------------------------
4547 >
4548 >    /**
4549 >     * Base class for bulk tasks. Repeats some fields and code from
4550 >     * class Traverser, because we need to subclass CountedCompleter.
4551 >     */
4552 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4553 >        Node<K,V>[] tab;        // same as Traverser
4554 >        Node<K,V> next;
4555 >        int index;
4556 >        int baseIndex;
4557 >        int baseLimit;
4558 >        final int baseSize;
4559 >        int batch;              // split control
4560 >
4561 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4562 >            super(par);
4563 >            this.batch = b;
4564 >            this.index = this.baseIndex = i;
4565 >            if ((this.tab = t) == null)
4566 >                this.baseSize = this.baseLimit = 0;
4567 >            else if (par == null)
4568 >                this.baseSize = this.baseLimit = t.length;
4569 >            else {
4570 >                this.baseLimit = f;
4571 >                this.baseSize = par.baseSize;
4572              }
4935            return b;
4573          }
4574  
4575          /**
4576 <         * Returns exportable snapshot entry.
4576 >         * Same as Traverser version
4577           */
4578 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4579 <            return new AbstractMap.SimpleEntry<K,V>(k, v);
4580 <        }
4581 <
4582 <        // Unsafe mechanics
4583 <        private static final sun.misc.Unsafe U;
4584 <        private static final long PENDING;
4585 <        static {
4586 <            try {
4587 <                U = getUnsafe();
4588 <                PENDING = U.objectFieldOffset
4589 <                    (BulkTask.class.getDeclaredField("pending"));
4590 <            } catch (Exception e) {
4591 <                throw new Error(e);
4578 >        final Node<K,V> advance() {
4579 >            Node<K,V> e;
4580 >            if ((e = next) != null)
4581 >                e = e.next;
4582 >            for (;;) {
4583 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4584 >                if (e != null)
4585 >                    return next = e;
4586 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4587 >                    (n = t.length) <= (i = index) || i < 0)
4588 >                    return next = null;
4589 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4590 >                    if (e instanceof ForwardingNode) {
4591 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4592 >                        e = null;
4593 >                        continue;
4594 >                    }
4595 >                    else if (e instanceof TreeBin)
4596 >                        e = ((TreeBin<K,V>)e).first;
4597 >                    else
4598 >                        e = null;
4599 >                }
4600 >                if ((index += baseSize) >= n)
4601 >                    index = ++baseIndex;    // visit upper slots if present
4602              }
4603          }
4604      }
# Line 4959 | Line 4606 | public class ConcurrentHashMapV8<K, V>
4606      /*
4607       * Task classes. Coded in a regular but ugly format/style to
4608       * simplify checks that each variant differs in the right way from
4609 <     * others.
4609 >     * others. The null screenings exist because compilers cannot tell
4610 >     * that we've already null-checked task arguments, so we force
4611 >     * simplest hoisted bypass to help avoid convoluted traps.
4612       */
4613 <
4614 <    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
4613 >    @SuppressWarnings("serial")
4614 >    static final class ForEachKeyTask<K,V>
4615          extends BulkTask<K,V,Void> {
4616 <        final Action<K> action;
4616 >        final Action<? super K> action;
4617          ForEachKeyTask
4618 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4619 <             Action<K> action) {
4620 <            super(m, p, b);
4618 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4619 >             Action<? super K> action) {
4620 >            super(p, b, i, f, t);
4621              this.action = action;
4622          }
4623 <        @SuppressWarnings("unchecked") public final boolean exec() {
4624 <            final Action<K> action = this.action;
4625 <            if (action == null)
4626 <                return abortOnNullFunction();
4627 <            try {
4628 <                int b = batch(), c;
4629 <                while (b > 1 && baseIndex != baseLimit) {
4630 <                    do {} while (!casPending(c = pending, c+1));
4631 <                    new ForEachKeyTask<K,V>(map, this, b >>>= 1, action).fork();
4632 <                }
4633 <                while (advance() != null)
4634 <                    action.apply((K)nextKey);
4635 <                tryComplete();
4987 <            } catch (Throwable ex) {
4988 <                return tryCompleteComputation(ex);
4623 >        public final void compute() {
4624 >            final Action<? super K> action;
4625 >            if ((action = this.action) != null) {
4626 >                for (int i = baseIndex, f, h; batch > 0 &&
4627 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4628 >                    addToPendingCount(1);
4629 >                    new ForEachKeyTask<K,V>
4630 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4631 >                         action).fork();
4632 >                }
4633 >                for (Node<K,V> p; (p = advance()) != null;)
4634 >                    action.apply(p.key);
4635 >                propagateCompletion();
4636              }
4990            return false;
4637          }
4638      }
4639  
4640 <    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
4640 >    @SuppressWarnings("serial")
4641 >    static final class ForEachValueTask<K,V>
4642          extends BulkTask<K,V,Void> {
4643 <        final Action<V> action;
4643 >        final Action<? super V> action;
4644          ForEachValueTask
4645 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4646 <             Action<V> action) {
4647 <            super(m, p, b);
4645 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4646 >             Action<? super V> action) {
4647 >            super(p, b, i, f, t);
4648              this.action = action;
4649          }
4650 <        @SuppressWarnings("unchecked") public final boolean exec() {
4651 <            final Action<V> action = this.action;
4652 <            if (action == null)
4653 <                return abortOnNullFunction();
4654 <            try {
4655 <                int b = batch(), c;
4656 <                while (b > 1 && baseIndex != baseLimit) {
4657 <                    do {} while (!casPending(c = pending, c+1));
4658 <                    new ForEachValueTask<K,V>(map, this, b >>>= 1, action).fork();
4659 <                }
4660 <                Object v;
4661 <                while ((v = advance()) != null)
4662 <                    action.apply((V)v);
5016 <                tryComplete();
5017 <            } catch (Throwable ex) {
5018 <                return tryCompleteComputation(ex);
4650 >        public final void compute() {
4651 >            final Action<? super V> action;
4652 >            if ((action = this.action) != null) {
4653 >                for (int i = baseIndex, f, h; batch > 0 &&
4654 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4655 >                    addToPendingCount(1);
4656 >                    new ForEachValueTask<K,V>
4657 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4658 >                         action).fork();
4659 >                }
4660 >                for (Node<K,V> p; (p = advance()) != null;)
4661 >                    action.apply(p.val);
4662 >                propagateCompletion();
4663              }
5020            return false;
4664          }
4665      }
4666  
4667 <    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
4667 >    @SuppressWarnings("serial")
4668 >    static final class ForEachEntryTask<K,V>
4669          extends BulkTask<K,V,Void> {
4670 <        final Action<Entry<K,V>> action;
4670 >        final Action<? super Entry<K,V>> action;
4671          ForEachEntryTask
4672 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4673 <             Action<Entry<K,V>> action) {
4674 <            super(m, p, b);
4672 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4673 >             Action<? super Entry<K,V>> action) {
4674 >            super(p, b, i, f, t);
4675              this.action = action;
4676          }
4677 <        @SuppressWarnings("unchecked") public final boolean exec() {
4678 <            final Action<Entry<K,V>> action = this.action;
4679 <            if (action == null)
4680 <                return abortOnNullFunction();
4681 <            try {
4682 <                int b = batch(), c;
4683 <                while (b > 1 && baseIndex != baseLimit) {
4684 <                    do {} while (!casPending(c = pending, c+1));
4685 <                    new ForEachEntryTask<K,V>(map, this, b >>>= 1, action).fork();
4686 <                }
4687 <                Object v;
4688 <                while ((v = advance()) != null)
4689 <                    action.apply(entryFor((K)nextKey, (V)v));
5046 <                tryComplete();
5047 <            } catch (Throwable ex) {
5048 <                return tryCompleteComputation(ex);
4677 >        public final void compute() {
4678 >            final Action<? super Entry<K,V>> action;
4679 >            if ((action = this.action) != null) {
4680 >                for (int i = baseIndex, f, h; batch > 0 &&
4681 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4682 >                    addToPendingCount(1);
4683 >                    new ForEachEntryTask<K,V>
4684 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4685 >                         action).fork();
4686 >                }
4687 >                for (Node<K,V> p; (p = advance()) != null; )
4688 >                    action.apply(p);
4689 >                propagateCompletion();
4690              }
5050            return false;
4691          }
4692      }
4693  
4694 <    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
4694 >    @SuppressWarnings("serial")
4695 >    static final class ForEachMappingTask<K,V>
4696          extends BulkTask<K,V,Void> {
4697 <        final BiAction<K,V> action;
4697 >        final BiAction<? super K, ? super V> action;
4698          ForEachMappingTask
4699 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4700 <             BiAction<K,V> action) {
4701 <            super(m, p, b);
4699 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4700 >             BiAction<? super K,? super V> action) {
4701 >            super(p, b, i, f, t);
4702              this.action = action;
4703          }
4704 <        @SuppressWarnings("unchecked") public final boolean exec() {
4705 <            final BiAction<K,V> action = this.action;
4706 <            if (action == null)
4707 <                return abortOnNullFunction();
4708 <            try {
4709 <                int b = batch(), c;
4710 <                while (b > 1 && baseIndex != baseLimit) {
4711 <                    do {} while (!casPending(c = pending, c+1));
4712 <                    new ForEachMappingTask<K,V>(map, this, b >>>= 1,
4713 <                                                action).fork();
4714 <                }
4715 <                Object v;
4716 <                while ((v = advance()) != null)
5076 <                    action.apply((K)nextKey, (V)v);
5077 <                tryComplete();
5078 <            } catch (Throwable ex) {
5079 <                return tryCompleteComputation(ex);
4704 >        public final void compute() {
4705 >            final BiAction<? super K, ? super V> action;
4706 >            if ((action = this.action) != null) {
4707 >                for (int i = baseIndex, f, h; batch > 0 &&
4708 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4709 >                    addToPendingCount(1);
4710 >                    new ForEachMappingTask<K,V>
4711 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4712 >                         action).fork();
4713 >                }
4714 >                for (Node<K,V> p; (p = advance()) != null; )
4715 >                    action.apply(p.key, p.val);
4716 >                propagateCompletion();
4717              }
5081            return false;
4718          }
4719      }
4720  
4721 <    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
4721 >    @SuppressWarnings("serial")
4722 >    static final class ForEachTransformedKeyTask<K,V,U>
4723          extends BulkTask<K,V,Void> {
4724          final Fun<? super K, ? extends U> transformer;
4725 <        final Action<U> action;
4725 >        final Action<? super U> action;
4726          ForEachTransformedKeyTask
4727 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4728 <             Fun<? super K, ? extends U> transformer,
4729 <             Action<U> action) {
4730 <            super(m, p, b);
4731 <            this.transformer = transformer;
4732 <            this.action = action;
4733 <
4734 <        }
4735 <        @SuppressWarnings("unchecked") public final boolean exec() {
4736 <            final Fun<? super K, ? extends U> transformer =
4737 <                this.transformer;
4738 <            final Action<U> action = this.action;
4739 <            if (transformer == null || action == null)
5103 <                return abortOnNullFunction();
5104 <            try {
5105 <                int b = batch(), c;
5106 <                while (b > 1 && baseIndex != baseLimit) {
5107 <                    do {} while (!casPending(c = pending, c+1));
4727 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4728 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4729 >            super(p, b, i, f, t);
4730 >            this.transformer = transformer; this.action = action;
4731 >        }
4732 >        public final void compute() {
4733 >            final Fun<? super K, ? extends U> transformer;
4734 >            final Action<? super U> action;
4735 >            if ((transformer = this.transformer) != null &&
4736 >                (action = this.action) != null) {
4737 >                for (int i = baseIndex, f, h; batch > 0 &&
4738 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4739 >                    addToPendingCount(1);
4740                      new ForEachTransformedKeyTask<K,V,U>
4741 <                        (map, this, b >>>= 1, transformer, action).fork();
4741 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4742 >                         transformer, action).fork();
4743                  }
4744 <                U u;
4745 <                while (advance() != null) {
4746 <                    if ((u = transformer.apply((K)nextKey)) != null)
4744 >                for (Node<K,V> p; (p = advance()) != null; ) {
4745 >                    U u;
4746 >                    if ((u = transformer.apply(p.key)) != null)
4747                          action.apply(u);
4748                  }
4749 <                tryComplete();
5117 <            } catch (Throwable ex) {
5118 <                return tryCompleteComputation(ex);
4749 >                propagateCompletion();
4750              }
5120            return false;
4751          }
4752      }
4753  
4754 <    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
4754 >    @SuppressWarnings("serial")
4755 >    static final class ForEachTransformedValueTask<K,V,U>
4756          extends BulkTask<K,V,Void> {
4757          final Fun<? super V, ? extends U> transformer;
4758 <        final Action<U> action;
4758 >        final Action<? super U> action;
4759          ForEachTransformedValueTask
4760 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4761 <             Fun<? super V, ? extends U> transformer,
4762 <             Action<U> action) {
4763 <            super(m, p, b);
4764 <            this.transformer = transformer;
4765 <            this.action = action;
4766 <
4767 <        }
4768 <        @SuppressWarnings("unchecked") public final boolean exec() {
4769 <            final Fun<? super V, ? extends U> transformer =
4770 <                this.transformer;
4771 <            final Action<U> action = this.action;
4772 <            if (transformer == null || action == null)
5142 <                return abortOnNullFunction();
5143 <            try {
5144 <                int b = batch(), c;
5145 <                while (b > 1 && baseIndex != baseLimit) {
5146 <                    do {} while (!casPending(c = pending, c+1));
4760 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4761 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4762 >            super(p, b, i, f, t);
4763 >            this.transformer = transformer; this.action = action;
4764 >        }
4765 >        public final void compute() {
4766 >            final Fun<? super V, ? extends U> transformer;
4767 >            final Action<? super U> action;
4768 >            if ((transformer = this.transformer) != null &&
4769 >                (action = this.action) != null) {
4770 >                for (int i = baseIndex, f, h; batch > 0 &&
4771 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4772 >                    addToPendingCount(1);
4773                      new ForEachTransformedValueTask<K,V,U>
4774 <                        (map, this, b >>>= 1, transformer, action).fork();
4774 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4775 >                         transformer, action).fork();
4776                  }
4777 <                Object v; U u;
4778 <                while ((v = advance()) != null) {
4779 <                    if ((u = transformer.apply((V)v)) != null)
4777 >                for (Node<K,V> p; (p = advance()) != null; ) {
4778 >                    U u;
4779 >                    if ((u = transformer.apply(p.val)) != null)
4780                          action.apply(u);
4781                  }
4782 <                tryComplete();
5156 <            } catch (Throwable ex) {
5157 <                return tryCompleteComputation(ex);
4782 >                propagateCompletion();
4783              }
5159            return false;
4784          }
4785      }
4786  
4787 <    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
4787 >    @SuppressWarnings("serial")
4788 >    static final class ForEachTransformedEntryTask<K,V,U>
4789          extends BulkTask<K,V,Void> {
4790          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4791 <        final Action<U> action;
4791 >        final Action<? super U> action;
4792          ForEachTransformedEntryTask
4793 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4794 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4795 <             Action<U> action) {
4796 <            super(m, p, b);
4797 <            this.transformer = transformer;
4798 <            this.action = action;
4799 <
4800 <        }
4801 <        @SuppressWarnings("unchecked") public final boolean exec() {
4802 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4803 <                this.transformer;
4804 <            final Action<U> action = this.action;
4805 <            if (transformer == null || action == null)
5181 <                return abortOnNullFunction();
5182 <            try {
5183 <                int b = batch(), c;
5184 <                while (b > 1 && baseIndex != baseLimit) {
5185 <                    do {} while (!casPending(c = pending, c+1));
4793 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4794 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4795 >            super(p, b, i, f, t);
4796 >            this.transformer = transformer; this.action = action;
4797 >        }
4798 >        public final void compute() {
4799 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
4800 >            final Action<? super U> action;
4801 >            if ((transformer = this.transformer) != null &&
4802 >                (action = this.action) != null) {
4803 >                for (int i = baseIndex, f, h; batch > 0 &&
4804 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4805 >                    addToPendingCount(1);
4806                      new ForEachTransformedEntryTask<K,V,U>
4807 <                        (map, this, b >>>= 1, transformer, action).fork();
4807 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4808 >                         transformer, action).fork();
4809                  }
4810 <                Object v; U u;
4811 <                while ((v = advance()) != null) {
4812 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
4810 >                for (Node<K,V> p; (p = advance()) != null; ) {
4811 >                    U u;
4812 >                    if ((u = transformer.apply(p)) != null)
4813                          action.apply(u);
4814                  }
4815 <                tryComplete();
5195 <            } catch (Throwable ex) {
5196 <                return tryCompleteComputation(ex);
4815 >                propagateCompletion();
4816              }
5198            return false;
4817          }
4818      }
4819  
4820 <    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
4820 >    @SuppressWarnings("serial")
4821 >    static final class ForEachTransformedMappingTask<K,V,U>
4822          extends BulkTask<K,V,Void> {
4823          final BiFun<? super K, ? super V, ? extends U> transformer;
4824 <        final Action<U> action;
4824 >        final Action<? super U> action;
4825          ForEachTransformedMappingTask
4826 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4826 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4827               BiFun<? super K, ? super V, ? extends U> transformer,
4828 <             Action<U> action) {
4829 <            super(m, p, b);
4830 <            this.transformer = transformer;
4831 <            this.action = action;
4832 <
4833 <        }
4834 <        @SuppressWarnings("unchecked") public final boolean exec() {
4835 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4836 <                this.transformer;
4837 <            final Action<U> action = this.action;
4838 <            if (transformer == null || action == null)
4839 <                return abortOnNullFunction();
5221 <            try {
5222 <                int b = batch(), c;
5223 <                while (b > 1 && baseIndex != baseLimit) {
5224 <                    do {} while (!casPending(c = pending, c+1));
4828 >             Action<? super U> action) {
4829 >            super(p, b, i, f, t);
4830 >            this.transformer = transformer; this.action = action;
4831 >        }
4832 >        public final void compute() {
4833 >            final BiFun<? super K, ? super V, ? extends U> transformer;
4834 >            final Action<? super U> action;
4835 >            if ((transformer = this.transformer) != null &&
4836 >                (action = this.action) != null) {
4837 >                for (int i = baseIndex, f, h; batch > 0 &&
4838 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4839 >                    addToPendingCount(1);
4840                      new ForEachTransformedMappingTask<K,V,U>
4841 <                        (map, this, b >>>= 1, transformer, action).fork();
4841 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4842 >                         transformer, action).fork();
4843                  }
4844 <                Object v; U u;
4845 <                while ((v = advance()) != null) {
4846 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
4844 >                for (Node<K,V> p; (p = advance()) != null; ) {
4845 >                    U u;
4846 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4847                          action.apply(u);
4848                  }
4849 <                tryComplete();
5234 <            } catch (Throwable ex) {
5235 <                return tryCompleteComputation(ex);
4849 >                propagateCompletion();
4850              }
5237            return false;
4851          }
4852      }
4853  
4854 <    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
4854 >    @SuppressWarnings("serial")
4855 >    static final class SearchKeysTask<K,V,U>
4856          extends BulkTask<K,V,U> {
4857          final Fun<? super K, ? extends U> searchFunction;
4858          final AtomicReference<U> result;
4859          SearchKeysTask
4860 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4860 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4861               Fun<? super K, ? extends U> searchFunction,
4862               AtomicReference<U> result) {
4863 <            super(m, p, b);
4863 >            super(p, b, i, f, t);
4864              this.searchFunction = searchFunction; this.result = result;
4865          }
4866 <        @SuppressWarnings("unchecked") public final boolean exec() {
4867 <            AtomicReference<U> result = this.result;
4868 <            final Fun<? super K, ? extends U> searchFunction =
4869 <                this.searchFunction;
4870 <            if (searchFunction == null || result == null)
4871 <                return abortOnNullFunction();
4872 <            try {
4873 <                int b = batch(), c;
4874 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4875 <                    do {} while (!casPending(c = pending, c+1));
4876 <                    new SearchKeysTask<K,V,U>(map, this, b >>>= 1,
4877 <                                              searchFunction, result).fork();
4878 <                }
4879 <                U u;
4880 <                while (result.get() == null && advance() != null) {
4881 <                    if ((u = searchFunction.apply((K)nextKey)) != null) {
4866 >        public final U getRawResult() { return result.get(); }
4867 >        public final void compute() {
4868 >            final Fun<? super K, ? extends U> searchFunction;
4869 >            final AtomicReference<U> result;
4870 >            if ((searchFunction = this.searchFunction) != null &&
4871 >                (result = this.result) != null) {
4872 >                for (int i = baseIndex, f, h; batch > 0 &&
4873 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4874 >                    if (result.get() != null)
4875 >                        return;
4876 >                    addToPendingCount(1);
4877 >                    new SearchKeysTask<K,V,U>
4878 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4879 >                         searchFunction, result).fork();
4880 >                }
4881 >                while (result.get() == null) {
4882 >                    U u;
4883 >                    Node<K,V> p;
4884 >                    if ((p = advance()) == null) {
4885 >                        propagateCompletion();
4886 >                        break;
4887 >                    }
4888 >                    if ((u = searchFunction.apply(p.key)) != null) {
4889                          if (result.compareAndSet(null, u))
4890 <                            tryCompleteComputation(null);
4890 >                            quietlyCompleteRoot();
4891                          break;
4892                      }
4893                  }
5273                tryComplete();
5274            } catch (Throwable ex) {
5275                return tryCompleteComputation(ex);
4894              }
5277            return false;
4895          }
5279        public final U getRawResult() { return result.get(); }
4896      }
4897  
4898 <    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
4898 >    @SuppressWarnings("serial")
4899 >    static final class SearchValuesTask<K,V,U>
4900          extends BulkTask<K,V,U> {
4901          final Fun<? super V, ? extends U> searchFunction;
4902          final AtomicReference<U> result;
4903          SearchValuesTask
4904 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4904 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4905               Fun<? super V, ? extends U> searchFunction,
4906               AtomicReference<U> result) {
4907 <            super(m, p, b);
4907 >            super(p, b, i, f, t);
4908              this.searchFunction = searchFunction; this.result = result;
4909          }
4910 <        @SuppressWarnings("unchecked") public final boolean exec() {
4911 <            AtomicReference<U> result = this.result;
4912 <            final Fun<? super V, ? extends U> searchFunction =
4913 <                this.searchFunction;
4914 <            if (searchFunction == null || result == null)
4915 <                return abortOnNullFunction();
4916 <            try {
4917 <                int b = batch(), c;
4918 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4919 <                    do {} while (!casPending(c = pending, c+1));
4920 <                    new SearchValuesTask<K,V,U>(map, this, b >>>= 1,
4921 <                                                searchFunction, result).fork();
4922 <                }
4923 <                Object v; U u;
4924 <                while (result.get() == null && (v = advance()) != null) {
4925 <                    if ((u = searchFunction.apply((V)v)) != null) {
4910 >        public final U getRawResult() { return result.get(); }
4911 >        public final void compute() {
4912 >            final Fun<? super V, ? extends U> searchFunction;
4913 >            final AtomicReference<U> result;
4914 >            if ((searchFunction = this.searchFunction) != null &&
4915 >                (result = this.result) != null) {
4916 >                for (int i = baseIndex, f, h; batch > 0 &&
4917 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4918 >                    if (result.get() != null)
4919 >                        return;
4920 >                    addToPendingCount(1);
4921 >                    new SearchValuesTask<K,V,U>
4922 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4923 >                         searchFunction, result).fork();
4924 >                }
4925 >                while (result.get() == null) {
4926 >                    U u;
4927 >                    Node<K,V> p;
4928 >                    if ((p = advance()) == null) {
4929 >                        propagateCompletion();
4930 >                        break;
4931 >                    }
4932 >                    if ((u = searchFunction.apply(p.val)) != null) {
4933                          if (result.compareAndSet(null, u))
4934 <                            tryCompleteComputation(null);
4934 >                            quietlyCompleteRoot();
4935                          break;
4936                      }
4937                  }
5314                tryComplete();
5315            } catch (Throwable ex) {
5316                return tryCompleteComputation(ex);
4938              }
5318            return false;
4939          }
5320        public final U getRawResult() { return result.get(); }
4940      }
4941  
4942 <    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
4942 >    @SuppressWarnings("serial")
4943 >    static final class SearchEntriesTask<K,V,U>
4944          extends BulkTask<K,V,U> {
4945          final Fun<Entry<K,V>, ? extends U> searchFunction;
4946          final AtomicReference<U> result;
4947          SearchEntriesTask
4948 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4948 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4949               Fun<Entry<K,V>, ? extends U> searchFunction,
4950               AtomicReference<U> result) {
4951 <            super(m, p, b);
4951 >            super(p, b, i, f, t);
4952              this.searchFunction = searchFunction; this.result = result;
4953          }
4954 <        @SuppressWarnings("unchecked") public final boolean exec() {
4955 <            AtomicReference<U> result = this.result;
4956 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
4957 <                this.searchFunction;
4958 <            if (searchFunction == null || result == null)
4959 <                return abortOnNullFunction();
4960 <            try {
4961 <                int b = batch(), c;
4962 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4963 <                    do {} while (!casPending(c = pending, c+1));
4964 <                    new SearchEntriesTask<K,V,U>(map, this, b >>>= 1,
4965 <                                                 searchFunction, result).fork();
4966 <                }
4967 <                Object v; U u;
4968 <                while (result.get() == null && (v = advance()) != null) {
4969 <                    if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
4970 <                        if (result.compareAndSet(null, u))
4971 <                            tryCompleteComputation(null);
4954 >        public final U getRawResult() { return result.get(); }
4955 >        public final void compute() {
4956 >            final Fun<Entry<K,V>, ? extends U> searchFunction;
4957 >            final AtomicReference<U> result;
4958 >            if ((searchFunction = this.searchFunction) != null &&
4959 >                (result = this.result) != null) {
4960 >                for (int i = baseIndex, f, h; batch > 0 &&
4961 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4962 >                    if (result.get() != null)
4963 >                        return;
4964 >                    addToPendingCount(1);
4965 >                    new SearchEntriesTask<K,V,U>
4966 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4967 >                         searchFunction, result).fork();
4968 >                }
4969 >                while (result.get() == null) {
4970 >                    U u;
4971 >                    Node<K,V> p;
4972 >                    if ((p = advance()) == null) {
4973 >                        propagateCompletion();
4974                          break;
4975                      }
4976 +                    if ((u = searchFunction.apply(p)) != null) {
4977 +                        if (result.compareAndSet(null, u))
4978 +                            quietlyCompleteRoot();
4979 +                        return;
4980 +                    }
4981                  }
5355                tryComplete();
5356            } catch (Throwable ex) {
5357                return tryCompleteComputation(ex);
4982              }
5359            return false;
4983          }
5361        public final U getRawResult() { return result.get(); }
4984      }
4985  
4986 <    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
4986 >    @SuppressWarnings("serial")
4987 >    static final class SearchMappingsTask<K,V,U>
4988          extends BulkTask<K,V,U> {
4989          final BiFun<? super K, ? super V, ? extends U> searchFunction;
4990          final AtomicReference<U> result;
4991          SearchMappingsTask
4992 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
4992 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4993               BiFun<? super K, ? super V, ? 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 <        @SuppressWarnings("unchecked") public final boolean exec() {
4999 <            AtomicReference<U> result = this.result;
5000 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5001 <                this.searchFunction;
5002 <            if (searchFunction == null || result == null)
5003 <                return abortOnNullFunction();
5004 <            try {
5005 <                int b = batch(), c;
5006 <                while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5007 <                    do {} while (!casPending(c = pending, c+1));
5008 <                    new SearchMappingsTask<K,V,U>(map, this, b >>>= 1,
5009 <                                                  searchFunction, result).fork();
5010 <                }
5011 <                Object v; U u;
5012 <                while (result.get() == null && (v = advance()) != null) {
5013 <                    if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
4998 >        public final U getRawResult() { return result.get(); }
4999 >        public final void compute() {
5000 >            final BiFun<? super K, ? super V, ? extends U> searchFunction;
5001 >            final AtomicReference<U> result;
5002 >            if ((searchFunction = this.searchFunction) != null &&
5003 >                (result = this.result) != null) {
5004 >                for (int i = baseIndex, f, h; batch > 0 &&
5005 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5006 >                    if (result.get() != null)
5007 >                        return;
5008 >                    addToPendingCount(1);
5009 >                    new SearchMappingsTask<K,V,U>
5010 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5011 >                         searchFunction, result).fork();
5012 >                }
5013 >                while (result.get() == null) {
5014 >                    U u;
5015 >                    Node<K,V> p;
5016 >                    if ((p = advance()) == null) {
5017 >                        propagateCompletion();
5018 >                        break;
5019 >                    }
5020 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5021                          if (result.compareAndSet(null, u))
5022 <                            tryCompleteComputation(null);
5022 >                            quietlyCompleteRoot();
5023                          break;
5024                      }
5025                  }
5396                tryComplete();
5397            } catch (Throwable ex) {
5398                return tryCompleteComputation(ex);
5026              }
5400            return false;
5027          }
5402        public final U getRawResult() { return result.get(); }
5028      }
5029  
5030 <    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5030 >    @SuppressWarnings("serial")
5031 >    static final class ReduceKeysTask<K,V>
5032          extends BulkTask<K,V,K> {
5033          final BiFun<? super K, ? super K, ? extends K> reducer;
5034          K result;
5035          ReduceKeysTask<K,V> rights, nextRight;
5036          ReduceKeysTask
5037 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5037 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5038               ReduceKeysTask<K,V> nextRight,
5039               BiFun<? super K, ? super K, ? extends K> reducer) {
5040 <            super(m, p, b); this.nextRight = nextRight;
5040 >            super(p, b, i, f, t); this.nextRight = nextRight;
5041              this.reducer = reducer;
5042          }
5043 <        @SuppressWarnings("unchecked") public final boolean exec() {
5044 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5045 <                this.reducer;
5046 <            if (reducer == null)
5047 <                return abortOnNullFunction();
5048 <            try {
5049 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5424 <                    do {} while (!casPending(c = pending, c+1));
5043 >        public final K getRawResult() { return result; }
5044 >        public final void compute() {
5045 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5046 >            if ((reducer = this.reducer) != null) {
5047 >                for (int i = baseIndex, f, h; batch > 0 &&
5048 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5049 >                    addToPendingCount(1);
5050                      (rights = new ReduceKeysTask<K,V>
5051 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5051 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5052 >                      rights, reducer)).fork();
5053                  }
5054                  K r = null;
5055 <                while (advance() != null) {
5056 <                    K u = (K)nextKey;
5057 <                    r = (r == null) ? u : reducer.apply(r, u);
5055 >                for (Node<K,V> p; (p = advance()) != null; ) {
5056 >                    K u = p.key;
5057 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5058                  }
5059                  result = r;
5060 <                for (ReduceKeysTask<K,V> t = this, s;;) {
5061 <                    int c; BulkTask<K,V,?> par; K tr, sr;
5062 <                    if ((c = t.pending) == 0) {
5063 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5064 <                            if ((sr = s.result) != null)
5065 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5066 <                        }
5067 <                        if ((par = t.parent) == null ||
5068 <                            !(par instanceof ReduceKeysTask)) {
5069 <                            t.quietlyComplete();
5070 <                            break;
5445 <                        }
5446 <                        t = (ReduceKeysTask<K,V>)par;
5060 >                CountedCompleter<?> c;
5061 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5062 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5063 >                        t = (ReduceKeysTask<K,V>)c,
5064 >                        s = t.rights;
5065 >                    while (s != null) {
5066 >                        K tr, sr;
5067 >                        if ((sr = s.result) != null)
5068 >                            t.result = (((tr = t.result) == null) ? sr :
5069 >                                        reducer.apply(tr, sr));
5070 >                        s = t.rights = s.nextRight;
5071                      }
5448                    else if (t.casPending(c, c - 1))
5449                        break;
5072                  }
5451            } catch (Throwable ex) {
5452                return tryCompleteComputation(ex);
5073              }
5454            return false;
5074          }
5456        public final K getRawResult() { return result; }
5075      }
5076  
5077 <    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5077 >    @SuppressWarnings("serial")
5078 >    static final class ReduceValuesTask<K,V>
5079          extends BulkTask<K,V,V> {
5080          final BiFun<? super V, ? super V, ? extends V> reducer;
5081          V result;
5082          ReduceValuesTask<K,V> rights, nextRight;
5083          ReduceValuesTask
5084 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5084 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5085               ReduceValuesTask<K,V> nextRight,
5086               BiFun<? super V, ? super V, ? extends V> reducer) {
5087 <            super(m, p, b); this.nextRight = nextRight;
5087 >            super(p, b, i, f, t); this.nextRight = nextRight;
5088              this.reducer = reducer;
5089          }
5090 <        @SuppressWarnings("unchecked") public final boolean exec() {
5091 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5092 <                this.reducer;
5093 <            if (reducer == null)
5094 <                return abortOnNullFunction();
5095 <            try {
5096 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5478 <                    do {} while (!casPending(c = pending, c+1));
5090 >        public final V getRawResult() { return result; }
5091 >        public final void compute() {
5092 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5093 >            if ((reducer = this.reducer) != null) {
5094 >                for (int i = baseIndex, f, h; batch > 0 &&
5095 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5096 >                    addToPendingCount(1);
5097                      (rights = new ReduceValuesTask<K,V>
5098 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5098 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5099 >                      rights, reducer)).fork();
5100                  }
5101                  V r = null;
5102 <                Object v;
5103 <                while ((v = advance()) != null) {
5104 <                    V u = (V)v;
5486 <                    r = (r == null) ? u : reducer.apply(r, u);
5102 >                for (Node<K,V> p; (p = advance()) != null; ) {
5103 >                    V v = p.val;
5104 >                    r = (r == null) ? v : reducer.apply(r, v);
5105                  }
5106                  result = r;
5107 <                for (ReduceValuesTask<K,V> t = this, s;;) {
5108 <                    int c; BulkTask<K,V,?> par; V tr, sr;
5109 <                    if ((c = t.pending) == 0) {
5110 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5111 <                            if ((sr = s.result) != null)
5112 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5113 <                        }
5114 <                        if ((par = t.parent) == null ||
5115 <                            !(par instanceof ReduceValuesTask)) {
5116 <                            t.quietlyComplete();
5117 <                            break;
5500 <                        }
5501 <                        t = (ReduceValuesTask<K,V>)par;
5107 >                CountedCompleter<?> c;
5108 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5109 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5110 >                        t = (ReduceValuesTask<K,V>)c,
5111 >                        s = t.rights;
5112 >                    while (s != null) {
5113 >                        V tr, sr;
5114 >                        if ((sr = s.result) != null)
5115 >                            t.result = (((tr = t.result) == null) ? sr :
5116 >                                        reducer.apply(tr, sr));
5117 >                        s = t.rights = s.nextRight;
5118                      }
5503                    else if (t.casPending(c, c - 1))
5504                        break;
5119                  }
5506            } catch (Throwable ex) {
5507                return tryCompleteComputation(ex);
5120              }
5509            return false;
5121          }
5511        public final V getRawResult() { return result; }
5122      }
5123  
5124 <    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
5124 >    @SuppressWarnings("serial")
5125 >    static final class ReduceEntriesTask<K,V>
5126          extends BulkTask<K,V,Map.Entry<K,V>> {
5127          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5128          Map.Entry<K,V> result;
5129          ReduceEntriesTask<K,V> rights, nextRight;
5130          ReduceEntriesTask
5131 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5131 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5132               ReduceEntriesTask<K,V> nextRight,
5133               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5134 <            super(m, p, b); this.nextRight = nextRight;
5134 >            super(p, b, i, f, t); this.nextRight = nextRight;
5135              this.reducer = reducer;
5136          }
5137 <        @SuppressWarnings("unchecked") public final boolean exec() {
5138 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5139 <                this.reducer;
5140 <            if (reducer == null)
5141 <                return abortOnNullFunction();
5142 <            try {
5143 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5533 <                    do {} while (!casPending(c = pending, c+1));
5137 >        public final Map.Entry<K,V> getRawResult() { return result; }
5138 >        public final void compute() {
5139 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5140 >            if ((reducer = this.reducer) != null) {
5141 >                for (int i = baseIndex, f, h; batch > 0 &&
5142 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5143 >                    addToPendingCount(1);
5144                      (rights = new ReduceEntriesTask<K,V>
5145 <                     (map, this, b >>>= 1, rights, reducer)).fork();
5145 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5146 >                      rights, reducer)).fork();
5147                  }
5148                  Map.Entry<K,V> r = null;
5149 <                Object v;
5150 <                while ((v = advance()) != null) {
5540 <                    Map.Entry<K,V> u = entryFor((K)nextKey, (V)v);
5541 <                    r = (r == null) ? u : reducer.apply(r, u);
5542 <                }
5149 >                for (Node<K,V> p; (p = advance()) != null; )
5150 >                    r = (r == null) ? p : reducer.apply(r, p);
5151                  result = r;
5152 <                for (ReduceEntriesTask<K,V> t = this, s;;) {
5153 <                    int c; BulkTask<K,V,?> par; Map.Entry<K,V> tr, sr;
5154 <                    if ((c = t.pending) == 0) {
5155 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5156 <                            if ((sr = s.result) != null)
5157 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5158 <                        }
5159 <                        if ((par = t.parent) == null ||
5160 <                            !(par instanceof ReduceEntriesTask)) {
5161 <                            t.quietlyComplete();
5162 <                            break;
5555 <                        }
5556 <                        t = (ReduceEntriesTask<K,V>)par;
5152 >                CountedCompleter<?> c;
5153 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5154 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5155 >                        t = (ReduceEntriesTask<K,V>)c,
5156 >                        s = t.rights;
5157 >                    while (s != null) {
5158 >                        Map.Entry<K,V> tr, sr;
5159 >                        if ((sr = s.result) != null)
5160 >                            t.result = (((tr = t.result) == null) ? sr :
5161 >                                        reducer.apply(tr, sr));
5162 >                        s = t.rights = s.nextRight;
5163                      }
5558                    else if (t.casPending(c, c - 1))
5559                        break;
5164                  }
5561            } catch (Throwable ex) {
5562                return tryCompleteComputation(ex);
5165              }
5564            return false;
5166          }
5566        public final Map.Entry<K,V> getRawResult() { return result; }
5167      }
5168  
5169 <    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
5169 >    @SuppressWarnings("serial")
5170 >    static final class MapReduceKeysTask<K,V,U>
5171          extends BulkTask<K,V,U> {
5172          final Fun<? super K, ? extends U> transformer;
5173          final BiFun<? super U, ? super U, ? extends U> reducer;
5174          U result;
5175          MapReduceKeysTask<K,V,U> rights, nextRight;
5176          MapReduceKeysTask
5177 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5177 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5178               MapReduceKeysTask<K,V,U> nextRight,
5179               Fun<? super K, ? extends U> transformer,
5180               BiFun<? super U, ? super U, ? extends U> reducer) {
5181 <            super(m, p, b); this.nextRight = nextRight;
5181 >            super(p, b, i, f, t); this.nextRight = nextRight;
5182              this.transformer = transformer;
5183              this.reducer = reducer;
5184          }
5185 <        @SuppressWarnings("unchecked") public final boolean exec() {
5186 <            final Fun<? super K, ? extends U> transformer =
5187 <                this.transformer;
5188 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5189 <                this.reducer;
5190 <            if (transformer == null || reducer == null)
5191 <                return abortOnNullFunction();
5192 <            try {
5193 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5593 <                    do {} while (!casPending(c = pending, c+1));
5185 >        public final U getRawResult() { return result; }
5186 >        public final void compute() {
5187 >            final Fun<? super K, ? extends U> transformer;
5188 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5189 >            if ((transformer = this.transformer) != null &&
5190 >                (reducer = this.reducer) != null) {
5191 >                for (int i = baseIndex, f, h; batch > 0 &&
5192 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5193 >                    addToPendingCount(1);
5194                      (rights = new MapReduceKeysTask<K,V,U>
5195 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5195 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5196 >                      rights, transformer, reducer)).fork();
5197                  }
5198 <                U r = null, u;
5199 <                while (advance() != null) {
5200 <                    if ((u = transformer.apply((K)nextKey)) != null)
5198 >                U r = null;
5199 >                for (Node<K,V> p; (p = advance()) != null; ) {
5200 >                    U u;
5201 >                    if ((u = transformer.apply(p.key)) != null)
5202                          r = (r == null) ? u : reducer.apply(r, u);
5203                  }
5204                  result = r;
5205 <                for (MapReduceKeysTask<K,V,U> t = this, s;;) {
5206 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5207 <                    if ((c = t.pending) == 0) {
5208 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5209 <                            if ((sr = s.result) != null)
5210 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5211 <                        }
5212 <                        if ((par = t.parent) == null ||
5213 <                            !(par instanceof MapReduceKeysTask)) {
5214 <                            t.quietlyComplete();
5215 <                            break;
5614 <                        }
5615 <                        t = (MapReduceKeysTask<K,V,U>)par;
5205 >                CountedCompleter<?> c;
5206 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5207 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5208 >                        t = (MapReduceKeysTask<K,V,U>)c,
5209 >                        s = t.rights;
5210 >                    while (s != null) {
5211 >                        U tr, sr;
5212 >                        if ((sr = s.result) != null)
5213 >                            t.result = (((tr = t.result) == null) ? sr :
5214 >                                        reducer.apply(tr, sr));
5215 >                        s = t.rights = s.nextRight;
5216                      }
5617                    else if (t.casPending(c, c - 1))
5618                        break;
5217                  }
5620            } catch (Throwable ex) {
5621                return tryCompleteComputation(ex);
5218              }
5623            return false;
5219          }
5625        public final U getRawResult() { return result; }
5220      }
5221  
5222 <    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
5222 >    @SuppressWarnings("serial")
5223 >    static final class MapReduceValuesTask<K,V,U>
5224          extends BulkTask<K,V,U> {
5225          final Fun<? super V, ? extends U> transformer;
5226          final BiFun<? super U, ? super U, ? extends U> reducer;
5227          U result;
5228          MapReduceValuesTask<K,V,U> rights, nextRight;
5229          MapReduceValuesTask
5230 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5230 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5231               MapReduceValuesTask<K,V,U> nextRight,
5232               Fun<? super V, ? extends U> transformer,
5233               BiFun<? super U, ? super U, ? extends U> reducer) {
5234 <            super(m, p, b); this.nextRight = nextRight;
5234 >            super(p, b, i, f, t); this.nextRight = nextRight;
5235              this.transformer = transformer;
5236              this.reducer = reducer;
5237          }
5238 <        @SuppressWarnings("unchecked") public final boolean exec() {
5239 <            final Fun<? super V, ? extends U> transformer =
5240 <                this.transformer;
5241 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5242 <                this.reducer;
5243 <            if (transformer == null || reducer == null)
5244 <                return abortOnNullFunction();
5245 <            try {
5246 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5652 <                    do {} while (!casPending(c = pending, c+1));
5238 >        public final U getRawResult() { return result; }
5239 >        public final void compute() {
5240 >            final Fun<? super V, ? extends U> transformer;
5241 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5242 >            if ((transformer = this.transformer) != null &&
5243 >                (reducer = this.reducer) != null) {
5244 >                for (int i = baseIndex, f, h; batch > 0 &&
5245 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5246 >                    addToPendingCount(1);
5247                      (rights = new MapReduceValuesTask<K,V,U>
5248 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5248 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5249 >                      rights, transformer, reducer)).fork();
5250                  }
5251 <                U r = null, u;
5252 <                Object v;
5253 <                while ((v = advance()) != null) {
5254 <                    if ((u = transformer.apply((V)v)) != null)
5251 >                U r = null;
5252 >                for (Node<K,V> p; (p = advance()) != null; ) {
5253 >                    U u;
5254 >                    if ((u = transformer.apply(p.val)) != null)
5255                          r = (r == null) ? u : reducer.apply(r, u);
5256                  }
5257                  result = r;
5258 <                for (MapReduceValuesTask<K,V,U> t = this, s;;) {
5259 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5260 <                    if ((c = t.pending) == 0) {
5261 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5262 <                            if ((sr = s.result) != null)
5263 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5264 <                        }
5265 <                        if ((par = t.parent) == null ||
5266 <                            !(par instanceof MapReduceValuesTask)) {
5267 <                            t.quietlyComplete();
5268 <                            break;
5674 <                        }
5675 <                        t = (MapReduceValuesTask<K,V,U>)par;
5258 >                CountedCompleter<?> c;
5259 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5260 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5261 >                        t = (MapReduceValuesTask<K,V,U>)c,
5262 >                        s = t.rights;
5263 >                    while (s != null) {
5264 >                        U tr, sr;
5265 >                        if ((sr = s.result) != null)
5266 >                            t.result = (((tr = t.result) == null) ? sr :
5267 >                                        reducer.apply(tr, sr));
5268 >                        s = t.rights = s.nextRight;
5269                      }
5677                    else if (t.casPending(c, c - 1))
5678                        break;
5270                  }
5680            } catch (Throwable ex) {
5681                return tryCompleteComputation(ex);
5271              }
5683            return false;
5272          }
5685        public final U getRawResult() { return result; }
5273      }
5274  
5275 <    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
5275 >    @SuppressWarnings("serial")
5276 >    static final class MapReduceEntriesTask<K,V,U>
5277          extends BulkTask<K,V,U> {
5278          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5279          final BiFun<? super U, ? super U, ? extends U> reducer;
5280          U result;
5281          MapReduceEntriesTask<K,V,U> rights, nextRight;
5282          MapReduceEntriesTask
5283 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5283 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5284               MapReduceEntriesTask<K,V,U> nextRight,
5285               Fun<Map.Entry<K,V>, ? extends U> transformer,
5286               BiFun<? super U, ? super U, ? extends U> reducer) {
5287 <            super(m, p, b); this.nextRight = nextRight;
5287 >            super(p, b, i, f, t); this.nextRight = nextRight;
5288              this.transformer = transformer;
5289              this.reducer = reducer;
5290          }
5291 <        @SuppressWarnings("unchecked") public final boolean exec() {
5292 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5293 <                this.transformer;
5294 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5295 <                this.reducer;
5296 <            if (transformer == null || reducer == null)
5297 <                return abortOnNullFunction();
5298 <            try {
5299 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5712 <                    do {} while (!casPending(c = pending, c+1));
5291 >        public final U getRawResult() { return result; }
5292 >        public final void compute() {
5293 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5294 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5295 >            if ((transformer = this.transformer) != null &&
5296 >                (reducer = this.reducer) != null) {
5297 >                for (int i = baseIndex, f, h; batch > 0 &&
5298 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5299 >                    addToPendingCount(1);
5300                      (rights = new MapReduceEntriesTask<K,V,U>
5301 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5301 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5302 >                      rights, transformer, reducer)).fork();
5303                  }
5304 <                U r = null, u;
5305 <                Object v;
5306 <                while ((v = advance()) != null) {
5307 <                    if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5304 >                U r = null;
5305 >                for (Node<K,V> p; (p = advance()) != null; ) {
5306 >                    U u;
5307 >                    if ((u = transformer.apply(p)) != null)
5308                          r = (r == null) ? u : reducer.apply(r, u);
5309                  }
5310                  result = r;
5311 <                for (MapReduceEntriesTask<K,V,U> t = this, s;;) {
5312 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5313 <                    if ((c = t.pending) == 0) {
5314 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5315 <                            if ((sr = s.result) != null)
5316 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5317 <                        }
5318 <                        if ((par = t.parent) == null ||
5319 <                            !(par instanceof MapReduceEntriesTask)) {
5320 <                            t.quietlyComplete();
5321 <                            break;
5734 <                        }
5735 <                        t = (MapReduceEntriesTask<K,V,U>)par;
5311 >                CountedCompleter<?> c;
5312 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5313 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5314 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5315 >                        s = t.rights;
5316 >                    while (s != null) {
5317 >                        U tr, sr;
5318 >                        if ((sr = s.result) != null)
5319 >                            t.result = (((tr = t.result) == null) ? sr :
5320 >                                        reducer.apply(tr, sr));
5321 >                        s = t.rights = s.nextRight;
5322                      }
5737                    else if (t.casPending(c, c - 1))
5738                        break;
5323                  }
5740            } catch (Throwable ex) {
5741                return tryCompleteComputation(ex);
5324              }
5743            return false;
5325          }
5745        public final U getRawResult() { return result; }
5326      }
5327  
5328 <    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
5328 >    @SuppressWarnings("serial")
5329 >    static final class MapReduceMappingsTask<K,V,U>
5330          extends BulkTask<K,V,U> {
5331          final BiFun<? super K, ? super V, ? extends U> transformer;
5332          final BiFun<? super U, ? super U, ? extends U> reducer;
5333          U result;
5334          MapReduceMappingsTask<K,V,U> rights, nextRight;
5335          MapReduceMappingsTask
5336 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5336 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5337               MapReduceMappingsTask<K,V,U> nextRight,
5338               BiFun<? super K, ? super V, ? extends U> transformer,
5339               BiFun<? super U, ? super U, ? extends U> reducer) {
5340 <            super(m, p, b); this.nextRight = nextRight;
5340 >            super(p, b, i, f, t); this.nextRight = nextRight;
5341              this.transformer = transformer;
5342              this.reducer = reducer;
5343          }
5344 <        @SuppressWarnings("unchecked") public final boolean exec() {
5345 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5346 <                this.transformer;
5347 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5348 <                this.reducer;
5349 <            if (transformer == null || reducer == null)
5350 <                return abortOnNullFunction();
5351 <            try {
5352 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5772 <                    do {} while (!casPending(c = pending, c+1));
5344 >        public final U getRawResult() { return result; }
5345 >        public final void compute() {
5346 >            final BiFun<? super K, ? super V, ? extends U> transformer;
5347 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5348 >            if ((transformer = this.transformer) != null &&
5349 >                (reducer = this.reducer) != null) {
5350 >                for (int i = baseIndex, f, h; batch > 0 &&
5351 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5352 >                    addToPendingCount(1);
5353                      (rights = new MapReduceMappingsTask<K,V,U>
5354 <                     (map, this, b >>>= 1, rights, transformer, reducer)).fork();
5354 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5355 >                      rights, transformer, reducer)).fork();
5356                  }
5357 <                U r = null, u;
5358 <                Object v;
5359 <                while ((v = advance()) != null) {
5360 <                    if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5357 >                U r = null;
5358 >                for (Node<K,V> p; (p = advance()) != null; ) {
5359 >                    U u;
5360 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5361                          r = (r == null) ? u : reducer.apply(r, u);
5362                  }
5363                  result = r;
5364 <                for (MapReduceMappingsTask<K,V,U> t = this, s;;) {
5365 <                    int c; BulkTask<K,V,?> par; U tr, sr;
5366 <                    if ((c = t.pending) == 0) {
5367 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5368 <                            if ((sr = s.result) != null)
5369 <                                t.result = ((tr = t.result) == null) ? sr : reducer.apply(tr, sr);
5370 <                        }
5371 <                        if ((par = t.parent) == null ||
5372 <                            !(par instanceof MapReduceMappingsTask)) {
5373 <                            t.quietlyComplete();
5374 <                            break;
5794 <                        }
5795 <                        t = (MapReduceMappingsTask<K,V,U>)par;
5364 >                CountedCompleter<?> c;
5365 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5366 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5367 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5368 >                        s = t.rights;
5369 >                    while (s != null) {
5370 >                        U tr, sr;
5371 >                        if ((sr = s.result) != null)
5372 >                            t.result = (((tr = t.result) == null) ? sr :
5373 >                                        reducer.apply(tr, sr));
5374 >                        s = t.rights = s.nextRight;
5375                      }
5797                    else if (t.casPending(c, c - 1))
5798                        break;
5376                  }
5800            } catch (Throwable ex) {
5801                return tryCompleteComputation(ex);
5377              }
5803            return false;
5378          }
5805        public final U getRawResult() { return result; }
5379      }
5380  
5381 <    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
5381 >    @SuppressWarnings("serial")
5382 >    static final class MapReduceKeysToDoubleTask<K,V>
5383          extends BulkTask<K,V,Double> {
5384          final ObjectToDouble<? super K> transformer;
5385          final DoubleByDoubleToDouble reducer;
# Line 5813 | Line 5387 | public class ConcurrentHashMapV8<K, V>
5387          double result;
5388          MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5389          MapReduceKeysToDoubleTask
5390 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5390 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5391               MapReduceKeysToDoubleTask<K,V> nextRight,
5392               ObjectToDouble<? super K> transformer,
5393               double basis,
5394               DoubleByDoubleToDouble reducer) {
5395 <            super(m, p, b); this.nextRight = nextRight;
5395 >            super(p, b, i, f, t); this.nextRight = nextRight;
5396              this.transformer = transformer;
5397              this.basis = basis; this.reducer = reducer;
5398          }
5399 <        @SuppressWarnings("unchecked") public final boolean exec() {
5400 <            final ObjectToDouble<? super K> transformer =
5401 <                this.transformer;
5402 <            final DoubleByDoubleToDouble reducer = this.reducer;
5403 <            if (transformer == null || reducer == null)
5404 <                return abortOnNullFunction();
5405 <            try {
5406 <                final double id = this.basis;
5407 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5408 <                    do {} while (!casPending(c = pending, c+1));
5399 >        public final Double getRawResult() { return result; }
5400 >        public final void compute() {
5401 >            final ObjectToDouble<? super K> transformer;
5402 >            final DoubleByDoubleToDouble reducer;
5403 >            if ((transformer = this.transformer) != null &&
5404 >                (reducer = this.reducer) != null) {
5405 >                double r = this.basis;
5406 >                for (int i = baseIndex, f, h; batch > 0 &&
5407 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5408 >                    addToPendingCount(1);
5409                      (rights = new MapReduceKeysToDoubleTask<K,V>
5410 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5410 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5411 >                      rights, transformer, r, reducer)).fork();
5412                  }
5413 <                double r = id;
5414 <                while (advance() != null)
5840 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5413 >                for (Node<K,V> p; (p = advance()) != null; )
5414 >                    r = reducer.apply(r, transformer.apply(p.key));
5415                  result = r;
5416 <                for (MapReduceKeysToDoubleTask<K,V> t = this, s;;) {
5417 <                    int c; BulkTask<K,V,?> par;
5418 <                    if ((c = t.pending) == 0) {
5419 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5420 <                            t.result = reducer.apply(t.result, s.result);
5421 <                        }
5422 <                        if ((par = t.parent) == null ||
5423 <                            !(par instanceof MapReduceKeysToDoubleTask)) {
5850 <                            t.quietlyComplete();
5851 <                            break;
5852 <                        }
5853 <                        t = (MapReduceKeysToDoubleTask<K,V>)par;
5416 >                CountedCompleter<?> c;
5417 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5419 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5420 >                        s = t.rights;
5421 >                    while (s != null) {
5422 >                        t.result = reducer.apply(t.result, s.result);
5423 >                        s = t.rights = s.nextRight;
5424                      }
5855                    else if (t.casPending(c, c - 1))
5856                        break;
5425                  }
5858            } catch (Throwable ex) {
5859                return tryCompleteComputation(ex);
5426              }
5861            return false;
5427          }
5863        public final Double getRawResult() { return result; }
5428      }
5429  
5430 <    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
5430 >    @SuppressWarnings("serial")
5431 >    static final class MapReduceValuesToDoubleTask<K,V>
5432          extends BulkTask<K,V,Double> {
5433          final ObjectToDouble<? super V> transformer;
5434          final DoubleByDoubleToDouble reducer;
# Line 5871 | Line 5436 | public class ConcurrentHashMapV8<K, V>
5436          double result;
5437          MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5438          MapReduceValuesToDoubleTask
5439 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5439 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5440               MapReduceValuesToDoubleTask<K,V> nextRight,
5441               ObjectToDouble<? super V> transformer,
5442               double basis,
5443               DoubleByDoubleToDouble reducer) {
5444 <            super(m, p, b); this.nextRight = nextRight;
5444 >            super(p, b, i, f, t); this.nextRight = nextRight;
5445              this.transformer = transformer;
5446              this.basis = basis; this.reducer = reducer;
5447          }
5448 <        @SuppressWarnings("unchecked") public final boolean exec() {
5449 <            final ObjectToDouble<? super V> transformer =
5450 <                this.transformer;
5451 <            final DoubleByDoubleToDouble reducer = this.reducer;
5452 <            if (transformer == null || reducer == null)
5453 <                return abortOnNullFunction();
5454 <            try {
5455 <                final double id = this.basis;
5456 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5457 <                    do {} while (!casPending(c = pending, c+1));
5448 >        public final Double getRawResult() { return result; }
5449 >        public final void compute() {
5450 >            final ObjectToDouble<? super V> transformer;
5451 >            final DoubleByDoubleToDouble reducer;
5452 >            if ((transformer = this.transformer) != null &&
5453 >                (reducer = this.reducer) != null) {
5454 >                double r = this.basis;
5455 >                for (int i = baseIndex, f, h; batch > 0 &&
5456 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5457 >                    addToPendingCount(1);
5458                      (rights = new MapReduceValuesToDoubleTask<K,V>
5459 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5459 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5460 >                      rights, transformer, r, reducer)).fork();
5461                  }
5462 <                double r = id;
5463 <                Object v;
5898 <                while ((v = advance()) != null)
5899 <                    r = reducer.apply(r, transformer.apply((V)v));
5462 >                for (Node<K,V> p; (p = advance()) != null; )
5463 >                    r = reducer.apply(r, transformer.apply(p.val));
5464                  result = r;
5465 <                for (MapReduceValuesToDoubleTask<K,V> t = this, s;;) {
5466 <                    int c; BulkTask<K,V,?> par;
5467 <                    if ((c = t.pending) == 0) {
5468 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5469 <                            t.result = reducer.apply(t.result, s.result);
5470 <                        }
5471 <                        if ((par = t.parent) == null ||
5472 <                            !(par instanceof MapReduceValuesToDoubleTask)) {
5909 <                            t.quietlyComplete();
5910 <                            break;
5911 <                        }
5912 <                        t = (MapReduceValuesToDoubleTask<K,V>)par;
5465 >                CountedCompleter<?> c;
5466 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5467 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5468 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5469 >                        s = t.rights;
5470 >                    while (s != null) {
5471 >                        t.result = reducer.apply(t.result, s.result);
5472 >                        s = t.rights = s.nextRight;
5473                      }
5914                    else if (t.casPending(c, c - 1))
5915                        break;
5474                  }
5917            } catch (Throwable ex) {
5918                return tryCompleteComputation(ex);
5475              }
5920            return false;
5476          }
5922        public final Double getRawResult() { return result; }
5477      }
5478  
5479 <    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
5479 >    @SuppressWarnings("serial")
5480 >    static final class MapReduceEntriesToDoubleTask<K,V>
5481          extends BulkTask<K,V,Double> {
5482          final ObjectToDouble<Map.Entry<K,V>> transformer;
5483          final DoubleByDoubleToDouble reducer;
# Line 5930 | Line 5485 | public class ConcurrentHashMapV8<K, V>
5485          double result;
5486          MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5487          MapReduceEntriesToDoubleTask
5488 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5488 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5489               MapReduceEntriesToDoubleTask<K,V> nextRight,
5490               ObjectToDouble<Map.Entry<K,V>> transformer,
5491               double basis,
5492               DoubleByDoubleToDouble reducer) {
5493 <            super(m, p, b); this.nextRight = nextRight;
5493 >            super(p, b, i, f, t); this.nextRight = nextRight;
5494              this.transformer = transformer;
5495              this.basis = basis; this.reducer = reducer;
5496          }
5497 <        @SuppressWarnings("unchecked") public final boolean exec() {
5498 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5499 <                this.transformer;
5500 <            final DoubleByDoubleToDouble reducer = this.reducer;
5501 <            if (transformer == null || reducer == null)
5502 <                return abortOnNullFunction();
5503 <            try {
5504 <                final double id = this.basis;
5505 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5506 <                    do {} while (!casPending(c = pending, c+1));
5497 >        public final Double getRawResult() { return result; }
5498 >        public final void compute() {
5499 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
5500 >            final DoubleByDoubleToDouble reducer;
5501 >            if ((transformer = this.transformer) != null &&
5502 >                (reducer = this.reducer) != null) {
5503 >                double r = this.basis;
5504 >                for (int i = baseIndex, f, h; batch > 0 &&
5505 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5506 >                    addToPendingCount(1);
5507                      (rights = new MapReduceEntriesToDoubleTask<K,V>
5508 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5508 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5509 >                      rights, transformer, r, reducer)).fork();
5510                  }
5511 <                double r = id;
5512 <                Object v;
5957 <                while ((v = advance()) != null)
5958 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5511 >                for (Node<K,V> p; (p = advance()) != null; )
5512 >                    r = reducer.apply(r, transformer.apply(p));
5513                  result = r;
5514 <                for (MapReduceEntriesToDoubleTask<K,V> t = this, s;;) {
5515 <                    int c; BulkTask<K,V,?> par;
5516 <                    if ((c = t.pending) == 0) {
5517 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5518 <                            t.result = reducer.apply(t.result, s.result);
5519 <                        }
5520 <                        if ((par = t.parent) == null ||
5521 <                            !(par instanceof MapReduceEntriesToDoubleTask)) {
5968 <                            t.quietlyComplete();
5969 <                            break;
5970 <                        }
5971 <                        t = (MapReduceEntriesToDoubleTask<K,V>)par;
5514 >                CountedCompleter<?> c;
5515 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5516 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5517 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5518 >                        s = t.rights;
5519 >                    while (s != null) {
5520 >                        t.result = reducer.apply(t.result, s.result);
5521 >                        s = t.rights = s.nextRight;
5522                      }
5973                    else if (t.casPending(c, c - 1))
5974                        break;
5523                  }
5976            } catch (Throwable ex) {
5977                return tryCompleteComputation(ex);
5524              }
5979            return false;
5525          }
5981        public final Double getRawResult() { return result; }
5526      }
5527  
5528 <    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
5528 >    @SuppressWarnings("serial")
5529 >    static final class MapReduceMappingsToDoubleTask<K,V>
5530          extends BulkTask<K,V,Double> {
5531          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5532          final DoubleByDoubleToDouble reducer;
# Line 5989 | Line 5534 | public class ConcurrentHashMapV8<K, V>
5534          double result;
5535          MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5536          MapReduceMappingsToDoubleTask
5537 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5537 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5538               MapReduceMappingsToDoubleTask<K,V> nextRight,
5539               ObjectByObjectToDouble<? super K, ? super V> transformer,
5540               double basis,
5541               DoubleByDoubleToDouble reducer) {
5542 <            super(m, p, b); this.nextRight = nextRight;
5542 >            super(p, b, i, f, t); this.nextRight = nextRight;
5543              this.transformer = transformer;
5544              this.basis = basis; this.reducer = reducer;
5545          }
5546 <        @SuppressWarnings("unchecked") public final boolean exec() {
5547 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5548 <                this.transformer;
5549 <            final DoubleByDoubleToDouble reducer = this.reducer;
5550 <            if (transformer == null || reducer == null)
5551 <                return abortOnNullFunction();
5552 <            try {
5553 <                final double id = this.basis;
5554 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5555 <                    do {} while (!casPending(c = pending, c+1));
5546 >        public final Double getRawResult() { return result; }
5547 >        public final void compute() {
5548 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
5549 >            final DoubleByDoubleToDouble reducer;
5550 >            if ((transformer = this.transformer) != null &&
5551 >                (reducer = this.reducer) != null) {
5552 >                double r = this.basis;
5553 >                for (int i = baseIndex, f, h; batch > 0 &&
5554 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5555 >                    addToPendingCount(1);
5556                      (rights = new MapReduceMappingsToDoubleTask<K,V>
5557 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5557 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5558 >                      rights, transformer, r, reducer)).fork();
5559                  }
5560 <                double r = id;
5561 <                Object v;
6016 <                while ((v = advance()) != null)
6017 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5560 >                for (Node<K,V> p; (p = advance()) != null; )
5561 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5562                  result = r;
5563 <                for (MapReduceMappingsToDoubleTask<K,V> t = this, s;;) {
5564 <                    int c; BulkTask<K,V,?> par;
5565 <                    if ((c = t.pending) == 0) {
5566 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5567 <                            t.result = reducer.apply(t.result, s.result);
5568 <                        }
5569 <                        if ((par = t.parent) == null ||
5570 <                            !(par instanceof MapReduceMappingsToDoubleTask)) {
6027 <                            t.quietlyComplete();
6028 <                            break;
6029 <                        }
6030 <                        t = (MapReduceMappingsToDoubleTask<K,V>)par;
5563 >                CountedCompleter<?> c;
5564 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5565 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5566 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5567 >                        s = t.rights;
5568 >                    while (s != null) {
5569 >                        t.result = reducer.apply(t.result, s.result);
5570 >                        s = t.rights = s.nextRight;
5571                      }
6032                    else if (t.casPending(c, c - 1))
6033                        break;
5572                  }
6035            } catch (Throwable ex) {
6036                return tryCompleteComputation(ex);
5573              }
6038            return false;
5574          }
6040        public final Double getRawResult() { return result; }
5575      }
5576  
5577 <    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
5577 >    @SuppressWarnings("serial")
5578 >    static final class MapReduceKeysToLongTask<K,V>
5579          extends BulkTask<K,V,Long> {
5580          final ObjectToLong<? super K> transformer;
5581          final LongByLongToLong reducer;
# Line 6048 | Line 5583 | public class ConcurrentHashMapV8<K, V>
5583          long result;
5584          MapReduceKeysToLongTask<K,V> rights, nextRight;
5585          MapReduceKeysToLongTask
5586 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5586 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5587               MapReduceKeysToLongTask<K,V> nextRight,
5588               ObjectToLong<? super K> transformer,
5589               long basis,
5590               LongByLongToLong reducer) {
5591 <            super(m, p, b); this.nextRight = nextRight;
5591 >            super(p, b, i, f, t); this.nextRight = nextRight;
5592              this.transformer = transformer;
5593              this.basis = basis; this.reducer = reducer;
5594          }
5595 <        @SuppressWarnings("unchecked") public final boolean exec() {
5596 <            final ObjectToLong<? super K> transformer =
5597 <                this.transformer;
5598 <            final LongByLongToLong reducer = this.reducer;
5599 <            if (transformer == null || reducer == null)
5600 <                return abortOnNullFunction();
5601 <            try {
5602 <                final long id = this.basis;
5603 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5604 <                    do {} while (!casPending(c = pending, c+1));
5595 >        public final Long getRawResult() { return result; }
5596 >        public final void compute() {
5597 >            final ObjectToLong<? super K> transformer;
5598 >            final LongByLongToLong reducer;
5599 >            if ((transformer = this.transformer) != null &&
5600 >                (reducer = this.reducer) != null) {
5601 >                long r = this.basis;
5602 >                for (int i = baseIndex, f, h; batch > 0 &&
5603 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5604 >                    addToPendingCount(1);
5605                      (rights = new MapReduceKeysToLongTask<K,V>
5606 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5606 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5607 >                      rights, transformer, r, reducer)).fork();
5608                  }
5609 <                long r = id;
5610 <                while (advance() != null)
6075 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5609 >                for (Node<K,V> p; (p = advance()) != null; )
5610 >                    r = reducer.apply(r, transformer.apply(p.key));
5611                  result = r;
5612 <                for (MapReduceKeysToLongTask<K,V> t = this, s;;) {
5613 <                    int c; BulkTask<K,V,?> par;
5614 <                    if ((c = t.pending) == 0) {
5615 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5616 <                            t.result = reducer.apply(t.result, s.result);
5617 <                        }
5618 <                        if ((par = t.parent) == null ||
5619 <                            !(par instanceof MapReduceKeysToLongTask)) {
6085 <                            t.quietlyComplete();
6086 <                            break;
6087 <                        }
6088 <                        t = (MapReduceKeysToLongTask<K,V>)par;
5612 >                CountedCompleter<?> c;
5613 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5614 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5615 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5616 >                        s = t.rights;
5617 >                    while (s != null) {
5618 >                        t.result = reducer.apply(t.result, s.result);
5619 >                        s = t.rights = s.nextRight;
5620                      }
6090                    else if (t.casPending(c, c - 1))
6091                        break;
5621                  }
6093            } catch (Throwable ex) {
6094                return tryCompleteComputation(ex);
5622              }
6096            return false;
5623          }
6098        public final Long getRawResult() { return result; }
5624      }
5625  
5626 <    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
5626 >    @SuppressWarnings("serial")
5627 >    static final class MapReduceValuesToLongTask<K,V>
5628          extends BulkTask<K,V,Long> {
5629          final ObjectToLong<? super V> transformer;
5630          final LongByLongToLong reducer;
# Line 6106 | Line 5632 | public class ConcurrentHashMapV8<K, V>
5632          long result;
5633          MapReduceValuesToLongTask<K,V> rights, nextRight;
5634          MapReduceValuesToLongTask
5635 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5635 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5636               MapReduceValuesToLongTask<K,V> nextRight,
5637               ObjectToLong<? super V> transformer,
5638               long basis,
5639               LongByLongToLong reducer) {
5640 <            super(m, p, b); this.nextRight = nextRight;
5640 >            super(p, b, i, f, t); this.nextRight = nextRight;
5641              this.transformer = transformer;
5642              this.basis = basis; this.reducer = reducer;
5643          }
5644 <        @SuppressWarnings("unchecked") public final boolean exec() {
5645 <            final ObjectToLong<? super V> transformer =
5646 <                this.transformer;
5647 <            final LongByLongToLong reducer = this.reducer;
5648 <            if (transformer == null || reducer == null)
5649 <                return abortOnNullFunction();
5650 <            try {
5651 <                final long id = this.basis;
5652 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5653 <                    do {} while (!casPending(c = pending, c+1));
5644 >        public final Long getRawResult() { return result; }
5645 >        public final void compute() {
5646 >            final ObjectToLong<? super V> transformer;
5647 >            final LongByLongToLong reducer;
5648 >            if ((transformer = this.transformer) != null &&
5649 >                (reducer = this.reducer) != null) {
5650 >                long r = this.basis;
5651 >                for (int i = baseIndex, f, h; batch > 0 &&
5652 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5653 >                    addToPendingCount(1);
5654                      (rights = new MapReduceValuesToLongTask<K,V>
5655 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5655 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5656 >                      rights, transformer, r, reducer)).fork();
5657                  }
5658 <                long r = id;
5659 <                Object v;
6133 <                while ((v = advance()) != null)
6134 <                    r = reducer.apply(r, transformer.apply((V)v));
5658 >                for (Node<K,V> p; (p = advance()) != null; )
5659 >                    r = reducer.apply(r, transformer.apply(p.val));
5660                  result = r;
5661 <                for (MapReduceValuesToLongTask<K,V> t = this, s;;) {
5662 <                    int c; BulkTask<K,V,?> par;
5663 <                    if ((c = t.pending) == 0) {
5664 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5665 <                            t.result = reducer.apply(t.result, s.result);
5666 <                        }
5667 <                        if ((par = t.parent) == null ||
5668 <                            !(par instanceof MapReduceValuesToLongTask)) {
6144 <                            t.quietlyComplete();
6145 <                            break;
6146 <                        }
6147 <                        t = (MapReduceValuesToLongTask<K,V>)par;
5661 >                CountedCompleter<?> c;
5662 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5663 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5664 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5665 >                        s = t.rights;
5666 >                    while (s != null) {
5667 >                        t.result = reducer.apply(t.result, s.result);
5668 >                        s = t.rights = s.nextRight;
5669                      }
6149                    else if (t.casPending(c, c - 1))
6150                        break;
5670                  }
6152            } catch (Throwable ex) {
6153                return tryCompleteComputation(ex);
5671              }
6155            return false;
5672          }
6157        public final Long getRawResult() { return result; }
5673      }
5674  
5675 <    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
5675 >    @SuppressWarnings("serial")
5676 >    static final class MapReduceEntriesToLongTask<K,V>
5677          extends BulkTask<K,V,Long> {
5678          final ObjectToLong<Map.Entry<K,V>> transformer;
5679          final LongByLongToLong reducer;
# Line 6165 | Line 5681 | public class ConcurrentHashMapV8<K, V>
5681          long result;
5682          MapReduceEntriesToLongTask<K,V> rights, nextRight;
5683          MapReduceEntriesToLongTask
5684 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5684 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5685               MapReduceEntriesToLongTask<K,V> nextRight,
5686               ObjectToLong<Map.Entry<K,V>> transformer,
5687               long basis,
5688               LongByLongToLong reducer) {
5689 <            super(m, p, b); this.nextRight = nextRight;
5689 >            super(p, b, i, f, t); this.nextRight = nextRight;
5690              this.transformer = transformer;
5691              this.basis = basis; this.reducer = reducer;
5692          }
5693 <        @SuppressWarnings("unchecked") public final boolean exec() {
5694 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5695 <                this.transformer;
5696 <            final LongByLongToLong reducer = this.reducer;
5697 <            if (transformer == null || reducer == null)
5698 <                return abortOnNullFunction();
5699 <            try {
5700 <                final long id = this.basis;
5701 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5702 <                    do {} while (!casPending(c = pending, c+1));
5693 >        public final Long getRawResult() { return result; }
5694 >        public final void compute() {
5695 >            final ObjectToLong<Map.Entry<K,V>> transformer;
5696 >            final LongByLongToLong reducer;
5697 >            if ((transformer = this.transformer) != null &&
5698 >                (reducer = this.reducer) != null) {
5699 >                long r = this.basis;
5700 >                for (int i = baseIndex, f, h; batch > 0 &&
5701 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5702 >                    addToPendingCount(1);
5703                      (rights = new MapReduceEntriesToLongTask<K,V>
5704 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5704 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5705 >                      rights, transformer, r, reducer)).fork();
5706                  }
5707 <                long r = id;
5708 <                Object v;
6192 <                while ((v = advance()) != null)
6193 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5707 >                for (Node<K,V> p; (p = advance()) != null; )
5708 >                    r = reducer.apply(r, transformer.apply(p));
5709                  result = r;
5710 <                for (MapReduceEntriesToLongTask<K,V> t = this, s;;) {
5711 <                    int c; BulkTask<K,V,?> par;
5712 <                    if ((c = t.pending) == 0) {
5713 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5714 <                            t.result = reducer.apply(t.result, s.result);
5715 <                        }
5716 <                        if ((par = t.parent) == null ||
5717 <                            !(par instanceof MapReduceEntriesToLongTask)) {
6203 <                            t.quietlyComplete();
6204 <                            break;
6205 <                        }
6206 <                        t = (MapReduceEntriesToLongTask<K,V>)par;
5710 >                CountedCompleter<?> c;
5711 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5712 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5713 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5714 >                        s = t.rights;
5715 >                    while (s != null) {
5716 >                        t.result = reducer.apply(t.result, s.result);
5717 >                        s = t.rights = s.nextRight;
5718                      }
6208                    else if (t.casPending(c, c - 1))
6209                        break;
5719                  }
6211            } catch (Throwable ex) {
6212                return tryCompleteComputation(ex);
5720              }
6214            return false;
5721          }
6216        public final Long getRawResult() { return result; }
5722      }
5723  
5724 <    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
5724 >    @SuppressWarnings("serial")
5725 >    static final class MapReduceMappingsToLongTask<K,V>
5726          extends BulkTask<K,V,Long> {
5727          final ObjectByObjectToLong<? super K, ? super V> transformer;
5728          final LongByLongToLong reducer;
# Line 6224 | Line 5730 | public class ConcurrentHashMapV8<K, V>
5730          long result;
5731          MapReduceMappingsToLongTask<K,V> rights, nextRight;
5732          MapReduceMappingsToLongTask
5733 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5733 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5734               MapReduceMappingsToLongTask<K,V> nextRight,
5735               ObjectByObjectToLong<? super K, ? super V> transformer,
5736               long basis,
5737               LongByLongToLong reducer) {
5738 <            super(m, p, b); this.nextRight = nextRight;
5738 >            super(p, b, i, f, t); this.nextRight = nextRight;
5739              this.transformer = transformer;
5740              this.basis = basis; this.reducer = reducer;
5741          }
5742 <        @SuppressWarnings("unchecked") public final boolean exec() {
5743 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5744 <                this.transformer;
5745 <            final LongByLongToLong reducer = this.reducer;
5746 <            if (transformer == null || reducer == null)
5747 <                return abortOnNullFunction();
5748 <            try {
5749 <                final long id = this.basis;
5750 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5751 <                    do {} while (!casPending(c = pending, c+1));
5742 >        public final Long getRawResult() { return result; }
5743 >        public final void compute() {
5744 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
5745 >            final LongByLongToLong reducer;
5746 >            if ((transformer = this.transformer) != null &&
5747 >                (reducer = this.reducer) != null) {
5748 >                long r = this.basis;
5749 >                for (int i = baseIndex, f, h; batch > 0 &&
5750 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5751 >                    addToPendingCount(1);
5752                      (rights = new MapReduceMappingsToLongTask<K,V>
5753 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5753 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5754 >                      rights, transformer, r, reducer)).fork();
5755                  }
5756 <                long r = id;
5757 <                Object v;
6251 <                while ((v = advance()) != null)
6252 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5756 >                for (Node<K,V> p; (p = advance()) != null; )
5757 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5758                  result = r;
5759 <                for (MapReduceMappingsToLongTask<K,V> t = this, s;;) {
5760 <                    int c; BulkTask<K,V,?> par;
5761 <                    if ((c = t.pending) == 0) {
5762 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5763 <                            t.result = reducer.apply(t.result, s.result);
5764 <                        }
5765 <                        if ((par = t.parent) == null ||
5766 <                            !(par instanceof MapReduceMappingsToLongTask)) {
6262 <                            t.quietlyComplete();
6263 <                            break;
6264 <                        }
6265 <                        t = (MapReduceMappingsToLongTask<K,V>)par;
5759 >                CountedCompleter<?> c;
5760 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5761 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5762 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5763 >                        s = t.rights;
5764 >                    while (s != null) {
5765 >                        t.result = reducer.apply(t.result, s.result);
5766 >                        s = t.rights = s.nextRight;
5767                      }
6267                    else if (t.casPending(c, c - 1))
6268                        break;
5768                  }
6270            } catch (Throwable ex) {
6271                return tryCompleteComputation(ex);
5769              }
6273            return false;
5770          }
6275        public final Long getRawResult() { return result; }
5771      }
5772  
5773 <    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
5773 >    @SuppressWarnings("serial")
5774 >    static final class MapReduceKeysToIntTask<K,V>
5775          extends BulkTask<K,V,Integer> {
5776          final ObjectToInt<? super K> transformer;
5777          final IntByIntToInt reducer;
# Line 6283 | Line 5779 | public class ConcurrentHashMapV8<K, V>
5779          int result;
5780          MapReduceKeysToIntTask<K,V> rights, nextRight;
5781          MapReduceKeysToIntTask
5782 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5782 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5783               MapReduceKeysToIntTask<K,V> nextRight,
5784               ObjectToInt<? super K> transformer,
5785               int basis,
5786               IntByIntToInt reducer) {
5787 <            super(m, p, b); this.nextRight = nextRight;
5787 >            super(p, b, i, f, t); this.nextRight = nextRight;
5788              this.transformer = transformer;
5789              this.basis = basis; this.reducer = reducer;
5790          }
5791 <        @SuppressWarnings("unchecked") public final boolean exec() {
5792 <            final ObjectToInt<? super K> transformer =
5793 <                this.transformer;
5794 <            final IntByIntToInt reducer = this.reducer;
5795 <            if (transformer == null || reducer == null)
5796 <                return abortOnNullFunction();
5797 <            try {
5798 <                final int id = this.basis;
5799 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5800 <                    do {} while (!casPending(c = pending, c+1));
5791 >        public final Integer getRawResult() { return result; }
5792 >        public final void compute() {
5793 >            final ObjectToInt<? super K> transformer;
5794 >            final IntByIntToInt reducer;
5795 >            if ((transformer = this.transformer) != null &&
5796 >                (reducer = this.reducer) != null) {
5797 >                int r = this.basis;
5798 >                for (int i = baseIndex, f, h; batch > 0 &&
5799 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5800 >                    addToPendingCount(1);
5801                      (rights = new MapReduceKeysToIntTask<K,V>
5802 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5802 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5803 >                      rights, transformer, r, reducer)).fork();
5804                  }
5805 <                int r = id;
5806 <                while (advance() != null)
6310 <                    r = reducer.apply(r, transformer.apply((K)nextKey));
5805 >                for (Node<K,V> p; (p = advance()) != null; )
5806 >                    r = reducer.apply(r, transformer.apply(p.key));
5807                  result = r;
5808 <                for (MapReduceKeysToIntTask<K,V> t = this, s;;) {
5809 <                    int c; BulkTask<K,V,?> par;
5810 <                    if ((c = t.pending) == 0) {
5811 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5812 <                            t.result = reducer.apply(t.result, s.result);
5813 <                        }
5814 <                        if ((par = t.parent) == null ||
5815 <                            !(par instanceof MapReduceKeysToIntTask)) {
6320 <                            t.quietlyComplete();
6321 <                            break;
6322 <                        }
6323 <                        t = (MapReduceKeysToIntTask<K,V>)par;
5808 >                CountedCompleter<?> c;
5809 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5810 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5811 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5812 >                        s = t.rights;
5813 >                    while (s != null) {
5814 >                        t.result = reducer.apply(t.result, s.result);
5815 >                        s = t.rights = s.nextRight;
5816                      }
6325                    else if (t.casPending(c, c - 1))
6326                        break;
5817                  }
6328            } catch (Throwable ex) {
6329                return tryCompleteComputation(ex);
5818              }
6331            return false;
5819          }
6333        public final Integer getRawResult() { return result; }
5820      }
5821  
5822 <    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
5822 >    @SuppressWarnings("serial")
5823 >    static final class MapReduceValuesToIntTask<K,V>
5824          extends BulkTask<K,V,Integer> {
5825          final ObjectToInt<? super V> transformer;
5826          final IntByIntToInt reducer;
# Line 6341 | Line 5828 | public class ConcurrentHashMapV8<K, V>
5828          int result;
5829          MapReduceValuesToIntTask<K,V> rights, nextRight;
5830          MapReduceValuesToIntTask
5831 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5831 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5832               MapReduceValuesToIntTask<K,V> nextRight,
5833               ObjectToInt<? super V> transformer,
5834               int basis,
5835               IntByIntToInt reducer) {
5836 <            super(m, p, b); this.nextRight = nextRight;
5836 >            super(p, b, i, f, t); this.nextRight = nextRight;
5837              this.transformer = transformer;
5838              this.basis = basis; this.reducer = reducer;
5839          }
5840 <        @SuppressWarnings("unchecked") public final boolean exec() {
5841 <            final ObjectToInt<? super V> transformer =
5842 <                this.transformer;
5843 <            final IntByIntToInt reducer = this.reducer;
5844 <            if (transformer == null || reducer == null)
5845 <                return abortOnNullFunction();
5846 <            try {
5847 <                final int id = this.basis;
5848 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5849 <                    do {} while (!casPending(c = pending, c+1));
5840 >        public final Integer getRawResult() { return result; }
5841 >        public final void compute() {
5842 >            final ObjectToInt<? super V> transformer;
5843 >            final IntByIntToInt reducer;
5844 >            if ((transformer = this.transformer) != null &&
5845 >                (reducer = this.reducer) != null) {
5846 >                int r = this.basis;
5847 >                for (int i = baseIndex, f, h; batch > 0 &&
5848 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5849 >                    addToPendingCount(1);
5850                      (rights = new MapReduceValuesToIntTask<K,V>
5851 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5851 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5852 >                      rights, transformer, r, reducer)).fork();
5853                  }
5854 <                int r = id;
5855 <                Object v;
6368 <                while ((v = advance()) != null)
6369 <                    r = reducer.apply(r, transformer.apply((V)v));
5854 >                for (Node<K,V> p; (p = advance()) != null; )
5855 >                    r = reducer.apply(r, transformer.apply(p.val));
5856                  result = r;
5857 <                for (MapReduceValuesToIntTask<K,V> t = this, s;;) {
5858 <                    int c; BulkTask<K,V,?> par;
5859 <                    if ((c = t.pending) == 0) {
5860 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5861 <                            t.result = reducer.apply(t.result, s.result);
5862 <                        }
5863 <                        if ((par = t.parent) == null ||
5864 <                            !(par instanceof MapReduceValuesToIntTask)) {
6379 <                            t.quietlyComplete();
6380 <                            break;
6381 <                        }
6382 <                        t = (MapReduceValuesToIntTask<K,V>)par;
5857 >                CountedCompleter<?> c;
5858 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5859 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5860 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5861 >                        s = t.rights;
5862 >                    while (s != null) {
5863 >                        t.result = reducer.apply(t.result, s.result);
5864 >                        s = t.rights = s.nextRight;
5865                      }
6384                    else if (t.casPending(c, c - 1))
6385                        break;
5866                  }
6387            } catch (Throwable ex) {
6388                return tryCompleteComputation(ex);
5867              }
6390            return false;
5868          }
6392        public final Integer getRawResult() { return result; }
5869      }
5870  
5871 <    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
5871 >    @SuppressWarnings("serial")
5872 >    static final class MapReduceEntriesToIntTask<K,V>
5873          extends BulkTask<K,V,Integer> {
5874          final ObjectToInt<Map.Entry<K,V>> transformer;
5875          final IntByIntToInt reducer;
# Line 6400 | Line 5877 | public class ConcurrentHashMapV8<K, V>
5877          int result;
5878          MapReduceEntriesToIntTask<K,V> rights, nextRight;
5879          MapReduceEntriesToIntTask
5880 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5880 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5881               MapReduceEntriesToIntTask<K,V> nextRight,
5882               ObjectToInt<Map.Entry<K,V>> transformer,
5883               int basis,
5884               IntByIntToInt reducer) {
5885 <            super(m, p, b); this.nextRight = nextRight;
5885 >            super(p, b, i, f, t); this.nextRight = nextRight;
5886              this.transformer = transformer;
5887              this.basis = basis; this.reducer = reducer;
5888          }
5889 <        @SuppressWarnings("unchecked") public final boolean exec() {
5890 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5891 <                this.transformer;
5892 <            final IntByIntToInt reducer = this.reducer;
5893 <            if (transformer == null || reducer == null)
5894 <                return abortOnNullFunction();
5895 <            try {
5896 <                final int id = this.basis;
5897 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5898 <                    do {} while (!casPending(c = pending, c+1));
5889 >        public final Integer getRawResult() { return result; }
5890 >        public final void compute() {
5891 >            final ObjectToInt<Map.Entry<K,V>> transformer;
5892 >            final IntByIntToInt reducer;
5893 >            if ((transformer = this.transformer) != null &&
5894 >                (reducer = this.reducer) != null) {
5895 >                int r = this.basis;
5896 >                for (int i = baseIndex, f, h; batch > 0 &&
5897 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5898 >                    addToPendingCount(1);
5899                      (rights = new MapReduceEntriesToIntTask<K,V>
5900 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5900 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5901 >                      rights, transformer, r, reducer)).fork();
5902                  }
5903 <                int r = id;
5904 <                Object v;
6427 <                while ((v = advance()) != null)
6428 <                    r = reducer.apply(r, transformer.apply(entryFor((K)nextKey, (V)v)));
5903 >                for (Node<K,V> p; (p = advance()) != null; )
5904 >                    r = reducer.apply(r, transformer.apply(p));
5905                  result = r;
5906 <                for (MapReduceEntriesToIntTask<K,V> t = this, s;;) {
5907 <                    int c; BulkTask<K,V,?> par;
5908 <                    if ((c = t.pending) == 0) {
5909 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5910 <                            t.result = reducer.apply(t.result, s.result);
5911 <                        }
5912 <                        if ((par = t.parent) == null ||
5913 <                            !(par instanceof MapReduceEntriesToIntTask)) {
6438 <                            t.quietlyComplete();
6439 <                            break;
6440 <                        }
6441 <                        t = (MapReduceEntriesToIntTask<K,V>)par;
5906 >                CountedCompleter<?> c;
5907 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5908 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5909 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5910 >                        s = t.rights;
5911 >                    while (s != null) {
5912 >                        t.result = reducer.apply(t.result, s.result);
5913 >                        s = t.rights = s.nextRight;
5914                      }
6443                    else if (t.casPending(c, c - 1))
6444                        break;
5915                  }
6446            } catch (Throwable ex) {
6447                return tryCompleteComputation(ex);
5916              }
6449            return false;
5917          }
6451        public final Integer getRawResult() { return result; }
5918      }
5919  
5920 <    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
5920 >    @SuppressWarnings("serial")
5921 >    static final class MapReduceMappingsToIntTask<K,V>
5922          extends BulkTask<K,V,Integer> {
5923          final ObjectByObjectToInt<? super K, ? super V> transformer;
5924          final IntByIntToInt reducer;
# Line 6459 | Line 5926 | public class ConcurrentHashMapV8<K, V>
5926          int result;
5927          MapReduceMappingsToIntTask<K,V> rights, nextRight;
5928          MapReduceMappingsToIntTask
5929 <            (ConcurrentHashMapV8<K,V> m, BulkTask<K,V,?> p, int b,
5930 <             MapReduceMappingsToIntTask<K,V> rights,
5929 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5930 >             MapReduceMappingsToIntTask<K,V> nextRight,
5931               ObjectByObjectToInt<? super K, ? super V> transformer,
5932               int basis,
5933               IntByIntToInt reducer) {
5934 <            super(m, p, b); this.nextRight = nextRight;
5934 >            super(p, b, i, f, t); this.nextRight = nextRight;
5935              this.transformer = transformer;
5936              this.basis = basis; this.reducer = reducer;
5937          }
5938 <        @SuppressWarnings("unchecked") public final boolean exec() {
5939 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
5940 <                this.transformer;
5941 <            final IntByIntToInt reducer = this.reducer;
5942 <            if (transformer == null || reducer == null)
5943 <                return abortOnNullFunction();
5944 <            try {
5945 <                final int id = this.basis;
5946 <                for (int c, b = batch(); b > 1 && baseIndex != baseLimit;) {
5947 <                    do {} while (!casPending(c = pending, c+1));
5938 >        public final Integer getRawResult() { return result; }
5939 >        public final void compute() {
5940 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
5941 >            final IntByIntToInt reducer;
5942 >            if ((transformer = this.transformer) != null &&
5943 >                (reducer = this.reducer) != null) {
5944 >                int r = this.basis;
5945 >                for (int i = baseIndex, f, h; batch > 0 &&
5946 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5947 >                    addToPendingCount(1);
5948                      (rights = new MapReduceMappingsToIntTask<K,V>
5949 <                     (map, this, b >>>= 1, rights, transformer, id, reducer)).fork();
5949 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5950 >                      rights, transformer, r, reducer)).fork();
5951                  }
5952 <                int r = id;
5953 <                Object v;
6486 <                while ((v = advance()) != null)
6487 <                    r = reducer.apply(r, transformer.apply((K)nextKey, (V)v));
5952 >                for (Node<K,V> p; (p = advance()) != null; )
5953 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5954                  result = r;
5955 <                for (MapReduceMappingsToIntTask<K,V> t = this, s;;) {
5956 <                    int c; BulkTask<K,V,?> par;
5957 <                    if ((c = t.pending) == 0) {
5958 <                        for (s = t.rights; s != null; s = t.rights = s.nextRight) {
5959 <                            t.result = reducer.apply(t.result, s.result);
5955 >                CountedCompleter<?> c;
5956 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5957 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
5958 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
5959 >                        s = t.rights;
5960 >                    while (s != null) {
5961 >                        t.result = reducer.apply(t.result, s.result);
5962 >                        s = t.rights = s.nextRight;
5963 >                    }
5964 >                }
5965 >            }
5966 >        }
5967 >    }
5968 >
5969 >    /* ---------------- Counters -------------- */
5970 >
5971 >    // Adapted from LongAdder and Striped64.
5972 >    // See their internal docs for explanation.
5973 >
5974 >    // A padded cell for distributing counts
5975 >    static final class CounterCell {
5976 >        volatile long p0, p1, p2, p3, p4, p5, p6;
5977 >        volatile long value;
5978 >        volatile long q0, q1, q2, q3, q4, q5, q6;
5979 >        CounterCell(long x) { value = x; }
5980 >    }
5981 >
5982 >    /**
5983 >     * Holder for the thread-local hash code determining which
5984 >     * CounterCell to use. The code is initialized via the
5985 >     * counterHashCodeGenerator, but may be moved upon collisions.
5986 >     */
5987 >    static final class CounterHashCode {
5988 >        int code;
5989 >    }
5990 >
5991 >    /**
5992 >     * Generates initial value for per-thread CounterHashCodes.
5993 >     */
5994 >    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
5995 >
5996 >    /**
5997 >     * Increment for counterHashCodeGenerator. See class ThreadLocal
5998 >     * for explanation.
5999 >     */
6000 >    static final int SEED_INCREMENT = 0x61c88647;
6001 >
6002 >    /**
6003 >     * Per-thread counter hash codes. Shared across all instances.
6004 >     */
6005 >    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6006 >        new ThreadLocal<CounterHashCode>();
6007 >
6008 >
6009 >    final long sumCount() {
6010 >        CounterCell[] as = counterCells; CounterCell a;
6011 >        long sum = baseCount;
6012 >        if (as != null) {
6013 >            for (int i = 0; i < as.length; ++i) {
6014 >                if ((a = as[i]) != null)
6015 >                    sum += a.value;
6016 >            }
6017 >        }
6018 >        return sum;
6019 >    }
6020 >
6021 >    // See LongAdder version for explanation
6022 >    private final void fullAddCount(long x, CounterHashCode hc,
6023 >                                    boolean wasUncontended) {
6024 >        int h;
6025 >        if (hc == null) {
6026 >            hc = new CounterHashCode();
6027 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6028 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6029 >            threadCounterHashCode.set(hc);
6030 >        }
6031 >        else
6032 >            h = hc.code;
6033 >        boolean collide = false;                // True if last slot nonempty
6034 >        for (;;) {
6035 >            CounterCell[] as; CounterCell a; int n; long v;
6036 >            if ((as = counterCells) != null && (n = as.length) > 0) {
6037 >                if ((a = as[(n - 1) & h]) == null) {
6038 >                    if (cellsBusy == 0) {            // Try to attach new Cell
6039 >                        CounterCell r = new CounterCell(x); // Optimistic create
6040 >                        if (cellsBusy == 0 &&
6041 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6042 >                            boolean created = false;
6043 >                            try {               // Recheck under lock
6044 >                                CounterCell[] rs; int m, j;
6045 >                                if ((rs = counterCells) != null &&
6046 >                                    (m = rs.length) > 0 &&
6047 >                                    rs[j = (m - 1) & h] == null) {
6048 >                                    rs[j] = r;
6049 >                                    created = true;
6050 >                                }
6051 >                            } finally {
6052 >                                cellsBusy = 0;
6053 >                            }
6054 >                            if (created)
6055 >                                break;
6056 >                            continue;           // Slot is now non-empty
6057                          }
6058 <                        if ((par = t.parent) == null ||
6059 <                            !(par instanceof MapReduceMappingsToIntTask)) {
6060 <                            t.quietlyComplete();
6061 <                            break;
6058 >                    }
6059 >                    collide = false;
6060 >                }
6061 >                else if (!wasUncontended)       // CAS already known to fail
6062 >                    wasUncontended = true;      // Continue after rehash
6063 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6064 >                    break;
6065 >                else if (counterCells != as || n >= NCPU)
6066 >                    collide = false;            // At max size or stale
6067 >                else if (!collide)
6068 >                    collide = true;
6069 >                else if (cellsBusy == 0 &&
6070 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6071 >                    try {
6072 >                        if (counterCells == as) {// Expand table unless stale
6073 >                            CounterCell[] rs = new CounterCell[n << 1];
6074 >                            for (int i = 0; i < n; ++i)
6075 >                                rs[i] = as[i];
6076 >                            counterCells = rs;
6077                          }
6078 <                        t = (MapReduceMappingsToIntTask<K,V>)par;
6078 >                    } finally {
6079 >                        cellsBusy = 0;
6080                      }
6081 <                    else if (t.casPending(c, c - 1))
6082 <                        break;
6081 >                    collide = false;
6082 >                    continue;                   // Retry with expanded table
6083                  }
6084 <            } catch (Throwable ex) {
6085 <                return tryCompleteComputation(ex);
6084 >                h ^= h << 13;                   // Rehash
6085 >                h ^= h >>> 17;
6086 >                h ^= h << 5;
6087 >            }
6088 >            else if (cellsBusy == 0 && counterCells == as &&
6089 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6090 >                boolean init = false;
6091 >                try {                           // Initialize table
6092 >                    if (counterCells == as) {
6093 >                        CounterCell[] rs = new CounterCell[2];
6094 >                        rs[h & 1] = new CounterCell(x);
6095 >                        counterCells = rs;
6096 >                        init = true;
6097 >                    }
6098 >                } finally {
6099 >                    cellsBusy = 0;
6100 >                }
6101 >                if (init)
6102 >                    break;
6103              }
6104 <            return false;
6104 >            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6105 >                break;                          // Fall back on using base
6106          }
6107 <        public final Integer getRawResult() { return result; }
6107 >        hc.code = h;                            // Record index for next time
6108      }
6109  
6513
6110      // Unsafe mechanics
6111 <    private static final sun.misc.Unsafe UNSAFE;
6112 <    private static final long counterOffset;
6113 <    private static final long sizeCtlOffset;
6111 >    private static final sun.misc.Unsafe U;
6112 >    private static final long SIZECTL;
6113 >    private static final long TRANSFERINDEX;
6114 >    private static final long TRANSFERORIGIN;
6115 >    private static final long BASECOUNT;
6116 >    private static final long CELLSBUSY;
6117 >    private static final long CELLVALUE;
6118      private static final long ABASE;
6119      private static final int ASHIFT;
6120  
6121      static {
6522        int ss;
6122          try {
6123 <            UNSAFE = getUnsafe();
6123 >            U = getUnsafe();
6124              Class<?> k = ConcurrentHashMapV8.class;
6125 <            counterOffset = UNSAFE.objectFieldOffset
6527 <                (k.getDeclaredField("counter"));
6528 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6125 >            SIZECTL = U.objectFieldOffset
6126                  (k.getDeclaredField("sizeCtl"));
6127 <            Class<?> sc = Node[].class;
6128 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6129 <            ss = UNSAFE.arrayIndexScale(sc);
6127 >            TRANSFERINDEX = U.objectFieldOffset
6128 >                (k.getDeclaredField("transferIndex"));
6129 >            TRANSFERORIGIN = U.objectFieldOffset
6130 >                (k.getDeclaredField("transferOrigin"));
6131 >            BASECOUNT = U.objectFieldOffset
6132 >                (k.getDeclaredField("baseCount"));
6133 >            CELLSBUSY = U.objectFieldOffset
6134 >                (k.getDeclaredField("cellsBusy"));
6135 >            Class<?> ck = CounterCell.class;
6136 >            CELLVALUE = U.objectFieldOffset
6137 >                (ck.getDeclaredField("value"));
6138 >            Class<?> ak = Node[].class;
6139 >            ABASE = U.arrayBaseOffset(ak);
6140 >            int scale = U.arrayIndexScale(ak);
6141 >            if ((scale & (scale - 1)) != 0)
6142 >                throw new Error("data type scale not a power of two");
6143 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6144          } catch (Exception e) {
6145              throw new Error(e);
6146          }
6536        if ((ss & (ss-1)) != 0)
6537            throw new Error("data type scale not a power of two");
6538        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6147      }
6148  
6149      /**
# Line 6548 | Line 6156 | public class ConcurrentHashMapV8<K, V>
6156      private static sun.misc.Unsafe getUnsafe() {
6157          try {
6158              return sun.misc.Unsafe.getUnsafe();
6159 <        } catch (SecurityException se) {
6160 <            try {
6161 <                return java.security.AccessController.doPrivileged
6162 <                    (new java.security
6163 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6164 <                        public sun.misc.Unsafe run() throws Exception {
6165 <                            java.lang.reflect.Field f = sun.misc
6166 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6167 <                            f.setAccessible(true);
6168 <                            return (sun.misc.Unsafe) f.get(null);
6169 <                        }});
6170 <            } catch (java.security.PrivilegedActionException e) {
6171 <                throw new RuntimeException("Could not initialize intrinsics",
6172 <                                           e.getCause());
6173 <            }
6159 >        } catch (SecurityException tryReflectionInstead) {}
6160 >        try {
6161 >            return java.security.AccessController.doPrivileged
6162 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6163 >                public sun.misc.Unsafe run() throws Exception {
6164 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6165 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6166 >                        f.setAccessible(true);
6167 >                        Object x = f.get(null);
6168 >                        if (k.isInstance(x))
6169 >                            return k.cast(x);
6170 >                    }
6171 >                    throw new NoSuchFieldError("the Unsafe");
6172 >                }});
6173 >        } catch (java.security.PrivilegedActionException e) {
6174 >            throw new RuntimeException("Could not initialize intrinsics",
6175 >                                       e.getCause());
6176          }
6177      }
6178   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines