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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines