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.52 by dl, Mon Aug 13 15:52:33 2012 UTC vs.
Revision 1.105 by jsr166, Wed Jun 19 17:08:59 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166e;
8 < import jsr166e.LongAdder;
8 >
9   import jsr166e.ForkJoinPool;
10 import jsr166e.ForkJoinTask;
10  
11 < import java.util.Comparator;
11 > import java.io.ObjectStreamField;
12 > import java.io.Serializable;
13 > import java.lang.reflect.ParameterizedType;
14 > import java.lang.reflect.Type;
15   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
16   import java.util.Collection;
17 < import java.util.AbstractMap;
18 < import java.util.AbstractSet;
19 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
17 > import java.util.Comparator;
18 > import java.util.ConcurrentModificationException;
19 > import java.util.Enumeration;
20   import java.util.HashMap;
21 + import java.util.Hashtable;
22   import java.util.Iterator;
23 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
23 > import java.util.Map;
24   import java.util.NoSuchElementException;
25 + import java.util.Set;
26   import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ThreadLocalRandom;
28 import java.util.concurrent.locks.LockSupport;
29 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
27   import java.util.concurrent.atomic.AtomicReference;
28 <
29 < import java.io.Serializable;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 > import java.util.concurrent.locks.LockSupport;
30 > import java.util.concurrent.locks.ReentrantLock;
31  
32   /**
33   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 41 | import java.io.Serializable;
41   * interoperable with {@code Hashtable} in programs that rely on its
42   * thread safety but not on its synchronization details.
43   *
44 < * <p> Retrieval operations (including {@code get}) generally do not
44 > * <p>Retrieval operations (including {@code get}) generally do not
45   * block, so may overlap with update operations (including {@code put}
46   * and {@code remove}). Retrievals reflect the results of the most
47   * recently <em>completed</em> update operations holding upon their
48 < * onset.  For aggregate operations such as {@code putAll} and {@code
49 < * clear}, concurrent retrievals may reflect insertion or removal of
50 < * only some entries.  Similarly, Iterators and Enumerations return
51 < * elements reflecting the state of the hash table at some point at or
52 < * since the creation of the iterator/enumeration.  They do
53 < * <em>not</em> throw {@link ConcurrentModificationException}.
54 < * However, iterators are designed to be used by only one thread at a
55 < * time.  Bear in mind that the results of aggregate status methods
56 < * including {@code size}, {@code isEmpty}, and {@code containsValue}
57 < * are typically useful only when a map is not undergoing concurrent
58 < * updates in other threads.  Otherwise the results of these methods
59 < * reflect transient states that may be adequate for monitoring
60 < * or estimation purposes, but not for program control.
48 > * onset. (More formally, an update operation for a given key bears a
49 > * <em>happens-before</em> relation with any (non-null) retrieval for
50 > * that key reporting the updated value.)  For aggregate operations
51 > * such as {@code putAll} and {@code clear}, concurrent retrievals may
52 > * reflect insertion or removal of only some entries.  Similarly,
53 > * Iterators and Enumerations return elements reflecting the state of
54 > * the hash table at some point at or since the creation of the
55 > * iterator/enumeration.  They do <em>not</em> throw {@link
56 > * ConcurrentModificationException}.  However, iterators are designed
57 > * to be used by only one thread at a time.  Bear in mind that the
58 > * results of aggregate status methods including {@code size}, {@code
59 > * isEmpty}, and {@code containsValue} are typically useful only when
60 > * a map is not undergoing concurrent updates in other threads.
61 > * Otherwise the results of these methods reflect transient states
62 > * that may be adequate for monitoring or estimation purposes, but not
63 > * for program control.
64   *
65 < * <p> The table is dynamically expanded when there are too many
65 > * <p>The table is dynamically expanded when there are too many
66   * collisions (i.e., keys that have distinct hash codes but fall into
67   * the same slot modulo the table size), with the expected average
68   * effect of maintaining roughly two bins per mapping (corresponding
# Line 80 | Line 81 | import java.io.Serializable;
81   * expected {@code concurrencyLevel} as an additional hint for
82   * internal sizing.  Note that using many keys with exactly the same
83   * {@code hashCode()} is a sure way to slow down performance of any
84 < * hash table.
84 > * hash table. To ameliorate impact, when keys are {@link Comparable},
85 > * this class may use comparison order among keys to help break ties.
86 > *
87 > * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
88 > * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
89 > * (using {@link #keySet(Object)} when only keys are of interest, and the
90 > * mapped values are (perhaps transiently) not used or all take the
91 > * same mapping value.
92   *
93   * <p>This class and its views and iterators implement all of the
94   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
95   * interfaces.
96   *
97 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
97 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
98   * does <em>not</em> allow {@code null} to be used as a key or value.
99   *
100 + * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
101 + * operations that are designed
102 + * to be safely, and often sensibly, applied even with maps that are
103 + * being concurrently updated by other threads; for example, when
104 + * computing a snapshot summary of the values in a shared registry.
105 + * There are three kinds of operation, each with four forms, accepting
106 + * functions with Keys, Values, Entries, and (Key, Value) arguments
107 + * and/or return values. Because the elements of a ConcurrentHashMapV8
108 + * are not ordered in any particular way, and may be processed in
109 + * different orders in different parallel executions, the correctness
110 + * of supplied functions should not depend on any ordering, or on any
111 + * other objects or values that may transiently change while
112 + * computation is in progress; and except for forEach actions, should
113 + * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
114 + * objects do not support method {@code setValue}.
115 + *
116 + * <ul>
117 + * <li> forEach: Perform a given action on each element.
118 + * A variant form applies a given transformation on each element
119 + * before performing the action.</li>
120 + *
121 + * <li> search: Return the first available non-null result of
122 + * applying a given function on each element; skipping further
123 + * search when a result is found.</li>
124 + *
125 + * <li> reduce: Accumulate each element.  The supplied reduction
126 + * function cannot rely on ordering (more formally, it should be
127 + * both associative and commutative).  There are five variants:
128 + *
129 + * <ul>
130 + *
131 + * <li> Plain reductions. (There is not a form of this method for
132 + * (key, value) function arguments since there is no corresponding
133 + * return type.)</li>
134 + *
135 + * <li> Mapped reductions that accumulate the results of a given
136 + * function applied to each element.</li>
137 + *
138 + * <li> Reductions to scalar doubles, longs, and ints, using a
139 + * given basis value.</li>
140 + *
141 + * </ul>
142 + * </li>
143 + * </ul>
144 + *
145 + * <p>These bulk operations accept a {@code parallelismThreshold}
146 + * argument. Methods proceed sequentially if the current map size is
147 + * estimated to be less than the given threshold. Using a value of
148 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
149 + * of {@code 1} results in maximal parallelism by partitioning into
150 + * enough subtasks to fully utilize the {@link
151 + * ForkJoinPool#commonPool()} that is used for all parallel
152 + * computations. Normally, you would initially choose one of these
153 + * extreme values, and then measure performance of using in-between
154 + * values that trade off overhead versus throughput.
155 + *
156 + * <p>The concurrency properties of bulk operations follow
157 + * from those of ConcurrentHashMapV8: Any non-null result returned
158 + * from {@code get(key)} and related access methods bears a
159 + * happens-before relation with the associated insertion or
160 + * update.  The result of any bulk operation reflects the
161 + * composition of these per-element relations (but is not
162 + * necessarily atomic with respect to the map as a whole unless it
163 + * is somehow known to be quiescent).  Conversely, because keys
164 + * and values in the map are never null, null serves as a reliable
165 + * atomic indicator of the current lack of any result.  To
166 + * maintain this property, null serves as an implicit basis for
167 + * all non-scalar reduction operations. For the double, long, and
168 + * int versions, the basis should be one that, when combined with
169 + * any other value, returns that other value (more formally, it
170 + * should be the identity element for the reduction). Most common
171 + * reductions have these properties; for example, computing a sum
172 + * with basis 0 or a minimum with basis MAX_VALUE.
173 + *
174 + * <p>Search and transformation functions provided as arguments
175 + * should similarly return null to indicate the lack of any result
176 + * (in which case it is not used). In the case of mapped
177 + * reductions, this also enables transformations to serve as
178 + * filters, returning null (or, in the case of primitive
179 + * specializations, the identity basis) if the element should not
180 + * be combined. You can create compound transformations and
181 + * filterings by composing them yourself under this "null means
182 + * there is nothing there now" rule before using them in search or
183 + * reduce operations.
184 + *
185 + * <p>Methods accepting and/or returning Entry arguments maintain
186 + * key-value associations. They may be useful for example when
187 + * finding the key for the greatest value. Note that "plain" Entry
188 + * arguments can be supplied using {@code new
189 + * AbstractMap.SimpleEntry(k,v)}.
190 + *
191 + * <p>Bulk operations may complete abruptly, throwing an
192 + * exception encountered in the application of a supplied
193 + * function. Bear in mind when handling such exceptions that other
194 + * concurrently executing functions could also have thrown
195 + * exceptions, or would have done so if the first exception had
196 + * not occurred.
197 + *
198 + * <p>Speedups for parallel compared to sequential forms are common
199 + * but not guaranteed.  Parallel operations involving brief functions
200 + * on small maps may execute more slowly than sequential forms if the
201 + * underlying work to parallelize the computation is more expensive
202 + * than the computation itself.  Similarly, parallelization may not
203 + * lead to much actual parallelism if all processors are busy
204 + * performing unrelated tasks.
205 + *
206 + * <p>All arguments to all task methods must be non-null.
207 + *
208 + * <p><em>jsr166e note: During transition, this class
209 + * uses nested functional interfaces with different names but the
210 + * same forms as those expected for JDK8.</em>
211 + *
212   * <p>This class is a member of the
213   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
214   * Java Collections Framework</a>.
215   *
96 * <p><em>jsr166e note: This class is a candidate replacement for
97 * java.util.concurrent.ConcurrentHashMap.  During transition, this
98 * class declares and uses nested functional interfaces with different
99 * names but the same forms as those expected for JDK8.<em>
100 *
216   * @since 1.5
217   * @author Doug Lea
218   * @param <K> the type of keys maintained by this map
219   * @param <V> the type of mapped values
220   */
221 < public class ConcurrentHashMapV8<K, V>
222 <    implements ConcurrentMap<K, V>, Serializable {
221 > public class ConcurrentHashMapV8<K,V>
222 >    implements ConcurrentMap<K,V>, Serializable {
223      private static final long serialVersionUID = 7249069246763182397L;
224  
225      /**
226 <     * A partitionable iterator. A Spliterator can be traversed
227 <     * directly, but can also be partitioned (before traversal) by
228 <     * creating another Spliterator that covers a non-overlapping
114 <     * portion of the elements, and so may be amenable to parallel
115 <     * execution.
116 <     *
117 <     * <p> This interface exports a subset of expected JDK8
118 <     * functionality.
119 <     *
120 <     * <p>Sample usage: Here is one (of the several) ways to compute
121 <     * the sum of the values held in a map using the ForkJoin
122 <     * framework. As illustrated here, Spliterators are well suited to
123 <     * designs in which a task repeatedly splits off half its work
124 <     * into forked subtasks until small enough to process directly,
125 <     * and then joins these subtasks. Variants of this style can also
126 <     * be used in completion-based designs.
127 <     *
128 <     * <pre>
129 <     * {@code ConcurrentHashMapV8<String, Long> m = ...
130 <     * // split as if have 8 * parallelism, for load balance
131 <     * int n = m.size();
132 <     * int p = aForkJoinPool.getParallelism() * 8;
133 <     * int split = (n < p)? n : p;
134 <     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
135 <     * // ...
136 <     * static class SumValues extends RecursiveTask<Long> {
137 <     *   final Spliterator<Long> s;
138 <     *   final int split;             // split while > 1
139 <     *   final SumValues nextJoin;    // records forked subtasks to join
140 <     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
141 <     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
142 <     *   }
143 <     *   public Long compute() {
144 <     *     long sum = 0;
145 <     *     SumValues subtasks = null; // fork subtasks
146 <     *     for (int s = split >>> 1; s > 0; s >>>= 1)
147 <     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
148 <     *     while (s.hasNext())        // directly process remaining elements
149 <     *       sum += s.next();
150 <     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
151 <     *       sum += t.join();         // collect subtask results
152 <     *     return sum;
153 <     *   }
154 <     * }
155 <     * }</pre>
226 >     * An object for traversing and partitioning elements of a source.
227 >     * This interface provides a subset of the functionality of JDK8
228 >     * java.util.Spliterator.
229       */
230 <    public static interface Spliterator<T> extends Iterator<T> {
230 >    public static interface ConcurrentHashMapSpliterator<T> {
231          /**
232 <         * Returns a Spliterator covering approximately half of the
233 <         * elements, guaranteed not to overlap with those subsequently
234 <         * returned by this Spliterator.  After invoking this method,
235 <         * the current Spliterator will <em>not</em> produce any of
236 <         * the elements of the returned Spliterator, but the two
237 <         * Spliterators together will produce all of the elements that
238 <         * would have been produced by this Spliterator had this
239 <         * method not been called. The exact number of elements
240 <         * produced by the returned Spliterator is not guaranteed, and
168 <         * may be zero (i.e., with {@code hasNext()} reporting {@code
169 <         * false}) if this Spliterator cannot be further split.
170 <         *
171 <         * @return a Spliterator covering approximately half of the
172 <         * elements
173 <         * @throws IllegalStateException if this Spliterator has
174 <         * already commenced traversing elements
232 >         * If possible, returns a new spliterator covering
233 >         * approximately one half of the elements, which will not be
234 >         * covered by this spliterator. Returns null if cannot be
235 >         * split.
236 >         */
237 >        ConcurrentHashMapSpliterator<T> trySplit();
238 >        /**
239 >         * Returns an estimate of the number of elements covered by
240 >         * this Spliterator.
241           */
242 <        Spliterator<T> split();
242 >        long estimateSize();
243 >
244 >        /** Applies the action to each untraversed element */
245 >        void forEachRemaining(Action<? super T> action);
246 >        /** If an element remains, applies the action and returns true. */
247 >        boolean tryAdvance(Action<? super T> action);
248      }
249  
250 +    // Sams
251 +    /** Interface describing a void action of one argument */
252 +    public interface Action<A> { void apply(A a); }
253 +    /** Interface describing a void action of two arguments */
254 +    public interface BiAction<A,B> { void apply(A a, B b); }
255 +    /** Interface describing a function of one argument */
256 +    public interface Fun<A,T> { T apply(A a); }
257 +    /** Interface describing a function of two arguments */
258 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
259 +    /** Interface describing a function mapping its argument to a double */
260 +    public interface ObjectToDouble<A> { double apply(A a); }
261 +    /** Interface describing a function mapping its argument to a long */
262 +    public interface ObjectToLong<A> { long apply(A a); }
263 +    /** Interface describing a function mapping its argument to an int */
264 +    public interface ObjectToInt<A> {int apply(A a); }
265 +    /** Interface describing a function mapping two arguments to a double */
266 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
267 +    /** Interface describing a function mapping two arguments to a long */
268 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
269 +    /** Interface describing a function mapping two arguments to an int */
270 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
271 +    /** Interface describing a function mapping two doubles to a double */
272 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
273 +    /** Interface describing a function mapping two longs to a long */
274 +    public interface LongByLongToLong { long apply(long a, long b); }
275 +    /** Interface describing a function mapping two ints to an int */
276 +    public interface IntByIntToInt { int apply(int a, int b); }
277 +
278      /*
279       * Overview:
280       *
# Line 186 | Line 285 | public class ConcurrentHashMapV8<K, V>
285       * the same or better than java.util.HashMap, and to support high
286       * initial insertion rates on an empty table by many threads.
287       *
288 <     * Each key-value mapping is held in a Node.  Because Node fields
289 <     * can contain special values, they are defined using plain Object
290 <     * types. Similarly in turn, all internal methods that use them
291 <     * work off Object types. And similarly, so do the internal
292 <     * methods of auxiliary iterator and view classes.  All public
293 <     * generic typed methods relay in/out of these internal methods,
294 <     * supplying null-checks and casts as needed. This also allows
295 <     * many of the public methods to be factored into a smaller number
296 <     * of internal methods (although sadly not so for the five
297 <     * variants of put-related operations). The validation-based
298 <     * approach explained below leads to a lot of code sprawl because
299 <     * retry-control precludes factoring into smaller methods.
288 >     * This map usually acts as a binned (bucketed) hash table.  Each
289 >     * key-value mapping is held in a Node.  Most nodes are instances
290 >     * of the basic Node class with hash, key, value, and next
291 >     * fields. However, various subclasses exist: TreeNodes are
292 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
293 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
294 >     * of bins during resizing. ReservationNodes are used as
295 >     * placeholders while establishing values in computeIfAbsent and
296 >     * related methods.  The types TreeBin, ForwardingNode, and
297 >     * ReservationNode do not hold normal user keys, values, or
298 >     * hashes, and are readily distinguishable during search etc
299 >     * because they have negative hash fields and null key and value
300 >     * fields. (These special nodes are either uncommon or transient,
301 >     * so the impact of carrying around some unused fields is
302 >     * insignficant.)
303       *
304       * The table is lazily initialized to a power-of-two size upon the
305       * first insertion.  Each bin in the table normally contains a
# Line 205 | Line 307 | public class ConcurrentHashMapV8<K, V>
307       * Table accesses require volatile/atomic reads, writes, and
308       * CASes.  Because there is no other way to arrange this without
309       * adding further indirections, we use intrinsics
310 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
311 <     * are always accurately traversable under volatile reads, so long
312 <     * as lookups check hash code and non-nullness of value before
313 <     * checking key equality.
314 <     *
315 <     * We use the top two bits of Node hash fields for control
214 <     * purposes -- they are available anyway because of addressing
215 <     * constraints.  As explained further below, these top bits are
216 <     * used as follows:
217 <     *  00 - Normal
218 <     *  01 - Locked
219 <     *  11 - Locked and may have a thread waiting for lock
220 <     *  10 - Node is a forwarding node
221 <     *
222 <     * The lower 30 bits of each Node's hash field contain a
223 <     * transformation of the key's hash code, except for forwarding
224 <     * nodes, for which the lower bits are zero (and so always have
225 <     * hash field == MOVED).
310 >     * (sun.misc.Unsafe) operations.
311 >     *
312 >     * We use the top (sign) bit of Node hash fields for control
313 >     * purposes -- it is available anyway because of addressing
314 >     * constraints.  Nodes with negative hash fields are specially
315 >     * handled or ignored in map methods.
316       *
317       * Insertion (via put or its variants) of the first node in an
318       * empty bin is performed by just CASing it to the bin.  This is
# Line 231 | Line 321 | public class ConcurrentHashMapV8<K, V>
321       * delete, and replace) require locks.  We do not want to waste
322       * the space required to associate a distinct lock object with
323       * each bin, so instead use the first node of a bin list itself as
324 <     * a lock. Blocking support for these locks relies on the builtin
325 <     * "synchronized" monitors.  However, we also need a tryLock
236 <     * construction, so we overlay these by using bits of the Node
237 <     * hash field for lock control (see above), and so normally use
238 <     * builtin monitors only for blocking and signalling using
239 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
324 >     * a lock. Locking support for these locks relies on builtin
325 >     * "synchronized" monitors.
326       *
327       * Using the first node of a list as a lock does not by itself
328       * suffice though: When a node is locked, any update must first
329       * validate that it is still the first node after locking it, and
330       * retry if not. Because new nodes are always appended to lists,
331       * once a node is first in a bin, it remains first until deleted
332 <     * or the bin becomes invalidated (upon resizing).  However,
247 <     * operations that only conditionally update may inspect nodes
248 <     * until the point of update. This is a converse of sorts to the
249 <     * lazy locking technique described by Herlihy & Shavit.
332 >     * or the bin becomes invalidated (upon resizing).
333       *
334       * The main disadvantage of per-bin locks is that other update
335       * operations on other nodes in a bin list protected by the same
# Line 279 | Line 362 | public class ConcurrentHashMapV8<K, V>
362       * sometimes deviate significantly from uniform randomness.  This
363       * includes the case when N > (1<<30), so some keys MUST collide.
364       * Similarly for dumb or hostile usages in which multiple keys are
365 <     * designed to have identical hash codes. Also, although we guard
366 <     * against the worst effects of this (see method spread), sets of
367 <     * hashes may differ only in bits that do not impact their bin
368 <     * index for a given power-of-two mask.  So we use a secondary
369 <     * strategy that applies when the number of nodes in a bin exceeds
370 <     * a threshold, and at least one of the keys implements
288 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
289 <     * (a specialized form of red-black trees), bounding search time
290 <     * to O(log N).  Each search step in a TreeBin is around twice as
365 >     * designed to have identical hash codes or ones that differs only
366 >     * in masked-out high bits. So we use a secondary strategy that
367 >     * applies when the number of nodes in a bin exceeds a
368 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
369 >     * specialized form of red-black trees), bounding search time to
370 >     * O(log N).  Each search step in a TreeBin is at least twice as
371       * slow as in a regular list, but given that N cannot exceed
372       * (1<<64) (before running out of addresses) this bounds search
373       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 298 | Line 378 | public class ConcurrentHashMapV8<K, V>
378       * iterators in the same way.
379       *
380       * The table is resized when occupancy exceeds a percentage
381 <     * threshold (nominally, 0.75, but see below).  Only a single
382 <     * thread performs the resize (using field "sizeCtl", to arrange
383 <     * exclusion), but the table otherwise remains usable for reads
384 <     * and updates. Resizing proceeds by transferring bins, one by
385 <     * one, from the table to the next table.  Because we are using
386 <     * power-of-two expansion, the elements from each bin must either
387 <     * stay at same index, or move with a power of two offset. We
388 <     * eliminate unnecessary node creation by catching cases where old
389 <     * nodes can be reused because their next fields won't change.  On
390 <     * average, only about one-sixth of them need cloning when a table
391 <     * doubles. The nodes they replace will be garbage collectable as
392 <     * soon as they are no longer referenced by any reader thread that
393 <     * may be in the midst of concurrently traversing table.  Upon
394 <     * transfer, the old table bin contains only a special forwarding
395 <     * node (with hash field "MOVED") that contains the next table as
396 <     * its key. On encountering a forwarding node, access and update
397 <     * operations restart, using the new table.
398 <     *
399 <     * Each bin transfer requires its bin lock. However, unlike other
400 <     * cases, a transfer can skip a bin if it fails to acquire its
401 <     * lock, and revisit it later (unless it is a TreeBin). Method
402 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
403 <     * have been skipped because of failure to acquire a lock, and
404 <     * blocks only if none are available (i.e., only very rarely).
405 <     * The transfer operation must also ensure that all accessible
406 <     * bins in both the old and new table are usable by any traversal.
407 <     * When there are no lock acquisition failures, this is arranged
408 <     * simply by proceeding from the last bin (table.length - 1) up
409 <     * towards the first.  Upon seeing a forwarding node, traversals
410 <     * (see class Iter) arrange to move to the new table
411 <     * without revisiting nodes.  However, when any node is skipped
412 <     * during a transfer, all earlier table bins may have become
413 <     * visible, so are initialized with a reverse-forwarding node back
414 <     * to the old table until the new ones are established. (This
415 <     * sometimes requires transiently locking a forwarding node, which
416 <     * is possible under the above encoding.) These more expensive
417 <     * mechanics trigger only when necessary.
381 >     * threshold (nominally, 0.75, but see below).  Any thread
382 >     * noticing an overfull bin may assist in resizing after the
383 >     * initiating thread allocates and sets up the replacement
384 >     * array. However, rather than stalling, these other threads may
385 >     * proceed with insertions etc.  The use of TreeBins shields us
386 >     * from the worst case effects of overfilling while resizes are in
387 >     * progress.  Resizing proceeds by transferring bins, one by one,
388 >     * from the table to the next table. To enable concurrency, the
389 >     * next table must be (incrementally) prefilled with place-holders
390 >     * serving as reverse forwarders to the old table.  Because we are
391 >     * using power-of-two expansion, the elements from each bin must
392 >     * either stay at same index, or move with a power of two
393 >     * offset. We eliminate unnecessary node creation by catching
394 >     * cases where old nodes can be reused because their next fields
395 >     * won't change.  On average, only about one-sixth of them need
396 >     * cloning when a table doubles. The nodes they replace will be
397 >     * garbage collectable as soon as they are no longer referenced by
398 >     * any reader thread that may be in the midst of concurrently
399 >     * traversing table.  Upon transfer, the old table bin contains
400 >     * only a special forwarding node (with hash field "MOVED") that
401 >     * contains the next table as its key. On encountering a
402 >     * forwarding node, access and update operations restart, using
403 >     * the new table.
404 >     *
405 >     * Each bin transfer requires its bin lock, which can stall
406 >     * waiting for locks while resizing. However, because other
407 >     * threads can join in and help resize rather than contend for
408 >     * locks, average aggregate waits become shorter as resizing
409 >     * progresses.  The transfer operation must also ensure that all
410 >     * accessible bins in both the old and new table are usable by any
411 >     * traversal.  This is arranged by proceeding from the last bin
412 >     * (table.length - 1) up towards the first.  Upon seeing a
413 >     * forwarding node, traversals (see class Traverser) arrange to
414 >     * move to the new table without revisiting nodes.  However, to
415 >     * ensure that no intervening nodes are skipped, bin splitting can
416 >     * only begin after the associated reverse-forwarders are in
417 >     * place.
418       *
419       * The traversal scheme also applies to partial traversals of
420       * ranges of bins (via an alternate Traverser constructor)
# Line 349 | Line 429 | public class ConcurrentHashMapV8<K, V>
429       * These cases attempt to override the initial capacity settings,
430       * but harmlessly fail to take effect in cases of races.
431       *
432 <     * The element count is maintained using a LongAdder, which avoids
433 <     * contention on updates but can encounter cache thrashing if read
434 <     * too frequently during concurrent access. To avoid reading so
435 <     * often, resizing is attempted either when a bin lock is
436 <     * contended, or upon adding to a bin already holding two or more
437 <     * nodes (checked before adding in the xIfAbsent methods, after
438 <     * adding in others). Under uniform hash distributions, the
439 <     * probability of this occurring at threshold is around 13%,
440 <     * meaning that only about 1 in 8 puts check threshold (and after
441 <     * resizing, many fewer do so). But this approximation has high
442 <     * variance for small table sizes, so we check on any collision
443 <     * for sizes <= 64. The bulk putAll operation further reduces
444 <     * contention by only committing count updates upon these size
445 <     * checks.
432 >     * The element count is maintained using a specialization of
433 >     * LongAdder. We need to incorporate a specialization rather than
434 >     * just use a LongAdder in order to access implicit
435 >     * contention-sensing that leads to creation of multiple
436 >     * CounterCells.  The counter mechanics avoid contention on
437 >     * updates but can encounter cache thrashing if read too
438 >     * frequently during concurrent access. To avoid reading so often,
439 >     * resizing under contention is attempted only upon adding to a
440 >     * bin already holding two or more nodes. Under uniform hash
441 >     * distributions, the probability of this occurring at threshold
442 >     * is around 13%, meaning that only about 1 in 8 puts check
443 >     * threshold (and after resizing, many fewer do so).
444 >     *
445 >     * TreeBins use a special form of comparison for search and
446 >     * related operations (which is the main reason we cannot use
447 >     * existing collections such as TreeMaps). TreeBins contain
448 >     * Comparable elements, but may contain others, as well as
449 >     * elements that are Comparable but not necessarily Comparable
450 >     * for the same T, so we cannot invoke compareTo among them. To
451 >     * handle this, the tree is ordered primarily by hash value, then
452 >     * by Comparable.compareTo order if applicable.  On lookup at a
453 >     * node, if elements are not comparable or compare as 0 then both
454 >     * left and right children may need to be searched in the case of
455 >     * tied hash values. (This corresponds to the full list search
456 >     * that would be necessary if all elements were non-Comparable and
457 >     * had tied hashes.)  The red-black balancing code is updated from
458 >     * pre-jdk-collections
459 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
460 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
461 >     * Algorithms" (CLR).
462 >     *
463 >     * TreeBins also require an additional locking mechanism.  While
464 >     * list traversal is always possible by readers even during
465 >     * updates, tree traversal is not, mainly beause of tree-rotations
466 >     * that may change the root node and/or its linkages.  TreeBins
467 >     * include a simple read-write lock mechanism parasitic on the
468 >     * main bin-synchronization strategy: Structural adjustments
469 >     * associated with an insertion or removal are already bin-locked
470 >     * (and so cannot conflict with other writers) but must wait for
471 >     * ongoing readers to finish. Since there can be only one such
472 >     * waiter, we use a simple scheme using a single "waiter" field to
473 >     * block writers.  However, readers need never block.  If the root
474 >     * lock is held, they proceed along the slow traversal path (via
475 >     * next-pointers) until the lock becomes available or the list is
476 >     * exhausted, whichever comes first. These cases are not fast, but
477 >     * maximize aggregate expected throughput.
478       *
479       * Maintaining API and serialization compatibility with previous
480       * versions of this class introduces several oddities. Mainly: We
# Line 372 | Line 484 | public class ConcurrentHashMapV8<K, V>
484       * time that we can guarantee to honor it.) We also declare an
485       * unused "Segment" class that is instantiated in minimal form
486       * only when serializing.
487 +     *
488 +     * This file is organized to make things a little easier to follow
489 +     * while reading than they might otherwise: First the main static
490 +     * declarations and utilities, then fields, then main public
491 +     * methods (with a few factorings of multiple public methods into
492 +     * internal ones), then sizing methods, trees, traversers, and
493 +     * bulk operations.
494       */
495  
496      /* ---------------- Constants -------------- */
# Line 413 | Line 532 | public class ConcurrentHashMapV8<K, V>
532      private static final float LOAD_FACTOR = 0.75f;
533  
534      /**
416     * The buffer size for skipped bins during transfers. The
417     * value is arbitrary but should be large enough to avoid
418     * most locking stalls during resizes.
419     */
420    private static final int TRANSFER_BUFFER_SIZE = 32;
421
422    /**
535       * The bin count threshold for using a tree rather than list for a
536 <     * bin.  The value reflects the approximate break-even point for
537 <     * using tree-based operations.
536 >     * bin.  Bins are converted to trees when adding an element to a
537 >     * bin with at least this many nodes. The value must be greater
538 >     * than 2, and should be at least 8 to mesh with assumptions in
539 >     * tree removal about conversion back to plain bins upon
540 >     * shrinkage.
541       */
542 <    private static final int TREE_THRESHOLD = 8;
428 <
429 <    /*
430 <     * Encodings for special uses of Node hash fields. See above for
431 <     * explanation.
432 <     */
433 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
434 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
435 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
436 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
437 <
438 <    /* ---------------- Fields -------------- */
542 >    static final int TREEIFY_THRESHOLD = 8;
543  
544      /**
545 <     * The array of bins. Lazily initialized upon first insertion.
546 <     * Size is always a power of two. Accessed directly by iterators.
545 >     * The bin count threshold for untreeifying a (split) bin during a
546 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
547 >     * most 6 to mesh with shrinkage detection under removal.
548       */
549 <    transient volatile Node[] table;
549 >    static final int UNTREEIFY_THRESHOLD = 6;
550  
551      /**
552 <     * The counter maintaining number of elements.
552 >     * The smallest table capacity for which bins may be treeified.
553 >     * (Otherwise the table is resized if too many nodes in a bin.)
554 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
555 >     * conflicts between resizing and treeification thresholds.
556       */
557 <    private transient final LongAdder counter;
557 >    static final int MIN_TREEIFY_CAPACITY = 64;
558  
559      /**
560 <     * Table initialization and resizing control.  When negative, the
561 <     * table is being initialized or resized. Otherwise, when table is
562 <     * null, holds the initial table size to use upon creation, or 0
563 <     * for default. After initialization, holds the next element count
564 <     * value upon which to resize the table.
560 >     * Minimum number of rebinnings per transfer step. Ranges are
561 >     * subdivided to allow multiple resizer threads.  This value
562 >     * serves as a lower bound to avoid resizers encountering
563 >     * excessive memory contention.  The value should be at least
564 >     * DEFAULT_CAPACITY.
565       */
566 <    private transient volatile int sizeCtl;
459 <
460 <    // views
461 <    private transient KeySet<K,V> keySet;
462 <    private transient Values<K,V> values;
463 <    private transient EntrySet<K,V> entrySet;
464 <
465 <    /** For serialization compatibility. Null unless serialized; see below */
466 <    private Segment<K,V>[] segments;
467 <
468 <    /* ---------------- Table element access -------------- */
566 >    private static final int MIN_TRANSFER_STRIDE = 16;
567  
568      /*
569 <     * Volatile access methods are used for table elements as well as
472 <     * elements of in-progress next table while resizing.  Uses are
473 <     * null checked by callers, and implicitly bounds-checked, relying
474 <     * on the invariants that tab arrays have non-zero size, and all
475 <     * indices are masked with (tab.length - 1) which is never
476 <     * negative and always less than length. Note that, to be correct
477 <     * wrt arbitrary concurrency errors by users, bounds checks must
478 <     * operate on local variables, which accounts for some odd-looking
479 <     * inline assignments below.
569 >     * Encodings for Node hash fields. See above for explanation.
570       */
571 <
572 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
573 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
574 <    }
575 <
576 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
577 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
578 <    }
579 <
580 <    private static final void setTabAt(Node[] tab, int i, Node v) {
581 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
582 <    }
571 >    static final int MOVED     = 0x8fffffff; // (-1) hash for forwarding nodes
572 >    static final int TREEBIN   = 0x80000000; // hash for heads of treea
573 >    static final int RESERVED  = 0x80000001; // hash for transient reservations
574 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
575 >
576 >    /** Number of CPUS, to place bounds on some sizings */
577 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
578 >
579 >    /** For serialization compatibility. */
580 >    private static final ObjectStreamField[] serialPersistentFields = {
581 >        new ObjectStreamField("segments", Segment[].class),
582 >        new ObjectStreamField("segmentMask", Integer.TYPE),
583 >        new ObjectStreamField("segmentShift", Integer.TYPE)
584 >    };
585  
586      /* ---------------- Nodes -------------- */
587  
588      /**
589 <     * Key-value entry. Note that this is never exported out as a
590 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
591 <     * field of MOVED are special, and do not contain user keys or
592 <     * values.  Otherwise, keys are never null, and null val fields
593 <     * indicate that a node is in the process of being deleted or
594 <     * created. For purposes of read-only access, a key may be read
595 <     * before a val, but can only be used after checking val to be
596 <     * non-null.
597 <     */
598 <    static class Node {
599 <        volatile int hash;
600 <        final Object key;
509 <        volatile Object val;
510 <        volatile Node next;
589 >     * Key-value entry.  This class is never exported out as a
590 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
591 >     * MapEntry below), but can be used for read-only traversals used
592 >     * in bulk tasks.  Subclasses of Node with a negativehash field
593 >     * are special, and contain null keys and values (but are never
594 >     * exported).  Otherwise, keys and vals are never null.
595 >     */
596 >    static class Node<K,V> implements Map.Entry<K,V> {
597 >        final int hash;
598 >        final K key;
599 >        volatile V val;
600 >        Node<K,V> next;
601  
602 <        Node(int hash, Object key, Object val, Node next) {
602 >        Node(int hash, K key, V val, Node<K,V> next) {
603              this.hash = hash;
604              this.key = key;
605              this.val = val;
606              this.next = next;
607          }
608  
609 <        /** CompareAndSet the hash field */
610 <        final boolean casHash(int cmp, int val) {
611 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
612 <        }
613 <
614 <        /** The number of spins before blocking for a lock */
525 <        static final int MAX_SPINS =
526 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
527 <
528 <        /**
529 <         * Spins a while if LOCKED bit set and this node is the first
530 <         * of its bin, and then sets WAITING bits on hash field and
531 <         * blocks (once) if they are still set.  It is OK for this
532 <         * method to return even if lock is not available upon exit,
533 <         * which enables these simple single-wait mechanics.
534 <         *
535 <         * The corresponding signalling operation is performed within
536 <         * callers: Upon detecting that WAITING has been set when
537 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
538 <         * state), unlockers acquire the sync lock and perform a
539 <         * notifyAll.
540 <         */
541 <        final void tryAwaitLock(Node[] tab, int i) {
542 <            if (tab != null && i >= 0 && i < tab.length) { // bounds check
543 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
544 <                int spins = MAX_SPINS, h;
545 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
546 <                    if (spins >= 0) {
547 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
548 <                        if (r >= 0 && --spins == 0)
549 <                            Thread.yield();  // yield before block
550 <                    }
551 <                    else if (casHash(h, h | WAITING)) {
552 <                        synchronized (this) {
553 <                            if (tabAt(tab, i) == this &&
554 <                                (hash & WAITING) == WAITING) {
555 <                                try {
556 <                                    wait();
557 <                                } catch (InterruptedException ie) {
558 <                                    Thread.currentThread().interrupt();
559 <                                }
560 <                            }
561 <                            else
562 <                                notifyAll(); // possibly won race vs signaller
563 <                        }
564 <                        break;
565 <                    }
566 <                }
567 <            }
568 <        }
569 <
570 <        // Unsafe mechanics for casHash
571 <        private static final sun.misc.Unsafe UNSAFE;
572 <        private static final long hashOffset;
573 <
574 <        static {
575 <            try {
576 <                UNSAFE = getUnsafe();
577 <                Class<?> k = Node.class;
578 <                hashOffset = UNSAFE.objectFieldOffset
579 <                    (k.getDeclaredField("hash"));
580 <            } catch (Exception e) {
581 <                throw new Error(e);
582 <            }
583 <        }
584 <    }
585 <
586 <    /* ---------------- TreeBins -------------- */
587 <
588 <    /**
589 <     * Nodes for use in TreeBins
590 <     */
591 <    static final class TreeNode extends Node {
592 <        TreeNode parent;  // red-black tree links
593 <        TreeNode left;
594 <        TreeNode right;
595 <        TreeNode prev;    // needed to unlink next upon deletion
596 <        boolean red;
597 <
598 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
599 <            super(hash, key, val, next);
600 <            this.parent = parent;
601 <        }
602 <    }
603 <
604 <    /**
605 <     * A specialized form of red-black tree for use in bins
606 <     * whose size exceeds a threshold.
607 <     *
608 <     * TreeBins use a special form of comparison for search and
609 <     * related operations (which is the main reason we cannot use
610 <     * existing collections such as TreeMaps). TreeBins contain
611 <     * Comparable elements, but may contain others, as well as
612 <     * elements that are Comparable but not necessarily Comparable<T>
613 <     * for the same T, so we cannot invoke compareTo among them. To
614 <     * handle this, the tree is ordered primarily by hash value, then
615 <     * by getClass().getName() order, and then by Comparator order
616 <     * among elements of the same class.  On lookup at a node, if
617 <     * elements are not comparable or compare as 0, both left and
618 <     * right children may need to be searched in the case of tied hash
619 <     * values. (This corresponds to the full list search that would be
620 <     * necessary if all elements were non-Comparable and had tied
621 <     * hashes.)  The red-black balancing code is updated from
622 <     * pre-jdk-collections
623 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
624 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
625 <     * Algorithms" (CLR).
626 <     *
627 <     * TreeBins also maintain a separate locking discipline than
628 <     * regular bins. Because they are forwarded via special MOVED
629 <     * nodes at bin heads (which can never change once established),
630 <     * we cannot use those nodes as locks. Instead, TreeBin
631 <     * extends AbstractQueuedSynchronizer to support a simple form of
632 <     * read-write lock. For update operations and table validation,
633 <     * the exclusive form of lock behaves in the same way as bin-head
634 <     * locks. However, lookups use shared read-lock mechanics to allow
635 <     * multiple readers in the absence of writers.  Additionally,
636 <     * these lookups do not ever block: While the lock is not
637 <     * available, they proceed along the slow traversal path (via
638 <     * next-pointers) until the lock becomes available or the list is
639 <     * exhausted, whichever comes first. (These cases are not fast,
640 <     * but maximize aggregate expected throughput.)  The AQS mechanics
641 <     * for doing this are straightforward.  The lock state is held as
642 <     * AQS getState().  Read counts are negative; the write count (1)
643 <     * is positive.  There are no signalling preferences among readers
644 <     * and writers. Since we don't need to export full Lock API, we
645 <     * just override the minimal AQS methods and use them directly.
646 <     */
647 <    static final class TreeBin extends AbstractQueuedSynchronizer {
648 <        private static final long serialVersionUID = 2249069246763182397L;
649 <        transient TreeNode root;  // root of tree
650 <        transient TreeNode first; // head of next-pointer list
651 <
652 <        /* AQS overrides */
653 <        public final boolean isHeldExclusively() { return getState() > 0; }
654 <        public final boolean tryAcquire(int ignore) {
655 <            if (compareAndSetState(0, 1)) {
656 <                setExclusiveOwnerThread(Thread.currentThread());
657 <                return true;
658 <            }
659 <            return false;
660 <        }
661 <        public final boolean tryRelease(int ignore) {
662 <            setExclusiveOwnerThread(null);
663 <            setState(0);
664 <            return true;
665 <        }
666 <        public final int tryAcquireShared(int ignore) {
667 <            for (int c;;) {
668 <                if ((c = getState()) > 0)
669 <                    return -1;
670 <                if (compareAndSetState(c, c -1))
671 <                    return 1;
672 <            }
673 <        }
674 <        public final boolean tryReleaseShared(int ignore) {
675 <            int c;
676 <            do {} while (!compareAndSetState(c = getState(), c + 1));
677 <            return c == -1;
678 <        }
679 <
680 <        /** From CLR */
681 <        private void rotateLeft(TreeNode p) {
682 <            if (p != null) {
683 <                TreeNode r = p.right, pp, rl;
684 <                if ((rl = p.right = r.left) != null)
685 <                    rl.parent = p;
686 <                if ((pp = r.parent = p.parent) == null)
687 <                    root = r;
688 <                else if (pp.left == p)
689 <                    pp.left = r;
690 <                else
691 <                    pp.right = r;
692 <                r.left = p;
693 <                p.parent = r;
694 <            }
695 <        }
696 <
697 <        /** From CLR */
698 <        private void rotateRight(TreeNode p) {
699 <            if (p != null) {
700 <                TreeNode l = p.left, pp, lr;
701 <                if ((lr = p.left = l.right) != null)
702 <                    lr.parent = p;
703 <                if ((pp = l.parent = p.parent) == null)
704 <                    root = l;
705 <                else if (pp.right == p)
706 <                    pp.right = l;
707 <                else
708 <                    pp.left = l;
709 <                l.right = p;
710 <                p.parent = l;
711 <            }
712 <        }
713 <
714 <        /**
715 <         * Return the TreeNode (or null if not found) for the given key
716 <         * starting at given root.
717 <         */
718 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
719 <            final TreeNode getTreeNode(int h, Object k, TreeNode p) {
720 <            Class<?> c = k.getClass();
721 <            while (p != null) {
722 <                int dir, ph;  Object pk; Class<?> pc;
723 <                if ((ph = p.hash) == h) {
724 <                    if ((pk = p.key) == k || k.equals(pk))
725 <                        return p;
726 <                    if (c != (pc = pk.getClass()) ||
727 <                        !(k instanceof Comparable) ||
728 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
729 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
730 <                        TreeNode r = null, s = null, pl, pr;
731 <                        if (dir >= 0) {
732 <                            if ((pl = p.left) != null && h <= pl.hash)
733 <                                s = pl;
734 <                        }
735 <                        else if ((pr = p.right) != null && h >= pr.hash)
736 <                            s = pr;
737 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
738 <                            return r;
739 <                    }
740 <                }
741 <                else
742 <                    dir = (h < ph) ? -1 : 1;
743 <                p = (dir > 0) ? p.right : p.left;
744 <            }
745 <            return null;
609 >        public final K getKey()       { return key; }
610 >        public final V getValue()     { return val; }
611 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
612 >        public final String toString(){ return key + "=" + val; }
613 >        public final V setValue(V value) {
614 >            throw new UnsupportedOperationException();
615          }
616  
617 <        /**
618 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
619 <         * read-lock to call getTreeNode, but during failure to get
620 <         * lock, searches along next links.
621 <         */
622 <        final Object getValue(int h, Object k) {
623 <            Node r = null;
755 <            int c = getState(); // Must read lock state first
756 <            for (Node e = first; e != null; e = e.next) {
757 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
758 <                    try {
759 <                        r = getTreeNode(h, k, root);
760 <                    } finally {
761 <                        releaseShared(0);
762 <                    }
763 <                    break;
764 <                }
765 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
766 <                    r = e;
767 <                    break;
768 <                }
769 <                else
770 <                    c = getState();
771 <            }
772 <            return r == null ? null : r.val;
617 >        public final boolean equals(Object o) {
618 >            Object k, v, u; Map.Entry<?,?> e;
619 >            return ((o instanceof Map.Entry) &&
620 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
621 >                    (v = e.getValue()) != null &&
622 >                    (k == key || k.equals(key)) &&
623 >                    (v == (u = val) || v.equals(u)));
624          }
625  
626          /**
627 <         * Finds or adds a node.
777 <         * @return null if added
627 >         * Virtualized support for map.get(); overridden in subclasses.
628           */
629 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
630 <            final TreeNode putTreeNode(int h, Object k, Object v) {
631 <            Class<?> c = k.getClass();
632 <            TreeNode pp = root, p = null;
633 <            int dir = 0;
634 <            while (pp != null) { // find existing node or leaf to insert at
635 <                int ph;  Object pk; Class<?> pc;
636 <                p = pp;
637 <                if ((ph = p.hash) == h) {
788 <                    if ((pk = p.key) == k || k.equals(pk))
789 <                        return p;
790 <                    if (c != (pc = pk.getClass()) ||
791 <                        !(k instanceof Comparable) ||
792 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
793 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
794 <                        TreeNode r = null, s = null, pl, pr;
795 <                        if (dir >= 0) {
796 <                            if ((pl = p.left) != null && h <= pl.hash)
797 <                                s = pl;
798 <                        }
799 <                        else if ((pr = p.right) != null && h >= pr.hash)
800 <                            s = pr;
801 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
802 <                            return r;
803 <                    }
804 <                }
805 <                else
806 <                    dir = (h < ph) ? -1 : 1;
807 <                pp = (dir > 0) ? p.right : p.left;
808 <            }
809 <
810 <            TreeNode f = first;
811 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
812 <            if (p == null)
813 <                root = x;
814 <            else { // attach and rebalance; adapted from CLR
815 <                TreeNode xp, xpp;
816 <                if (f != null)
817 <                    f.prev = x;
818 <                if (dir <= 0)
819 <                    p.left = x;
820 <                else
821 <                    p.right = x;
822 <                x.red = true;
823 <                while (x != null && (xp = x.parent) != null && xp.red &&
824 <                       (xpp = xp.parent) != null) {
825 <                    TreeNode xppl = xpp.left;
826 <                    if (xp == xppl) {
827 <                        TreeNode y = xpp.right;
828 <                        if (y != null && y.red) {
829 <                            y.red = false;
830 <                            xp.red = false;
831 <                            xpp.red = true;
832 <                            x = xpp;
833 <                        }
834 <                        else {
835 <                            if (x == xp.right) {
836 <                                rotateLeft(x = xp);
837 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
838 <                            }
839 <                            if (xp != null) {
840 <                                xp.red = false;
841 <                                if (xpp != null) {
842 <                                    xpp.red = true;
843 <                                    rotateRight(xpp);
844 <                                }
845 <                            }
846 <                        }
847 <                    }
848 <                    else {
849 <                        TreeNode y = xppl;
850 <                        if (y != null && y.red) {
851 <                            y.red = false;
852 <                            xp.red = false;
853 <                            xpp.red = true;
854 <                            x = xpp;
855 <                        }
856 <                        else {
857 <                            if (x == xp.left) {
858 <                                rotateRight(x = xp);
859 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
860 <                            }
861 <                            if (xp != null) {
862 <                                xp.red = false;
863 <                                if (xpp != null) {
864 <                                    xpp.red = true;
865 <                                    rotateLeft(xpp);
866 <                                }
867 <                            }
868 <                        }
869 <                    }
870 <                }
871 <                TreeNode r = root;
872 <                if (r != null && r.red)
873 <                    r.red = false;
629 >        Node<K,V> find(int h, Object k) {
630 >            Node<K,V> e = this;
631 >            if (k != null) {
632 >                do {
633 >                    K ek;
634 >                    if (e.hash == h &&
635 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
636 >                        return e;
637 >                } while ((e = e.next) != null);
638              }
639              return null;
640          }
877
878        /**
879         * Removes the given node, that must be present before this
880         * call.  This is messier than typical red-black deletion code
881         * because we cannot swap the contents of an interior node
882         * with a leaf successor that is pinned by "next" pointers
883         * that are accessible independently of lock. So instead we
884         * swap the tree linkages.
885         */
886        final void deleteTreeNode(TreeNode p) {
887            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
888            TreeNode pred = p.prev;
889            if (pred == null)
890                first = next;
891            else
892                pred.next = next;
893            if (next != null)
894                next.prev = pred;
895            TreeNode replacement;
896            TreeNode pl = p.left;
897            TreeNode pr = p.right;
898            if (pl != null && pr != null) {
899                TreeNode s = pr, sl;
900                while ((sl = s.left) != null) // find successor
901                    s = sl;
902                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
903                TreeNode sr = s.right;
904                TreeNode pp = p.parent;
905                if (s == pr) { // p was s's direct parent
906                    p.parent = s;
907                    s.right = p;
908                }
909                else {
910                    TreeNode sp = s.parent;
911                    if ((p.parent = sp) != null) {
912                        if (s == sp.left)
913                            sp.left = p;
914                        else
915                            sp.right = p;
916                    }
917                    if ((s.right = pr) != null)
918                        pr.parent = s;
919                }
920                p.left = null;
921                if ((p.right = sr) != null)
922                    sr.parent = p;
923                if ((s.left = pl) != null)
924                    pl.parent = s;
925                if ((s.parent = pp) == null)
926                    root = s;
927                else if (p == pp.left)
928                    pp.left = s;
929                else
930                    pp.right = s;
931                replacement = sr;
932            }
933            else
934                replacement = (pl != null) ? pl : pr;
935            TreeNode pp = p.parent;
936            if (replacement == null) {
937                if (pp == null) {
938                    root = null;
939                    return;
940                }
941                replacement = p;
942            }
943            else {
944                replacement.parent = pp;
945                if (pp == null)
946                    root = replacement;
947                else if (p == pp.left)
948                    pp.left = replacement;
949                else
950                    pp.right = replacement;
951                p.left = p.right = p.parent = null;
952            }
953            if (!p.red) { // rebalance, from CLR
954                TreeNode x = replacement;
955                while (x != null) {
956                    TreeNode xp, xpl;
957                    if (x.red || (xp = x.parent) == null) {
958                        x.red = false;
959                        break;
960                    }
961                    if (x == (xpl = xp.left)) {
962                        TreeNode sib = xp.right;
963                        if (sib != null && sib.red) {
964                            sib.red = false;
965                            xp.red = true;
966                            rotateLeft(xp);
967                            sib = (xp = x.parent) == null ? null : xp.right;
968                        }
969                        if (sib == null)
970                            x = xp;
971                        else {
972                            TreeNode sl = sib.left, sr = sib.right;
973                            if ((sr == null || !sr.red) &&
974                                (sl == null || !sl.red)) {
975                                sib.red = true;
976                                x = xp;
977                            }
978                            else {
979                                if (sr == null || !sr.red) {
980                                    if (sl != null)
981                                        sl.red = false;
982                                    sib.red = true;
983                                    rotateRight(sib);
984                                    sib = (xp = x.parent) == null ? null : xp.right;
985                                }
986                                if (sib != null) {
987                                    sib.red = (xp == null) ? false : xp.red;
988                                    if ((sr = sib.right) != null)
989                                        sr.red = false;
990                                }
991                                if (xp != null) {
992                                    xp.red = false;
993                                    rotateLeft(xp);
994                                }
995                                x = root;
996                            }
997                        }
998                    }
999                    else { // symmetric
1000                        TreeNode sib = xpl;
1001                        if (sib != null && sib.red) {
1002                            sib.red = false;
1003                            xp.red = true;
1004                            rotateRight(xp);
1005                            sib = (xp = x.parent) == null ? null : xp.left;
1006                        }
1007                        if (sib == null)
1008                            x = xp;
1009                        else {
1010                            TreeNode sl = sib.left, sr = sib.right;
1011                            if ((sl == null || !sl.red) &&
1012                                (sr == null || !sr.red)) {
1013                                sib.red = true;
1014                                x = xp;
1015                            }
1016                            else {
1017                                if (sl == null || !sl.red) {
1018                                    if (sr != null)
1019                                        sr.red = false;
1020                                    sib.red = true;
1021                                    rotateLeft(sib);
1022                                    sib = (xp = x.parent) == null ? null : xp.left;
1023                                }
1024                                if (sib != null) {
1025                                    sib.red = (xp == null) ? false : xp.red;
1026                                    if ((sl = sib.left) != null)
1027                                        sl.red = false;
1028                                }
1029                                if (xp != null) {
1030                                    xp.red = false;
1031                                    rotateRight(xp);
1032                                }
1033                                x = root;
1034                            }
1035                        }
1036                    }
1037                }
1038            }
1039            if (p == replacement && (pp = p.parent) != null) {
1040                if (p == pp.left) // detach pointers
1041                    pp.left = null;
1042                else if (p == pp.right)
1043                    pp.right = null;
1044                p.parent = null;
1045            }
1046        }
641      }
642  
643 <    /* ---------------- Collision reduction methods -------------- */
643 >    /* ---------------- Static utilities -------------- */
644  
645      /**
646 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
647 <     * Because the table uses power-of-two masking, sets of hashes
648 <     * that vary only in bits above the current mask will always
649 <     * collide. (Among known examples are sets of Float keys holding
650 <     * consecutive whole numbers in small tables.)  To counter this,
651 <     * we apply a transform that spreads the impact of higher bits
646 >     * Spreads (XORs) higher bits of hash to lower and also forces top
647 >     * bit to 0. Because the table uses power-of-two masking, sets of
648 >     * hashes that vary only in bits above the current mask will
649 >     * always collide. (Among known examples are sets of Float keys
650 >     * holding consecutive whole numbers in small tables.)  So we
651 >     * apply a transform that spreads the impact of higher bits
652       * downward. There is a tradeoff between speed, utility, and
653       * quality of bit-spreading. Because many common sets of hashes
654 <     * are already reasonably distributed across bits (so don't benefit
655 <     * from spreading), and because we use trees to handle large sets
656 <     * of collisions in bins, we don't need excessively high quality.
654 >     * are already reasonably distributed (so don't benefit from
655 >     * spreading), and because we use trees to handle large sets of
656 >     * collisions in bins, we just XOR some shifted bits in the
657 >     * cheapest possible way to reduce systematic lossage, as well as
658 >     * to incorporate impact of the highest bits that would otherwise
659 >     * never be used in index calculations because of table bounds.
660       */
661 <    private static final int spread(int h) {
662 <        h ^= (h >>> 18) ^ (h >>> 12);
1066 <        return (h ^ (h >>> 10)) & HASH_BITS;
661 >    static final int spread(int h) {
662 >        return (h ^ (h >>> 16)) & HASH_BITS;
663      }
664  
665      /**
666 <     * Replaces a list bin with a tree bin. Call only when locked.
667 <     * Fails to replace if the given key is non-comparable or table
1072 <     * is, or needs, resizing.
666 >     * Returns a power of two table size for the given desired capacity.
667 >     * See Hackers Delight, sec 3.2
668       */
669 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
670 <        if ((key instanceof Comparable) &&
671 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
672 <            TreeBin t = new TreeBin();
673 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
674 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
675 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
676 <        }
669 >    private static final int tableSizeFor(int c) {
670 >        int n = c - 1;
671 >        n |= n >>> 1;
672 >        n |= n >>> 2;
673 >        n |= n >>> 4;
674 >        n |= n >>> 8;
675 >        n |= n >>> 16;
676 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
677      }
678  
679 <    /* ---------------- Internal access and update methods -------------- */
680 <
681 <    /** Implementation for get and containsKey */
682 <    private final Object internalGet(Object k) {
683 <        int h = spread(k.hashCode());
684 <        retry: for (Node[] tab = table; tab != null;) {
685 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
686 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
687 <                if ((eh = e.hash) == MOVED) {
688 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
689 <                        return ((TreeBin)ek).getValue(h, k);
690 <                    else {                        // restart with new table
691 <                        tab = (Node[])ek;
692 <                        continue retry;
693 <                    }
679 >    /**
680 >     * Returns x's Class if it is of the form "class C implements
681 >     * Comparable<C>", else null.
682 >     */
683 >    static Class<?> comparableClassFor(Object x) {
684 >        if (x instanceof Comparable) {
685 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
686 >            if ((c = x.getClass()) == String.class) // bypass checks
687 >                return c;
688 >            if ((ts = c.getGenericInterfaces()) != null) {
689 >                for (int i = 0; i < ts.length; ++i) {
690 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
691 >                        ((p = (ParameterizedType)t).getRawType() ==
692 >                         Comparable.class) &&
693 >                        (as = p.getActualTypeArguments()) != null &&
694 >                        as.length == 1 && as[0] == c) // type arg is c
695 >                        return c;
696                  }
1100                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1101                         ((ek = e.key) == k || k.equals(ek)))
1102                    return ev;
697              }
1104            break;
698          }
699          return null;
700      }
701  
702      /**
703 <     * Implementation for the four public remove/replace methods:
704 <     * Replaces node value with v, conditional upon match of cv if
1112 <     * non-null.  If resulting value is null, delete.
703 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
704 >     * class), else 0.
705       */
706 <    private final Object internalReplace(Object k, Object v, Object cv) {
707 <        int h = spread(k.hashCode());
708 <        Object oldVal = null;
709 <        for (Node[] tab = table;;) {
1118 <            Node f; int i, fh; Object fk;
1119 <            if (tab == null ||
1120 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1121 <                break;
1122 <            else if ((fh = f.hash) == MOVED) {
1123 <                if ((fk = f.key) instanceof TreeBin) {
1124 <                    TreeBin t = (TreeBin)fk;
1125 <                    boolean validated = false;
1126 <                    boolean deleted = false;
1127 <                    t.acquire(0);
1128 <                    try {
1129 <                        if (tabAt(tab, i) == f) {
1130 <                            validated = true;
1131 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1132 <                            if (p != null) {
1133 <                                Object pv = p.val;
1134 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1135 <                                    oldVal = pv;
1136 <                                    if ((p.val = v) == null) {
1137 <                                        deleted = true;
1138 <                                        t.deleteTreeNode(p);
1139 <                                    }
1140 <                                }
1141 <                            }
1142 <                        }
1143 <                    } finally {
1144 <                        t.release(0);
1145 <                    }
1146 <                    if (validated) {
1147 <                        if (deleted)
1148 <                            counter.add(-1L);
1149 <                        break;
1150 <                    }
1151 <                }
1152 <                else
1153 <                    tab = (Node[])fk;
1154 <            }
1155 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1156 <                break;                          // rules out possible existence
1157 <            else if ((fh & LOCKED) != 0) {
1158 <                checkForResize();               // try resizing if can't get lock
1159 <                f.tryAwaitLock(tab, i);
1160 <            }
1161 <            else if (f.casHash(fh, fh | LOCKED)) {
1162 <                boolean validated = false;
1163 <                boolean deleted = false;
1164 <                try {
1165 <                    if (tabAt(tab, i) == f) {
1166 <                        validated = true;
1167 <                        for (Node e = f, pred = null;;) {
1168 <                            Object ek, ev;
1169 <                            if ((e.hash & HASH_BITS) == h &&
1170 <                                ((ev = e.val) != null) &&
1171 <                                ((ek = e.key) == k || k.equals(ek))) {
1172 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1173 <                                    oldVal = ev;
1174 <                                    if ((e.val = v) == null) {
1175 <                                        deleted = true;
1176 <                                        Node en = e.next;
1177 <                                        if (pred != null)
1178 <                                            pred.next = en;
1179 <                                        else
1180 <                                            setTabAt(tab, i, en);
1181 <                                    }
1182 <                                }
1183 <                                break;
1184 <                            }
1185 <                            pred = e;
1186 <                            if ((e = e.next) == null)
1187 <                                break;
1188 <                        }
1189 <                    }
1190 <                } finally {
1191 <                    if (!f.casHash(fh | LOCKED, fh)) {
1192 <                        f.hash = fh;
1193 <                        synchronized (f) { f.notifyAll(); };
1194 <                    }
1195 <                }
1196 <                if (validated) {
1197 <                    if (deleted)
1198 <                        counter.add(-1L);
1199 <                    break;
1200 <                }
1201 <            }
1202 <        }
1203 <        return oldVal;
706 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
707 >    static int compareComparables(Class<?> kc, Object k, Object x) {
708 >        return (x == null || x.getClass() != kc ? 0 :
709 >                ((Comparable)k).compareTo(x));
710      }
711  
712 <    /*
1207 <     * Internal versions of the five insertion methods, each a
1208 <     * little more complicated than the last. All have
1209 <     * the same basic structure as the first (internalPut):
1210 <     *  1. If table uninitialized, create
1211 <     *  2. If bin empty, try to CAS new node
1212 <     *  3. If bin stale, use new table
1213 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1214 <     *  5. Lock and validate; if valid, scan and add or update
1215 <     *
1216 <     * The others interweave other checks and/or alternative actions:
1217 <     *  * Plain put checks for and performs resize after insertion.
1218 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1219 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1220 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1221 <     *    mechanics to deal with, calls, potential exceptions and null
1222 <     *    returns from function call.
1223 <     *  * compute uses the same function-call mechanics, but without
1224 <     *    the prescans
1225 <     *  * putAll attempts to pre-allocate enough table space
1226 <     *    and more lazily performs count updates and checks.
1227 <     *
1228 <     * Someday when details settle down a bit more, it might be worth
1229 <     * some factoring to reduce sprawl.
1230 <     */
1231 <
1232 <    /** Implementation for put */
1233 <    private final Object internalPut(Object k, Object v) {
1234 <        int h = spread(k.hashCode());
1235 <        int count = 0;
1236 <        for (Node[] tab = table;;) {
1237 <            int i; Node f; int fh; Object fk;
1238 <            if (tab == null)
1239 <                tab = initTable();
1240 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1241 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1242 <                    break;                   // no lock when adding to empty bin
1243 <            }
1244 <            else if ((fh = f.hash) == MOVED) {
1245 <                if ((fk = f.key) instanceof TreeBin) {
1246 <                    TreeBin t = (TreeBin)fk;
1247 <                    Object oldVal = null;
1248 <                    t.acquire(0);
1249 <                    try {
1250 <                        if (tabAt(tab, i) == f) {
1251 <                            count = 2;
1252 <                            TreeNode p = t.putTreeNode(h, k, v);
1253 <                            if (p != null) {
1254 <                                oldVal = p.val;
1255 <                                p.val = v;
1256 <                            }
1257 <                        }
1258 <                    } finally {
1259 <                        t.release(0);
1260 <                    }
1261 <                    if (count != 0) {
1262 <                        if (oldVal != null)
1263 <                            return oldVal;
1264 <                        break;
1265 <                    }
1266 <                }
1267 <                else
1268 <                    tab = (Node[])fk;
1269 <            }
1270 <            else if ((fh & LOCKED) != 0) {
1271 <                checkForResize();
1272 <                f.tryAwaitLock(tab, i);
1273 <            }
1274 <            else if (f.casHash(fh, fh | LOCKED)) {
1275 <                Object oldVal = null;
1276 <                try {                        // needed in case equals() throws
1277 <                    if (tabAt(tab, i) == f) {
1278 <                        count = 1;
1279 <                        for (Node e = f;; ++count) {
1280 <                            Object ek, ev;
1281 <                            if ((e.hash & HASH_BITS) == h &&
1282 <                                (ev = e.val) != null &&
1283 <                                ((ek = e.key) == k || k.equals(ek))) {
1284 <                                oldVal = ev;
1285 <                                e.val = v;
1286 <                                break;
1287 <                            }
1288 <                            Node last = e;
1289 <                            if ((e = e.next) == null) {
1290 <                                last.next = new Node(h, k, v, null);
1291 <                                if (count >= TREE_THRESHOLD)
1292 <                                    replaceWithTreeBin(tab, i, k);
1293 <                                break;
1294 <                            }
1295 <                        }
1296 <                    }
1297 <                } finally {                  // unlock and signal if needed
1298 <                    if (!f.casHash(fh | LOCKED, fh)) {
1299 <                        f.hash = fh;
1300 <                        synchronized (f) { f.notifyAll(); };
1301 <                    }
1302 <                }
1303 <                if (count != 0) {
1304 <                    if (oldVal != null)
1305 <                        return oldVal;
1306 <                    if (tab.length <= 64)
1307 <                        count = 2;
1308 <                    break;
1309 <                }
1310 <            }
1311 <        }
1312 <        counter.add(1L);
1313 <        if (count > 1)
1314 <            checkForResize();
1315 <        return null;
1316 <    }
1317 <
1318 <    /** Implementation for putIfAbsent */
1319 <    private final Object internalPutIfAbsent(Object k, Object v) {
1320 <        int h = spread(k.hashCode());
1321 <        int count = 0;
1322 <        for (Node[] tab = table;;) {
1323 <            int i; Node f; int fh; Object fk, fv;
1324 <            if (tab == null)
1325 <                tab = initTable();
1326 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1327 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1328 <                    break;
1329 <            }
1330 <            else if ((fh = f.hash) == MOVED) {
1331 <                if ((fk = f.key) instanceof TreeBin) {
1332 <                    TreeBin t = (TreeBin)fk;
1333 <                    Object oldVal = null;
1334 <                    t.acquire(0);
1335 <                    try {
1336 <                        if (tabAt(tab, i) == f) {
1337 <                            count = 2;
1338 <                            TreeNode p = t.putTreeNode(h, k, v);
1339 <                            if (p != null)
1340 <                                oldVal = p.val;
1341 <                        }
1342 <                    } finally {
1343 <                        t.release(0);
1344 <                    }
1345 <                    if (count != 0) {
1346 <                        if (oldVal != null)
1347 <                            return oldVal;
1348 <                        break;
1349 <                    }
1350 <                }
1351 <                else
1352 <                    tab = (Node[])fk;
1353 <            }
1354 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1355 <                     ((fk = f.key) == k || k.equals(fk)))
1356 <                return fv;
1357 <            else {
1358 <                Node g = f.next;
1359 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1360 <                    for (Node e = g;;) {
1361 <                        Object ek, ev;
1362 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1363 <                            ((ek = e.key) == k || k.equals(ek)))
1364 <                            return ev;
1365 <                        if ((e = e.next) == null) {
1366 <                            checkForResize();
1367 <                            break;
1368 <                        }
1369 <                    }
1370 <                }
1371 <                if (((fh = f.hash) & LOCKED) != 0) {
1372 <                    checkForResize();
1373 <                    f.tryAwaitLock(tab, i);
1374 <                }
1375 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1376 <                    Object oldVal = null;
1377 <                    try {
1378 <                        if (tabAt(tab, i) == f) {
1379 <                            count = 1;
1380 <                            for (Node e = f;; ++count) {
1381 <                                Object ek, ev;
1382 <                                if ((e.hash & HASH_BITS) == h &&
1383 <                                    (ev = e.val) != null &&
1384 <                                    ((ek = e.key) == k || k.equals(ek))) {
1385 <                                    oldVal = ev;
1386 <                                    break;
1387 <                                }
1388 <                                Node last = e;
1389 <                                if ((e = e.next) == null) {
1390 <                                    last.next = new Node(h, k, v, null);
1391 <                                    if (count >= TREE_THRESHOLD)
1392 <                                        replaceWithTreeBin(tab, i, k);
1393 <                                    break;
1394 <                                }
1395 <                            }
1396 <                        }
1397 <                    } finally {
1398 <                        if (!f.casHash(fh | LOCKED, fh)) {
1399 <                            f.hash = fh;
1400 <                            synchronized (f) { f.notifyAll(); };
1401 <                        }
1402 <                    }
1403 <                    if (count != 0) {
1404 <                        if (oldVal != null)
1405 <                            return oldVal;
1406 <                        if (tab.length <= 64)
1407 <                            count = 2;
1408 <                        break;
1409 <                    }
1410 <                }
1411 <            }
1412 <        }
1413 <        counter.add(1L);
1414 <        if (count > 1)
1415 <            checkForResize();
1416 <        return null;
1417 <    }
712 >    /* ---------------- Table element access -------------- */
713  
714 <    /** Implementation for computeIfAbsent */
715 <    private final Object internalComputeIfAbsent(K k,
716 <                                                 Fun<? super K, ?> mf) {
717 <        int h = spread(k.hashCode());
718 <        Object val = null;
719 <        int count = 0;
720 <        for (Node[] tab = table;;) {
721 <            Node f; int i, fh; Object fk, fv;
722 <            if (tab == null)
723 <                tab = initTable();
724 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
725 <                Node node = new Node(fh = h | LOCKED, k, null, null);
726 <                if (casTabAt(tab, i, null, node)) {
727 <                    count = 1;
1433 <                    try {
1434 <                        if ((val = mf.apply(k)) != null)
1435 <                            node.val = val;
1436 <                    } finally {
1437 <                        if (val == null)
1438 <                            setTabAt(tab, i, null);
1439 <                        if (!node.casHash(fh, h)) {
1440 <                            node.hash = h;
1441 <                            synchronized (node) { node.notifyAll(); };
1442 <                        }
1443 <                    }
1444 <                }
1445 <                if (count != 0)
1446 <                    break;
1447 <            }
1448 <            else if ((fh = f.hash) == MOVED) {
1449 <                if ((fk = f.key) instanceof TreeBin) {
1450 <                    TreeBin t = (TreeBin)fk;
1451 <                    boolean added = false;
1452 <                    t.acquire(0);
1453 <                    try {
1454 <                        if (tabAt(tab, i) == f) {
1455 <                            count = 1;
1456 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1457 <                            if (p != null)
1458 <                                val = p.val;
1459 <                            else if ((val = mf.apply(k)) != null) {
1460 <                                added = true;
1461 <                                count = 2;
1462 <                                t.putTreeNode(h, k, val);
1463 <                            }
1464 <                        }
1465 <                    } finally {
1466 <                        t.release(0);
1467 <                    }
1468 <                    if (count != 0) {
1469 <                        if (!added)
1470 <                            return val;
1471 <                        break;
1472 <                    }
1473 <                }
1474 <                else
1475 <                    tab = (Node[])fk;
1476 <            }
1477 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1478 <                     ((fk = f.key) == k || k.equals(fk)))
1479 <                return fv;
1480 <            else {
1481 <                Node g = f.next;
1482 <                if (g != null) {
1483 <                    for (Node e = g;;) {
1484 <                        Object ek, ev;
1485 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1486 <                            ((ek = e.key) == k || k.equals(ek)))
1487 <                            return ev;
1488 <                        if ((e = e.next) == null) {
1489 <                            checkForResize();
1490 <                            break;
1491 <                        }
1492 <                    }
1493 <                }
1494 <                if (((fh = f.hash) & LOCKED) != 0) {
1495 <                    checkForResize();
1496 <                    f.tryAwaitLock(tab, i);
1497 <                }
1498 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1499 <                    boolean added = false;
1500 <                    try {
1501 <                        if (tabAt(tab, i) == f) {
1502 <                            count = 1;
1503 <                            for (Node e = f;; ++count) {
1504 <                                Object ek, ev;
1505 <                                if ((e.hash & HASH_BITS) == h &&
1506 <                                    (ev = e.val) != null &&
1507 <                                    ((ek = e.key) == k || k.equals(ek))) {
1508 <                                    val = ev;
1509 <                                    break;
1510 <                                }
1511 <                                Node last = e;
1512 <                                if ((e = e.next) == null) {
1513 <                                    if ((val = mf.apply(k)) != null) {
1514 <                                        added = true;
1515 <                                        last.next = new Node(h, k, val, null);
1516 <                                        if (count >= TREE_THRESHOLD)
1517 <                                            replaceWithTreeBin(tab, i, k);
1518 <                                    }
1519 <                                    break;
1520 <                                }
1521 <                            }
1522 <                        }
1523 <                    } finally {
1524 <                        if (!f.casHash(fh | LOCKED, fh)) {
1525 <                            f.hash = fh;
1526 <                            synchronized (f) { f.notifyAll(); };
1527 <                        }
1528 <                    }
1529 <                    if (count != 0) {
1530 <                        if (!added)
1531 <                            return val;
1532 <                        if (tab.length <= 64)
1533 <                            count = 2;
1534 <                        break;
1535 <                    }
1536 <                }
1537 <            }
1538 <        }
1539 <        if (val != null) {
1540 <            counter.add(1L);
1541 <            if (count > 1)
1542 <                checkForResize();
1543 <        }
1544 <        return val;
1545 <    }
714 >    /*
715 >     * Volatile access methods are used for table elements as well as
716 >     * elements of in-progress next table while resizing.  All uses of
717 >     * the tab arguments must be null checked by callers.  All callers
718 >     * also paranoically precheck that tab's length is not zero (or an
719 >     * equivalent check), thus ensuring that any index argument taking
720 >     * the form of a hash value anded with (length - 1) is a valid
721 >     * index.  Note that, to be correct wrt arbitrary concurrency
722 >     * errors by users, these checks must operate on local variables,
723 >     * which accounts for some odd-looking inline assignments below.
724 >     * Note that calls to setTabAt always occur within locked regions,
725 >     * and so do not need full volatile semantics, but still require
726 >     * ordering to maintain concurrent readability.
727 >     */
728  
1547    /** Implementation for compute */
729      @SuppressWarnings("unchecked")
730 <        private final Object internalCompute(K k, boolean onlyIfPresent,
731 <                                             BiFun<? super K, ? super V, ? extends V> mf) {
1551 <        int h = spread(k.hashCode());
1552 <        Object val = null;
1553 <        int delta = 0;
1554 <        int count = 0;
1555 <        for (Node[] tab = table;;) {
1556 <            Node f; int i, fh; Object fk;
1557 <            if (tab == null)
1558 <                tab = initTable();
1559 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1560 <                if (onlyIfPresent)
1561 <                    break;
1562 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1563 <                if (casTabAt(tab, i, null, node)) {
1564 <                    try {
1565 <                        count = 1;
1566 <                        if ((val = mf.apply(k, null)) != null) {
1567 <                            node.val = val;
1568 <                            delta = 1;
1569 <                        }
1570 <                    } finally {
1571 <                        if (delta == 0)
1572 <                            setTabAt(tab, i, null);
1573 <                        if (!node.casHash(fh, h)) {
1574 <                            node.hash = h;
1575 <                            synchronized (node) { node.notifyAll(); };
1576 <                        }
1577 <                    }
1578 <                }
1579 <                if (count != 0)
1580 <                    break;
1581 <            }
1582 <            else if ((fh = f.hash) == MOVED) {
1583 <                if ((fk = f.key) instanceof TreeBin) {
1584 <                    TreeBin t = (TreeBin)fk;
1585 <                    t.acquire(0);
1586 <                    try {
1587 <                        if (tabAt(tab, i) == f) {
1588 <                            count = 1;
1589 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1590 <                            Object pv = (p == null) ? null : p.val;
1591 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1592 <                                if (p != null)
1593 <                                    p.val = val;
1594 <                                else {
1595 <                                    count = 2;
1596 <                                    delta = 1;
1597 <                                    t.putTreeNode(h, k, val);
1598 <                                }
1599 <                            }
1600 <                            else if (p != null) {
1601 <                                delta = -1;
1602 <                                t.deleteTreeNode(p);
1603 <                            }
1604 <                        }
1605 <                    } finally {
1606 <                        t.release(0);
1607 <                    }
1608 <                    if (count != 0)
1609 <                        break;
1610 <                }
1611 <                else
1612 <                    tab = (Node[])fk;
1613 <            }
1614 <            else if ((fh & LOCKED) != 0) {
1615 <                checkForResize();
1616 <                f.tryAwaitLock(tab, i);
1617 <            }
1618 <            else if (f.casHash(fh, fh | LOCKED)) {
1619 <                try {
1620 <                    if (tabAt(tab, i) == f) {
1621 <                        count = 1;
1622 <                        for (Node e = f, pred = null;; ++count) {
1623 <                            Object ek, ev;
1624 <                            if ((e.hash & HASH_BITS) == h &&
1625 <                                (ev = e.val) != null &&
1626 <                                ((ek = e.key) == k || k.equals(ek))) {
1627 <                                val = mf.apply(k, (V)ev);
1628 <                                if (val != null)
1629 <                                    e.val = val;
1630 <                                else {
1631 <                                    delta = -1;
1632 <                                    Node en = e.next;
1633 <                                    if (pred != null)
1634 <                                        pred.next = en;
1635 <                                    else
1636 <                                        setTabAt(tab, i, en);
1637 <                                }
1638 <                                break;
1639 <                            }
1640 <                            pred = e;
1641 <                            if ((e = e.next) == null) {
1642 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1643 <                                    pred.next = new Node(h, k, val, null);
1644 <                                    delta = 1;
1645 <                                    if (count >= TREE_THRESHOLD)
1646 <                                        replaceWithTreeBin(tab, i, k);
1647 <                                }
1648 <                                break;
1649 <                            }
1650 <                        }
1651 <                    }
1652 <                } finally {
1653 <                    if (!f.casHash(fh | LOCKED, fh)) {
1654 <                        f.hash = fh;
1655 <                        synchronized (f) { f.notifyAll(); };
1656 <                    }
1657 <                }
1658 <                if (count != 0) {
1659 <                    if (tab.length <= 64)
1660 <                        count = 2;
1661 <                    break;
1662 <                }
1663 <            }
1664 <        }
1665 <        if (delta != 0) {
1666 <            counter.add((long)delta);
1667 <            if (count > 1)
1668 <                checkForResize();
1669 <        }
1670 <        return val;
730 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
731 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
732      }
733  
734 <    private final Object internalMerge(K k, V v,
735 <                                       BiFun<? super V, ? super V, ? extends V> mf) {
736 <        int h = spread(k.hashCode());
1676 <        Object val = null;
1677 <        int delta = 0;
1678 <        int count = 0;
1679 <        for (Node[] tab = table;;) {
1680 <            int i; Node f; int fh; Object fk, fv;
1681 <            if (tab == null)
1682 <                tab = initTable();
1683 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1684 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1685 <                    delta = 1;
1686 <                    val = v;
1687 <                    break;
1688 <                }
1689 <            }
1690 <            else if ((fh = f.hash) == MOVED) {
1691 <                if ((fk = f.key) instanceof TreeBin) {
1692 <                    TreeBin t = (TreeBin)fk;
1693 <                    t.acquire(0);
1694 <                    try {
1695 <                        if (tabAt(tab, i) == f) {
1696 <                            count = 1;
1697 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1698 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1699 <                            if (val != null) {
1700 <                                if (p != null)
1701 <                                    p.val = val;
1702 <                                else {
1703 <                                    count = 2;
1704 <                                    delta = 1;
1705 <                                    t.putTreeNode(h, k, val);
1706 <                                }
1707 <                            }
1708 <                            else if (p != null) {
1709 <                                delta = -1;
1710 <                                t.deleteTreeNode(p);
1711 <                            }
1712 <                        }
1713 <                    } finally {
1714 <                        t.release(0);
1715 <                    }
1716 <                    if (count != 0)
1717 <                        break;
1718 <                }
1719 <                else
1720 <                    tab = (Node[])fk;
1721 <            }
1722 <            else if ((fh & LOCKED) != 0) {
1723 <                checkForResize();
1724 <                f.tryAwaitLock(tab, i);
1725 <            }
1726 <            else if (f.casHash(fh, fh | LOCKED)) {
1727 <                try {
1728 <                    if (tabAt(tab, i) == f) {
1729 <                        count = 1;
1730 <                        for (Node e = f, pred = null;; ++count) {
1731 <                            Object ek, ev;
1732 <                            if ((e.hash & HASH_BITS) == h &&
1733 <                                (ev = e.val) != null &&
1734 <                                ((ek = e.key) == k || k.equals(ek))) {
1735 <                                val = mf.apply(v, (V)ev);
1736 <                                if (val != null)
1737 <                                    e.val = val;
1738 <                                else {
1739 <                                    delta = -1;
1740 <                                    Node en = e.next;
1741 <                                    if (pred != null)
1742 <                                        pred.next = en;
1743 <                                    else
1744 <                                        setTabAt(tab, i, en);
1745 <                                }
1746 <                                break;
1747 <                            }
1748 <                            pred = e;
1749 <                            if ((e = e.next) == null) {
1750 <                                val = v;
1751 <                                pred.next = new Node(h, k, val, null);
1752 <                                delta = 1;
1753 <                                if (count >= TREE_THRESHOLD)
1754 <                                    replaceWithTreeBin(tab, i, k);
1755 <                                break;
1756 <                            }
1757 <                        }
1758 <                    }
1759 <                } finally {
1760 <                    if (!f.casHash(fh | LOCKED, fh)) {
1761 <                        f.hash = fh;
1762 <                        synchronized (f) { f.notifyAll(); };
1763 <                    }
1764 <                }
1765 <                if (count != 0) {
1766 <                    if (tab.length <= 64)
1767 <                        count = 2;
1768 <                    break;
1769 <                }
1770 <            }
1771 <        }
1772 <        if (delta != 0) {
1773 <            counter.add((long)delta);
1774 <            if (count > 1)
1775 <                checkForResize();
1776 <        }
1777 <        return val;
734 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
735 >                                        Node<K,V> c, Node<K,V> v) {
736 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
737      }
738  
739 <    /** Implementation for putAll */
740 <    private final void internalPutAll(Map<?, ?> m) {
1782 <        tryPresize(m.size());
1783 <        long delta = 0L;     // number of uncommitted additions
1784 <        boolean npe = false; // to throw exception on exit for nulls
1785 <        try {                // to clean up counts on other exceptions
1786 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1787 <                Object k, v;
1788 <                if (entry == null || (k = entry.getKey()) == null ||
1789 <                    (v = entry.getValue()) == null) {
1790 <                    npe = true;
1791 <                    break;
1792 <                }
1793 <                int h = spread(k.hashCode());
1794 <                for (Node[] tab = table;;) {
1795 <                    int i; Node f; int fh; Object fk;
1796 <                    if (tab == null)
1797 <                        tab = initTable();
1798 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1799 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1800 <                            ++delta;
1801 <                            break;
1802 <                        }
1803 <                    }
1804 <                    else if ((fh = f.hash) == MOVED) {
1805 <                        if ((fk = f.key) instanceof TreeBin) {
1806 <                            TreeBin t = (TreeBin)fk;
1807 <                            boolean validated = false;
1808 <                            t.acquire(0);
1809 <                            try {
1810 <                                if (tabAt(tab, i) == f) {
1811 <                                    validated = true;
1812 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1813 <                                    if (p != null)
1814 <                                        p.val = v;
1815 <                                    else {
1816 <                                        t.putTreeNode(h, k, v);
1817 <                                        ++delta;
1818 <                                    }
1819 <                                }
1820 <                            } finally {
1821 <                                t.release(0);
1822 <                            }
1823 <                            if (validated)
1824 <                                break;
1825 <                        }
1826 <                        else
1827 <                            tab = (Node[])fk;
1828 <                    }
1829 <                    else if ((fh & LOCKED) != 0) {
1830 <                        counter.add(delta);
1831 <                        delta = 0L;
1832 <                        checkForResize();
1833 <                        f.tryAwaitLock(tab, i);
1834 <                    }
1835 <                    else if (f.casHash(fh, fh | LOCKED)) {
1836 <                        int count = 0;
1837 <                        try {
1838 <                            if (tabAt(tab, i) == f) {
1839 <                                count = 1;
1840 <                                for (Node e = f;; ++count) {
1841 <                                    Object ek, ev;
1842 <                                    if ((e.hash & HASH_BITS) == h &&
1843 <                                        (ev = e.val) != null &&
1844 <                                        ((ek = e.key) == k || k.equals(ek))) {
1845 <                                        e.val = v;
1846 <                                        break;
1847 <                                    }
1848 <                                    Node last = e;
1849 <                                    if ((e = e.next) == null) {
1850 <                                        ++delta;
1851 <                                        last.next = new Node(h, k, v, null);
1852 <                                        if (count >= TREE_THRESHOLD)
1853 <                                            replaceWithTreeBin(tab, i, k);
1854 <                                        break;
1855 <                                    }
1856 <                                }
1857 <                            }
1858 <                        } finally {
1859 <                            if (!f.casHash(fh | LOCKED, fh)) {
1860 <                                f.hash = fh;
1861 <                                synchronized (f) { f.notifyAll(); };
1862 <                            }
1863 <                        }
1864 <                        if (count != 0) {
1865 <                            if (count > 1) {
1866 <                                counter.add(delta);
1867 <                                delta = 0L;
1868 <                                checkForResize();
1869 <                            }
1870 <                            break;
1871 <                        }
1872 <                    }
1873 <                }
1874 <            }
1875 <        } finally {
1876 <            if (delta != 0)
1877 <                counter.add(delta);
1878 <        }
1879 <        if (npe)
1880 <            throw new NullPointerException();
739 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
740 >        U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
741      }
742  
743 <    /* ---------------- Table Initialization and Resizing -------------- */
743 >    /* ---------------- Fields -------------- */
744  
745      /**
746 <     * Returns a power of two table size for the given desired capacity.
747 <     * See Hackers Delight, sec 3.2
746 >     * The array of bins. Lazily initialized upon first insertion.
747 >     * Size is always a power of two. Accessed directly by iterators.
748       */
749 <    private static final int tableSizeFor(int c) {
1890 <        int n = c - 1;
1891 <        n |= n >>> 1;
1892 <        n |= n >>> 2;
1893 <        n |= n >>> 4;
1894 <        n |= n >>> 8;
1895 <        n |= n >>> 16;
1896 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1897 <    }
749 >    transient volatile Node<K,V>[] table;
750  
751      /**
752 <     * Initializes table, using the size recorded in sizeCtl.
752 >     * The next table to use; non-null only while resizing.
753       */
754 <    private final Node[] initTable() {
1903 <        Node[] tab; int sc;
1904 <        while ((tab = table) == null) {
1905 <            if ((sc = sizeCtl) < 0)
1906 <                Thread.yield(); // lost initialization race; just spin
1907 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1908 <                try {
1909 <                    if ((tab = table) == null) {
1910 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1911 <                        tab = table = new Node[n];
1912 <                        sc = n - (n >>> 2);
1913 <                    }
1914 <                } finally {
1915 <                    sizeCtl = sc;
1916 <                }
1917 <                break;
1918 <            }
1919 <        }
1920 <        return tab;
1921 <    }
1922 <
1923 <    /**
1924 <     * If table is too small and not already resizing, creates next
1925 <     * table and transfers bins.  Rechecks occupancy after a transfer
1926 <     * to see if another resize is already needed because resizings
1927 <     * are lagging additions.
1928 <     */
1929 <    private final void checkForResize() {
1930 <        Node[] tab; int n, sc;
1931 <        while ((tab = table) != null &&
1932 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1933 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1934 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1935 <            try {
1936 <                if (tab == table) {
1937 <                    table = rebuild(tab);
1938 <                    sc = (n << 1) - (n >>> 1);
1939 <                }
1940 <            } finally {
1941 <                sizeCtl = sc;
1942 <            }
1943 <        }
1944 <    }
754 >    private transient volatile Node<K,V>[] nextTable;
755  
756      /**
757 <     * Tries to presize table to accommodate the given number of elements.
758 <     *
759 <     * @param size number of elements (doesn't need to be perfectly accurate)
757 >     * Base counter value, used mainly when there is no contention,
758 >     * but also as a fallback during table initialization
759 >     * races. Updated via CAS.
760       */
761 <    private final void tryPresize(int size) {
1952 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1953 <            tableSizeFor(size + (size >>> 1) + 1);
1954 <        int sc;
1955 <        while ((sc = sizeCtl) >= 0) {
1956 <            Node[] tab = table; int n;
1957 <            if (tab == null || (n = tab.length) == 0) {
1958 <                n = (sc > c) ? sc : c;
1959 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1960 <                    try {
1961 <                        if (table == tab) {
1962 <                            table = new Node[n];
1963 <                            sc = n - (n >>> 2);
1964 <                        }
1965 <                    } finally {
1966 <                        sizeCtl = sc;
1967 <                    }
1968 <                }
1969 <            }
1970 <            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1971 <                break;
1972 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1973 <                try {
1974 <                    if (table == tab) {
1975 <                        table = rebuild(tab);
1976 <                        sc = (n << 1) - (n >>> 1);
1977 <                    }
1978 <                } finally {
1979 <                    sizeCtl = sc;
1980 <                }
1981 <            }
1982 <        }
1983 <    }
761 >    private transient volatile long baseCount;
762  
763 <    /*
764 <     * Moves and/or copies the nodes in each bin to new table. See
765 <     * above for explanation.
766 <     *
767 <     * @return the new table
763 >    /**
764 >     * Table initialization and resizing control.  When negative, the
765 >     * table is being initialized or resized: -1 for initialization,
766 >     * else -(1 + the number of active resizing threads).  Otherwise,
767 >     * when table is null, holds the initial table size to use upon
768 >     * creation, or 0 for default. After initialization, holds the
769 >     * next element count value upon which to resize the table.
770       */
771 <    private static final Node[] rebuild(Node[] tab) {
1992 <        int n = tab.length;
1993 <        Node[] nextTab = new Node[n << 1];
1994 <        Node fwd = new Node(MOVED, nextTab, null, null);
1995 <        int[] buffer = null;       // holds bins to revisit; null until needed
1996 <        Node rev = null;           // reverse forwarder; null until needed
1997 <        int nbuffered = 0;         // the number of bins in buffer list
1998 <        int bufferIndex = 0;       // buffer index of current buffered bin
1999 <        int bin = n - 1;           // current non-buffered bin or -1 if none
2000 <
2001 <        for (int i = bin;;) {      // start upwards sweep
2002 <            int fh; Node f;
2003 <            if ((f = tabAt(tab, i)) == null) {
2004 <                if (bin >= 0) {    // no lock needed (or available)
2005 <                    if (!casTabAt(tab, i, f, fwd))
2006 <                        continue;
2007 <                }
2008 <                else {             // transiently use a locked forwarding node
2009 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2010 <                    if (!casTabAt(tab, i, f, g))
2011 <                        continue;
2012 <                    setTabAt(nextTab, i, null);
2013 <                    setTabAt(nextTab, i + n, null);
2014 <                    setTabAt(tab, i, fwd);
2015 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2016 <                        g.hash = MOVED;
2017 <                        synchronized (g) { g.notifyAll(); }
2018 <                    }
2019 <                }
2020 <            }
2021 <            else if ((fh = f.hash) == MOVED) {
2022 <                Object fk = f.key;
2023 <                if (fk instanceof TreeBin) {
2024 <                    TreeBin t = (TreeBin)fk;
2025 <                    boolean validated = false;
2026 <                    t.acquire(0);
2027 <                    try {
2028 <                        if (tabAt(tab, i) == f) {
2029 <                            validated = true;
2030 <                            splitTreeBin(nextTab, i, t);
2031 <                            setTabAt(tab, i, fwd);
2032 <                        }
2033 <                    } finally {
2034 <                        t.release(0);
2035 <                    }
2036 <                    if (!validated)
2037 <                        continue;
2038 <                }
2039 <            }
2040 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2041 <                boolean validated = false;
2042 <                try {              // split to lo and hi lists; copying as needed
2043 <                    if (tabAt(tab, i) == f) {
2044 <                        validated = true;
2045 <                        splitBin(nextTab, i, f);
2046 <                        setTabAt(tab, i, fwd);
2047 <                    }
2048 <                } finally {
2049 <                    if (!f.casHash(fh | LOCKED, fh)) {
2050 <                        f.hash = fh;
2051 <                        synchronized (f) { f.notifyAll(); };
2052 <                    }
2053 <                }
2054 <                if (!validated)
2055 <                    continue;
2056 <            }
2057 <            else {
2058 <                if (buffer == null) // initialize buffer for revisits
2059 <                    buffer = new int[TRANSFER_BUFFER_SIZE];
2060 <                if (bin < 0 && bufferIndex > 0) {
2061 <                    int j = buffer[--bufferIndex];
2062 <                    buffer[bufferIndex] = i;
2063 <                    i = j;         // swap with another bin
2064 <                    continue;
2065 <                }
2066 <                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2067 <                    f.tryAwaitLock(tab, i);
2068 <                    continue;      // no other options -- block
2069 <                }
2070 <                if (rev == null)   // initialize reverse-forwarder
2071 <                    rev = new Node(MOVED, tab, null, null);
2072 <                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2073 <                    continue;      // recheck before adding to list
2074 <                buffer[nbuffered++] = i;
2075 <                setTabAt(nextTab, i, rev);     // install place-holders
2076 <                setTabAt(nextTab, i + n, rev);
2077 <            }
2078 <
2079 <            if (bin > 0)
2080 <                i = --bin;
2081 <            else if (buffer != null && nbuffered > 0) {
2082 <                bin = -1;
2083 <                i = buffer[bufferIndex = --nbuffered];
2084 <            }
2085 <            else
2086 <                return nextTab;
2087 <        }
2088 <    }
771 >    private transient volatile int sizeCtl;
772  
773      /**
774 <     * Splits a normal bin with list headed by e into lo and hi parts;
2092 <     * installs in given table.
774 >     * The next table index (plus one) to split while resizing.
775       */
776 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2095 <        int bit = nextTab.length >>> 1; // bit to split on
2096 <        int runBit = e.hash & bit;
2097 <        Node lastRun = e, lo = null, hi = null;
2098 <        for (Node p = e.next; p != null; p = p.next) {
2099 <            int b = p.hash & bit;
2100 <            if (b != runBit) {
2101 <                runBit = b;
2102 <                lastRun = p;
2103 <            }
2104 <        }
2105 <        if (runBit == 0)
2106 <            lo = lastRun;
2107 <        else
2108 <            hi = lastRun;
2109 <        for (Node p = e; p != lastRun; p = p.next) {
2110 <            int ph = p.hash & HASH_BITS;
2111 <            Object pk = p.key, pv = p.val;
2112 <            if ((ph & bit) == 0)
2113 <                lo = new Node(ph, pk, pv, lo);
2114 <            else
2115 <                hi = new Node(ph, pk, pv, hi);
2116 <        }
2117 <        setTabAt(nextTab, i, lo);
2118 <        setTabAt(nextTab, i + bit, hi);
2119 <    }
776 >    private transient volatile int transferIndex;
777  
778      /**
779 <     * Splits a tree bin into lo and hi parts; installs in given table.
779 >     * The least available table index to split while resizing.
780       */
781 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2125 <        int bit = nextTab.length >>> 1;
2126 <        TreeBin lt = new TreeBin();
2127 <        TreeBin ht = new TreeBin();
2128 <        int lc = 0, hc = 0;
2129 <        for (Node e = t.first; e != null; e = e.next) {
2130 <            int h = e.hash & HASH_BITS;
2131 <            Object k = e.key, v = e.val;
2132 <            if ((h & bit) == 0) {
2133 <                ++lc;
2134 <                lt.putTreeNode(h, k, v);
2135 <            }
2136 <            else {
2137 <                ++hc;
2138 <                ht.putTreeNode(h, k, v);
2139 <            }
2140 <        }
2141 <        Node ln, hn; // throw away trees if too small
2142 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2143 <            ln = null;
2144 <            for (Node p = lt.first; p != null; p = p.next)
2145 <                ln = new Node(p.hash, p.key, p.val, ln);
2146 <        }
2147 <        else
2148 <            ln = new Node(MOVED, lt, null, null);
2149 <        setTabAt(nextTab, i, ln);
2150 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2151 <            hn = null;
2152 <            for (Node p = ht.first; p != null; p = p.next)
2153 <                hn = new Node(p.hash, p.key, p.val, hn);
2154 <        }
2155 <        else
2156 <            hn = new Node(MOVED, ht, null, null);
2157 <        setTabAt(nextTab, i + bit, hn);
2158 <    }
781 >    private transient volatile int transferOrigin;
782  
783      /**
784 <     * Implementation for clear. Steps through each bin, removing all
2162 <     * nodes.
784 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
785       */
786 <    private final void internalClear() {
2165 <        long delta = 0L; // negative number of deletions
2166 <        int i = 0;
2167 <        Node[] tab = table;
2168 <        while (tab != null && i < tab.length) {
2169 <            int fh; Object fk;
2170 <            Node f = tabAt(tab, i);
2171 <            if (f == null)
2172 <                ++i;
2173 <            else if ((fh = f.hash) == MOVED) {
2174 <                if ((fk = f.key) instanceof TreeBin) {
2175 <                    TreeBin t = (TreeBin)fk;
2176 <                    t.acquire(0);
2177 <                    try {
2178 <                        if (tabAt(tab, i) == f) {
2179 <                            for (Node p = t.first; p != null; p = p.next) {
2180 <                                p.val = null;
2181 <                                --delta;
2182 <                            }
2183 <                            t.first = null;
2184 <                            t.root = null;
2185 <                            ++i;
2186 <                        }
2187 <                    } finally {
2188 <                        t.release(0);
2189 <                    }
2190 <                }
2191 <                else
2192 <                    tab = (Node[])fk;
2193 <            }
2194 <            else if ((fh & LOCKED) != 0) {
2195 <                counter.add(delta); // opportunistically update count
2196 <                delta = 0L;
2197 <                f.tryAwaitLock(tab, i);
2198 <            }
2199 <            else if (f.casHash(fh, fh | LOCKED)) {
2200 <                try {
2201 <                    if (tabAt(tab, i) == f) {
2202 <                        for (Node e = f; e != null; e = e.next) {
2203 <                            e.val = null;
2204 <                            --delta;
2205 <                        }
2206 <                        setTabAt(tab, i, null);
2207 <                        ++i;
2208 <                    }
2209 <                } finally {
2210 <                    if (!f.casHash(fh | LOCKED, fh)) {
2211 <                        f.hash = fh;
2212 <                        synchronized (f) { f.notifyAll(); };
2213 <                    }
2214 <                }
2215 <            }
2216 <        }
2217 <        if (delta != 0)
2218 <            counter.add(delta);
2219 <    }
2220 <
2221 <    /* ----------------Table Traversal -------------- */
786 >    private transient volatile int cellsBusy;
787  
788      /**
789 <     * Encapsulates traversal for methods such as containsValue; also
790 <     * serves as a base class for other iterators.
791 <     *
2227 <     * At each step, the iterator snapshots the key ("nextKey") and
2228 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2229 <     * snapshot, has a non-null user value). Because val fields can
2230 <     * change (including to null, indicating deletion), field nextVal
2231 <     * might not be accurate at point of use, but still maintains the
2232 <     * weak consistency property of holding a value that was once
2233 <     * valid.
2234 <     *
2235 <     * Internal traversals directly access these fields, as in:
2236 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2237 <     *
2238 <     * Exported iterators must track whether the iterator has advanced
2239 <     * (in hasNext vs next) (by setting/checking/nulling field
2240 <     * nextVal), and then extract key, value, or key-value pairs as
2241 <     * return values of next().
2242 <     *
2243 <     * The iterator visits once each still-valid node that was
2244 <     * reachable upon iterator construction. It might miss some that
2245 <     * were added to a bin after the bin was visited, which is OK wrt
2246 <     * consistency guarantees. Maintaining this property in the face
2247 <     * of possible ongoing resizes requires a fair amount of
2248 <     * bookkeeping state that is difficult to optimize away amidst
2249 <     * volatile accesses.  Even so, traversal maintains reasonable
2250 <     * throughput.
2251 <     *
2252 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2253 <     * However, if the table has been resized, then all future steps
2254 <     * must traverse both the bin at the current index as well as at
2255 <     * (index + baseSize); and so on for further resizings. To
2256 <     * paranoically cope with potential sharing by users of iterators
2257 <     * across threads, iteration terminates if a bounds checks fails
2258 <     * for a table read.
2259 <     *
2260 <     * This class extends ForkJoinTask to streamline parallel
2261 <     * iteration in bulk operations (see BulkTask). This adds only an
2262 <     * int of space overhead, which is close enough to negligible in
2263 <     * cases where it is not needed to not worry about it.
2264 <     */
2265 <    static class Traverser<K,V,R> extends ForkJoinTask<R> {
2266 <        final ConcurrentHashMapV8<K, V> map;
2267 <        Node next;           // the next entry to use
2268 <        Node last;           // the last entry used
2269 <        Object nextKey;      // cached key field of next
2270 <        Object nextVal;      // cached val field of next
2271 <        Node[] tab;          // current table; updated if resized
2272 <        int index;           // index of bin to use next
2273 <        int baseIndex;       // current index of initial table
2274 <        int baseLimit;       // index bound for initial table
2275 <        final int baseSize;  // initial table size
2276 <
2277 <        /** Creates iterator for all entries in the table. */
2278 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2279 <            this.tab = (this.map = map).table;
2280 <            baseLimit = baseSize = (tab == null) ? 0 : tab.length;
2281 <        }
2282 <
2283 <        /** Creates iterator for split() methods */
2284 <        Traverser(Traverser<K,V,?> it, boolean split) {
2285 <            this.map = it.map;
2286 <            this.tab = it.tab;
2287 <            this.baseSize = it.baseSize;
2288 <            int lo = it.baseIndex;
2289 <            int hi = this.baseLimit = it.baseLimit;
2290 <            int i;
2291 <            if (split) // adjust parent
2292 <                i = it.baseLimit = (lo + hi + 1) >>> 1;
2293 <            else       // clone parent
2294 <                i = lo;
2295 <            this.index = this.baseIndex = i;
2296 <        }
2297 <
2298 <        /**
2299 <         * Advances next; returns nextVal or null if terminated.
2300 <         * See above for explanation.
2301 <         */
2302 <        final Object advance() {
2303 <            Node e = last = next;
2304 <            Object ev = null;
2305 <            outer: do {
2306 <                if (e != null)                  // advance past used/skipped node
2307 <                    e = e.next;
2308 <                while (e == null) {             // get to next non-null bin
2309 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2310 <                    if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
2311 <                        (t = tab) == null || i >= (n = t.length))
2312 <                        break outer;
2313 <                    else if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2314 <                        if ((ek = e.key) instanceof TreeBin)
2315 <                            e = ((TreeBin)ek).first;
2316 <                        else {
2317 <                            tab = (Node[])ek;
2318 <                            continue;           // restarts due to null val
2319 <                        }
2320 <                    }                           // visit upper slots if present
2321 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2322 <                }
2323 <                nextKey = e.key;
2324 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2325 <            next = e;
2326 <            return nextVal = ev;
2327 <        }
2328 <
2329 <        public final void remove() {
2330 <            if (nextVal == null)
2331 <                advance();
2332 <            Node e = last;
2333 <            if (e == null)
2334 <                throw new IllegalStateException();
2335 <            last = null;
2336 <            map.remove(e.key);
2337 <        }
789 >     * Table of counter cells. When non-null, size is a power of 2.
790 >     */
791 >    private transient volatile CounterCell[] counterCells;
792  
793 <        public final boolean hasNext() {
794 <            return nextVal != null || advance() != null;
795 <        }
793 >    // views
794 >    private transient KeySetView<K,V> keySet;
795 >    private transient ValuesView<K,V> values;
796 >    private transient EntrySetView<K,V> entrySet;
797  
2343        public final boolean hasMoreElements() { return hasNext(); }
2344        public final void setRawResult(Object x) { }
2345        public R getRawResult() { return null; }
2346        public boolean exec() { return true; }
2347    }
798  
799      /* ---------------- Public operations -------------- */
800  
# Line 2352 | Line 802 | public class ConcurrentHashMapV8<K, V>
802       * Creates a new, empty map with the default initial table size (16).
803       */
804      public ConcurrentHashMapV8() {
2355        this.counter = new LongAdder();
805      }
806  
807      /**
# Line 2371 | Line 820 | public class ConcurrentHashMapV8<K, V>
820          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
821                     MAXIMUM_CAPACITY :
822                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2374        this.counter = new LongAdder();
823          this.sizeCtl = cap;
824      }
825  
# Line 2381 | Line 829 | public class ConcurrentHashMapV8<K, V>
829       * @param m the map
830       */
831      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2384        this.counter = new LongAdder();
832          this.sizeCtl = DEFAULT_CAPACITY;
833 <        internalPutAll(m);
833 >        putAll(m);
834      }
835  
836      /**
# Line 2424 | Line 871 | public class ConcurrentHashMapV8<K, V>
871       * nonpositive
872       */
873      public ConcurrentHashMapV8(int initialCapacity,
874 <                               float loadFactor, int concurrencyLevel) {
874 >                             float loadFactor, int concurrencyLevel) {
875          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
876              throw new IllegalArgumentException();
877          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2432 | Line 879 | public class ConcurrentHashMapV8<K, V>
879          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
880          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
881              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2435        this.counter = new LongAdder();
882          this.sizeCtl = cap;
883      }
884  
885 <    /**
2440 <     * {@inheritDoc}
2441 <     */
2442 <    public boolean isEmpty() {
2443 <        return counter.sum() <= 0L; // ignore transient negative values
2444 <    }
885 >    // Original (since JDK1.2) Map methods
886  
887      /**
888       * {@inheritDoc}
889       */
890      public int size() {
891 <        long n = counter.sum();
891 >        long n = sumCount();
892          return ((n < 0L) ? 0 :
893                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
894                  (int)n);
895      }
896  
897      /**
898 <     * Returns the number of mappings. This method should be used
2458 <     * instead of {@link #size} because a ConcurrentHashMap may
2459 <     * contain more mappings than can be represented as an int. The
2460 <     * value returned is a snapshot; the actual count may differ if
2461 <     * there are ongoing concurrent insertions of removals.
2462 <     *
2463 <     * @return the number of mappings
898 >     * {@inheritDoc}
899       */
900 <    public long mappingCount() {
901 <        long n = counter.sum();
2467 <        return (n < 0L) ? 0L : n;
900 >    public boolean isEmpty() {
901 >        return sumCount() <= 0L; // ignore transient negative values
902      }
903  
904      /**
# Line 2478 | Line 912 | public class ConcurrentHashMapV8<K, V>
912       *
913       * @throws NullPointerException if the specified key is null
914       */
915 <    @SuppressWarnings("unchecked")
916 <        public V get(Object key) {
917 <        if (key == null)
918 <            throw new NullPointerException();
919 <        return (V)internalGet(key);
915 >    public V get(Object key) {
916 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
917 >        int h = spread(key.hashCode());
918 >        if ((tab = table) != null && (n = tab.length) > 0 &&
919 >            (e = tabAt(tab, (n - 1) & h)) != null) {
920 >            if ((eh = e.hash) == h) {
921 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
922 >                    return e.val;
923 >            }
924 >            else if (eh < 0)
925 >                return (p = e.find(h, key)) != null ? p.val : null;
926 >            while ((e = e.next) != null) {
927 >                if (e.hash == h &&
928 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
929 >                    return e.val;
930 >            }
931 >        }
932 >        return null;
933      }
934  
935      /**
936       * Tests if the specified object is a key in this table.
937       *
938 <     * @param  key   possible key
938 >     * @param  key possible key
939       * @return {@code true} if and only if the specified object
940       *         is a key in this table, as determined by the
941       *         {@code equals} method; {@code false} otherwise
942       * @throws NullPointerException if the specified key is null
943       */
944      public boolean containsKey(Object key) {
945 <        if (key == null)
2499 <            throw new NullPointerException();
2500 <        return internalGet(key) != null;
945 >        return get(key) != null;
946      }
947  
948      /**
# Line 2513 | Line 958 | public class ConcurrentHashMapV8<K, V>
958      public boolean containsValue(Object value) {
959          if (value == null)
960              throw new NullPointerException();
961 <        Object v;
962 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
963 <        while ((v = it.advance()) != null) {
964 <            if (v == value || value.equals(v))
965 <                return true;
961 >        Node<K,V>[] t;
962 >        if ((t = table) != null) {
963 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
964 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
965 >                V v;
966 >                if ((v = p.val) == value || (v != null && value.equals(v)))
967 >                    return true;
968 >            }
969          }
970          return false;
971      }
972  
973      /**
2526     * Legacy method testing if some key maps into the specified value
2527     * in this table.  This method is identical in functionality to
2528     * {@link #containsValue}, and exists solely to ensure
2529     * full compatibility with class {@link java.util.Hashtable},
2530     * which supported this method prior to introduction of the
2531     * Java Collections framework.
2532     *
2533     * @param  value a value to search for
2534     * @return {@code true} if and only if some key maps to the
2535     *         {@code value} argument in this table as
2536     *         determined by the {@code equals} method;
2537     *         {@code false} otherwise
2538     * @throws NullPointerException if the specified value is null
2539     */
2540    public boolean contains(Object value) {
2541        return containsValue(value);
2542    }
2543
2544    /**
974       * Maps the specified key to the specified value in this table.
975       * Neither the key nor the value can be null.
976       *
977 <     * <p> The value can be retrieved by calling the {@code get} method
977 >     * <p>The value can be retrieved by calling the {@code get} method
978       * with a key that is equal to the original key.
979       *
980       * @param key key with which the specified value is to be associated
# Line 2554 | Line 983 | public class ConcurrentHashMapV8<K, V>
983       *         {@code null} if there was no mapping for {@code key}
984       * @throws NullPointerException if the specified key or value is null
985       */
986 <    @SuppressWarnings("unchecked")
987 <        public V put(K key, V value) {
2559 <        if (key == null || value == null)
2560 <            throw new NullPointerException();
2561 <        return (V)internalPut(key, value);
986 >    public V put(K key, V value) {
987 >        return putVal(key, value, false);
988      }
989  
990 <    /**
991 <     * {@inheritDoc}
992 <     *
993 <     * @return the previous value associated with the specified key,
994 <     *         or {@code null} if there was no mapping for the key
995 <     * @throws NullPointerException if the specified key or value is null
996 <     */
997 <    @SuppressWarnings("unchecked")
998 <        public V putIfAbsent(K key, V value) {
999 <        if (key == null || value == null)
1000 <            throw new NullPointerException();
1001 <        return (V)internalPutIfAbsent(key, value);
990 >    /** Implementation for put and putIfAbsent */
991 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
992 >        if (key == null || value == null) throw new NullPointerException();
993 >        int hash = spread(key.hashCode());
994 >        int binCount = 0;
995 >        for (Node<K,V>[] tab = table;;) {
996 >            Node<K,V> f; int n, i, fh;
997 >            if (tab == null || (n = tab.length) == 0)
998 >                tab = initTable();
999 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1000 >                if (casTabAt(tab, i, null,
1001 >                             new Node<K,V>(hash, key, value, null)))
1002 >                    break;                   // no lock when adding to empty bin
1003 >            }
1004 >            else if ((fh = f.hash) == MOVED)
1005 >                tab = helpTransfer(tab, f);
1006 >            else {
1007 >                V oldVal = null;
1008 >                synchronized (f) {
1009 >                    if (tabAt(tab, i) == f) {
1010 >                        if (fh >= 0) {
1011 >                            binCount = 1;
1012 >                            for (Node<K,V> e = f;; ++binCount) {
1013 >                                K ek;
1014 >                                if (e.hash == hash &&
1015 >                                    ((ek = e.key) == key ||
1016 >                                     (ek != null && key.equals(ek)))) {
1017 >                                    oldVal = e.val;
1018 >                                    if (!onlyIfAbsent)
1019 >                                        e.val = value;
1020 >                                    break;
1021 >                                }
1022 >                                Node<K,V> pred = e;
1023 >                                if ((e = e.next) == null) {
1024 >                                    pred.next = new Node<K,V>(hash, key,
1025 >                                                              value, null);
1026 >                                    break;
1027 >                                }
1028 >                            }
1029 >                        }
1030 >                        else if (f instanceof TreeBin) {
1031 >                            Node<K,V> p;
1032 >                            binCount = 2;
1033 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1034 >                                                           value)) != null) {
1035 >                                oldVal = p.val;
1036 >                                if (!onlyIfAbsent)
1037 >                                    p.val = value;
1038 >                            }
1039 >                        }
1040 >                    }
1041 >                }
1042 >                if (binCount != 0) {
1043 >                    if (binCount >= TREEIFY_THRESHOLD)
1044 >                        treeifyBin(tab, i);
1045 >                    if (oldVal != null)
1046 >                        return oldVal;
1047 >                    break;
1048 >                }
1049 >            }
1050 >        }
1051 >        addCount(1L, binCount);
1052 >        return null;
1053      }
1054  
1055      /**
# Line 2583 | Line 1060 | public class ConcurrentHashMapV8<K, V>
1060       * @param m mappings to be stored in this map
1061       */
1062      public void putAll(Map<? extends K, ? extends V> m) {
1063 <        internalPutAll(m);
1064 <    }
1065 <
2589 <    /**
2590 <     * If the specified key is not already associated with a value,
2591 <     * computes its value using the given mappingFunction and enters
2592 <     * it into the map unless null.  This is equivalent to
2593 <     * <pre> {@code
2594 <     * if (map.containsKey(key))
2595 <     *   return map.get(key);
2596 <     * value = mappingFunction.apply(key);
2597 <     * if (value != null)
2598 <     *   map.put(key, value);
2599 <     * return value;}</pre>
2600 <     *
2601 <     * except that the action is performed atomically.  If the
2602 <     * function returns {@code null} no mapping is recorded. If the
2603 <     * function itself throws an (unchecked) exception, the exception
2604 <     * is rethrown to its caller, and no mapping is recorded.  Some
2605 <     * attempted update operations on this map by other threads may be
2606 <     * blocked while computation is in progress, so the computation
2607 <     * should be short and simple, and must not attempt to update any
2608 <     * other mappings of this Map. The most appropriate usage is to
2609 <     * construct a new object serving as an initial mapped value, or
2610 <     * memoized result, as in:
2611 <     *
2612 <     *  <pre> {@code
2613 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2614 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2615 <     *
2616 <     * @param key key with which the specified value is to be associated
2617 <     * @param mappingFunction the function to compute a value
2618 <     * @return the current (existing or computed) value associated with
2619 <     *         the specified key, or null if the computed value is null.
2620 <     * @throws NullPointerException if the specified key or mappingFunction
2621 <     *         is null
2622 <     * @throws IllegalStateException if the computation detectably
2623 <     *         attempts a recursive update to this map that would
2624 <     *         otherwise never complete
2625 <     * @throws RuntimeException or Error if the mappingFunction does so,
2626 <     *         in which case the mapping is left unestablished
2627 <     */
2628 <    @SuppressWarnings("unchecked")
2629 <        public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
2630 <        if (key == null || mappingFunction == null)
2631 <            throw new NullPointerException();
2632 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2633 <    }
2634 <
2635 <    /**
2636 <     * If the given key is present, computes a new mapping value given a key and
2637 <     * its current mapped value. This is equivalent to
2638 <     *  <pre> {@code
2639 <     *   if (map.containsKey(key)) {
2640 <     *     value = remappingFunction.apply(key, map.get(key));
2641 <     *     if (value != null)
2642 <     *       map.put(key, value);
2643 <     *     else
2644 <     *       map.remove(key);
2645 <     *   }
2646 <     * }</pre>
2647 <     *
2648 <     * except that the action is performed atomically.  If the
2649 <     * function returns {@code null}, the mapping is removed.  If the
2650 <     * function itself throws an (unchecked) exception, the exception
2651 <     * is rethrown to its caller, and the current mapping is left
2652 <     * unchanged.  Some attempted update operations on this map by
2653 <     * other threads may be blocked while computation is in progress,
2654 <     * so the computation should be short and simple, and must not
2655 <     * attempt to update any other mappings of this Map. For example,
2656 <     * to either create or append new messages to a value mapping:
2657 <     *
2658 <     * @param key key with which the specified value is to be associated
2659 <     * @param remappingFunction the function to compute a value
2660 <     * @return the new value associated with
2661 <     *         the specified key, or null if none.
2662 <     * @throws NullPointerException if the specified key or remappingFunction
2663 <     *         is null
2664 <     * @throws IllegalStateException if the computation detectably
2665 <     *         attempts a recursive update to this map that would
2666 <     *         otherwise never complete
2667 <     * @throws RuntimeException or Error if the remappingFunction does so,
2668 <     *         in which case the mapping is unchanged
2669 <     */
2670 <    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2671 <        if (key == null || remappingFunction == null)
2672 <            throw new NullPointerException();
2673 <        return (V)internalCompute(key, true, remappingFunction);
2674 <    }
2675 <
2676 <    /**
2677 <     * Computes a new mapping value given a key and
2678 <     * its current mapped value (or {@code null} if there is no current
2679 <     * mapping). This is equivalent to
2680 <     *  <pre> {@code
2681 <     *   value = remappingFunction.apply(key, map.get(key));
2682 <     *   if (value != null)
2683 <     *     map.put(key, value);
2684 <     *   else
2685 <     *     map.remove(key);
2686 <     * }</pre>
2687 <     *
2688 <     * except that the action is performed atomically.  If the
2689 <     * function returns {@code null}, the mapping is removed.  If the
2690 <     * function itself throws an (unchecked) exception, the exception
2691 <     * is rethrown to its caller, and the current mapping is left
2692 <     * unchanged.  Some attempted update operations on this map by
2693 <     * other threads may be blocked while computation is in progress,
2694 <     * so the computation should be short and simple, and must not
2695 <     * attempt to update any other mappings of this Map. For example,
2696 <     * to either create or append new messages to a value mapping:
2697 <     *
2698 <     * <pre> {@code
2699 <     * Map<Key, String> map = ...;
2700 <     * final String msg = ...;
2701 <     * map.compute(key, new BiFun<Key, String, String>() {
2702 <     *   public String apply(Key k, String v) {
2703 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2704 <     *
2705 <     * @param key key with which the specified value is to be associated
2706 <     * @param remappingFunction the function to compute a value
2707 <     * @return the new value associated with
2708 <     *         the specified key, or null if none.
2709 <     * @throws NullPointerException if the specified key or remappingFunction
2710 <     *         is null
2711 <     * @throws IllegalStateException if the computation detectably
2712 <     *         attempts a recursive update to this map that would
2713 <     *         otherwise never complete
2714 <     * @throws RuntimeException or Error if the remappingFunction does so,
2715 <     *         in which case the mapping is unchanged
2716 <     */
2717 <    //    @SuppressWarnings("unchecked")
2718 <    public V compute(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2719 <        if (key == null || remappingFunction == null)
2720 <            throw new NullPointerException();
2721 <        return (V)internalCompute(key, false, remappingFunction);
2722 <    }
2723 <
2724 <    /**
2725 <     * If the specified key is not already associated
2726 <     * with a value, associate it with the given value.
2727 <     * Otherwise, replace the value with the results of
2728 <     * the given remapping function. This is equivalent to:
2729 <     *  <pre> {@code
2730 <     *   if (!map.containsKey(key))
2731 <     *     map.put(value);
2732 <     *   else {
2733 <     *     newValue = remappingFunction.apply(map.get(key), value);
2734 <     *     if (value != null)
2735 <     *       map.put(key, value);
2736 <     *     else
2737 <     *       map.remove(key);
2738 <     *   }
2739 <     * }</pre>
2740 <     * except that the action is performed atomically.  If the
2741 <     * function returns {@code null}, the mapping is removed.  If the
2742 <     * function itself throws an (unchecked) exception, the exception
2743 <     * is rethrown to its caller, and the current mapping is left
2744 <     * unchanged.  Some attempted update operations on this map by
2745 <     * other threads may be blocked while computation is in progress,
2746 <     * so the computation should be short and simple, and must not
2747 <     * attempt to update any other mappings of this Map.
2748 <     */
2749 <    //    @SuppressWarnings("unchecked")
2750 <    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2751 <        if (key == null || value == null || remappingFunction == null)
2752 <            throw new NullPointerException();
2753 <        return (V)internalMerge(key, value, remappingFunction);
1063 >        tryPresize(m.size());
1064 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1065 >            putVal(e.getKey(), e.getValue(), false);
1066      }
1067  
1068      /**
# Line 2762 | Line 1074 | public class ConcurrentHashMapV8<K, V>
1074       *         {@code null} if there was no mapping for {@code key}
1075       * @throws NullPointerException if the specified key is null
1076       */
1077 <    @SuppressWarnings("unchecked")
1078 <        public V remove(Object key) {
2767 <        if (key == null)
2768 <            throw new NullPointerException();
2769 <        return (V)internalReplace(key, null, null);
1077 >    public V remove(Object key) {
1078 >        return replaceNode(key, null, null);
1079      }
1080  
1081      /**
1082 <     * {@inheritDoc}
1083 <     *
1084 <     * @throws NullPointerException if the specified key is null
2776 <     */
2777 <    public boolean remove(Object key, Object value) {
2778 <        if (key == null)
2779 <            throw new NullPointerException();
2780 <        if (value == null)
2781 <            return false;
2782 <        return internalReplace(key, null, value) != null;
2783 <    }
2784 <
2785 <    /**
2786 <     * {@inheritDoc}
2787 <     *
2788 <     * @throws NullPointerException if any of the arguments are null
2789 <     */
2790 <    public boolean replace(K key, V oldValue, V newValue) {
2791 <        if (key == null || oldValue == null || newValue == null)
2792 <            throw new NullPointerException();
2793 <        return internalReplace(key, newValue, oldValue) != null;
2794 <    }
2795 <
2796 <    /**
2797 <     * {@inheritDoc}
2798 <     *
2799 <     * @return the previous value associated with the specified key,
2800 <     *         or {@code null} if there was no mapping for the key
2801 <     * @throws NullPointerException if the specified key or value is null
1082 >     * Implementation for the four public remove/replace methods:
1083 >     * Replaces node value with v, conditional upon match of cv if
1084 >     * non-null.  If resulting value is null, delete.
1085       */
1086 <    @SuppressWarnings("unchecked")
1087 <        public V replace(K key, V value) {
1088 <        if (key == null || value == null)
1089 <            throw new NullPointerException();
1090 <        return (V)internalReplace(key, value, null);
1086 >    final V replaceNode(Object key, V value, Object cv) {
1087 >        int hash = spread(key.hashCode());
1088 >        for (Node<K,V>[] tab = table;;) {
1089 >            Node<K,V> f; int n, i, fh;
1090 >            if (tab == null || (n = tab.length) == 0 ||
1091 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1092 >                break;
1093 >            else if ((fh = f.hash) == MOVED)
1094 >                tab = helpTransfer(tab, f);
1095 >            else {
1096 >                V oldVal = null;
1097 >                boolean validated = false;
1098 >                synchronized (f) {
1099 >                    if (tabAt(tab, i) == f) {
1100 >                        if (fh >= 0) {
1101 >                            validated = true;
1102 >                            for (Node<K,V> e = f, pred = null;;) {
1103 >                                K ek;
1104 >                                if (e.hash == hash &&
1105 >                                    ((ek = e.key) == key ||
1106 >                                     (ek != null && key.equals(ek)))) {
1107 >                                    V ev = e.val;
1108 >                                    if (cv == null || cv == ev ||
1109 >                                        (ev != null && cv.equals(ev))) {
1110 >                                        oldVal = ev;
1111 >                                        if (value != null)
1112 >                                            e.val = value;
1113 >                                        else if (pred != null)
1114 >                                            pred.next = e.next;
1115 >                                        else
1116 >                                            setTabAt(tab, i, e.next);
1117 >                                    }
1118 >                                    break;
1119 >                                }
1120 >                                pred = e;
1121 >                                if ((e = e.next) == null)
1122 >                                    break;
1123 >                            }
1124 >                        }
1125 >                        else if (f instanceof TreeBin) {
1126 >                            validated = true;
1127 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1128 >                            TreeNode<K,V> r, p;
1129 >                            if ((r = t.root) != null &&
1130 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1131 >                                V pv = p.val;
1132 >                                if (cv == null || cv == pv ||
1133 >                                    (pv != null && cv.equals(pv))) {
1134 >                                    oldVal = pv;
1135 >                                    if (value != null)
1136 >                                        p.val = value;
1137 >                                    else if (t.removeTreeNode(p))
1138 >                                        setTabAt(tab, i, untreeify(t.first));
1139 >                                }
1140 >                            }
1141 >                        }
1142 >                    }
1143 >                }
1144 >                if (validated) {
1145 >                    if (oldVal != null) {
1146 >                        if (value == null)
1147 >                            addCount(-1L, -1);
1148 >                        return oldVal;
1149 >                    }
1150 >                    break;
1151 >                }
1152 >            }
1153 >        }
1154 >        return null;
1155      }
1156  
1157      /**
1158       * Removes all of the mappings from this map.
1159       */
1160      public void clear() {
1161 <        internalClear();
1161 >        long delta = 0L; // negative number of deletions
1162 >        int i = 0;
1163 >        Node<K,V>[] tab = table;
1164 >        while (tab != null && i < tab.length) {
1165 >            int fh;
1166 >            Node<K,V> f = tabAt(tab, i);
1167 >            if (f == null)
1168 >                ++i;
1169 >            else if ((fh = f.hash) == MOVED) {
1170 >                tab = helpTransfer(tab, f);
1171 >                i = 0; // restart
1172 >            }
1173 >            else {
1174 >                synchronized (f) {
1175 >                    if (tabAt(tab, i) == f) {
1176 >                        Node<K,V> p = (fh >= 0 ? f :
1177 >                                       (f instanceof TreeBin) ?
1178 >                                       ((TreeBin<K,V>)f).first : null);
1179 >                        while (p != null) {
1180 >                            --delta;
1181 >                            p = p.next;
1182 >                        }
1183 >                        setTabAt(tab, i++, null);
1184 >                    }
1185 >                }
1186 >            }
1187 >        }
1188 >        if (delta != 0L)
1189 >            addCount(delta, -1);
1190      }
1191  
1192      /**
1193       * Returns a {@link Set} view of the keys contained in this map.
1194       * The set is backed by the map, so changes to the map are
1195 <     * reflected in the set, and vice-versa.  The set supports element
1195 >     * reflected in the set, and vice-versa. The set supports element
1196       * removal, which removes the corresponding mapping from this map,
1197       * via the {@code Iterator.remove}, {@code Set.remove},
1198       * {@code removeAll}, {@code retainAll}, and {@code clear}
# Line 2829 | Line 1204 | public class ConcurrentHashMapV8<K, V>
1204       * and guarantees to traverse elements as they existed upon
1205       * construction of the iterator, and may (but is not guaranteed to)
1206       * reflect any modifications subsequent to construction.
1207 +     *
1208 +     * @return the set view
1209       */
1210 <    public Set<K> keySet() {
1211 <        KeySet<K,V> ks = keySet;
1212 <        return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
1210 >    public KeySetView<K,V> keySet() {
1211 >        KeySetView<K,V> ks;
1212 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1213      }
1214  
1215      /**
# Line 2850 | Line 1227 | public class ConcurrentHashMapV8<K, V>
1227       * and guarantees to traverse elements as they existed upon
1228       * construction of the iterator, and may (but is not guaranteed to)
1229       * reflect any modifications subsequent to construction.
1230 +     *
1231 +     * @return the collection view
1232       */
1233      public Collection<V> values() {
1234 <        Values<K,V> vs = values;
1235 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
1234 >        ValuesView<K,V> vs;
1235 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1236      }
1237  
1238      /**
# Line 2863 | Line 1242 | public class ConcurrentHashMapV8<K, V>
1242       * removal, which removes the corresponding mapping from the map,
1243       * via the {@code Iterator.remove}, {@code Set.remove},
1244       * {@code removeAll}, {@code retainAll}, and {@code clear}
1245 <     * operations.  It does not support the {@code add} or
2867 <     * {@code addAll} operations.
1245 >     * operations.
1246       *
1247       * <p>The view's {@code iterator} is a "weakly consistent" iterator
1248       * that will never throw {@link ConcurrentModificationException},
1249       * and guarantees to traverse elements as they existed upon
1250       * construction of the iterator, and may (but is not guaranteed to)
1251       * reflect any modifications subsequent to construction.
2874     */
2875    public Set<Map.Entry<K,V>> entrySet() {
2876        EntrySet<K,V> es = entrySet;
2877        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2878    }
2879
2880    /**
2881     * Returns an enumeration of the keys in this table.
1252       *
1253 <     * @return an enumeration of the keys in this table
2884 <     * @see #keySet()
1253 >     * @return the set view
1254       */
1255 <    public Enumeration<K> keys() {
1256 <        return new KeyIterator<K,V>(this);
1257 <    }
2889 <
2890 <    /**
2891 <     * Returns an enumeration of the values in this table.
2892 <     *
2893 <     * @return an enumeration of the values in this table
2894 <     * @see #values()
2895 <     */
2896 <    public Enumeration<V> elements() {
2897 <        return new ValueIterator<K,V>(this);
2898 <    }
2899 <
2900 <    /**
2901 <     * Returns a partionable iterator of the keys in this map.
2902 <     *
2903 <     * @return a partionable iterator of the keys in this map
2904 <     */
2905 <    public Spliterator<K> keySpliterator() {
2906 <        return new KeyIterator<K,V>(this);
2907 <    }
2908 <
2909 <    /**
2910 <     * Returns a partionable iterator of the values in this map.
2911 <     *
2912 <     * @return a partionable iterator of the values in this map
2913 <     */
2914 <    public Spliterator<V> valueSpliterator() {
2915 <        return new ValueIterator<K,V>(this);
2916 <    }
2917 <
2918 <    /**
2919 <     * Returns a partionable iterator of the entries in this map.
2920 <     *
2921 <     * @return a partionable iterator of the entries in this map
2922 <     */
2923 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2924 <        return new EntryIterator<K,V>(this);
1255 >    public Set<Map.Entry<K,V>> entrySet() {
1256 >        EntrySetView<K,V> es;
1257 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1258      }
1259  
1260      /**
# Line 2933 | Line 1266 | public class ConcurrentHashMapV8<K, V>
1266       */
1267      public int hashCode() {
1268          int h = 0;
1269 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1270 <        Object v;
1271 <        while ((v = it.advance()) != null) {
1272 <            h += it.nextKey.hashCode() ^ v.hashCode();
1269 >        Node<K,V>[] t;
1270 >        if ((t = table) != null) {
1271 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1272 >            for (Node<K,V> p; (p = it.advance()) != null; )
1273 >                h += p.key.hashCode() ^ p.val.hashCode();
1274          }
1275          return h;
1276      }
# Line 2953 | Line 1287 | public class ConcurrentHashMapV8<K, V>
1287       * @return a string representation of this map
1288       */
1289      public String toString() {
1290 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1290 >        Node<K,V>[] t;
1291 >        int f = (t = table) == null ? 0 : t.length;
1292 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1293          StringBuilder sb = new StringBuilder();
1294          sb.append('{');
1295 <        Object v;
1296 <        if ((v = it.advance()) != null) {
1295 >        Node<K,V> p;
1296 >        if ((p = it.advance()) != null) {
1297              for (;;) {
1298 <                Object k = it.nextKey;
1298 >                K k = p.key;
1299 >                V v = p.val;
1300                  sb.append(k == this ? "(this Map)" : k);
1301                  sb.append('=');
1302                  sb.append(v == this ? "(this Map)" : v);
1303 <                if ((v = it.advance()) == null)
1303 >                if ((p = it.advance()) == null)
1304                      break;
1305                  sb.append(',').append(' ');
1306              }
# Line 2986 | Line 1323 | public class ConcurrentHashMapV8<K, V>
1323              if (!(o instanceof Map))
1324                  return false;
1325              Map<?,?> m = (Map<?,?>) o;
1326 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1327 <            Object val;
1328 <            while ((val = it.advance()) != null) {
1329 <                Object v = m.get(it.nextKey);
1326 >            Node<K,V>[] t;
1327 >            int f = (t = table) == null ? 0 : t.length;
1328 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1329 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1330 >                V val = p.val;
1331 >                Object v = m.get(p.key);
1332                  if (v == null || (v != val && !v.equals(val)))
1333                      return false;
1334              }
# Line 2997 | Line 1336 | public class ConcurrentHashMapV8<K, V>
1336                  Object mk, mv, v;
1337                  if ((mk = e.getKey()) == null ||
1338                      (mv = e.getValue()) == null ||
1339 <                    (v = internalGet(mk)) == null ||
1339 >                    (v = get(mk)) == null ||
1340                      (mv != v && !mv.equals(v)))
1341                      return false;
1342              }
# Line 3005 | Line 1344 | public class ConcurrentHashMapV8<K, V>
1344          return true;
1345      }
1346  
1347 <    /* ----------------Iterators -------------- */
1347 >    /**
1348 >     * Stripped-down version of helper class used in previous version,
1349 >     * declared for the sake of serialization compatibility
1350 >     */
1351 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1352 >        private static final long serialVersionUID = 2249069246763182397L;
1353 >        final float loadFactor;
1354 >        Segment(float lf) { this.loadFactor = lf; }
1355 >    }
1356  
1357 <    static final class KeyIterator<K,V> extends Traverser<K,V,Object>
1358 <        implements Spliterator<K>, Enumeration<K> {
1359 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1360 <        KeyIterator(Traverser<K,V,Object> it, boolean split) {
1361 <            super(it, split);
1362 <        }
1363 <        public KeyIterator<K,V> split() {
1364 <            if (last != null || (next != null && nextVal == null))
1365 <                throw new IllegalStateException();
1366 <            return new KeyIterator<K,V>(this, true);
1367 <        }
1368 <        @SuppressWarnings("unchecked")
1369 <            public final K next() {
1370 <            if (nextVal == null && advance() == null)
1371 <                throw new NoSuchElementException();
1372 <            Object k = nextKey;
1373 <            nextVal = null;
1374 <            return (K) k;
1357 >    /**
1358 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1359 >     * stream (i.e., serializes it).
1360 >     * @param s the stream
1361 >     * @serialData
1362 >     * the key (Object) and value (Object)
1363 >     * for each key-value mapping, followed by a null pair.
1364 >     * The key-value mappings are emitted in no particular order.
1365 >     */
1366 >    private void writeObject(java.io.ObjectOutputStream s)
1367 >        throws java.io.IOException {
1368 >        // For serialization compatibility
1369 >        // Emulate segment calculation from previous version of this class
1370 >        int sshift = 0;
1371 >        int ssize = 1;
1372 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1373 >            ++sshift;
1374 >            ssize <<= 1;
1375 >        }
1376 >        int segmentShift = 32 - sshift;
1377 >        int segmentMask = ssize - 1;
1378 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1379 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1380 >        for (int i = 0; i < segments.length; ++i)
1381 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1382 >        s.putFields().put("segments", segments);
1383 >        s.putFields().put("segmentShift", segmentShift);
1384 >        s.putFields().put("segmentMask", segmentMask);
1385 >        s.writeFields();
1386 >
1387 >        Node<K,V>[] t;
1388 >        if ((t = table) != null) {
1389 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1390 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1391 >                s.writeObject(p.key);
1392 >                s.writeObject(p.val);
1393 >            }
1394          }
1395 <
1396 <        public final K nextElement() { return next(); }
1395 >        s.writeObject(null);
1396 >        s.writeObject(null);
1397 >        segments = null; // throw away
1398      }
1399  
1400 <    static final class ValueIterator<K,V> extends Traverser<K,V,Object>
1401 <        implements Spliterator<V>, Enumeration<V> {
1402 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1403 <        ValueIterator(Traverser<K,V,Object> it, boolean split) {
1404 <            super(it, split);
1405 <        }
1406 <        public ValueIterator<K,V> split() {
1407 <            if (last != null || (next != null && nextVal == null))
1408 <                throw new IllegalStateException();
1409 <            return new ValueIterator<K,V>(this, true);
1400 >    /**
1401 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1402 >     * @param s the stream
1403 >     */
1404 >    private void readObject(java.io.ObjectInputStream s)
1405 >        throws java.io.IOException, ClassNotFoundException {
1406 >        /*
1407 >         * To improve performance in typical cases, we create nodes
1408 >         * while reading, then place in table once size is known.
1409 >         * However, we must also validate uniqueness and deal with
1410 >         * overpopulated bins while doing so, which requires
1411 >         * specialized versions of putVal mechanics.
1412 >         */
1413 >        sizeCtl = -1; // force exclusion for table construction
1414 >        s.defaultReadObject();
1415 >        long size = 0L;
1416 >        Node<K,V> p = null;
1417 >        for (;;) {
1418 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1419 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1420 >            if (k != null && v != null) {
1421 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1422 >                ++size;
1423 >            }
1424 >            else
1425 >                break;
1426          }
1427 <
1428 <        @SuppressWarnings("unchecked")
1429 <            public final V next() {
1430 <            Object v;
1431 <            if ((v = nextVal) == null && (v = advance()) == null)
1432 <                throw new NoSuchElementException();
1433 <            nextVal = null;
1434 <            return (V) v;
1427 >        if (size == 0L)
1428 >            sizeCtl = 0;
1429 >        else {
1430 >            int n;
1431 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1432 >                n = MAXIMUM_CAPACITY;
1433 >            else {
1434 >                int sz = (int)size;
1435 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1436 >            }
1437 >            @SuppressWarnings({"rawtypes","unchecked"})
1438 >                Node<K,V>[] tab = (Node<K,V>[])new Node[n];
1439 >            int mask = n - 1;
1440 >            long added = 0L;
1441 >            while (p != null) {
1442 >                boolean insertAtFront;
1443 >                Node<K,V> next = p.next, first;
1444 >                int h = p.hash, j = h & mask;
1445 >                if ((first = tabAt(tab, j)) == null)
1446 >                    insertAtFront = true;
1447 >                else {
1448 >                    K k = p.key;
1449 >                    if (first.hash < 0) {
1450 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1451 >                        if (t.putTreeVal(h, k, p.val) == null)
1452 >                            ++added;
1453 >                        insertAtFront = false;
1454 >                    }
1455 >                    else {
1456 >                        int binCount = 0;
1457 >                        insertAtFront = true;
1458 >                        Node<K,V> q; K qk;
1459 >                        for (q = first; q != null; q = q.next) {
1460 >                            if (q.hash == h &&
1461 >                                ((qk = q.key) == k ||
1462 >                                 (qk != null && k.equals(qk)))) {
1463 >                                insertAtFront = false;
1464 >                                break;
1465 >                            }
1466 >                            ++binCount;
1467 >                        }
1468 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1469 >                            insertAtFront = false;
1470 >                            ++added;
1471 >                            p.next = first;
1472 >                            TreeNode<K,V> hd = null, tl = null;
1473 >                            for (q = p; q != null; q = q.next) {
1474 >                                TreeNode<K,V> t = new TreeNode<K,V>
1475 >                                    (q.hash, q.key, q.val, null, null);
1476 >                                if ((t.prev = tl) == null)
1477 >                                    hd = t;
1478 >                                else
1479 >                                    tl.next = t;
1480 >                                tl = t;
1481 >                            }
1482 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1483 >                        }
1484 >                    }
1485 >                }
1486 >                if (insertAtFront) {
1487 >                    ++added;
1488 >                    p.next = first;
1489 >                    setTabAt(tab, j, p);
1490 >                }
1491 >                p = next;
1492 >            }
1493 >            table = tab;
1494 >            sizeCtl = n - (n >>> 2);
1495 >            baseCount = added;
1496          }
3053
3054        public final V nextElement() { return next(); }
1497      }
1498  
1499 <    static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3058 <        implements Spliterator<Map.Entry<K,V>> {
3059 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3060 <        EntryIterator(Traverser<K,V,Object> it, boolean split) {
3061 <            super(it, split);
3062 <        }
3063 <        public EntryIterator<K,V> split() {
3064 <            if (last != null || (next != null && nextVal == null))
3065 <                throw new IllegalStateException();
3066 <            return new EntryIterator<K,V>(this, true);
3067 <        }
1499 >    // ConcurrentMap methods
1500  
1501 <        @SuppressWarnings("unchecked")
1502 <            public final Map.Entry<K,V> next() {
1503 <            Object v;
1504 <            if ((v = nextVal) == null && (v = advance()) == null)
1505 <                throw new NoSuchElementException();
1506 <            Object k = nextKey;
1507 <            nextVal = null;
1508 <            return new MapEntry<K,V>((K)k, (V)v, map);
1509 <        }
1501 >    /**
1502 >     * {@inheritDoc}
1503 >     *
1504 >     * @return the previous value associated with the specified key,
1505 >     *         or {@code null} if there was no mapping for the key
1506 >     * @throws NullPointerException if the specified key or value is null
1507 >     */
1508 >    public V putIfAbsent(K key, V value) {
1509 >        return putVal(key, value, true);
1510      }
1511  
1512      /**
1513 <     * Exported Entry for iterators
1513 >     * {@inheritDoc}
1514 >     *
1515 >     * @throws NullPointerException if the specified key is null
1516       */
1517 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
1518 <        final K key; // non-null
1519 <        V val;       // non-null
1520 <        final ConcurrentHashMapV8<K, V> map;
3087 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3088 <            this.key = key;
3089 <            this.val = val;
3090 <            this.map = map;
3091 <        }
3092 <        public final K getKey()       { return key; }
3093 <        public final V getValue()     { return val; }
3094 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3095 <        public final String toString(){ return key + "=" + val; }
3096 <
3097 <        public final boolean equals(Object o) {
3098 <            Object k, v; Map.Entry<?,?> e;
3099 <            return ((o instanceof Map.Entry) &&
3100 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3101 <                    (v = e.getValue()) != null &&
3102 <                    (k == key || k.equals(key)) &&
3103 <                    (v == val || v.equals(val)));
3104 <        }
3105 <
3106 <        /**
3107 <         * Sets our entry's value and writes through to the map. The
3108 <         * value to return is somewhat arbitrary here. Since we do not
3109 <         * necessarily track asynchronous changes, the most recent
3110 <         * "previous" value could be different from what we return (or
3111 <         * could even have been removed in which case the put will
3112 <         * re-establish). We do not and cannot guarantee more.
3113 <         */
3114 <        public final V setValue(V value) {
3115 <            if (value == null) throw new NullPointerException();
3116 <            V v = val;
3117 <            val = value;
3118 <            map.put(key, value);
3119 <            return v;
3120 <        }
1517 >    public boolean remove(Object key, Object value) {
1518 >        if (key == null)
1519 >            throw new NullPointerException();
1520 >        return value != null && replaceNode(key, null, value) != null;
1521      }
1522  
1523 <    /* ----------------Views -------------- */
1523 >    /**
1524 >     * {@inheritDoc}
1525 >     *
1526 >     * @throws NullPointerException if any of the arguments are null
1527 >     */
1528 >    public boolean replace(K key, V oldValue, V newValue) {
1529 >        if (key == null || oldValue == null || newValue == null)
1530 >            throw new NullPointerException();
1531 >        return replaceNode(key, newValue, oldValue) != null;
1532 >    }
1533  
1534      /**
1535 <     * Base class for views.
1535 >     * {@inheritDoc}
1536 >     *
1537 >     * @return the previous value associated with the specified key,
1538 >     *         or {@code null} if there was no mapping for the key
1539 >     * @throws NullPointerException if the specified key or value is null
1540       */
1541 <    static abstract class CHMView<K, V> {
1542 <        final ConcurrentHashMapV8<K, V> map;
1543 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
1544 <        public final int size()                 { return map.size(); }
1545 <        public final boolean isEmpty()          { return map.isEmpty(); }
3133 <        public final void clear()               { map.clear(); }
1541 >    public V replace(K key, V value) {
1542 >        if (key == null || value == null)
1543 >            throw new NullPointerException();
1544 >        return replaceNode(key, value, null);
1545 >    }
1546  
1547 <        // implementations below rely on concrete classes supplying these
3136 <        abstract public Iterator<?> iterator();
3137 <        abstract public boolean contains(Object o);
3138 <        abstract public boolean remove(Object o);
1547 >    // Overrides of JDK8+ Map extension method defaults
1548  
1549 <        private static final String oomeMsg = "Required array size too large";
1549 >    /**
1550 >     * Returns the value to which the specified key is mapped, or the
1551 >     * given default value if this map contains no mapping for the
1552 >     * key.
1553 >     *
1554 >     * @param key the key whose associated value is to be returned
1555 >     * @param defaultValue the value to return if this map contains
1556 >     * no mapping for the given key
1557 >     * @return the mapping for the key, if present; else the default value
1558 >     * @throws NullPointerException if the specified key is null
1559 >     */
1560 >    public V getOrDefault(Object key, V defaultValue) {
1561 >        V v;
1562 >        return (v = get(key)) == null ? defaultValue : v;
1563 >    }
1564 >
1565 >    public void forEach(BiAction<? super K, ? super V> action) {
1566 >        if (action == null) throw new NullPointerException();
1567 >        Node<K,V>[] t;
1568 >        if ((t = table) != null) {
1569 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1570 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1571 >                action.apply(p.key, p.val);
1572 >            }
1573 >        }
1574 >    }
1575  
1576 <        public final Object[] toArray() {
1577 <            long sz = map.mappingCount();
1578 <            if (sz > (long)(MAX_ARRAY_SIZE))
1579 <                throw new OutOfMemoryError(oomeMsg);
1580 <            int n = (int)sz;
1581 <            Object[] r = new Object[n];
1582 <            int i = 0;
1583 <            Iterator<?> it = iterator();
1584 <            while (it.hasNext()) {
1585 <                if (i == n) {
1586 <                    if (n >= MAX_ARRAY_SIZE)
1587 <                        throw new OutOfMemoryError(oomeMsg);
1588 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1589 <                        n = MAX_ARRAY_SIZE;
3156 <                    else
3157 <                        n += (n >>> 1) + 1;
3158 <                    r = Arrays.copyOf(r, n);
1576 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1577 >        if (function == null) throw new NullPointerException();
1578 >        Node<K,V>[] t;
1579 >        if ((t = table) != null) {
1580 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1581 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1582 >                V oldValue = p.val;
1583 >                for (K key = p.key;;) {
1584 >                    V newValue = function.apply(key, oldValue);
1585 >                    if (newValue == null)
1586 >                        throw new NullPointerException();
1587 >                    if (replaceNode(key, newValue, oldValue) != null ||
1588 >                        (oldValue = get(key)) == null)
1589 >                        break;
1590                  }
3160                r[i++] = it.next();
1591              }
3162            return (i == n) ? r : Arrays.copyOf(r, i);
1592          }
1593 +    }
1594  
1595 <        @SuppressWarnings("unchecked")
1596 <            public final <T> T[] toArray(T[] a) {
1597 <            long sz = map.mappingCount();
1598 <            if (sz > (long)(MAX_ARRAY_SIZE))
1599 <                throw new OutOfMemoryError(oomeMsg);
1600 <            int m = (int)sz;
1601 <            T[] r = (a.length >= m) ? a :
1602 <                (T[])java.lang.reflect.Array
1603 <                .newInstance(a.getClass().getComponentType(), m);
1604 <            int n = r.length;
1605 <            int i = 0;
1606 <            Iterator<?> it = iterator();
1607 <            while (it.hasNext()) {
1608 <                if (i == n) {
1609 <                    if (n >= MAX_ARRAY_SIZE)
1610 <                        throw new OutOfMemoryError(oomeMsg);
1611 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1612 <                        n = MAX_ARRAY_SIZE;
1613 <                    else
1614 <                        n += (n >>> 1) + 1;
1615 <                    r = Arrays.copyOf(r, n);
1595 >    /**
1596 >     * If the specified key is not already associated with a value,
1597 >     * attempts to compute its value using the given mapping function
1598 >     * and enters it into this map unless {@code null}.  The entire
1599 >     * method invocation is performed atomically, so the function is
1600 >     * applied at most once per key.  Some attempted update operations
1601 >     * on this map by other threads may be blocked while computation
1602 >     * is in progress, so the computation should be short and simple,
1603 >     * and must not attempt to update any other mappings of this map.
1604 >     *
1605 >     * @param key key with which the specified value is to be associated
1606 >     * @param mappingFunction the function to compute a value
1607 >     * @return the current (existing or computed) value associated with
1608 >     *         the specified key, or null if the computed value is null
1609 >     * @throws NullPointerException if the specified key or mappingFunction
1610 >     *         is null
1611 >     * @throws IllegalStateException if the computation detectably
1612 >     *         attempts a recursive update to this map that would
1613 >     *         otherwise never complete
1614 >     * @throws RuntimeException or Error if the mappingFunction does so,
1615 >     *         in which case the mapping is left unestablished
1616 >     */
1617 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1618 >        if (key == null || mappingFunction == null)
1619 >            throw new NullPointerException();
1620 >        int h = spread(key.hashCode());
1621 >        V val = null;
1622 >        int binCount = 0;
1623 >        for (Node<K,V>[] tab = table;;) {
1624 >            Node<K,V> f; int n, i, fh;
1625 >            if (tab == null || (n = tab.length) == 0)
1626 >                tab = initTable();
1627 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1628 >                Node<K,V> r = new ReservationNode<K,V>();
1629 >                synchronized (r) {
1630 >                    if (casTabAt(tab, i, null, r)) {
1631 >                        binCount = 1;
1632 >                        Node<K,V> node = null;
1633 >                        try {
1634 >                            if ((val = mappingFunction.apply(key)) != null)
1635 >                                node = new Node<K,V>(h, key, val, null);
1636 >                        } finally {
1637 >                            setTabAt(tab, i, node);
1638 >                        }
1639 >                    }
1640                  }
1641 <                r[i++] = (T)it.next();
1641 >                if (binCount != 0)
1642 >                    break;
1643              }
1644 <            if (a == r && i < n) {
1645 <                r[i] = null; // null-terminate
1646 <                return r;
1644 >            else if ((fh = f.hash) == MOVED)
1645 >                tab = helpTransfer(tab, f);
1646 >            else {
1647 >                boolean added = false;
1648 >                synchronized (f) {
1649 >                    if (tabAt(tab, i) == f) {
1650 >                        if (fh >= 0) {
1651 >                            binCount = 1;
1652 >                            for (Node<K,V> e = f;; ++binCount) {
1653 >                                K ek; V ev;
1654 >                                if (e.hash == h &&
1655 >                                    ((ek = e.key) == key ||
1656 >                                     (ek != null && key.equals(ek)))) {
1657 >                                    val = e.val;
1658 >                                    break;
1659 >                                }
1660 >                                Node<K,V> pred = e;
1661 >                                if ((e = e.next) == null) {
1662 >                                    if ((val = mappingFunction.apply(key)) != null) {
1663 >                                        added = true;
1664 >                                        pred.next = new Node<K,V>(h, key, val, null);
1665 >                                    }
1666 >                                    break;
1667 >                                }
1668 >                            }
1669 >                        }
1670 >                        else if (f instanceof TreeBin) {
1671 >                            binCount = 2;
1672 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1673 >                            TreeNode<K,V> r, p;
1674 >                            if ((r = t.root) != null &&
1675 >                                (p = r.findTreeNode(h, key, null)) != null)
1676 >                                val = p.val;
1677 >                            else if ((val = mappingFunction.apply(key)) != null) {
1678 >                                added = true;
1679 >                                t.putTreeVal(h, key, val);
1680 >                            }
1681 >                        }
1682 >                    }
1683 >                }
1684 >                if (binCount != 0) {
1685 >                    if (binCount >= TREEIFY_THRESHOLD)
1686 >                        treeifyBin(tab, i);
1687 >                    if (!added)
1688 >                        return val;
1689 >                    break;
1690 >                }
1691              }
3193            return (i == n) ? r : Arrays.copyOf(r, i);
3194        }
3195
3196        public final int hashCode() {
3197            int h = 0;
3198            for (Iterator<?> it = iterator(); it.hasNext();)
3199                h += it.next().hashCode();
3200            return h;
1692          }
1693 +        if (val != null)
1694 +            addCount(1L, binCount);
1695 +        return val;
1696 +    }
1697  
1698 <        public final String toString() {
1699 <            StringBuilder sb = new StringBuilder();
1700 <            sb.append('[');
1701 <            Iterator<?> it = iterator();
1702 <            if (it.hasNext()) {
1703 <                for (;;) {
1704 <                    Object e = it.next();
1705 <                    sb.append(e == this ? "(this Collection)" : e);
1706 <                    if (!it.hasNext())
1707 <                        break;
1708 <                    sb.append(',').append(' ');
1698 >    /**
1699 >     * If the value for the specified key is present, attempts to
1700 >     * compute a new mapping given the key and its current mapped
1701 >     * value.  The entire method invocation is performed atomically.
1702 >     * Some attempted update operations on this map by other threads
1703 >     * may be blocked while computation is in progress, so the
1704 >     * computation should be short and simple, and must not attempt to
1705 >     * update any other mappings of this map.
1706 >     *
1707 >     * @param key key with which a value may be associated
1708 >     * @param remappingFunction the function to compute a value
1709 >     * @return the new value associated with the specified key, or null if none
1710 >     * @throws NullPointerException if the specified key or remappingFunction
1711 >     *         is null
1712 >     * @throws IllegalStateException if the computation detectably
1713 >     *         attempts a recursive update to this map that would
1714 >     *         otherwise never complete
1715 >     * @throws RuntimeException or Error if the remappingFunction does so,
1716 >     *         in which case the mapping is unchanged
1717 >     */
1718 >    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1719 >        if (key == null || remappingFunction == null)
1720 >            throw new NullPointerException();
1721 >        int h = spread(key.hashCode());
1722 >        V val = null;
1723 >        int delta = 0;
1724 >        int binCount = 0;
1725 >        for (Node<K,V>[] tab = table;;) {
1726 >            Node<K,V> f; int n, i, fh;
1727 >            if (tab == null || (n = tab.length) == 0)
1728 >                tab = initTable();
1729 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1730 >                break;
1731 >            else if ((fh = f.hash) == MOVED)
1732 >                tab = helpTransfer(tab, f);
1733 >            else {
1734 >                synchronized (f) {
1735 >                    if (tabAt(tab, i) == f) {
1736 >                        if (fh >= 0) {
1737 >                            binCount = 1;
1738 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1739 >                                K ek;
1740 >                                if (e.hash == h &&
1741 >                                    ((ek = e.key) == key ||
1742 >                                     (ek != null && key.equals(ek)))) {
1743 >                                    val = remappingFunction.apply(key, e.val);
1744 >                                    if (val != null)
1745 >                                        e.val = val;
1746 >                                    else {
1747 >                                        delta = -1;
1748 >                                        Node<K,V> en = e.next;
1749 >                                        if (pred != null)
1750 >                                            pred.next = en;
1751 >                                        else
1752 >                                            setTabAt(tab, i, en);
1753 >                                    }
1754 >                                    break;
1755 >                                }
1756 >                                pred = e;
1757 >                                if ((e = e.next) == null)
1758 >                                    break;
1759 >                            }
1760 >                        }
1761 >                        else if (f instanceof TreeBin) {
1762 >                            binCount = 2;
1763 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1764 >                            TreeNode<K,V> r, p;
1765 >                            if ((r = t.root) != null &&
1766 >                                (p = r.findTreeNode(h, key, null)) != null) {
1767 >                                val = remappingFunction.apply(key, p.val);
1768 >                                if (val != null)
1769 >                                    p.val = val;
1770 >                                else {
1771 >                                    delta = -1;
1772 >                                    if (t.removeTreeNode(p))
1773 >                                        setTabAt(tab, i, untreeify(t.first));
1774 >                                }
1775 >                            }
1776 >                        }
1777 >                    }
1778                  }
1779 +                if (binCount != 0)
1780 +                    break;
1781              }
3216            return sb.append(']').toString();
1782          }
1783 +        if (delta != 0)
1784 +            addCount((long)delta, binCount);
1785 +        return val;
1786 +    }
1787  
1788 <        public final boolean containsAll(Collection<?> c) {
1789 <            if (c != this) {
1790 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
1791 <                    Object e = it.next();
1792 <                    if (e == null || !contains(e))
1793 <                        return false;
1788 >    /**
1789 >     * Attempts to compute a mapping for the specified key and its
1790 >     * current mapped value (or {@code null} if there is no current
1791 >     * mapping). The entire method invocation is performed atomically.
1792 >     * Some attempted update operations on this map by other threads
1793 >     * may be blocked while computation is in progress, so the
1794 >     * computation should be short and simple, and must not attempt to
1795 >     * update any other mappings of this Map.
1796 >     *
1797 >     * @param key key with which the specified value is to be associated
1798 >     * @param remappingFunction the function to compute a value
1799 >     * @return the new value associated with the specified key, or null if none
1800 >     * @throws NullPointerException if the specified key or remappingFunction
1801 >     *         is null
1802 >     * @throws IllegalStateException if the computation detectably
1803 >     *         attempts a recursive update to this map that would
1804 >     *         otherwise never complete
1805 >     * @throws RuntimeException or Error if the remappingFunction does so,
1806 >     *         in which case the mapping is unchanged
1807 >     */
1808 >    public V compute(K key,
1809 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1810 >        if (key == null || remappingFunction == null)
1811 >            throw new NullPointerException();
1812 >        int h = spread(key.hashCode());
1813 >        V val = null;
1814 >        int delta = 0;
1815 >        int binCount = 0;
1816 >        for (Node<K,V>[] tab = table;;) {
1817 >            Node<K,V> f; int n, i, fh;
1818 >            if (tab == null || (n = tab.length) == 0)
1819 >                tab = initTable();
1820 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1821 >                Node<K,V> r = new ReservationNode<K,V>();
1822 >                synchronized (r) {
1823 >                    if (casTabAt(tab, i, null, r)) {
1824 >                        binCount = 1;
1825 >                        Node<K,V> node = null;
1826 >                        try {
1827 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1828 >                                delta = 1;
1829 >                                node = new Node<K,V>(h, key, val, null);
1830 >                            }
1831 >                        } finally {
1832 >                            setTabAt(tab, i, node);
1833 >                        }
1834 >                    }
1835                  }
1836 +                if (binCount != 0)
1837 +                    break;
1838              }
1839 <            return true;
1840 <        }
1841 <
1842 <        public final boolean removeAll(Collection<?> c) {
1843 <            boolean modified = false;
1844 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1845 <                if (c.contains(it.next())) {
1846 <                    it.remove();
1847 <                    modified = true;
1839 >            else if ((fh = f.hash) == MOVED)
1840 >                tab = helpTransfer(tab, f);
1841 >            else {
1842 >                synchronized (f) {
1843 >                    if (tabAt(tab, i) == f) {
1844 >                        if (fh >= 0) {
1845 >                            binCount = 1;
1846 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1847 >                                K ek;
1848 >                                if (e.hash == h &&
1849 >                                    ((ek = e.key) == key ||
1850 >                                     (ek != null && key.equals(ek)))) {
1851 >                                    val = remappingFunction.apply(key, e.val);
1852 >                                    if (val != null)
1853 >                                        e.val = val;
1854 >                                    else {
1855 >                                        delta = -1;
1856 >                                        Node<K,V> en = e.next;
1857 >                                        if (pred != null)
1858 >                                            pred.next = en;
1859 >                                        else
1860 >                                            setTabAt(tab, i, en);
1861 >                                    }
1862 >                                    break;
1863 >                                }
1864 >                                pred = e;
1865 >                                if ((e = e.next) == null) {
1866 >                                    val = remappingFunction.apply(key, null);
1867 >                                    if (val != null) {
1868 >                                        delta = 1;
1869 >                                        pred.next =
1870 >                                            new Node<K,V>(h, key, val, null);
1871 >                                    }
1872 >                                    break;
1873 >                                }
1874 >                            }
1875 >                        }
1876 >                        else if (f instanceof TreeBin) {
1877 >                            binCount = 1;
1878 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1879 >                            TreeNode<K,V> r, p;
1880 >                            if ((r = t.root) != null)
1881 >                                p = r.findTreeNode(h, key, null);
1882 >                            else
1883 >                                p = null;
1884 >                            V pv = (p == null) ? null : p.val;
1885 >                            val = remappingFunction.apply(key, pv);
1886 >                            if (val != null) {
1887 >                                if (p != null)
1888 >                                    p.val = val;
1889 >                                else {
1890 >                                    delta = 1;
1891 >                                    t.putTreeVal(h, key, val);
1892 >                                }
1893 >                            }
1894 >                            else if (p != null) {
1895 >                                delta = -1;
1896 >                                if (t.removeTreeNode(p))
1897 >                                    setTabAt(tab, i, untreeify(t.first));
1898 >                            }
1899 >                        }
1900 >                    }
1901 >                }
1902 >                if (binCount != 0) {
1903 >                    if (binCount >= TREEIFY_THRESHOLD)
1904 >                        treeifyBin(tab, i);
1905 >                    break;
1906                  }
1907              }
3238            return modified;
1908          }
1909 +        if (delta != 0)
1910 +            addCount((long)delta, binCount);
1911 +        return val;
1912 +    }
1913  
1914 <        public final boolean retainAll(Collection<?> c) {
1915 <            boolean modified = false;
1916 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1917 <                if (!c.contains(it.next())) {
1918 <                    it.remove();
1919 <                    modified = true;
1914 >    /**
1915 >     * If the specified key is not already associated with a
1916 >     * (non-null) value, associates it with the given value.
1917 >     * Otherwise, replaces the value with the results of the given
1918 >     * remapping function, or removes if {@code null}. The entire
1919 >     * method invocation is performed atomically.  Some attempted
1920 >     * update operations on this map by other threads may be blocked
1921 >     * while computation is in progress, so the computation should be
1922 >     * short and simple, and must not attempt to update any other
1923 >     * mappings of this Map.
1924 >     *
1925 >     * @param key key with which the specified value is to be associated
1926 >     * @param value the value to use if absent
1927 >     * @param remappingFunction the function to recompute a value if present
1928 >     * @return the new value associated with the specified key, or null if none
1929 >     * @throws NullPointerException if the specified key or the
1930 >     *         remappingFunction is null
1931 >     * @throws RuntimeException or Error if the remappingFunction does so,
1932 >     *         in which case the mapping is unchanged
1933 >     */
1934 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1935 >        if (key == null || value == null || remappingFunction == null)
1936 >            throw new NullPointerException();
1937 >        int h = spread(key.hashCode());
1938 >        V val = null;
1939 >        int delta = 0;
1940 >        int binCount = 0;
1941 >        for (Node<K,V>[] tab = table;;) {
1942 >            Node<K,V> f; int n, i, fh;
1943 >            if (tab == null || (n = tab.length) == 0)
1944 >                tab = initTable();
1945 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1946 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1947 >                    delta = 1;
1948 >                    val = value;
1949 >                    break;
1950 >                }
1951 >            }
1952 >            else if ((fh = f.hash) == MOVED)
1953 >                tab = helpTransfer(tab, f);
1954 >            else {
1955 >                synchronized (f) {
1956 >                    if (tabAt(tab, i) == f) {
1957 >                        if (fh >= 0) {
1958 >                            binCount = 1;
1959 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1960 >                                K ek;
1961 >                                if (e.hash == h &&
1962 >                                    ((ek = e.key) == key ||
1963 >                                     (ek != null && key.equals(ek)))) {
1964 >                                    val = remappingFunction.apply(e.val, value);
1965 >                                    if (val != null)
1966 >                                        e.val = val;
1967 >                                    else {
1968 >                                        delta = -1;
1969 >                                        Node<K,V> en = e.next;
1970 >                                        if (pred != null)
1971 >                                            pred.next = en;
1972 >                                        else
1973 >                                            setTabAt(tab, i, en);
1974 >                                    }
1975 >                                    break;
1976 >                                }
1977 >                                pred = e;
1978 >                                if ((e = e.next) == null) {
1979 >                                    delta = 1;
1980 >                                    val = value;
1981 >                                    pred.next =
1982 >                                        new Node<K,V>(h, key, val, null);
1983 >                                    break;
1984 >                                }
1985 >                            }
1986 >                        }
1987 >                        else if (f instanceof TreeBin) {
1988 >                            binCount = 2;
1989 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1990 >                            TreeNode<K,V> r = t.root;
1991 >                            TreeNode<K,V> p = (r == null) ? null :
1992 >                                r.findTreeNode(h, key, null);
1993 >                            val = (p == null) ? value :
1994 >                                remappingFunction.apply(p.val, value);
1995 >                            if (val != null) {
1996 >                                if (p != null)
1997 >                                    p.val = val;
1998 >                                else {
1999 >                                    delta = 1;
2000 >                                    t.putTreeVal(h, key, val);
2001 >                                }
2002 >                            }
2003 >                            else if (p != null) {
2004 >                                delta = -1;
2005 >                                if (t.removeTreeNode(p))
2006 >                                    setTabAt(tab, i, untreeify(t.first));
2007 >                            }
2008 >                        }
2009 >                    }
2010 >                }
2011 >                if (binCount != 0) {
2012 >                    if (binCount >= TREEIFY_THRESHOLD)
2013 >                        treeifyBin(tab, i);
2014 >                    break;
2015                  }
2016              }
3249            return modified;
2017          }
2018 +        if (delta != 0)
2019 +            addCount((long)delta, binCount);
2020 +        return val;
2021 +    }
2022 +
2023 +    // Hashtable legacy methods
2024 +
2025 +    /**
2026 +     * Legacy method testing if some key maps into the specified value
2027 +     * in this table.  This method is identical in functionality to
2028 +     * {@link #containsValue(Object)}, and exists solely to ensure
2029 +     * full compatibility with class {@link java.util.Hashtable},
2030 +     * which supported this method prior to introduction of the
2031 +     * Java Collections framework.
2032 +     *
2033 +     * @param  value a value to search for
2034 +     * @return {@code true} if and only if some key maps to the
2035 +     *         {@code value} argument in this table as
2036 +     *         determined by the {@code equals} method;
2037 +     *         {@code false} otherwise
2038 +     * @throws NullPointerException if the specified value is null
2039 +     */
2040 +    @Deprecated public boolean contains(Object value) {
2041 +        return containsValue(value);
2042 +    }
2043  
2044 +    /**
2045 +     * Returns an enumeration of the keys in this table.
2046 +     *
2047 +     * @return an enumeration of the keys in this table
2048 +     * @see #keySet()
2049 +     */
2050 +    public Enumeration<K> keys() {
2051 +        Node<K,V>[] t;
2052 +        int f = (t = table) == null ? 0 : t.length;
2053 +        return new KeyIterator<K,V>(t, f, 0, f, this);
2054      }
2055  
2056 <    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) {
3264 <            throw new UnsupportedOperationException();
3265 <        }
3266 <        public final boolean addAll(Collection<? extends K> c) {
3267 <            throw new UnsupportedOperationException();
3268 <        }
3269 <        public boolean equals(Object o) {
3270 <            Set<?> c;
3271 <            return ((o instanceof Set) &&
3272 <                    ((c = (Set<?>)o) == this ||
3273 <                     (containsAll(c) && c.containsAll(this))));
3274 <        }
2056 >    /**
2057 >     * Returns an enumeration of the values in this table.
2058 >     *
2059 >     * @return an enumeration of the values in this table
2060 >     * @see #values()
2061 >     */
2062 >    public Enumeration<V> elements() {
2063 >        Node<K,V>[] t;
2064 >        int f = (t = table) == null ? 0 : t.length;
2065 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2066      }
2067  
2068 +    // ConcurrentHashMapV8-only methods
2069  
2070 <    static final class Values<K,V> extends CHMView<K,V>
2071 <        implements Collection<V> {
2072 <        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
2073 <        public final boolean contains(Object o) { return map.containsValue(o); }
2074 <        public final boolean remove(Object o) {
2075 <            if (o != null) {
2076 <                Iterator<V> it = new ValueIterator<K,V>(map);
2077 <                while (it.hasNext()) {
2078 <                    if (o.equals(it.next())) {
2079 <                        it.remove();
2080 <                        return true;
2081 <                    }
2082 <                }
2083 <            }
3292 <            return false;
3293 <        }
3294 <        public final Iterator<V> iterator() {
3295 <            return new ValueIterator<K,V>(map);
3296 <        }
3297 <        public final boolean add(V e) {
3298 <            throw new UnsupportedOperationException();
3299 <        }
3300 <        public final boolean addAll(Collection<? extends V> c) {
3301 <            throw new UnsupportedOperationException();
3302 <        }
2070 >    /**
2071 >     * Returns the number of mappings. This method should be used
2072 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2073 >     * contain more mappings than can be represented as an int. The
2074 >     * value returned is an estimate; the actual count may differ if
2075 >     * there are concurrent insertions or removals.
2076 >     *
2077 >     * @return the number of mappings
2078 >     * @since 1.8
2079 >     */
2080 >    public long mappingCount() {
2081 >        long n = sumCount();
2082 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2083 >    }
2084  
2085 +    /**
2086 +     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2087 +     * from the given type to {@code Boolean.TRUE}.
2088 +     *
2089 +     * @return the new set
2090 +     * @since 1.8
2091 +     */
2092 +    public static <K> KeySetView<K,Boolean> newKeySet() {
2093 +        return new KeySetView<K,Boolean>
2094 +            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2095      }
2096  
2097 <    static final class EntrySet<K,V> extends CHMView<K,V>
2098 <        implements Set<Map.Entry<K,V>> {
2099 <        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2100 <        public final boolean contains(Object o) {
2101 <            Object k, v, r; Map.Entry<?,?> e;
2102 <            return ((o instanceof Map.Entry) &&
2103 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2104 <                    (r = map.get(k)) != null &&
2105 <                    (v = e.getValue()) != null &&
2106 <                    (v == r || v.equals(r)));
2107 <        }
2108 <        public final boolean remove(Object o) {
2109 <            Object k, v; Map.Entry<?,?> e;
2110 <            return ((o instanceof Map.Entry) &&
2111 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2112 <                    (v = e.getValue()) != null &&
2113 <                    map.remove(k, v));
2114 <        }
2115 <        public final Iterator<Map.Entry<K,V>> iterator() {
2116 <            return new EntryIterator<K,V>(map);
2117 <        }
2118 <        public final boolean add(Entry<K,V> e) {
2119 <            throw new UnsupportedOperationException();
2097 >    /**
2098 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2099 >     * from the given type to {@code Boolean.TRUE}.
2100 >     *
2101 >     * @param initialCapacity The implementation performs internal
2102 >     * sizing to accommodate this many elements.
2103 >     * @throws IllegalArgumentException if the initial capacity of
2104 >     * elements is negative
2105 >     * @return the new set
2106 >     * @since 1.8
2107 >     */
2108 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2109 >        return new KeySetView<K,Boolean>
2110 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2111 >    }
2112 >
2113 >    /**
2114 >     * Returns a {@link Set} view of the keys in this map, using the
2115 >     * given common mapped value for any additions (i.e., {@link
2116 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2117 >     * This is of course only appropriate if it is acceptable to use
2118 >     * the same value for all additions from this view.
2119 >     *
2120 >     * @param mappedValue the mapped value to use for any additions
2121 >     * @return the set view
2122 >     * @throws NullPointerException if the mappedValue is null
2123 >     */
2124 >    public KeySetView<K,V> keySet(V mappedValue) {
2125 >        if (mappedValue == null)
2126 >            throw new NullPointerException();
2127 >        return new KeySetView<K,V>(this, mappedValue);
2128 >    }
2129 >
2130 >    /* ---------------- Special Nodes -------------- */
2131 >
2132 >    /**
2133 >     * A node inserted at head of bins during transfer operations.
2134 >     */
2135 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2136 >        final Node<K,V>[] nextTable;
2137 >        ForwardingNode(Node<K,V>[] tab) {
2138 >            super(MOVED, null, null, null);
2139 >            this.nextTable = tab;
2140 >        }
2141 >
2142 >        Node<K,V> find(int h, Object k) {
2143 >            Node<K,V> e; int n;
2144 >            Node<K,V>[] tab = nextTable;
2145 >            if (k != null && tab != null && (n = tab.length) > 0 &&
2146 >                (e = tabAt(tab, (n - 1) & h)) != null) {
2147 >                do {
2148 >                    int eh; K ek;
2149 >                    if ((eh = e.hash) == h &&
2150 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2151 >                        return e;
2152 >                    if (eh < 0)
2153 >                        return e.find(h, k);
2154 >                } while ((e = e.next) != null);
2155 >            }
2156 >            return null;
2157          }
2158 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
2159 <            throw new UnsupportedOperationException();
2158 >    }
2159 >
2160 >    /**
2161 >     * A place-holder node used in computeIfAbsent and compute
2162 >     */
2163 >    static final class ReservationNode<K,V> extends Node<K,V> {
2164 >        ReservationNode() {
2165 >            super(RESERVED, null, null, null);
2166          }
2167 <        public boolean equals(Object o) {
2168 <            Set<?> c;
2169 <            return ((o instanceof Set) &&
3336 <                    ((c = (Set<?>)o) == this ||
3337 <                     (containsAll(c) && c.containsAll(this))));
2167 >
2168 >        Node<K,V> find(int h, Object k) {
2169 >            return null;
2170          }
2171      }
2172  
2173 <    /* ---------------- Serialization Support -------------- */
2173 >    /* ---------------- Table Initialization and Resizing -------------- */
2174  
2175      /**
2176 <     * Stripped-down version of helper class used in previous version,
3345 <     * declared for the sake of serialization compatibility
2176 >     * Initializes table, using the size recorded in sizeCtl.
2177       */
2178 <    static class Segment<K,V> implements Serializable {
2179 <        private static final long serialVersionUID = 2249069246763182397L;
2180 <        final float loadFactor;
2181 <        Segment(float lf) { this.loadFactor = lf; }
2178 >    private final Node<K,V>[] initTable() {
2179 >        Node<K,V>[] tab; int sc;
2180 >        while ((tab = table) == null || tab.length == 0) {
2181 >            if ((sc = sizeCtl) < 0)
2182 >                Thread.yield(); // lost initialization race; just spin
2183 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2184 >                try {
2185 >                    if ((tab = table) == null || tab.length == 0) {
2186 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2187 >                        @SuppressWarnings({"rawtypes","unchecked"})
2188 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2189 >                        table = tab = nt;
2190 >                        sc = n - (n >>> 2);
2191 >                    }
2192 >                } finally {
2193 >                    sizeCtl = sc;
2194 >                }
2195 >                break;
2196 >            }
2197 >        }
2198 >        return tab;
2199      }
2200  
2201      /**
2202 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
2203 <     * stream (i.e., serializes it).
2204 <     * @param s the stream
2205 <     * @serialData
2206 <     * the key (Object) and value (Object)
2207 <     * for each key-value mapping, followed by a null pair.
2208 <     * The key-value mappings are emitted in no particular order.
2209 <     */
2210 <    @SuppressWarnings("unchecked")
2211 <        private void writeObject(java.io.ObjectOutputStream s)
2212 <        throws java.io.IOException {
2213 <        if (segments == null) { // for serialization compatibility
2214 <            segments = (Segment<K,V>[])
2215 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
2216 <            for (int i = 0; i < segments.length; ++i)
2217 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
2218 <        }
2219 <        s.defaultWriteObject();
2220 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2221 <        Object v;
2222 <        while ((v = it.advance()) != null) {
2223 <            s.writeObject(it.nextKey);
2224 <            s.writeObject(v);
2202 >     * Adds to count, and if table is too small and not already
2203 >     * resizing, initiates transfer. If already resizing, helps
2204 >     * perform transfer if work is available.  Rechecks occupancy
2205 >     * after a transfer to see if another resize is already needed
2206 >     * because resizings are lagging additions.
2207 >     *
2208 >     * @param x the count to add
2209 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2210 >     */
2211 >    private final void addCount(long x, int check) {
2212 >        CounterCell[] as; long b, s;
2213 >        if ((as = counterCells) != null ||
2214 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2215 >            CounterHashCode hc; CounterCell a; long v; int m;
2216 >            boolean uncontended = true;
2217 >            if ((hc = threadCounterHashCode.get()) == null ||
2218 >                as == null || (m = as.length - 1) < 0 ||
2219 >                (a = as[m & hc.code]) == null ||
2220 >                !(uncontended =
2221 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2222 >                fullAddCount(x, hc, uncontended);
2223 >                return;
2224 >            }
2225 >            if (check <= 1)
2226 >                return;
2227 >            s = sumCount();
2228 >        }
2229 >        if (check >= 0) {
2230 >            Node<K,V>[] tab, nt; int sc;
2231 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2232 >                   tab.length < MAXIMUM_CAPACITY) {
2233 >                if (sc < 0) {
2234 >                    if (sc == -1 || transferIndex <= transferOrigin ||
2235 >                        (nt = nextTable) == null)
2236 >                        break;
2237 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2238 >                        transfer(tab, nt);
2239 >                }
2240 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2241 >                    transfer(tab, null);
2242 >                s = sumCount();
2243 >            }
2244          }
3378        s.writeObject(null);
3379        s.writeObject(null);
3380        segments = null; // throw away
2245      }
2246  
2247      /**
2248 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3385 <     * @param s the stream
2248 >     * Helps transfer if a resize is in progress.
2249       */
2250 <    @SuppressWarnings("unchecked")
2251 <        private void readObject(java.io.ObjectInputStream s)
2252 <        throws java.io.IOException, ClassNotFoundException {
2253 <        s.defaultReadObject();
2254 <        this.segments = null; // unneeded
2255 <        // initialize transient final field
2256 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
2250 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2251 >        Node<K,V>[] nextTab; int sc;
2252 >        if ((f instanceof ForwardingNode) &&
2253 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2254 >            if (nextTab == nextTable && tab == table &&
2255 >                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2256 >                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2257 >                transfer(tab, nextTab);
2258 >            return nextTab;
2259 >        }
2260 >        return table;
2261 >    }
2262  
2263 <        // Create all nodes, then place in table once size is known
2264 <        long size = 0L;
2265 <        Node p = null;
2266 <        for (;;) {
2267 <            K k = (K) s.readObject();
2268 <            V v = (V) s.readObject();
2269 <            if (k != null && v != null) {
2270 <                int h = spread(k.hashCode());
2271 <                p = new Node(h, k, v, p);
2272 <                ++size;
2263 >    /**
2264 >     * Tries to presize table to accommodate the given number of elements.
2265 >     *
2266 >     * @param size number of elements (doesn't need to be perfectly accurate)
2267 >     */
2268 >    private final void tryPresize(int size) {
2269 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2270 >            tableSizeFor(size + (size >>> 1) + 1);
2271 >        int sc;
2272 >        while ((sc = sizeCtl) >= 0) {
2273 >            Node<K,V>[] tab = table; int n;
2274 >            if (tab == null || (n = tab.length) == 0) {
2275 >                n = (sc > c) ? sc : c;
2276 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2277 >                    try {
2278 >                        if (table == tab) {
2279 >                            @SuppressWarnings({"rawtypes","unchecked"})
2280 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2281 >                            table = nt;
2282 >                            sc = n - (n >>> 2);
2283 >                        }
2284 >                    } finally {
2285 >                        sizeCtl = sc;
2286 >                    }
2287 >                }
2288              }
2289 <            else
2289 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2290                  break;
2291 +            else if (tab == table &&
2292 +                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2293 +                transfer(tab, null);
2294          }
2295 <        if (p != null) {
2296 <            boolean init = false;
2297 <            int n;
2298 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
2299 <                n = MAXIMUM_CAPACITY;
2300 <            else {
2301 <                int sz = (int)size;
2302 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
2303 <            }
2304 <            int sc = sizeCtl;
2305 <            boolean collide = false;
2306 <            if (n > sc &&
2307 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2308 <                try {
2309 <                    if (table == null) {
2310 <                        init = true;
2311 <                        Node[] tab = new Node[n];
2312 <                        int mask = n - 1;
2313 <                        while (p != null) {
2314 <                            int j = p.hash & mask;
2315 <                            Node next = p.next;
2316 <                            Node q = p.next = tabAt(tab, j);
2317 <                            setTabAt(tab, j, p);
2318 <                            if (!collide && q != null && q.hash == p.hash)
2319 <                                collide = true;
2320 <                            p = next;
2295 >    }
2296 >
2297 >    /**
2298 >     * Moves and/or copies the nodes in each bin to new table. See
2299 >     * above for explanation.
2300 >     */
2301 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2302 >        int n = tab.length, stride;
2303 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2304 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2305 >        if (nextTab == null) {            // initiating
2306 >            try {
2307 >                @SuppressWarnings({"rawtypes","unchecked"})
2308 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2309 >                nextTab = nt;
2310 >            } catch (Throwable ex) {      // try to cope with OOME
2311 >                sizeCtl = Integer.MAX_VALUE;
2312 >                return;
2313 >            }
2314 >            nextTable = nextTab;
2315 >            transferOrigin = n;
2316 >            transferIndex = n;
2317 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2318 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2319 >                int nextk = (k > stride) ? k - stride : 0;
2320 >                for (int m = nextk; m < k; ++m)
2321 >                    nextTab[m] = rev;
2322 >                for (int m = n + nextk; m < n + k; ++m)
2323 >                    nextTab[m] = rev;
2324 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2325 >            }
2326 >        }
2327 >        int nextn = nextTab.length;
2328 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2329 >        boolean advance = true;
2330 >        for (int i = 0, bound = 0;;) {
2331 >            int nextIndex, nextBound, fh; Node<K,V> f;
2332 >            while (advance) {
2333 >                if (--i >= bound)
2334 >                    advance = false;
2335 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2336 >                    i = -1;
2337 >                    advance = false;
2338 >                }
2339 >                else if (U.compareAndSwapInt
2340 >                         (this, TRANSFERINDEX, nextIndex,
2341 >                          nextBound = (nextIndex > stride ?
2342 >                                       nextIndex - stride : 0))) {
2343 >                    bound = nextBound;
2344 >                    i = nextIndex - 1;
2345 >                    advance = false;
2346 >                }
2347 >            }
2348 >            if (i < 0 || i >= n || i + n >= nextn) {
2349 >                for (int sc;;) {
2350 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2351 >                        if (sc == -1) {
2352 >                            nextTable = null;
2353 >                            table = nextTab;
2354 >                            sizeCtl = (n << 1) - (n >>> 1);
2355                          }
2356 <                        table = tab;
3437 <                        counter.add(size);
3438 <                        sc = n - (n >>> 2);
2356 >                        return;
2357                      }
3440                } finally {
3441                    sizeCtl = sc;
2358                  }
2359 <                if (collide) { // rescan and convert to TreeBins
2360 <                    Node[] tab = table;
2361 <                    for (int i = 0; i < tab.length; ++i) {
2362 <                        int c = 0;
2363 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
2364 <                            if (++c > TREE_THRESHOLD &&
2365 <                                (e.key instanceof Comparable)) {
2366 <                                replaceWithTreeBin(tab, i, e.key);
2367 <                                break;
2359 >            }
2360 >            else if ((f = tabAt(tab, i)) == null) {
2361 >                if (casTabAt(tab, i, null, fwd)) {
2362 >                    setTabAt(nextTab, i, null);
2363 >                    setTabAt(nextTab, i + n, null);
2364 >                    advance = true;
2365 >                }
2366 >            }
2367 >            else if ((fh = f.hash) == MOVED)
2368 >                advance = true; // already processed
2369 >            else {
2370 >                synchronized (f) {
2371 >                    if (tabAt(tab, i) == f) {
2372 >                        Node<K,V> ln, hn;
2373 >                        if (fh >= 0) {
2374 >                            int runBit = fh & n;
2375 >                            Node<K,V> lastRun = f;
2376 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2377 >                                int b = p.hash & n;
2378 >                                if (b != runBit) {
2379 >                                    runBit = b;
2380 >                                    lastRun = p;
2381 >                                }
2382 >                            }
2383 >                            if (runBit == 0) {
2384 >                                ln = lastRun;
2385 >                                hn = null;
2386 >                            }
2387 >                            else {
2388 >                                hn = lastRun;
2389 >                                ln = null;
2390 >                            }
2391 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2392 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2393 >                                if ((ph & n) == 0)
2394 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2395 >                                else
2396 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2397                              }
2398                          }
2399 +                        else if (f instanceof TreeBin) {
2400 +                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2401 +                            TreeNode<K,V> lo = null, loTail = null;
2402 +                            TreeNode<K,V> hi = null, hiTail = null;
2403 +                            int lc = 0, hc = 0;
2404 +                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2405 +                                int h = e.hash;
2406 +                                TreeNode<K,V> p = new TreeNode<K,V>
2407 +                                    (h, e.key, e.val, null, null);
2408 +                                if ((h & n) == 0) {
2409 +                                    if ((p.prev = loTail) == null)
2410 +                                        lo = p;
2411 +                                    else
2412 +                                        loTail.next = p;
2413 +                                    loTail = p;
2414 +                                    ++lc;
2415 +                                }
2416 +                                else {
2417 +                                    if ((p.prev = hiTail) == null)
2418 +                                        hi = p;
2419 +                                    else
2420 +                                        hiTail.next = p;
2421 +                                    hiTail = p;
2422 +                                    ++hc;
2423 +                                }
2424 +                            }
2425 +                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2426 +                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2427 +                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2428 +                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2429 +                        }
2430 +                        else
2431 +                            ln = hn = null;
2432 +                        setTabAt(nextTab, i, ln);
2433 +                        setTabAt(nextTab, i + n, hn);
2434 +                        setTabAt(tab, i, fwd);
2435 +                        advance = true;
2436                      }
2437                  }
2438              }
3457            if (!init) { // Can only happen if unsafely published.
3458                while (p != null) {
3459                    internalPut(p.key, p.val);
3460                    p = p.next;
3461                }
3462            }
2439          }
2440      }
2441  
2442 +    /* ---------------- Conversion from/to TreeBins -------------- */
2443  
2444 <    // -------------------------------------------------------
2445 <
2446 <    // Sams
2447 <    /** Interface describing a void action of one argument */
2448 <    public interface Action<A> { void apply(A a); }
2449 <    /** Interface describing a void action of two arguments */
2450 <    public interface BiAction<A,B> { void apply(A a, B b); }
2451 <    /** Interface describing a function of one argument */
2452 <    public interface Fun<A,T> { T apply(A a); }
2453 <    /** Interface describing a function of two arguments */
2454 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
2455 <    /** Interface describing a function of no arguments */
2456 <    public interface Generator<T> { T apply(); }
2457 <    /** Interface describing a function mapping its argument to a double */
2458 <    public interface ObjectToDouble<A> { double apply(A a); }
2459 <    /** Interface describing a function mapping its argument to a long */
2460 <    public interface ObjectToLong<A> { long apply(A a); }
2461 <    /** Interface describing a function mapping its argument to an int */
2462 <    public interface ObjectToInt<A> {int apply(A a); }
2463 <    /** Interface describing a function mapping two arguments to a double */
2464 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
2465 <    /** Interface describing a function mapping two arguments to a long */
2466 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
2467 <    /** Interface describing a function mapping two arguments to an int */
2468 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
2469 <    /** Interface describing a function mapping a double to a double */
2470 <    public interface DoubleToDouble { double apply(double a); }
2471 <    /** Interface describing a function mapping a long to a long */
2472 <    public interface LongToLong { long apply(long a); }
2473 <    /** Interface describing a function mapping an int to an int */
2474 <    public interface IntToInt { int apply(int a); }
2475 <    /** Interface describing a function mapping two doubles to a double */
3499 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3500 <    /** Interface describing a function mapping two longs to a long */
3501 <    public interface LongByLongToLong { long apply(long a, long b); }
3502 <    /** Interface describing a function mapping two ints to an int */
3503 <    public interface IntByIntToInt { int apply(int a, int b); }
3504 <
3505 <
3506 <    // -------------------------------------------------------
2444 >    /**
2445 >     * Replaces all linked nodes in bin at given index unless table is
2446 >     * too small, in which case resizes instead.
2447 >     */
2448 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2449 >        Node<K,V> b; int n, sc;
2450 >        if (tab != null) {
2451 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2452 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2453 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2454 >                    transfer(tab, null);
2455 >            }
2456 >            else if ((b = tabAt(tab, index)) != null) {
2457 >                synchronized (b) {
2458 >                    if (tabAt(tab, index) == b) {
2459 >                        TreeNode<K,V> hd = null, tl = null;
2460 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2461 >                            TreeNode<K,V> p =
2462 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2463 >                                                  null, null);
2464 >                            if ((p.prev = tl) == null)
2465 >                                hd = p;
2466 >                            else
2467 >                                tl.next = p;
2468 >                            tl = p;
2469 >                        }
2470 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2471 >                    }
2472 >                }
2473 >            }
2474 >        }
2475 >    }
2476  
2477      /**
2478 <     * Returns an extended {@link Parallel} view of this map using the
3510 <     * given executor for bulk parallel operations.
3511 <     *
3512 <     * @param executor the executor
3513 <     * @return a parallel view
2478 >     * Returns a list on non-TreeNodes replacing those in given list.
2479       */
2480 <    public Parallel parallel(ForkJoinPool executor)  {
2481 <        return new Parallel(executor);
2480 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2481 >        Node<K,V> hd = null, tl = null;
2482 >        for (Node<K,V> q = b; q != null; q = q.next) {
2483 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2484 >            if (tl == null)
2485 >                hd = p;
2486 >            else
2487 >                tl.next = p;
2488 >            tl = p;
2489 >        }
2490 >        return hd;
2491      }
2492  
2493 +    /* ---------------- TreeNodes -------------- */
2494 +
2495      /**
2496 <     * An extended view of a ConcurrentHashMap supporting bulk
3521 <     * parallel operations. These operations are designed to be be
3522 <     * safely, and often sensibly, applied even with maps that are
3523 <     * being concurrently updated by other threads; for example, when
3524 <     * computing a snapshot summary of the values in a shared
3525 <     * registry.  There are three kinds of operation, each with four
3526 <     * forms, accepting functions with Keys, Values, Entries, and
3527 <     * (Key, Value) arguments and/or return values. Because the
3528 <     * elements of a ConcurrentHashMap are not ordered in any
3529 <     * particular way, and may be processed in different orders in
3530 <     * different parallel executions, the correctness of supplied
3531 <     * functions should not depend on any ordering, or on any other
3532 <     * objects or values that may transiently change while computation
3533 <     * is in progress; and except for forEach actions, should ideally
3534 <     * be side-effect-free.
3535 <     *
3536 <     * <ul>
3537 <     * <li> forEach: Perform a given action on each element.
3538 <     * A variant form applies a given transformation on each element
3539 <     * before performing the action.</li>
3540 <     *
3541 <     * <li> search: Return the first available non-null result of
3542 <     * applying a given function on each element; skipping further
3543 <     * search when a result is found.</li>
3544 <     *
3545 <     * <li> reduce: Accumulate each element.  The supplied reduction
3546 <     * function cannot rely on ordering (more formally, it should be
3547 <     * both associative and commutative).  There are five variants:
3548 <     *
3549 <     * <ul>
3550 <     *
3551 <     * <li> Plain reductions. (There is not a form of this method for
3552 <     * (key, value) function arguments since there is no corresponding
3553 <     * return type.)</li>
3554 <     *
3555 <     * <li> Mapped reductions that accumulate the results of a given
3556 <     * function applied to each element.</li>
3557 <     *
3558 <     * <li> Reductions to scalar doubles, longs, and ints, using a
3559 <     * given basis value.</li>
3560 <     *
3561 <     * </li>
3562 <     * </ul>
3563 <     * </ul>
3564 <     *
3565 <     * <p>The concurrency properties of the bulk operations follow
3566 <     * from those of ConcurrentHashMap: Any non-null result returned
3567 <     * from {@code get(key)} and related access methods bears a
3568 <     * happens-before relation with the associated insertion or
3569 <     * update.  The result of any bulk operation reflects the
3570 <     * composition of these per-element relations (but is not
3571 <     * necessarily atomic with respect to the map as a whole unless it
3572 <     * is somehow known to be quiescent).  Conversely, because keys
3573 <     * and values in the map are never null, null serves as a reliable
3574 <     * atomic indicator of the current lack of any result.  To
3575 <     * maintain this property, null serves as an implicit basis for
3576 <     * all non-scalar reduction operations. For the double, long, and
3577 <     * int versions, the basis should be one that, when combined with
3578 <     * any other value, returns that other value (more formally, it
3579 <     * should be the identity element for the reduction). Most common
3580 <     * reductions have these properties; for example, computing a sum
3581 <     * with basis 0 or a minimum with basis MAX_VALUE.
3582 <     *
3583 <     * <p>Search and transformation functions provided as arguments
3584 <     * should similarly return null to indicate the lack of any result
3585 <     * (in which case it is not used). In the case of mapped
3586 <     * reductions, this also enables transformations to serve as
3587 <     * filters, returning null (or, in the case of primitive
3588 <     * specializations, the identity basis) if the element should not
3589 <     * be combined. You can create compound transformations and
3590 <     * filterings by composing them yourself under this "null means
3591 <     * there is nothing there now" rule before using them in search or
3592 <     * reduce operations.
3593 <     *
3594 <     * <p>Methods accepting and/or returning Entry arguments maintain
3595 <     * key-value associations. They may be useful for example when
3596 <     * finding the key for the greatest value. Note that "plain" Entry
3597 <     * arguments can be supplied using {@code new
3598 <     * AbstractMap.SimpleEntry(k,v)}.
3599 <     *
3600 <     * <p> Bulk operations may complete abruptly, throwing an
3601 <     * exception encountered in the application of a supplied
3602 <     * function. Bear in mind when handling such exceptions that other
3603 <     * concurrently executing functions could also have thrown
3604 <     * exceptions, or would have done so if the first exception had
3605 <     * not occurred.
3606 <     *
3607 <     * <p>Parallel speedups compared to sequential processing are
3608 <     * common but not guaranteed.  Operations involving brief
3609 <     * functions on small maps may execute more slowly than sequential
3610 <     * loops if the underlying work to parallelize the computation is
3611 <     * more expensive than the computation itself. Similarly,
3612 <     * parallelization may not lead to much actual parallelism if all
3613 <     * processors are busy performing unrelated tasks.
3614 <     *
3615 <     * <p> All arguments to all task methods must be non-null.
3616 <     *
3617 <     * <p><em>jsr166e note: During transition, this class
3618 <     * uses nested functional interfaces with different names but the
3619 <     * same forms as those expected for JDK8.<em>
2496 >     * Nodes for use in TreeBins
2497       */
2498 <    public class Parallel {
2499 <        final ForkJoinPool fjp;
2498 >    static final class TreeNode<K,V> extends Node<K,V> {
2499 >        TreeNode<K,V> parent;  // red-black tree links
2500 >        TreeNode<K,V> left;
2501 >        TreeNode<K,V> right;
2502 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2503 >        boolean red;
2504  
2505 <        /**
2506 <         * Returns an extended view of this map using the given
2507 <         * executor for bulk parallel operations.
2508 <         *
3628 <         * @param executor the executor
3629 <         */
3630 <        public Parallel(ForkJoinPool executor)  {
3631 <            this.fjp = executor;
2505 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2506 >                 TreeNode<K,V> parent) {
2507 >            super(hash, key, val, next);
2508 >            this.parent = parent;
2509          }
2510  
2511 <        /**
2512 <         * Performs the given action for each (key, value).
3636 <         *
3637 <         * @param action the action
3638 <         */
3639 <        public void forEach(BiAction<K,V> action) {
3640 <            fjp.invoke(ForkJoinTasks.forEach
3641 <                       (ConcurrentHashMapV8.this, action));
2511 >        Node<K,V> find(int h, Object k) {
2512 >            return findTreeNode(h, k, null);
2513          }
2514  
2515          /**
2516 <         * Performs the given action for each non-null transformation
2517 <         * of each (key, value).
3647 <         *
3648 <         * @param transformer a function returning the transformation
3649 <         * for an element, or null of there is no transformation (in
3650 <         * which case the action is not applied).
3651 <         * @param action the action
2516 >         * Returns the TreeNode (or null if not found) for the given key
2517 >         * starting at given root.
2518           */
2519 <        public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
2520 <                                Action<U> action) {
2521 <            fjp.invoke(ForkJoinTasks.forEach
2522 <                       (ConcurrentHashMapV8.this, transformer, action));
2519 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2520 >            if (k != null) {
2521 >                TreeNode<K,V> p = this;
2522 >                do  {
2523 >                    int ph, dir; K pk; TreeNode<K,V> q;
2524 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2525 >                    if ((ph = p.hash) > h)
2526 >                        p = pl;
2527 >                    else if (ph < h)
2528 >                        p = pr;
2529 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2530 >                        return p;
2531 >                    else if (pl == null && pr == null)
2532 >                        break;
2533 >                    else if ((kc != null ||
2534 >                              (kc = comparableClassFor(k)) != null) &&
2535 >                             (dir = compareComparables(kc, k, pk)) != 0)
2536 >                        p = (dir < 0) ? pl : pr;
2537 >                    else if (pl == null)
2538 >                        p = pr;
2539 >                    else if (pr == null ||
2540 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2541 >                        p = pl;
2542 >                    else
2543 >                        return q;
2544 >                } while (p != null);
2545 >            }
2546 >            return null;
2547          }
2548 +    }
2549  
2550 <        /**
2551 <         * Returns a non-null result from applying the given search
2552 <         * function on each (key, value), or null if none.  Further
2553 <         * element processing is suppressed upon success. However,
2554 <         * this method does not return until other in-progress
2555 <         * parallel invocations of the search function also complete.
2556 <         *
2557 <         * @param searchFunction a function returning a non-null
2558 <         * result on success, else null
2559 <         * @return a non-null result from applying the given search
2560 <         * function on each (key, value), or null if none
2561 <         */
2562 <        public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
2563 <            return fjp.invoke(ForkJoinTasks.search
2564 <                              (ConcurrentHashMapV8.this, searchFunction));
2550 >    /* ---------------- TreeBins -------------- */
2551 >
2552 >    /**
2553 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2554 >     * keys or values, but instead point to list of TreeNodes and
2555 >     * their root. They also maintain a parasitic read-write lock
2556 >     * forcing writers (who hold bin lock) to wait for readers (who do
2557 >     * not) to complete before tree restructuring operations.
2558 >     */
2559 >    static final class TreeBin<K,V> extends Node<K,V> {
2560 >        TreeNode<K,V> root;
2561 >        volatile TreeNode<K,V> first;
2562 >        volatile Thread waiter;
2563 >        volatile int lockState;
2564 >        // values for lockState
2565 >        static final int WRITER = 1; // set while holding write lock
2566 >        static final int WAITER = 2; // set when waiting for write lock
2567 >        static final int READER = 4; // increment value for setting read lock
2568 >
2569 >        /**
2570 >         * Creates bin with initial set of nodes headed by b.
2571 >         */
2572 >        TreeBin(TreeNode<K,V> b) {
2573 >            super(TREEBIN, null, null, null);
2574 >            this.first = b;
2575 >            TreeNode<K,V> r = null;
2576 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2577 >                next = (TreeNode<K,V>)x.next;
2578 >                x.left = x.right = null;
2579 >                if (r == null) {
2580 >                    x.parent = null;
2581 >                    x.red = false;
2582 >                    r = x;
2583 >                }
2584 >                else {
2585 >                    Object key = x.key;
2586 >                    int hash = x.hash;
2587 >                    Class<?> kc = null;
2588 >                    for (TreeNode<K,V> p = r;;) {
2589 >                        int dir, ph;
2590 >                        if ((ph = p.hash) > hash)
2591 >                            dir = -1;
2592 >                        else if (ph < hash)
2593 >                            dir = 1;
2594 >                        else if ((kc != null ||
2595 >                                  (kc = comparableClassFor(key)) != null))
2596 >                            dir = compareComparables(kc, key, p.key);
2597 >                        else
2598 >                            dir = 0;
2599 >                        TreeNode<K,V> xp = p;
2600 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2601 >                            x.parent = xp;
2602 >                            if (dir <= 0)
2603 >                                xp.left = x;
2604 >                            else
2605 >                                xp.right = x;
2606 >                            r = balanceInsertion(r, x);
2607 >                            break;
2608 >                        }
2609 >                    }
2610 >                }
2611 >            }
2612 >            this.root = r;
2613          }
2614  
2615          /**
2616 <         * Returns the result of accumulating the given transformation
3678 <         * of all (key, value) pairs using the given reducer to
3679 <         * combine values, or null if none.
3680 <         *
3681 <         * @param transformer a function returning the transformation
3682 <         * for an element, or null of there is no transformation (in
3683 <         * which case it is not combined).
3684 <         * @param reducer a commutative associative combining function
3685 <         * @return the result of accumulating the given transformation
3686 <         * of all (key, value) pairs
2616 >         * Acquires write lock for tree restructuring.
2617           */
2618 <        public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
2619 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
2620 <            return fjp.invoke(ForkJoinTasks.reduce
3691 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2618 >        private final void lockRoot() {
2619 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2620 >                contendedLock(); // offload to separate method
2621          }
2622  
2623          /**
2624 <         * Returns the result of accumulating the given transformation
3696 <         * of all (key, value) pairs using the given reducer to
3697 <         * combine values, and the given basis as an identity value.
3698 <         *
3699 <         * @param transformer a function returning the transformation
3700 <         * for an element
3701 <         * @param basis the identity (initial default value) for the reduction
3702 <         * @param reducer a commutative associative combining function
3703 <         * @return the result of accumulating the given transformation
3704 <         * of all (key, value) pairs
2624 >         * Releases write lock for tree restructuring.
2625           */
2626 <        public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
2627 <                                     double basis,
3708 <                                     DoubleByDoubleToDouble reducer) {
3709 <            return fjp.invoke(ForkJoinTasks.reduceToDouble
3710 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2626 >        private final void unlockRoot() {
2627 >            lockState = 0;
2628          }
2629  
2630          /**
2631 <         * Returns the result of accumulating the given transformation
3715 <         * of all (key, value) pairs using the given reducer to
3716 <         * combine values, and the given basis as an identity value.
3717 <         *
3718 <         * @param transformer a function returning the transformation
3719 <         * for an element
3720 <         * @param basis the identity (initial default value) for the reduction
3721 <         * @param reducer a commutative associative combining function
3722 <         * @return the result of accumulating the given transformation
3723 <         * of all (key, value) pairs using the given reducer to
3724 <         * combine values, and the given basis as an identity value.
2631 >         * Possibly blocks awaiting root lock.
2632           */
2633 <        public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
2634 <                                 long basis,
2635 <                                 LongByLongToLong reducer) {
2636 <            return fjp.invoke(ForkJoinTasks.reduceToLong
2637 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2633 >        private final void contendedLock() {
2634 >            boolean waiting = false;
2635 >            for (int s;;) {
2636 >                if (((s = lockState) & WRITER) == 0) {
2637 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2638 >                        if (waiting)
2639 >                            waiter = null;
2640 >                        return;
2641 >                    }
2642 >                }
2643 >                else if ((s | WAITER) == 0) {
2644 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2645 >                        waiting = true;
2646 >                        waiter = Thread.currentThread();
2647 >                    }
2648 >                }
2649 >                else if (waiting)
2650 >                    LockSupport.park(this);
2651 >            }
2652          }
2653  
2654          /**
2655 <         * Returns the result of accumulating the given transformation
2656 <         * of all (key, value) pairs using the given reducer to
2657 <         * combine values, and the given basis as an identity value.
3737 <         *
3738 <         * @param transformer a function returning the transformation
3739 <         * for an element
3740 <         * @param basis the identity (initial default value) for the reduction
3741 <         * @param reducer a commutative associative combining function
3742 <         * @return the result of accumulating the given transformation
3743 <         * of all (key, value) pairs
2655 >         * Returns matching node or null if none. Tries to search
2656 >         * using tree compareisons from root, but continues linear
2657 >         * search when lock not available.
2658           */
2659 <        public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
2660 <                               int basis,
2661 <                               IntByIntToInt reducer) {
2662 <            return fjp.invoke(ForkJoinTasks.reduceToInt
2663 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2659 >        final Node<K,V> find(int h, Object k) {
2660 >            if (k != null) {
2661 >                for (Node<K,V> e = first; e != null; e = e.next) {
2662 >                    int s; K ek;
2663 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2664 >                        if (e.hash == h &&
2665 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2666 >                            return e;
2667 >                    }
2668 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2669 >                                                 s + READER)) {
2670 >                        TreeNode<K,V> r, p;
2671 >                        try {
2672 >                            p = ((r = root) == null ? null :
2673 >                                 r.findTreeNode(h, k, null));
2674 >                        } finally {
2675 >                            Thread w;
2676 >                            int ls;
2677 >                            do {} while (!U.compareAndSwapInt
2678 >                                         (this, LOCKSTATE,
2679 >                                          ls = lockState, ls - READER));
2680 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2681 >                                LockSupport.unpark(w);
2682 >                        }
2683 >                        return p;
2684 >                    }
2685 >                }
2686 >            }
2687 >            return null;
2688          }
2689  
2690          /**
2691 <         * Performs the given action for each key
2692 <         *
3755 <         * @param action the action
2691 >         * Finds or adds a node.
2692 >         * @return null if added
2693           */
2694 <        public void forEachKey(Action<K> action) {
2695 <            fjp.invoke(ForkJoinTasks.forEachKey
2696 <                       (ConcurrentHashMapV8.this, action));
2694 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2695 >            Class<?> kc = null;
2696 >            for (TreeNode<K,V> p = root;;) {
2697 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2698 >                if (p == null) {
2699 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2700 >                    break;
2701 >                }
2702 >                else if ((ph = p.hash) > h)
2703 >                    dir = -1;
2704 >                else if (ph < h)
2705 >                    dir = 1;
2706 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2707 >                    return p;
2708 >                else if ((kc == null &&
2709 >                          (kc = comparableClassFor(k)) == null) ||
2710 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2711 >                    if (p.left == null)
2712 >                        dir = 1;
2713 >                    else if ((pr = p.right) == null ||
2714 >                             (q = pr.findTreeNode(h, k, kc)) == null)
2715 >                        dir = -1;
2716 >                    else
2717 >                        return q;
2718 >                }
2719 >                TreeNode<K,V> xp = p;
2720 >                if ((p = (dir < 0) ? p.left : p.right) == null) {
2721 >                    TreeNode<K,V> x, f = first;
2722 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2723 >                    if (f != null)
2724 >                        f.prev = x;
2725 >                    if (dir < 0)
2726 >                        xp.left = x;
2727 >                    else
2728 >                        xp.right = x;
2729 >                    if (!xp.red)
2730 >                        x.red = true;
2731 >                    else {
2732 >                        lockRoot();
2733 >                        try {
2734 >                            root = balanceInsertion(root, x);
2735 >                        } finally {
2736 >                            unlockRoot();
2737 >                        }
2738 >                    }
2739 >                    break;
2740 >                }
2741 >            }
2742 >            assert checkInvariants(root);
2743 >            return null;
2744          }
2745  
2746          /**
2747 <         * Performs the given action for each non-null transformation
2748 <         * of each key
2747 >         * Removes the given node, that must be present before this
2748 >         * call.  This is messier than typical red-black deletion code
2749 >         * because we cannot swap the contents of an interior node
2750 >         * with a leaf successor that is pinned by "next" pointers
2751 >         * that are accessible independently of lock. So instead we
2752 >         * swap the tree linkages.
2753           *
2754 <         * @param transformer a function returning the transformation
3767 <         * for an element, or null of there is no transformation (in
3768 <         * which case the action is not applied).
3769 <         * @param action the action
2754 >         * @return true if now too small so should be untreeified.
2755           */
2756 <        public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
2757 <                                   Action<U> action) {
2758 <            fjp.invoke(ForkJoinTasks.forEachKey
2759 <                       (ConcurrentHashMapV8.this, transformer, action));
2756 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2757 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2758 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2759 >            TreeNode<K,V> r, rl;
2760 >            if (pred == null)
2761 >                first = next;
2762 >            else
2763 >                pred.next = next;
2764 >            if (next != null)
2765 >                next.prev = pred;
2766 >            if (first == null) {
2767 >                root = null;
2768 >                return true;
2769 >            }
2770 >            if ((r = root) == null || r.right == null || // too small
2771 >                (rl = r.left) == null || rl.left == null)
2772 >                return true;
2773 >            lockRoot();
2774 >            try {
2775 >                TreeNode<K,V> replacement;
2776 >                TreeNode<K,V> pl = p.left;
2777 >                TreeNode<K,V> pr = p.right;
2778 >                if (pl != null && pr != null) {
2779 >                    TreeNode<K,V> s = pr, sl;
2780 >                    while ((sl = s.left) != null) // find successor
2781 >                        s = sl;
2782 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2783 >                    TreeNode<K,V> sr = s.right;
2784 >                    TreeNode<K,V> pp = p.parent;
2785 >                    if (s == pr) { // p was s's direct parent
2786 >                        p.parent = s;
2787 >                        s.right = p;
2788 >                    }
2789 >                    else {
2790 >                        TreeNode<K,V> sp = s.parent;
2791 >                        if ((p.parent = sp) != null) {
2792 >                            if (s == sp.left)
2793 >                                sp.left = p;
2794 >                            else
2795 >                                sp.right = p;
2796 >                        }
2797 >                        if ((s.right = pr) != null)
2798 >                            pr.parent = s;
2799 >                    }
2800 >                    p.left = null;
2801 >                    if ((p.right = sr) != null)
2802 >                        sr.parent = p;
2803 >                    if ((s.left = pl) != null)
2804 >                        pl.parent = s;
2805 >                    if ((s.parent = pp) == null)
2806 >                        r = s;
2807 >                    else if (p == pp.left)
2808 >                        pp.left = s;
2809 >                    else
2810 >                        pp.right = s;
2811 >                    if (sr != null)
2812 >                        replacement = sr;
2813 >                    else
2814 >                        replacement = p;
2815 >                }
2816 >                else if (pl != null)
2817 >                    replacement = pl;
2818 >                else if (pr != null)
2819 >                    replacement = pr;
2820 >                else
2821 >                    replacement = p;
2822 >                if (replacement != p) {
2823 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2824 >                    if (pp == null)
2825 >                        r = replacement;
2826 >                    else if (p == pp.left)
2827 >                        pp.left = replacement;
2828 >                    else
2829 >                        pp.right = replacement;
2830 >                    p.left = p.right = p.parent = null;
2831 >                }
2832 >
2833 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2834 >
2835 >                if (p == replacement) {  // detach pointers
2836 >                    TreeNode<K,V> pp;
2837 >                    if ((pp = p.parent) != null) {
2838 >                        if (p == pp.left)
2839 >                            pp.left = null;
2840 >                        else if (p == pp.right)
2841 >                            pp.right = null;
2842 >                        p.parent = null;
2843 >                    }
2844 >                }
2845 >            } finally {
2846 >                unlockRoot();
2847 >            }
2848 >            assert checkInvariants(root);
2849 >            return false;
2850          }
2851  
2852 <        /**
2853 <         * Returns a non-null result from applying the given search
2854 <         * function on each key, or null if none.  Further element
2855 <         * processing is suppressed upon success. However, this method
2856 <         * does not return until other in-progress parallel
2857 <         * invocations of the search function also complete.
2858 <         *
2859 <         * @param searchFunction a function returning a non-null
2860 <         * result on success, else null
2861 <         * @return a non-null result from applying the given search
2862 <         * function on each key, or null if none
2863 <         */
2864 <        public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
2865 <            return fjp.invoke(ForkJoinTasks.searchKeys
2866 <                              (ConcurrentHashMapV8.this, searchFunction));
2852 >        /* ------------------------------------------------------------ */
2853 >        // Red-black tree methods, all adapted from CLR
2854 >
2855 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2856 >                                              TreeNode<K,V> p) {
2857 >            TreeNode<K,V> r, pp, rl;
2858 >            if (p != null && (r = p.right) != null) {
2859 >                if ((rl = p.right = r.left) != null)
2860 >                    rl.parent = p;
2861 >                if ((pp = r.parent = p.parent) == null)
2862 >                    (root = r).red = false;
2863 >                else if (pp.left == p)
2864 >                    pp.left = r;
2865 >                else
2866 >                    pp.right = r;
2867 >                r.left = p;
2868 >                p.parent = r;
2869 >            }
2870 >            return root;
2871          }
2872  
2873 <        /**
2874 <         * Returns the result of accumulating all keys using the given
2875 <         * reducer to combine values, or null if none.
2876 <         *
2877 <         * @param reducer a commutative associative combining function
2878 <         * @return the result of accumulating all keys using the given
2879 <         * reducer to combine values, or null if none
2880 <         */
2881 <        public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
2882 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2883 <                              (ConcurrentHashMapV8.this, reducer));
2873 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2874 >                                               TreeNode<K,V> p) {
2875 >            TreeNode<K,V> l, pp, lr;
2876 >            if (p != null && (l = p.left) != null) {
2877 >                if ((lr = p.left = l.right) != null)
2878 >                    lr.parent = p;
2879 >                if ((pp = l.parent = p.parent) == null)
2880 >                    (root = l).red = false;
2881 >                else if (pp.right == p)
2882 >                    pp.right = l;
2883 >                else
2884 >                    pp.left = l;
2885 >                l.right = p;
2886 >                p.parent = l;
2887 >            }
2888 >            return root;
2889          }
2890  
2891 <        /**
2892 <         * Returns the result of accumulating the given transformation
2893 <         * of all keys using the given reducer to combine values, or
2894 <         * null if none.
2895 <         *
2896 <         * @param transformer a function returning the transformation
2897 <         * for an element, or null of there is no transformation (in
2898 <         * which case it is not combined).
2899 <         * @param reducer a commutative associative combining function
2900 <         * @return the result of accumulating the given transformation
2901 <         * of all keys
2902 <         */
2903 <        public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
2904 <                                BiFun<? super U, ? super U, ? extends U> reducer) {
2905 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2906 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2891 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2892 >                                                    TreeNode<K,V> x) {
2893 >            x.red = true;
2894 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2895 >                if ((xp = x.parent) == null) {
2896 >                    x.red = false;
2897 >                    return x;
2898 >                }
2899 >                else if (!xp.red || (xpp = xp.parent) == null)
2900 >                    return root;
2901 >                if (xp == (xppl = xpp.left)) {
2902 >                    if ((xppr = xpp.right) != null && xppr.red) {
2903 >                        xppr.red = false;
2904 >                        xp.red = false;
2905 >                        xpp.red = true;
2906 >                        x = xpp;
2907 >                    }
2908 >                    else {
2909 >                        if (x == xp.right) {
2910 >                            root = rotateLeft(root, x = xp);
2911 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2912 >                        }
2913 >                        if (xp != null) {
2914 >                            xp.red = false;
2915 >                            if (xpp != null) {
2916 >                                xpp.red = true;
2917 >                                root = rotateRight(root, xpp);
2918 >                            }
2919 >                        }
2920 >                    }
2921 >                }
2922 >                else {
2923 >                    if (xppl != null && xppl.red) {
2924 >                        xppl.red = false;
2925 >                        xp.red = false;
2926 >                        xpp.red = true;
2927 >                        x = xpp;
2928 >                    }
2929 >                    else {
2930 >                        if (x == xp.left) {
2931 >                            root = rotateRight(root, x = xp);
2932 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2933 >                        }
2934 >                        if (xp != null) {
2935 >                            xp.red = false;
2936 >                            if (xpp != null) {
2937 >                                xpp.red = true;
2938 >                                root = rotateLeft(root, xpp);
2939 >                            }
2940 >                        }
2941 >                    }
2942 >                }
2943 >            }
2944          }
2945  
2946 <        /**
2947 <         * Returns the result of accumulating the given transformation
2948 <         * of all keys using the given reducer to combine values, and
2949 <         * the given basis as an identity value.
2950 <         *
2951 <         * @param transformer a function returning the transformation
2952 <         * for an element
2953 <         * @param basis the identity (initial default value) for the reduction
2954 <         * @param reducer a commutative associative combining function
2955 <         * @return  the result of accumulating the given transformation
2956 <         * of all keys
2957 <         */
2958 <        public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
2959 <                                         double basis,
2960 <                                         DoubleByDoubleToDouble reducer) {
2961 <            return fjp.invoke(ForkJoinTasks.reduceKeysToDouble
2962 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2946 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2947 >                                                   TreeNode<K,V> x) {
2948 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2949 >                if (x == null || x == root)
2950 >                    return root;
2951 >                else if ((xp = x.parent) == null) {
2952 >                    x.red = false;
2953 >                    return x;
2954 >                }
2955 >                else if (x.red) {
2956 >                    x.red = false;
2957 >                    return root;
2958 >                }
2959 >                else if ((xpl = xp.left) == x) {
2960 >                    if ((xpr = xp.right) != null && xpr.red) {
2961 >                        xpr.red = false;
2962 >                        xp.red = true;
2963 >                        root = rotateLeft(root, xp);
2964 >                        xpr = (xp = x.parent) == null ? null : xp.right;
2965 >                    }
2966 >                    if (xpr == null)
2967 >                        x = xp;
2968 >                    else {
2969 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2970 >                        if ((sr == null || !sr.red) &&
2971 >                            (sl == null || !sl.red)) {
2972 >                            xpr.red = true;
2973 >                            x = xp;
2974 >                        }
2975 >                        else {
2976 >                            if (sr == null || !sr.red) {
2977 >                                if (sl != null)
2978 >                                    sl.red = false;
2979 >                                xpr.red = true;
2980 >                                root = rotateRight(root, xpr);
2981 >                                xpr = (xp = x.parent) == null ?
2982 >                                    null : xp.right;
2983 >                            }
2984 >                            if (xpr != null) {
2985 >                                xpr.red = (xp == null) ? false : xp.red;
2986 >                                if ((sr = xpr.right) != null)
2987 >                                    sr.red = false;
2988 >                            }
2989 >                            if (xp != null) {
2990 >                                xp.red = false;
2991 >                                root = rotateLeft(root, xp);
2992 >                            }
2993 >                            x = root;
2994 >                        }
2995 >                    }
2996 >                }
2997 >                else { // symmetric
2998 >                    if (xpl != null && xpl.red) {
2999 >                        xpl.red = false;
3000 >                        xp.red = true;
3001 >                        root = rotateRight(root, xp);
3002 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3003 >                    }
3004 >                    if (xpl == null)
3005 >                        x = xp;
3006 >                    else {
3007 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3008 >                        if ((sl == null || !sl.red) &&
3009 >                            (sr == null || !sr.red)) {
3010 >                            xpl.red = true;
3011 >                            x = xp;
3012 >                        }
3013 >                        else {
3014 >                            if (sl == null || !sl.red) {
3015 >                                if (sr != null)
3016 >                                    sr.red = false;
3017 >                                xpl.red = true;
3018 >                                root = rotateLeft(root, xpl);
3019 >                                xpl = (xp = x.parent) == null ?
3020 >                                    null : xp.left;
3021 >                            }
3022 >                            if (xpl != null) {
3023 >                                xpl.red = (xp == null) ? false : xp.red;
3024 >                                if ((sl = xpl.left) != null)
3025 >                                    sl.red = false;
3026 >                            }
3027 >                            if (xp != null) {
3028 >                                xp.red = false;
3029 >                                root = rotateRight(root, xp);
3030 >                            }
3031 >                            x = root;
3032 >                        }
3033 >                    }
3034 >                }
3035 >            }
3036          }
3037  
3038          /**
3039 <         * Returns the result of accumulating the given transformation
3846 <         * of all keys using the given reducer to combine values, and
3847 <         * the given basis as an identity value.
3848 <         *
3849 <         * @param transformer a function returning the transformation
3850 <         * for an element
3851 <         * @param basis the identity (initial default value) for the reduction
3852 <         * @param reducer a commutative associative combining function
3853 <         * @return the result of accumulating the given transformation
3854 <         * of all keys
3039 >         * Recursive invariant check
3040           */
3041 <        public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3042 <                                     long basis,
3043 <                                     LongByLongToLong reducer) {
3044 <            return fjp.invoke(ForkJoinTasks.reduceKeysToLong
3045 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3041 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3042 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3043 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3044 >            if (tb != null && tb.next != t)
3045 >                return false;
3046 >            if (tn != null && tn.prev != t)
3047 >                return false;
3048 >            if (tp != null && t != tp.left && t != tp.right)
3049 >                return false;
3050 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3051 >                return false;
3052 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3053 >                return false;
3054 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3055 >                return false;
3056 >            if (tl != null && !checkInvariants(tl))
3057 >                return false;
3058 >            if (tr != null && !checkInvariants(tr))
3059 >                return false;
3060 >            return true;
3061          }
3062  
3063 <        /**
3064 <         * Returns the result of accumulating the given transformation
3065 <         * of all keys using the given reducer to combine values, and
3066 <         * the given basis as an identity value.
3067 <         *
3068 <         * @param transformer a function returning the transformation
3069 <         * for an element
3070 <         * @param basis the identity (initial default value) for the reduction
3071 <         * @param reducer a commutative associative combining function
3072 <         * @return the result of accumulating the given transformation
3073 <         * of all keys
3874 <         */
3875 <        public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3876 <                                   int basis,
3877 <                                   IntByIntToInt reducer) {
3878 <            return fjp.invoke(ForkJoinTasks.reduceKeysToInt
3879 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3063 >        private static final sun.misc.Unsafe U;
3064 >        private static final long LOCKSTATE;
3065 >        static {
3066 >            try {
3067 >                U = getUnsafe();
3068 >                Class<?> k = TreeBin.class;
3069 >                LOCKSTATE = U.objectFieldOffset
3070 >                    (k.getDeclaredField("lockState"));
3071 >            } catch (Exception e) {
3072 >                throw new Error(e);
3073 >            }
3074          }
3075 +    }
3076  
3077 <        /**
3078 <         * Performs the given action for each value
3079 <         *
3080 <         * @param action the action
3081 <         */
3082 <        public void forEachValue(Action<V> action) {
3083 <            fjp.invoke(ForkJoinTasks.forEachValue
3084 <                       (ConcurrentHashMapV8.this, action));
3077 >    /* ----------------Table Traversal -------------- */
3078 >
3079 >    /**
3080 >     * Encapsulates traversal for methods such as containsValue; also
3081 >     * serves as a base class for other iterators and spliterators.
3082 >     *
3083 >     * Method advance visits once each still-valid node that was
3084 >     * reachable upon iterator construction. It might miss some that
3085 >     * were added to a bin after the bin was visited, which is OK wrt
3086 >     * consistency guarantees. Maintaining this property in the face
3087 >     * of possible ongoing resizes requires a fair amount of
3088 >     * bookkeeping state that is difficult to optimize away amidst
3089 >     * volatile accesses.  Even so, traversal maintains reasonable
3090 >     * throughput.
3091 >     *
3092 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3093 >     * However, if the table has been resized, then all future steps
3094 >     * must traverse both the bin at the current index as well as at
3095 >     * (index + baseSize); and so on for further resizings. To
3096 >     * paranoically cope with potential sharing by users of iterators
3097 >     * across threads, iteration terminates if a bounds checks fails
3098 >     * for a table read.
3099 >     */
3100 >    static class Traverser<K,V> {
3101 >        Node<K,V>[] tab;        // current table; updated if resized
3102 >        Node<K,V> next;         // the next entry to use
3103 >        int index;              // index of bin to use next
3104 >        int baseIndex;          // current index of initial table
3105 >        int baseLimit;          // index bound for initial table
3106 >        final int baseSize;     // initial table size
3107 >
3108 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3109 >            this.tab = tab;
3110 >            this.baseSize = size;
3111 >            this.baseIndex = this.index = index;
3112 >            this.baseLimit = limit;
3113 >            this.next = null;
3114          }
3115  
3116          /**
3117 <         * Performs the given action for each non-null transformation
3118 <         * of each value
3119 <         *
3120 <         * @param transformer a function returning the transformation
3121 <         * for an element, or null of there is no transformation (in
3122 <         * which case the action is not applied).
3123 <         */
3124 <        public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3125 <                                     Action<U> action) {
3126 <            fjp.invoke(ForkJoinTasks.forEachValue
3127 <                       (ConcurrentHashMapV8.this, transformer, action));
3117 >         * Advances if possible, returning next valid node, or null if none.
3118 >         */
3119 >        final Node<K,V> advance() {
3120 >            Node<K,V> e;
3121 >            if ((e = next) != null)
3122 >                e = e.next;
3123 >            for (;;) {
3124 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3125 >                if (e != null)
3126 >                    return next = e;
3127 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3128 >                    (n = t.length) <= (i = index) || i < 0)
3129 >                    return next = null;
3130 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3131 >                    if (e instanceof ForwardingNode) {
3132 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3133 >                        e = null;
3134 >                        continue;
3135 >                    }
3136 >                    else if (e instanceof TreeBin)
3137 >                        e = ((TreeBin<K,V>)e).first;
3138 >                    else
3139 >                        e = null;
3140 >                }
3141 >                if ((index += baseSize) >= n)
3142 >                    index = ++baseIndex;    // visit upper slots if present
3143 >            }
3144          }
3145 +    }
3146  
3147 <        /**
3148 <         * Returns a non-null result from applying the given search
3149 <         * function on each value, or null if none.  Further element
3150 <         * processing is suppressed upon success. However, this method
3151 <         * does not return until other in-progress parallel
3152 <         * invocations of the search function also complete.
3153 <         *
3154 <         * @param searchFunction a function returning a non-null
3155 <         * result on success, else null
3156 <         * @return a non-null result from applying the given search
3157 <         * function on each value, or null if none
3158 <         *
3918 <         */
3919 <        public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3920 <            return fjp.invoke(ForkJoinTasks.searchValues
3921 <                              (ConcurrentHashMapV8.this, searchFunction));
3147 >    /**
3148 >     * Base of key, value, and entry Iterators. Adds fields to
3149 >     * Traverser to support iterator.remove.
3150 >     */
3151 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3152 >        final ConcurrentHashMapV8<K,V> map;
3153 >        Node<K,V> lastReturned;
3154 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3155 >                    ConcurrentHashMapV8<K,V> map) {
3156 >            super(tab, size, index, limit);
3157 >            this.map = map;
3158 >            advance();
3159          }
3160  
3161 <        /**
3162 <         * Returns the result of accumulating all values using the
3163 <         * given reducer to combine values, or null if none.
3164 <         *
3165 <         * @param reducer a commutative associative combining function
3166 <         * @return  the result of accumulating all values
3167 <         */
3168 <        public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3169 <            return fjp.invoke(ForkJoinTasks.reduceValues
3933 <                              (ConcurrentHashMapV8.this, reducer));
3161 >        public final boolean hasNext() { return next != null; }
3162 >        public final boolean hasMoreElements() { return next != null; }
3163 >
3164 >        public final void remove() {
3165 >            Node<K,V> p;
3166 >            if ((p = lastReturned) == null)
3167 >                throw new IllegalStateException();
3168 >            lastReturned = null;
3169 >            map.replaceNode(p.key, null, null);
3170          }
3171 +    }
3172  
3173 <        /**
3174 <         * Returns the result of accumulating the given transformation
3175 <         * of all values using the given reducer to combine values, or
3176 <         * null if none.
3177 <         *
3941 <         * @param transformer a function returning the transformation
3942 <         * for an element, or null of there is no transformation (in
3943 <         * which case it is not combined).
3944 <         * @param reducer a commutative associative combining function
3945 <         * @return the result of accumulating the given transformation
3946 <         * of all values
3947 <         */
3948 <        public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3949 <                                  BiFun<? super U, ? super U, ? extends U> reducer) {
3950 <            return fjp.invoke(ForkJoinTasks.reduceValues
3951 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3173 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3174 >        implements Iterator<K>, Enumeration<K> {
3175 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3176 >                    ConcurrentHashMapV8<K,V> map) {
3177 >            super(tab, index, size, limit, map);
3178          }
3179  
3180 <        /**
3181 <         * Returns the result of accumulating the given transformation
3182 <         * of all values using the given reducer to combine values,
3183 <         * and the given basis as an identity value.
3184 <         *
3185 <         * @param transformer a function returning the transformation
3186 <         * for an element
3187 <         * @param basis the identity (initial default value) for the reduction
3962 <         * @param reducer a commutative associative combining function
3963 <         * @return the result of accumulating the given transformation
3964 <         * of all values
3965 <         */
3966 <        public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3967 <                                           double basis,
3968 <                                           DoubleByDoubleToDouble reducer) {
3969 <            return fjp.invoke(ForkJoinTasks.reduceValuesToDouble
3970 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3180 >        public final K next() {
3181 >            Node<K,V> p;
3182 >            if ((p = next) == null)
3183 >                throw new NoSuchElementException();
3184 >            K k = p.key;
3185 >            lastReturned = p;
3186 >            advance();
3187 >            return k;
3188          }
3189  
3190 <        /**
3191 <         * Returns the result of accumulating the given transformation
3192 <         * of all values using the given reducer to combine values,
3193 <         * and the given basis as an identity value.
3194 <         *
3195 <         * @param transformer a function returning the transformation
3196 <         * for an element
3197 <         * @param basis the identity (initial default value) for the reduction
3981 <         * @param reducer a commutative associative combining function
3982 <         * @return the result of accumulating the given transformation
3983 <         * of all values
3984 <         */
3985 <        public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3986 <                                       long basis,
3987 <                                       LongByLongToLong reducer) {
3988 <            return fjp.invoke(ForkJoinTasks.reduceValuesToLong
3989 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3190 >        public final K nextElement() { return next(); }
3191 >    }
3192 >
3193 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3194 >        implements Iterator<V>, Enumeration<V> {
3195 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3196 >                      ConcurrentHashMapV8<K,V> map) {
3197 >            super(tab, index, size, limit, map);
3198          }
3199  
3200 <        /**
3201 <         * Returns the result of accumulating the given transformation
3202 <         * of all values using the given reducer to combine values,
3203 <         * and the given basis as an identity value.
3204 <         *
3205 <         * @param transformer a function returning the transformation
3206 <         * for an element
3207 <         * @param basis the identity (initial default value) for the reduction
4000 <         * @param reducer a commutative associative combining function
4001 <         * @return the result of accumulating the given transformation
4002 <         * of all values
4003 <         */
4004 <        public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4005 <                                     int basis,
4006 <                                     IntByIntToInt reducer) {
4007 <            return fjp.invoke(ForkJoinTasks.reduceValuesToInt
4008 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3200 >        public final V next() {
3201 >            Node<K,V> p;
3202 >            if ((p = next) == null)
3203 >                throw new NoSuchElementException();
3204 >            V v = p.val;
3205 >            lastReturned = p;
3206 >            advance();
3207 >            return v;
3208          }
3209  
3210 <        /**
3211 <         * Perform the given action for each entry
3212 <         *
3213 <         * @param action the action
3214 <         */
3215 <        public void forEachEntry(Action<Map.Entry<K,V>> action) {
3216 <            fjp.invoke(ForkJoinTasks.forEachEntry
3217 <                       (ConcurrentHashMapV8.this, action));
3210 >        public final V nextElement() { return next(); }
3211 >    }
3212 >
3213 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3214 >        implements Iterator<Map.Entry<K,V>> {
3215 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3216 >                      ConcurrentHashMapV8<K,V> map) {
3217 >            super(tab, index, size, limit, map);
3218          }
3219  
3220 <        /**
3221 <         * Perform the given action for each non-null transformation
3222 <         * of each entry
3223 <         *
3224 <         * @param transformer a function returning the transformation
3225 <         * for an element, or null of there is no transformation (in
3226 <         * which case the action is not applied).
3227 <         * @param action the action
3228 <         */
4030 <        public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4031 <                                     Action<U> action) {
4032 <            fjp.invoke(ForkJoinTasks.forEachEntry
4033 <                       (ConcurrentHashMapV8.this, transformer, action));
3220 >        public final Map.Entry<K,V> next() {
3221 >            Node<K,V> p;
3222 >            if ((p = next) == null)
3223 >                throw new NoSuchElementException();
3224 >            K k = p.key;
3225 >            V v = p.val;
3226 >            lastReturned = p;
3227 >            advance();
3228 >            return new MapEntry<K,V>(k, v, map);
3229          }
3230 +    }
3231  
3232 <        /**
3233 <         * Returns a non-null result from applying the given search
3234 <         * function on each entry, or null if none.  Further element
3235 <         * processing is suppressed upon success. However, this method
3236 <         * does not return until other in-progress parallel
3237 <         * invocations of the search function also complete.
3238 <         *
3239 <         * @param searchFunction a function returning a non-null
3240 <         * result on success, else null
3241 <         * @return a non-null result from applying the given search
3242 <         * function on each entry, or null if none
4047 <         */
4048 <        public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4049 <            return fjp.invoke(ForkJoinTasks.searchEntries
4050 <                              (ConcurrentHashMapV8.this, searchFunction));
3232 >    /**
3233 >     * Exported Entry for EntryIterator
3234 >     */
3235 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3236 >        final K key; // non-null
3237 >        V val;       // non-null
3238 >        final ConcurrentHashMapV8<K,V> map;
3239 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3240 >            this.key = key;
3241 >            this.val = val;
3242 >            this.map = map;
3243          }
3244 +        public K getKey()        { return key; }
3245 +        public V getValue()      { return val; }
3246 +        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3247 +        public String toString() { return key + "=" + val; }
3248  
3249 <        /**
3250 <         * Returns the result of accumulating all entries using the
3251 <         * given reducer to combine values, or null if none.
3252 <         *
3253 <         * @param reducer a commutative associative combining function
3254 <         * @return the result of accumulating all entries
3255 <         */
4060 <        public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4061 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4062 <                              (ConcurrentHashMapV8.this, reducer));
3249 >        public boolean equals(Object o) {
3250 >            Object k, v; Map.Entry<?,?> e;
3251 >            return ((o instanceof Map.Entry) &&
3252 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3253 >                    (v = e.getValue()) != null &&
3254 >                    (k == key || k.equals(key)) &&
3255 >                    (v == val || v.equals(val)));
3256          }
3257  
3258          /**
3259 <         * Returns the result of accumulating the given transformation
3260 <         * of all entries using the given reducer to combine values,
3261 <         * or null if none.
3262 <         *
3263 <         * @param transformer a function returning the transformation
3264 <         * for an element, or null of there is no transformation (in
4072 <         * which case it is not combined).
4073 <         * @param reducer a commutative associative combining function
4074 <         * @return the result of accumulating the given transformation
4075 <         * of all entries
3259 >         * Sets our entry's value and writes through to the map. The
3260 >         * value to return is somewhat arbitrary here. Since we do not
3261 >         * necessarily track asynchronous changes, the most recent
3262 >         * "previous" value could be different from what we return (or
3263 >         * could even have been removed, in which case the put will
3264 >         * re-establish). We do not and cannot guarantee more.
3265           */
3266 <        public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
3267 <                                   BiFun<? super U, ? super U, ? extends U> reducer) {
3268 <            return fjp.invoke(ForkJoinTasks.reduceEntries
3269 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3266 >        public V setValue(V value) {
3267 >            if (value == null) throw new NullPointerException();
3268 >            V v = val;
3269 >            val = value;
3270 >            map.put(key, value);
3271 >            return v;
3272          }
3273 +    }
3274  
3275 <        /**
3276 <         * Returns the result of accumulating the given transformation
3277 <         * of all entries using the given reducer to combine values,
3278 <         * and the given basis as an identity value.
3279 <         *
3280 <         * @param transformer a function returning the transformation
3281 <         * for an element
3282 <         * @param basis the identity (initial default value) for the reduction
3283 <         * @param reducer a commutative associative combining function
3284 <         * @return the result of accumulating the given transformation
3285 <         * of all entries
3286 <         */
3287 <        public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
3288 <                                            double basis,
4097 <                                            DoubleByDoubleToDouble reducer) {
4098 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToDouble
4099 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3275 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3276 >        implements ConcurrentHashMapSpliterator<K> {
3277 >        long est;               // size estimate
3278 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3279 >                       long est) {
3280 >            super(tab, size, index, limit);
3281 >            this.est = est;
3282 >        }
3283 >
3284 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3285 >            int i, f, h;
3286 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3287 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3288 >                                        f, est >>>= 1);
3289          }
3290  
3291 <        /**
3292 <         * Returns the result of accumulating the given transformation
3293 <         * of all entries using the given reducer to combine values,
3294 <         * and the given basis as an identity value.
4106 <         *
4107 <         * @param transformer a function returning the transformation
4108 <         * for an element
4109 <         * @param basis the identity (initial default value) for the reduction
4110 <         * @param reducer a commutative associative combining function
4111 <         * @return  the result of accumulating the given transformation
4112 <         * of all entries
4113 <         */
4114 <        public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4115 <                                        long basis,
4116 <                                        LongByLongToLong reducer) {
4117 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToLong
4118 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3291 >        public void forEachRemaining(Action<? super K> action) {
3292 >            if (action == null) throw new NullPointerException();
3293 >            for (Node<K,V> p; (p = advance()) != null;)
3294 >                action.apply(p.key);
3295          }
3296  
3297 <        /**
3298 <         * Returns the result of accumulating the given transformation
3299 <         * of all entries using the given reducer to combine values,
3300 <         * and the given basis as an identity value.
3301 <         *
3302 <         * @param transformer a function returning the transformation
3303 <         * for an element
4128 <         * @param basis the identity (initial default value) for the reduction
4129 <         * @param reducer a commutative associative combining function
4130 <         * @return the result of accumulating the given transformation
4131 <         * of all entries
4132 <         */
4133 <        public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4134 <                                      int basis,
4135 <                                      IntByIntToInt reducer) {
4136 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToInt
4137 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3297 >        public boolean tryAdvance(Action<? super K> action) {
3298 >            if (action == null) throw new NullPointerException();
3299 >            Node<K,V> p;
3300 >            if ((p = advance()) == null)
3301 >                return false;
3302 >            action.apply(p.key);
3303 >            return true;
3304          }
3305 +
3306 +        public long estimateSize() { return est; }
3307 +
3308      }
3309  
3310 <    // ---------------------------------------------------------------------
3310 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3311 >        implements ConcurrentHashMapSpliterator<V> {
3312 >        long est;               // size estimate
3313 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3314 >                         long est) {
3315 >            super(tab, size, index, limit);
3316 >            this.est = est;
3317 >        }
3318  
3319 <    /**
3320 <     * Predefined tasks for performing bulk parallel operations on
3321 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
3322 <     * in class {@link Parallel}. Each method has the same name, but
3323 <     * returns a task rather than invoking it. These methods may be
3324 <     * useful in custom applications such as submitting a task without
4149 <     * waiting for completion, or combining with other tasks.
4150 <     */
4151 <    public static class ForkJoinTasks {
4152 <        private ForkJoinTasks() {}
3319 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3320 >            int i, f, h;
3321 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3322 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3323 >                                          f, est >>>= 1);
3324 >        }
3325  
3326 <        /**
4155 <         * Returns a task that when invoked, performs the given
4156 <         * action for each (key, value)
4157 <         *
4158 <         * @param map the map
4159 <         * @param action the action
4160 <         * @return the task
4161 <         */
4162 <        public static <K,V> ForkJoinTask<Void> forEach
4163 <            (ConcurrentHashMapV8<K,V> map,
4164 <             BiAction<K,V> action) {
3326 >        public void forEachRemaining(Action<? super V> action) {
3327              if (action == null) throw new NullPointerException();
3328 <            return new ForEachMappingTask<K,V>(map, action);
3328 >            for (Node<K,V> p; (p = advance()) != null;)
3329 >                action.apply(p.val);
3330          }
3331  
3332 <        /**
3333 <         * Returns a task that when invoked, performs the given
3334 <         * action for each non-null transformation of each (key, value)
3335 <         *
3336 <         * @param map the map
3337 <         * @param transformer a function returning the transformation
3338 <         * for an element, or null of there is no transformation (in
4176 <         * which case the action is not applied).
4177 <         * @param action the action
4178 <         * @return the task
4179 <         */
4180 <        public static <K,V,U> ForkJoinTask<Void> forEach
4181 <            (ConcurrentHashMapV8<K,V> map,
4182 <             BiFun<? super K, ? super V, ? extends U> transformer,
4183 <             Action<U> action) {
4184 <            if (transformer == null || action == null)
4185 <                throw new NullPointerException();
4186 <            return new ForEachTransformedMappingTask<K,V,U>
4187 <                (map, transformer, action);
3332 >        public boolean tryAdvance(Action<? super V> action) {
3333 >            if (action == null) throw new NullPointerException();
3334 >            Node<K,V> p;
3335 >            if ((p = advance()) == null)
3336 >                return false;
3337 >            action.apply(p.val);
3338 >            return true;
3339          }
3340  
3341 <        /**
3342 <         * Returns a task that when invoked, returns a non-null
3343 <         * result from applying the given search function on each
3344 <         * (key, value), or null if none.  Further element processing
3345 <         * is suppressed upon success. However, this method does not
3346 <         * return until other in-progress parallel invocations of the
3347 <         * search function also complete.
3348 <         *
3349 <         * @param map the map
3350 <         * @param searchFunction a function returning a non-null
3351 <         * result on success, else null
3352 <         * @return the task
3353 <         */
4203 <        public static <K,V,U> ForkJoinTask<U> search
4204 <            (ConcurrentHashMapV8<K,V> map,
4205 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4206 <            if (searchFunction == null) throw new NullPointerException();
4207 <            return new SearchMappingsTask<K,V,U>
4208 <                (map, searchFunction,
4209 <                 new AtomicReference<U>());
3341 >        public long estimateSize() { return est; }
3342 >
3343 >    }
3344 >
3345 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3346 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3347 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3348 >        long est;               // size estimate
3349 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3350 >                         long est, ConcurrentHashMapV8<K,V> map) {
3351 >            super(tab, size, index, limit);
3352 >            this.map = map;
3353 >            this.est = est;
3354          }
3355  
3356 <        /**
3357 <         * Returns a task that when invoked, returns the result of
3358 <         * accumulating the given transformation of all (key, value) pairs
3359 <         * using the given reducer to combine values, or null if none.
3360 <         *
4217 <         * @param map the map
4218 <         * @param transformer a function returning the transformation
4219 <         * for an element, or null of there is no transformation (in
4220 <         * which case it is not combined).
4221 <         * @param reducer a commutative associative combining function
4222 <         * @return the task
4223 <         */
4224 <        public static <K,V,U> ForkJoinTask<U> reduce
4225 <            (ConcurrentHashMapV8<K,V> map,
4226 <             BiFun<? super K, ? super V, ? extends U> transformer,
4227 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4228 <            if (transformer == null || reducer == null)
4229 <                throw new NullPointerException();
4230 <            return new MapReduceMappingsTask<K,V,U>
4231 <                (map, transformer, reducer);
3356 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3357 >            int i, f, h;
3358 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3359 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3360 >                                          f, est >>>= 1, map);
3361          }
3362  
3363 <        /**
3364 <         * Returns a task that when invoked, returns the result of
3365 <         * accumulating the given transformation of all (key, value) pairs
3366 <         * using the given reducer to combine values, and the given
4238 <         * basis as an identity value.
4239 <         *
4240 <         * @param map the map
4241 <         * @param transformer a function returning the transformation
4242 <         * for an element
4243 <         * @param basis the identity (initial default value) for the reduction
4244 <         * @param reducer a commutative associative combining function
4245 <         * @return the task
4246 <         */
4247 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4248 <            (ConcurrentHashMapV8<K,V> map,
4249 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4250 <             double basis,
4251 <             DoubleByDoubleToDouble reducer) {
4252 <            if (transformer == null || reducer == null)
4253 <                throw new NullPointerException();
4254 <            return new MapReduceMappingsToDoubleTask<K,V>
4255 <                (map, transformer, basis, reducer);
3363 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3364 >            if (action == null) throw new NullPointerException();
3365 >            for (Node<K,V> p; (p = advance()) != null; )
3366 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3367          }
3368  
3369 <        /**
3370 <         * Returns a task that when invoked, returns the result of
3371 <         * accumulating the given transformation of all (key, value) pairs
3372 <         * using the given reducer to combine values, and the given
3373 <         * basis as an identity value.
3374 <         *
3375 <         * @param map the map
4265 <         * @param transformer a function returning the transformation
4266 <         * for an element
4267 <         * @param basis the identity (initial default value) for the reduction
4268 <         * @param reducer a commutative associative combining function
4269 <         * @return the task
4270 <         */
4271 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4272 <            (ConcurrentHashMapV8<K,V> map,
4273 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4274 <             long basis,
4275 <             LongByLongToLong reducer) {
4276 <            if (transformer == null || reducer == null)
4277 <                throw new NullPointerException();
4278 <            return new MapReduceMappingsToLongTask<K,V>
4279 <                (map, transformer, basis, reducer);
3369 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3370 >            if (action == null) throw new NullPointerException();
3371 >            Node<K,V> p;
3372 >            if ((p = advance()) == null)
3373 >                return false;
3374 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3375 >            return true;
3376          }
3377  
3378 +        public long estimateSize() { return est; }
3379 +
3380 +    }
3381 +
3382 +    // Parallel bulk operations
3383 +
3384 +    /**
3385 +     * Computes initial batch value for bulk tasks. The returned value
3386 +     * is approximately exp2 of the number of times (minus one) to
3387 +     * split task by two before executing leaf action. This value is
3388 +     * faster to compute and more convenient to use as a guide to
3389 +     * splitting than is the depth, since it is used while dividing by
3390 +     * two anyway.
3391 +     */
3392 +    final int batchFor(long b) {
3393 +        long n;
3394 +        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3395 +            return 0;
3396 +        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3397 +        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3398 +    }
3399 +
3400 +    /**
3401 +     * Performs the given action for each (key, value).
3402 +     *
3403 +     * @param parallelismThreshold the (estimated) number of elements
3404 +     * needed for this operation to be executed in parallel
3405 +     * @param action the action
3406 +     * @since 1.8
3407 +     */
3408 +    public void forEach(long parallelismThreshold,
3409 +                        BiAction<? super K,? super V> action) {
3410 +        if (action == null) throw new NullPointerException();
3411 +        new ForEachMappingTask<K,V>
3412 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3413 +             action).invoke();
3414 +    }
3415 +
3416 +    /**
3417 +     * Performs the given action for each non-null transformation
3418 +     * of each (key, value).
3419 +     *
3420 +     * @param parallelismThreshold the (estimated) number of elements
3421 +     * needed for this operation to be executed in parallel
3422 +     * @param transformer a function returning the transformation
3423 +     * for an element, or null if there is no transformation (in
3424 +     * which case the action is not applied)
3425 +     * @param action the action
3426 +     * @since 1.8
3427 +     */
3428 +    public <U> void forEach(long parallelismThreshold,
3429 +                            BiFun<? super K, ? super V, ? extends U> transformer,
3430 +                            Action<? super U> action) {
3431 +        if (transformer == null || action == null)
3432 +            throw new NullPointerException();
3433 +        new ForEachTransformedMappingTask<K,V,U>
3434 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3435 +             transformer, action).invoke();
3436 +    }
3437 +
3438 +    /**
3439 +     * Returns a non-null result from applying the given search
3440 +     * function on each (key, value), or null if none.  Upon
3441 +     * success, further element processing is suppressed and the
3442 +     * results of any other parallel invocations of the search
3443 +     * function are ignored.
3444 +     *
3445 +     * @param parallelismThreshold the (estimated) number of elements
3446 +     * needed for this operation to be executed in parallel
3447 +     * @param searchFunction a function returning a non-null
3448 +     * result on success, else null
3449 +     * @return a non-null result from applying the given search
3450 +     * function on each (key, value), or null if none
3451 +     * @since 1.8
3452 +     */
3453 +    public <U> U search(long parallelismThreshold,
3454 +                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3455 +        if (searchFunction == null) throw new NullPointerException();
3456 +        return new SearchMappingsTask<K,V,U>
3457 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3458 +             searchFunction, new AtomicReference<U>()).invoke();
3459 +    }
3460 +
3461 +    /**
3462 +     * Returns the result of accumulating the given transformation
3463 +     * of all (key, value) pairs using the given reducer to
3464 +     * combine values, or null if none.
3465 +     *
3466 +     * @param parallelismThreshold the (estimated) number of elements
3467 +     * needed for this operation to be executed in parallel
3468 +     * @param transformer a function returning the transformation
3469 +     * for an element, or null if there is no transformation (in
3470 +     * which case it is not combined)
3471 +     * @param reducer a commutative associative combining function
3472 +     * @return the result of accumulating the given transformation
3473 +     * of all (key, value) pairs
3474 +     * @since 1.8
3475 +     */
3476 +    public <U> U reduce(long parallelismThreshold,
3477 +                        BiFun<? super K, ? super V, ? extends U> transformer,
3478 +                        BiFun<? super U, ? super U, ? extends U> reducer) {
3479 +        if (transformer == null || reducer == null)
3480 +            throw new NullPointerException();
3481 +        return new MapReduceMappingsTask<K,V,U>
3482 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3483 +             null, transformer, reducer).invoke();
3484 +    }
3485 +
3486 +    /**
3487 +     * Returns the result of accumulating the given transformation
3488 +     * of all (key, value) pairs using the given reducer to
3489 +     * combine values, and the given basis as an identity value.
3490 +     *
3491 +     * @param parallelismThreshold the (estimated) number of elements
3492 +     * needed for this operation to be executed in parallel
3493 +     * @param transformer a function returning the transformation
3494 +     * for an element
3495 +     * @param basis the identity (initial default value) for the reduction
3496 +     * @param reducer a commutative associative combining function
3497 +     * @return the result of accumulating the given transformation
3498 +     * of all (key, value) pairs
3499 +     * @since 1.8
3500 +     */
3501 +    public double reduceToDoubleIn(long parallelismThreshold,
3502 +                                   ObjectByObjectToDouble<? super K, ? super V> transformer,
3503 +                                   double basis,
3504 +                                   DoubleByDoubleToDouble reducer) {
3505 +        if (transformer == null || reducer == null)
3506 +            throw new NullPointerException();
3507 +        return new MapReduceMappingsToDoubleTask<K,V>
3508 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3509 +             null, transformer, basis, reducer).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, and the given basis as an identity value.
3516 +     *
3517 +     * @param parallelismThreshold the (estimated) number of elements
3518 +     * needed for this operation to be executed in parallel
3519 +     * @param transformer a function returning the transformation
3520 +     * for an element
3521 +     * @param basis the identity (initial default value) for the reduction
3522 +     * @param reducer a commutative associative combining function
3523 +     * @return the result of accumulating the given transformation
3524 +     * of all (key, value) pairs
3525 +     * @since 1.8
3526 +     */
3527 +    public long reduceToLong(long parallelismThreshold,
3528 +                             ObjectByObjectToLong<? super K, ? super V> transformer,
3529 +                             long basis,
3530 +                             LongByLongToLong reducer) {
3531 +        if (transformer == null || reducer == null)
3532 +            throw new NullPointerException();
3533 +        return new MapReduceMappingsToLongTask<K,V>
3534 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3535 +             null, transformer, basis, reducer).invoke();
3536 +    }
3537 +
3538 +    /**
3539 +     * Returns the result of accumulating the given transformation
3540 +     * of all (key, value) pairs using the given reducer to
3541 +     * combine values, and the given basis as an identity value.
3542 +     *
3543 +     * @param parallelismThreshold the (estimated) number of elements
3544 +     * needed for this operation to be executed in parallel
3545 +     * @param transformer a function returning the transformation
3546 +     * for an element
3547 +     * @param basis the identity (initial default value) for the reduction
3548 +     * @param reducer a commutative associative combining function
3549 +     * @return the result of accumulating the given transformation
3550 +     * of all (key, value) pairs
3551 +     * @since 1.8
3552 +     */
3553 +    public int reduceToInt(long parallelismThreshold,
3554 +                           ObjectByObjectToInt<? super K, ? super V> transformer,
3555 +                           int basis,
3556 +                           IntByIntToInt reducer) {
3557 +        if (transformer == null || reducer == null)
3558 +            throw new NullPointerException();
3559 +        return new MapReduceMappingsToIntTask<K,V>
3560 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3561 +             null, transformer, basis, reducer).invoke();
3562 +    }
3563 +
3564 +    /**
3565 +     * Performs the given action for each key.
3566 +     *
3567 +     * @param parallelismThreshold the (estimated) number of elements
3568 +     * needed for this operation to be executed in parallel
3569 +     * @param action the action
3570 +     * @since 1.8
3571 +     */
3572 +    public void forEachKey(long parallelismThreshold,
3573 +                           Action<? super K> action) {
3574 +        if (action == null) throw new NullPointerException();
3575 +        new ForEachKeyTask<K,V>
3576 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3577 +             action).invoke();
3578 +    }
3579 +
3580 +    /**
3581 +     * Performs the given action for each non-null transformation
3582 +     * of each key.
3583 +     *
3584 +     * @param parallelismThreshold the (estimated) number of elements
3585 +     * needed for this operation to be executed in parallel
3586 +     * @param transformer a function returning the transformation
3587 +     * for an element, or null if there is no transformation (in
3588 +     * which case the action is not applied)
3589 +     * @param action the action
3590 +     * @since 1.8
3591 +     */
3592 +    public <U> void forEachKey(long parallelismThreshold,
3593 +                               Fun<? super K, ? extends U> transformer,
3594 +                               Action<? super U> action) {
3595 +        if (transformer == null || action == null)
3596 +            throw new NullPointerException();
3597 +        new ForEachTransformedKeyTask<K,V,U>
3598 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3599 +             transformer, action).invoke();
3600 +    }
3601 +
3602 +    /**
3603 +     * Returns a non-null result from applying the given search
3604 +     * function on each key, or null if none. Upon success,
3605 +     * further element processing is suppressed and the results of
3606 +     * any other parallel invocations of the search function are
3607 +     * ignored.
3608 +     *
3609 +     * @param parallelismThreshold the (estimated) number of elements
3610 +     * needed for this operation to be executed in parallel
3611 +     * @param searchFunction a function returning a non-null
3612 +     * result on success, else null
3613 +     * @return a non-null result from applying the given search
3614 +     * function on each key, or null if none
3615 +     * @since 1.8
3616 +     */
3617 +    public <U> U searchKeys(long parallelismThreshold,
3618 +                            Fun<? super K, ? extends U> searchFunction) {
3619 +        if (searchFunction == null) throw new NullPointerException();
3620 +        return new SearchKeysTask<K,V,U>
3621 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3622 +             searchFunction, new AtomicReference<U>()).invoke();
3623 +    }
3624 +
3625 +    /**
3626 +     * Returns the result of accumulating all keys using the given
3627 +     * reducer to combine values, or null if none.
3628 +     *
3629 +     * @param parallelismThreshold the (estimated) number of elements
3630 +     * needed for this operation to be executed in parallel
3631 +     * @param reducer a commutative associative combining function
3632 +     * @return the result of accumulating all keys using the given
3633 +     * reducer to combine values, or null if none
3634 +     * @since 1.8
3635 +     */
3636 +    public K reduceKeys(long parallelismThreshold,
3637 +                        BiFun<? super K, ? super K, ? extends K> reducer) {
3638 +        if (reducer == null) throw new NullPointerException();
3639 +        return new ReduceKeysTask<K,V>
3640 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3641 +             null, reducer).invoke();
3642 +    }
3643 +
3644 +    /**
3645 +     * Returns the result of accumulating the given transformation
3646 +     * of all keys using the given reducer to combine values, or
3647 +     * null if none.
3648 +     *
3649 +     * @param parallelismThreshold the (estimated) number of elements
3650 +     * needed for this operation to be executed in parallel
3651 +     * @param transformer a function returning the transformation
3652 +     * for an element, or null if there is no transformation (in
3653 +     * which case it is not combined)
3654 +     * @param reducer a commutative associative combining function
3655 +     * @return the result of accumulating the given transformation
3656 +     * of all keys
3657 +     * @since 1.8
3658 +     */
3659 +    public <U> U reduceKeys(long parallelismThreshold,
3660 +                            Fun<? super K, ? extends U> transformer,
3661 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3662 +        if (transformer == null || reducer == null)
3663 +            throw new NullPointerException();
3664 +        return new MapReduceKeysTask<K,V,U>
3665 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3666 +             null, transformer, reducer).invoke();
3667 +    }
3668 +
3669 +    /**
3670 +     * Returns the result of accumulating the given transformation
3671 +     * of all keys using the given reducer to combine values, and
3672 +     * the given basis as an identity value.
3673 +     *
3674 +     * @param parallelismThreshold the (estimated) number of elements
3675 +     * needed for this operation to be executed in parallel
3676 +     * @param transformer a function returning the transformation
3677 +     * for an element
3678 +     * @param basis the identity (initial default value) for the reduction
3679 +     * @param reducer a commutative associative combining function
3680 +     * @return the result of accumulating the given transformation
3681 +     * of all keys
3682 +     * @since 1.8
3683 +     */
3684 +    public double reduceKeysToDouble(long parallelismThreshold,
3685 +                                     ObjectToDouble<? super K> transformer,
3686 +                                     double basis,
3687 +                                     DoubleByDoubleToDouble reducer) {
3688 +        if (transformer == null || reducer == null)
3689 +            throw new NullPointerException();
3690 +        return new MapReduceKeysToDoubleTask<K,V>
3691 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3692 +             null, transformer, basis, 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, and
3698 +     * the given basis as an identity value.
3699 +     *
3700 +     * @param parallelismThreshold the (estimated) number of elements
3701 +     * needed for this operation to be executed in parallel
3702 +     * @param transformer a function returning the transformation
3703 +     * for an element
3704 +     * @param basis the identity (initial default value) for the reduction
3705 +     * @param reducer a commutative associative combining function
3706 +     * @return the result of accumulating the given transformation
3707 +     * of all keys
3708 +     * @since 1.8
3709 +     */
3710 +    public long reduceKeysToLong(long parallelismThreshold,
3711 +                                 ObjectToLong<? super K> transformer,
3712 +                                 long basis,
3713 +                                 LongByLongToLong reducer) {
3714 +        if (transformer == null || reducer == null)
3715 +            throw new NullPointerException();
3716 +        return new MapReduceKeysToLongTask<K,V>
3717 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3718 +             null, transformer, basis, reducer).invoke();
3719 +    }
3720 +
3721 +    /**
3722 +     * Returns the result of accumulating the given transformation
3723 +     * of all keys using the given reducer to combine values, and
3724 +     * the given basis as an identity value.
3725 +     *
3726 +     * @param parallelismThreshold the (estimated) number of elements
3727 +     * needed for this operation to be executed in parallel
3728 +     * @param transformer a function returning the transformation
3729 +     * for an element
3730 +     * @param basis the identity (initial default value) for the reduction
3731 +     * @param reducer a commutative associative combining function
3732 +     * @return the result of accumulating the given transformation
3733 +     * of all keys
3734 +     * @since 1.8
3735 +     */
3736 +    public int reduceKeysToInt(long parallelismThreshold,
3737 +                               ObjectToInt<? super K> transformer,
3738 +                               int basis,
3739 +                               IntByIntToInt reducer) {
3740 +        if (transformer == null || reducer == null)
3741 +            throw new NullPointerException();
3742 +        return new MapReduceKeysToIntTask<K,V>
3743 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3744 +             null, transformer, basis, reducer).invoke();
3745 +    }
3746 +
3747 +    /**
3748 +     * Performs the given action for each value.
3749 +     *
3750 +     * @param parallelismThreshold the (estimated) number of elements
3751 +     * needed for this operation to be executed in parallel
3752 +     * @param action the action
3753 +     * @since 1.8
3754 +     */
3755 +    public void forEachValue(long parallelismThreshold,
3756 +                             Action<? super V> action) {
3757 +        if (action == null)
3758 +            throw new NullPointerException();
3759 +        new ForEachValueTask<K,V>
3760 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3761 +             action).invoke();
3762 +    }
3763 +
3764 +    /**
3765 +     * Performs the given action for each non-null transformation
3766 +     * of each value.
3767 +     *
3768 +     * @param parallelismThreshold the (estimated) number of elements
3769 +     * needed for this operation to be executed in parallel
3770 +     * @param transformer a function returning the transformation
3771 +     * for an element, or null if there is no transformation (in
3772 +     * which case the action is not applied)
3773 +     * @param action the action
3774 +     * @since 1.8
3775 +     */
3776 +    public <U> void forEachValue(long parallelismThreshold,
3777 +                                 Fun<? super V, ? extends U> transformer,
3778 +                                 Action<? super U> action) {
3779 +        if (transformer == null || action == null)
3780 +            throw new NullPointerException();
3781 +        new ForEachTransformedValueTask<K,V,U>
3782 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3783 +             transformer, action).invoke();
3784 +    }
3785 +
3786 +    /**
3787 +     * Returns a non-null result from applying the given search
3788 +     * function on each value, or null if none.  Upon success,
3789 +     * further element processing is suppressed and the results of
3790 +     * any other parallel invocations of the search function are
3791 +     * ignored.
3792 +     *
3793 +     * @param parallelismThreshold the (estimated) number of elements
3794 +     * needed for this operation to be executed in parallel
3795 +     * @param searchFunction a function returning a non-null
3796 +     * result on success, else null
3797 +     * @return a non-null result from applying the given search
3798 +     * function on each value, or null if none
3799 +     * @since 1.8
3800 +     */
3801 +    public <U> U searchValues(long parallelismThreshold,
3802 +                              Fun<? super V, ? extends U> searchFunction) {
3803 +        if (searchFunction == null) throw new NullPointerException();
3804 +        return new SearchValuesTask<K,V,U>
3805 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3806 +             searchFunction, new AtomicReference<U>()).invoke();
3807 +    }
3808 +
3809 +    /**
3810 +     * Returns the result of accumulating all values using the
3811 +     * given reducer to combine values, or null if none.
3812 +     *
3813 +     * @param parallelismThreshold the (estimated) number of elements
3814 +     * needed for this operation to be executed in parallel
3815 +     * @param reducer a commutative associative combining function
3816 +     * @return the result of accumulating all values
3817 +     * @since 1.8
3818 +     */
3819 +    public V reduceValues(long parallelismThreshold,
3820 +                          BiFun<? super V, ? super V, ? extends V> reducer) {
3821 +        if (reducer == null) throw new NullPointerException();
3822 +        return new ReduceValuesTask<K,V>
3823 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3824 +             null, reducer).invoke();
3825 +    }
3826 +
3827 +    /**
3828 +     * Returns the result of accumulating the given transformation
3829 +     * of all values using the given reducer to combine values, or
3830 +     * null if none.
3831 +     *
3832 +     * @param parallelismThreshold the (estimated) number of elements
3833 +     * needed for this operation to be executed in parallel
3834 +     * @param transformer a function returning the transformation
3835 +     * for an element, or null if there is no transformation (in
3836 +     * which case it is not combined)
3837 +     * @param reducer a commutative associative combining function
3838 +     * @return the result of accumulating the given transformation
3839 +     * of all values
3840 +     * @since 1.8
3841 +     */
3842 +    public <U> U reduceValues(long parallelismThreshold,
3843 +                              Fun<? super V, ? extends U> transformer,
3844 +                              BiFun<? super U, ? super U, ? extends U> reducer) {
3845 +        if (transformer == null || reducer == null)
3846 +            throw new NullPointerException();
3847 +        return new MapReduceValuesTask<K,V,U>
3848 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3849 +             null, transformer, reducer).invoke();
3850 +    }
3851 +
3852 +    /**
3853 +     * Returns the result of accumulating the given transformation
3854 +     * of all values using the given reducer to combine values,
3855 +     * and the given basis as an identity value.
3856 +     *
3857 +     * @param parallelismThreshold the (estimated) number of elements
3858 +     * needed for this operation to be executed in parallel
3859 +     * @param transformer a function returning the transformation
3860 +     * for an element
3861 +     * @param basis the identity (initial default value) for the reduction
3862 +     * @param reducer a commutative associative combining function
3863 +     * @return the result of accumulating the given transformation
3864 +     * of all values
3865 +     * @since 1.8
3866 +     */
3867 +    public double reduceValuesToDouble(long parallelismThreshold,
3868 +                                       ObjectToDouble<? super V> transformer,
3869 +                                       double basis,
3870 +                                       DoubleByDoubleToDouble reducer) {
3871 +        if (transformer == null || reducer == null)
3872 +            throw new NullPointerException();
3873 +        return new MapReduceValuesToDoubleTask<K,V>
3874 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3875 +             null, transformer, basis, 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,
3881 +     * and the given basis as an identity value.
3882 +     *
3883 +     * @param parallelismThreshold the (estimated) number of elements
3884 +     * needed for this operation to be executed in parallel
3885 +     * @param transformer a function returning the transformation
3886 +     * for an element
3887 +     * @param basis the identity (initial default value) for the reduction
3888 +     * @param reducer a commutative associative combining function
3889 +     * @return the result of accumulating the given transformation
3890 +     * of all values
3891 +     * @since 1.8
3892 +     */
3893 +    public long reduceValuesToLong(long parallelismThreshold,
3894 +                                   ObjectToLong<? super V> transformer,
3895 +                                   long basis,
3896 +                                   LongByLongToLong reducer) {
3897 +        if (transformer == null || reducer == null)
3898 +            throw new NullPointerException();
3899 +        return new MapReduceValuesToLongTask<K,V>
3900 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3901 +             null, transformer, basis, reducer).invoke();
3902 +    }
3903 +
3904 +    /**
3905 +     * Returns the result of accumulating the given transformation
3906 +     * of all values using the given reducer to combine values,
3907 +     * and the given basis as an identity value.
3908 +     *
3909 +     * @param parallelismThreshold the (estimated) number of elements
3910 +     * needed for this operation to be executed in parallel
3911 +     * @param transformer a function returning the transformation
3912 +     * for an element
3913 +     * @param basis the identity (initial default value) for the reduction
3914 +     * @param reducer a commutative associative combining function
3915 +     * @return the result of accumulating the given transformation
3916 +     * of all values
3917 +     * @since 1.8
3918 +     */
3919 +    public int reduceValuesToInt(long parallelismThreshold,
3920 +                                 ObjectToInt<? super V> transformer,
3921 +                                 int basis,
3922 +                                 IntByIntToInt reducer) {
3923 +        if (transformer == null || reducer == null)
3924 +            throw new NullPointerException();
3925 +        return new MapReduceValuesToIntTask<K,V>
3926 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3927 +             null, transformer, basis, reducer).invoke();
3928 +    }
3929 +
3930 +    /**
3931 +     * Performs the given action for each entry.
3932 +     *
3933 +     * @param parallelismThreshold the (estimated) number of elements
3934 +     * needed for this operation to be executed in parallel
3935 +     * @param action the action
3936 +     * @since 1.8
3937 +     */
3938 +    public void forEachEntry(long parallelismThreshold,
3939 +                             Action<? super Map.Entry<K,V>> action) {
3940 +        if (action == null) throw new NullPointerException();
3941 +        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3942 +                                  action).invoke();
3943 +    }
3944 +
3945 +    /**
3946 +     * Performs the given action for each non-null transformation
3947 +     * of each entry.
3948 +     *
3949 +     * @param parallelismThreshold the (estimated) number of elements
3950 +     * needed for this operation to be executed in parallel
3951 +     * @param transformer a function returning the transformation
3952 +     * for an element, or null if there is no transformation (in
3953 +     * which case the action is not applied)
3954 +     * @param action the action
3955 +     * @since 1.8
3956 +     */
3957 +    public <U> void forEachEntry(long parallelismThreshold,
3958 +                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
3959 +                                 Action<? super U> action) {
3960 +        if (transformer == null || action == null)
3961 +            throw new NullPointerException();
3962 +        new ForEachTransformedEntryTask<K,V,U>
3963 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3964 +             transformer, action).invoke();
3965 +    }
3966 +
3967 +    /**
3968 +     * Returns a non-null result from applying the given search
3969 +     * function on each entry, or null if none.  Upon success,
3970 +     * further element processing is suppressed and the results of
3971 +     * any other parallel invocations of the search function are
3972 +     * ignored.
3973 +     *
3974 +     * @param parallelismThreshold the (estimated) number of elements
3975 +     * needed for this operation to be executed in parallel
3976 +     * @param searchFunction a function returning a non-null
3977 +     * result on success, else null
3978 +     * @return a non-null result from applying the given search
3979 +     * function on each entry, or null if none
3980 +     * @since 1.8
3981 +     */
3982 +    public <U> U searchEntries(long parallelismThreshold,
3983 +                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3984 +        if (searchFunction == null) throw new NullPointerException();
3985 +        return new SearchEntriesTask<K,V,U>
3986 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3987 +             searchFunction, new AtomicReference<U>()).invoke();
3988 +    }
3989 +
3990 +    /**
3991 +     * Returns the result of accumulating all entries using the
3992 +     * given reducer to combine values, or null if none.
3993 +     *
3994 +     * @param parallelismThreshold the (estimated) number of elements
3995 +     * needed for this operation to be executed in parallel
3996 +     * @param reducer a commutative associative combining function
3997 +     * @return the result of accumulating all entries
3998 +     * @since 1.8
3999 +     */
4000 +    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4001 +                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4002 +        if (reducer == null) throw new NullPointerException();
4003 +        return new ReduceEntriesTask<K,V>
4004 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4005 +             null, reducer).invoke();
4006 +    }
4007 +
4008 +    /**
4009 +     * Returns the result of accumulating the given transformation
4010 +     * of all entries using the given reducer to combine values,
4011 +     * or null if none.
4012 +     *
4013 +     * @param parallelismThreshold the (estimated) number of elements
4014 +     * needed for this operation to be executed in parallel
4015 +     * @param transformer a function returning the transformation
4016 +     * for an element, or null if there is no transformation (in
4017 +     * which case it is not combined)
4018 +     * @param reducer a commutative associative combining function
4019 +     * @return the result of accumulating the given transformation
4020 +     * of all entries
4021 +     * @since 1.8
4022 +     */
4023 +    public <U> U reduceEntries(long parallelismThreshold,
4024 +                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4025 +                               BiFun<? super U, ? super U, ? extends U> reducer) {
4026 +        if (transformer == null || reducer == null)
4027 +            throw new NullPointerException();
4028 +        return new MapReduceEntriesTask<K,V,U>
4029 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4030 +             null, transformer, reducer).invoke();
4031 +    }
4032 +
4033 +    /**
4034 +     * Returns the result of accumulating the given transformation
4035 +     * of all entries using the given reducer to combine values,
4036 +     * and the given basis as an identity value.
4037 +     *
4038 +     * @param parallelismThreshold the (estimated) number of elements
4039 +     * needed for this operation to be executed in parallel
4040 +     * @param transformer a function returning the transformation
4041 +     * for an element
4042 +     * @param basis the identity (initial default value) for the reduction
4043 +     * @param reducer a commutative associative combining function
4044 +     * @return the result of accumulating the given transformation
4045 +     * of all entries
4046 +     * @since 1.8
4047 +     */
4048 +    public double reduceEntriesToDouble(long parallelismThreshold,
4049 +                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4050 +                                        double basis,
4051 +                                        DoubleByDoubleToDouble reducer) {
4052 +        if (transformer == null || reducer == null)
4053 +            throw new NullPointerException();
4054 +        return new MapReduceEntriesToDoubleTask<K,V>
4055 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4056 +             null, transformer, basis, 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 +     * and the given basis as an identity value.
4063 +     *
4064 +     * @param parallelismThreshold the (estimated) number of elements
4065 +     * needed for this operation to be executed in parallel
4066 +     * @param transformer a function returning the transformation
4067 +     * for an element
4068 +     * @param basis the identity (initial default value) for the reduction
4069 +     * @param reducer a commutative associative combining function
4070 +     * @return the result of accumulating the given transformation
4071 +     * of all entries
4072 +     * @since 1.8
4073 +     */
4074 +    public long reduceEntriesToLong(long parallelismThreshold,
4075 +                                    ObjectToLong<Map.Entry<K,V>> transformer,
4076 +                                    long basis,
4077 +                                    LongByLongToLong reducer) {
4078 +        if (transformer == null || reducer == null)
4079 +            throw new NullPointerException();
4080 +        return new MapReduceEntriesToLongTask<K,V>
4081 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4082 +             null, transformer, basis, reducer).invoke();
4083 +    }
4084 +
4085 +    /**
4086 +     * Returns the result of accumulating the given transformation
4087 +     * of all entries using the given reducer to combine values,
4088 +     * and the given basis as an identity value.
4089 +     *
4090 +     * @param parallelismThreshold the (estimated) number of elements
4091 +     * needed for this operation to be executed in parallel
4092 +     * @param transformer a function returning the transformation
4093 +     * for an element
4094 +     * @param basis the identity (initial default value) for the reduction
4095 +     * @param reducer a commutative associative combining function
4096 +     * @return the result of accumulating the given transformation
4097 +     * of all entries
4098 +     * @since 1.8
4099 +     */
4100 +    public int reduceEntriesToInt(long parallelismThreshold,
4101 +                                  ObjectToInt<Map.Entry<K,V>> transformer,
4102 +                                  int basis,
4103 +                                  IntByIntToInt reducer) {
4104 +        if (transformer == null || reducer == null)
4105 +            throw new NullPointerException();
4106 +        return new MapReduceEntriesToIntTask<K,V>
4107 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4108 +             null, transformer, basis, reducer).invoke();
4109 +    }
4110 +
4111 +
4112 +    /* ----------------Views -------------- */
4113 +
4114 +    /**
4115 +     * Base class for views.
4116 +     */
4117 +    abstract static class CollectionView<K,V,E>
4118 +        implements Collection<E>, java.io.Serializable {
4119 +        private static final long serialVersionUID = 7249069246763182397L;
4120 +        final ConcurrentHashMapV8<K,V> map;
4121 +        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4122 +
4123          /**
4124 <         * Returns a task that when invoked, returns the result of
4284 <         * accumulating the given transformation of all (key, value) pairs
4285 <         * using the given reducer to combine values, and the given
4286 <         * basis as an identity value.
4124 >         * Returns the map backing this view.
4125           *
4126 <         * @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
4126 >         * @return the map backing this view
4127           */
4128 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4295 <            (ConcurrentHashMapV8<K,V> map,
4296 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4297 <             int basis,
4298 <             IntByIntToInt reducer) {
4299 <            if (transformer == null || reducer == null)
4300 <                throw new NullPointerException();
4301 <            return new MapReduceMappingsToIntTask<K,V>
4302 <                (map, transformer, basis, reducer);
4303 <        }
4128 >        public ConcurrentHashMapV8<K,V> getMap() { return map; }
4129  
4130          /**
4131 <         * Returns a task that when invoked, performs the given action
4132 <         * for each key
4308 <         *
4309 <         * @param map the map
4310 <         * @param action the action
4311 <         * @return the task
4131 >         * Removes all of the elements from this view, by removing all
4132 >         * the mappings from the map backing this view.
4133           */
4134 <        public static <K,V> ForkJoinTask<Void> forEachKey
4135 <            (ConcurrentHashMapV8<K,V> map,
4136 <             Action<K> action) {
4316 <            if (action == null) throw new NullPointerException();
4317 <            return new ForEachKeyTask<K,V>(map, action);
4318 <        }
4134 >        public final void clear()      { map.clear(); }
4135 >        public final int size()        { return map.size(); }
4136 >        public final boolean isEmpty() { return map.isEmpty(); }
4137  
4138 +        // implementations below rely on concrete classes supplying these
4139 +        // abstract methods
4140          /**
4141 <         * Returns a task that when invoked, performs the given action
4142 <         * for each non-null transformation of each key
4143 <         *
4144 <         * @param map the map
4145 <         * @param transformer a function returning the transformation
4146 <         * for an element, or null of there is no transformation (in
4147 <         * which case the action is not applied).
4148 <         * @param action the action
4149 <         * @return the task
4150 <         */
4151 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4152 <            (ConcurrentHashMapV8<K,V> map,
4153 <             Fun<? super K, ? extends U> transformer,
4154 <             Action<U> action) {
4155 <            if (transformer == null || action == null)
4156 <                throw new NullPointerException();
4157 <            return new ForEachTransformedKeyTask<K,V,U>
4158 <                (map, transformer, action);
4141 >         * Returns a "weakly consistent" iterator that will never
4142 >         * throw {@link ConcurrentModificationException}, and
4143 >         * guarantees to traverse elements as they existed upon
4144 >         * construction of the iterator, and may (but is not
4145 >         * guaranteed to) reflect any modifications subsequent to
4146 >         * construction.
4147 >         */
4148 >        public abstract Iterator<E> iterator();
4149 >        public abstract boolean contains(Object o);
4150 >        public abstract boolean remove(Object o);
4151 >
4152 >        private static final String oomeMsg = "Required array size too large";
4153 >
4154 >        public final Object[] toArray() {
4155 >            long sz = map.mappingCount();
4156 >            if (sz > MAX_ARRAY_SIZE)
4157 >                throw new OutOfMemoryError(oomeMsg);
4158 >            int n = (int)sz;
4159 >            Object[] r = new Object[n];
4160 >            int i = 0;
4161 >            for (E e : this) {
4162 >                if (i == n) {
4163 >                    if (n >= MAX_ARRAY_SIZE)
4164 >                        throw new OutOfMemoryError(oomeMsg);
4165 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4166 >                        n = MAX_ARRAY_SIZE;
4167 >                    else
4168 >                        n += (n >>> 1) + 1;
4169 >                    r = Arrays.copyOf(r, n);
4170 >                }
4171 >                r[i++] = e;
4172 >            }
4173 >            return (i == n) ? r : Arrays.copyOf(r, i);
4174          }
4175  
4176 <        /**
4177 <         * Returns a task that when invoked, returns a non-null result
4178 <         * from applying the given search function on each key, or
4179 <         * null if none.  Further element processing is suppressed
4180 <         * upon success. However, this method does not return until
4181 <         * other in-progress parallel invocations of the search
4182 <         * function also complete.
4183 <         *
4184 <         * @param map the map
4185 <         * @param searchFunction a function returning a non-null
4186 <         * result on success, else null
4187 <         * @return the task
4188 <         */
4189 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4190 <            (ConcurrentHashMapV8<K,V> map,
4191 <             Fun<? super K, ? extends U> searchFunction) {
4192 <            if (searchFunction == null) throw new NullPointerException();
4193 <            return new SearchKeysTask<K,V,U>
4194 <                (map, searchFunction,
4195 <                 new AtomicReference<U>());
4176 >        @SuppressWarnings("unchecked")
4177 >        public final <T> T[] toArray(T[] a) {
4178 >            long sz = map.mappingCount();
4179 >            if (sz > MAX_ARRAY_SIZE)
4180 >                throw new OutOfMemoryError(oomeMsg);
4181 >            int m = (int)sz;
4182 >            T[] r = (a.length >= m) ? a :
4183 >                (T[])java.lang.reflect.Array
4184 >                .newInstance(a.getClass().getComponentType(), m);
4185 >            int n = r.length;
4186 >            int i = 0;
4187 >            for (E e : this) {
4188 >                if (i == n) {
4189 >                    if (n >= MAX_ARRAY_SIZE)
4190 >                        throw new OutOfMemoryError(oomeMsg);
4191 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4192 >                        n = MAX_ARRAY_SIZE;
4193 >                    else
4194 >                        n += (n >>> 1) + 1;
4195 >                    r = Arrays.copyOf(r, n);
4196 >                }
4197 >                r[i++] = (T)e;
4198 >            }
4199 >            if (a == r && i < n) {
4200 >                r[i] = null; // null-terminate
4201 >                return r;
4202 >            }
4203 >            return (i == n) ? r : Arrays.copyOf(r, i);
4204          }
4205  
4206          /**
4207 <         * Returns a task that when invoked, returns the result of
4208 <         * accumulating all keys using the given reducer to combine
4209 <         * values, or null if none.
4207 >         * Returns a string representation of this collection.
4208 >         * The string representation consists of the string representations
4209 >         * of the collection's elements in the order they are returned by
4210 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4211 >         * Adjacent elements are separated by the characters {@code ", "}
4212 >         * (comma and space).  Elements are converted to strings as by
4213 >         * {@link String#valueOf(Object)}.
4214           *
4215 <         * @param map the map
4369 <         * @param reducer a commutative associative combining function
4370 <         * @return the task
4215 >         * @return a string representation of this collection
4216           */
4217 <        public static <K,V> ForkJoinTask<K> reduceKeys
4218 <            (ConcurrentHashMapV8<K,V> map,
4219 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4220 <            if (reducer == null) throw new NullPointerException();
4221 <            return new ReduceKeysTask<K,V>
4222 <                (map, reducer);
4217 >        public final String toString() {
4218 >            StringBuilder sb = new StringBuilder();
4219 >            sb.append('[');
4220 >            Iterator<E> it = iterator();
4221 >            if (it.hasNext()) {
4222 >                for (;;) {
4223 >                    Object e = it.next();
4224 >                    sb.append(e == this ? "(this Collection)" : e);
4225 >                    if (!it.hasNext())
4226 >                        break;
4227 >                    sb.append(',').append(' ');
4228 >                }
4229 >            }
4230 >            return sb.append(']').toString();
4231          }
4232 <        /**
4233 <         * Returns a task that when invoked, returns the result of
4234 <         * accumulating the given transformation of all keys using the given
4235 <         * reducer to combine values, or null if none.
4236 <         *
4237 <         * @param map the map
4238 <         * @param transformer a function returning the transformation
4239 <         * for an element, or null of there is no transformation (in
4240 <         * which case it is not combined).
4388 <         * @param reducer a commutative associative combining function
4389 <         * @return the task
4390 <         */
4391 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4392 <            (ConcurrentHashMapV8<K,V> map,
4393 <             Fun<? super K, ? extends U> transformer,
4394 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4395 <            if (transformer == null || reducer == null)
4396 <                throw new NullPointerException();
4397 <            return new MapReduceKeysTask<K,V,U>
4398 <                (map, transformer, reducer);
4232 >
4233 >        public final boolean containsAll(Collection<?> c) {
4234 >            if (c != this) {
4235 >                for (Object e : c) {
4236 >                    if (e == null || !contains(e))
4237 >                        return false;
4238 >                }
4239 >            }
4240 >            return true;
4241          }
4242  
4243 <        /**
4244 <         * Returns a task that when invoked, returns the result of
4245 <         * accumulating the given transformation of all keys using the given
4246 <         * reducer to combine values, and the given basis as an
4247 <         * identity value.
4248 <         *
4249 <         * @param map the map
4250 <         * @param transformer a function returning the transformation
4251 <         * for an element
4410 <         * @param basis the identity (initial default value) for the reduction
4411 <         * @param reducer a commutative associative combining function
4412 <         * @return the task
4413 <         */
4414 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4415 <            (ConcurrentHashMapV8<K,V> map,
4416 <             ObjectToDouble<? super K> transformer,
4417 <             double basis,
4418 <             DoubleByDoubleToDouble reducer) {
4419 <            if (transformer == null || reducer == null)
4420 <                throw new NullPointerException();
4421 <            return new MapReduceKeysToDoubleTask<K,V>
4422 <                (map, transformer, basis, reducer);
4243 >        public final boolean removeAll(Collection<?> c) {
4244 >            boolean modified = false;
4245 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4246 >                if (c.contains(it.next())) {
4247 >                    it.remove();
4248 >                    modified = true;
4249 >                }
4250 >            }
4251 >            return modified;
4252          }
4253  
4254 <        /**
4255 <         * Returns a task that when invoked, returns the result of
4256 <         * accumulating the given transformation of all keys using the given
4257 <         * reducer to combine values, and the given basis as an
4258 <         * identity value.
4259 <         *
4260 <         * @param map the map
4261 <         * @param transformer a function returning the transformation
4262 <         * for an element
4434 <         * @param basis the identity (initial default value) for the reduction
4435 <         * @param reducer a commutative associative combining function
4436 <         * @return the task
4437 <         */
4438 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4439 <            (ConcurrentHashMapV8<K,V> map,
4440 <             ObjectToLong<? super K> transformer,
4441 <             long basis,
4442 <             LongByLongToLong reducer) {
4443 <            if (transformer == null || reducer == null)
4444 <                throw new NullPointerException();
4445 <            return new MapReduceKeysToLongTask<K,V>
4446 <                (map, transformer, basis, reducer);
4254 >        public final boolean retainAll(Collection<?> c) {
4255 >            boolean modified = false;
4256 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4257 >                if (!c.contains(it.next())) {
4258 >                    it.remove();
4259 >                    modified = true;
4260 >                }
4261 >            }
4262 >            return modified;
4263          }
4264  
4265 <        /**
4266 <         * Returns a task that when invoked, returns the result of
4267 <         * accumulating the given transformation of all keys using the given
4268 <         * reducer to combine values, and the given basis as an
4269 <         * identity value.
4270 <         *
4271 <         * @param map the map
4272 <         * @param transformer a function returning the transformation
4273 <         * for an element
4274 <         * @param basis the identity (initial default value) for the reduction
4275 <         * @param reducer a commutative associative combining function
4276 <         * @return the task
4277 <         */
4278 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4279 <            (ConcurrentHashMapV8<K,V> map,
4280 <             ObjectToInt<? super K> transformer,
4281 <             int basis,
4282 <             IntByIntToInt reducer) {
4283 <            if (transformer == null || reducer == null)
4284 <                throw new NullPointerException();
4469 <            return new MapReduceKeysToIntTask<K,V>
4470 <                (map, transformer, basis, reducer);
4265 >    }
4266 >
4267 >    /**
4268 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4269 >     * which additions may optionally be enabled by mapping to a
4270 >     * common value.  This class cannot be directly instantiated.
4271 >     * See {@link #keySet() keySet()},
4272 >     * {@link #keySet(Object) keySet(V)},
4273 >     * {@link #newKeySet() newKeySet()},
4274 >     * {@link #newKeySet(int) newKeySet(int)}.
4275 >     *
4276 >     * @since 1.8
4277 >     */
4278 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4279 >        implements Set<K>, java.io.Serializable {
4280 >        private static final long serialVersionUID = 7249069246763182397L;
4281 >        private final V value;
4282 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4283 >            super(map);
4284 >            this.value = value;
4285          }
4286  
4287          /**
4288 <         * Returns a task that when invoked, performs the given action
4289 <         * for each value
4288 >         * Returns the default mapped value for additions,
4289 >         * or {@code null} if additions are not supported.
4290           *
4291 <         * @param map the map
4292 <         * @param action the action
4291 >         * @return the default mapped value for additions, or {@code null}
4292 >         * if not supported
4293           */
4294 <        public static <K,V> ForkJoinTask<Void> forEachValue
4481 <            (ConcurrentHashMapV8<K,V> map,
4482 <             Action<V> action) {
4483 <            if (action == null) throw new NullPointerException();
4484 <            return new ForEachValueTask<K,V>(map, action);
4485 <        }
4294 >        public V getMappedValue() { return value; }
4295  
4296          /**
4297 <         * Returns a task that when invoked, performs the given action
4298 <         * for each non-null transformation of each value
4490 <         *
4491 <         * @param map the map
4492 <         * @param transformer a function returning the transformation
4493 <         * for an element, or null of there is no transformation (in
4494 <         * which case the action is not applied).
4495 <         * @param action the action
4297 >         * {@inheritDoc}
4298 >         * @throws NullPointerException if the specified key is null
4299           */
4300 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4498 <            (ConcurrentHashMapV8<K,V> map,
4499 <             Fun<? super V, ? extends U> transformer,
4500 <             Action<U> action) {
4501 <            if (transformer == null || action == null)
4502 <                throw new NullPointerException();
4503 <            return new ForEachTransformedValueTask<K,V,U>
4504 <                (map, transformer, action);
4505 <        }
4300 >        public boolean contains(Object o) { return map.containsKey(o); }
4301  
4302          /**
4303 <         * Returns a task that when invoked, returns a non-null result
4304 <         * from applying the given search function on each value, or
4305 <         * null if none.  Further element processing is suppressed
4511 <         * upon success. However, this method does not return until
4512 <         * other in-progress parallel invocations of the search
4513 <         * function also complete.
4514 <         *
4515 <         * @param map the map
4516 <         * @param searchFunction a function returning a non-null
4517 <         * result on success, else null
4518 <         * @return the task
4303 >         * Removes the key from this map view, by removing the key (and its
4304 >         * corresponding value) from the backing map.  This method does
4305 >         * nothing if the key is not in the map.
4306           *
4307 +         * @param  o the key to be removed from the backing map
4308 +         * @return {@code true} if the backing map contained the specified key
4309 +         * @throws NullPointerException if the specified key is null
4310           */
4311 <        public static <K,V,U> ForkJoinTask<U> searchValues
4522 <            (ConcurrentHashMapV8<K,V> map,
4523 <             Fun<? super V, ? extends U> searchFunction) {
4524 <            if (searchFunction == null) throw new NullPointerException();
4525 <            return new SearchValuesTask<K,V,U>
4526 <                (map, searchFunction,
4527 <                 new AtomicReference<U>());
4528 <        }
4311 >        public boolean remove(Object o) { return map.remove(o) != null; }
4312  
4313          /**
4314 <         * Returns a task that when invoked, returns the result of
4532 <         * accumulating all values using the given reducer to combine
4533 <         * values, or null if none.
4534 <         *
4535 <         * @param map the map
4536 <         * @param reducer a commutative associative combining function
4537 <         * @return the task
4314 >         * @return an iterator over the keys of the backing map
4315           */
4316 <        public static <K,V> ForkJoinTask<V> reduceValues
4317 <            (ConcurrentHashMapV8<K,V> map,
4318 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4319 <            if (reducer == null) throw new NullPointerException();
4320 <            return new ReduceValuesTask<K,V>
4544 <                (map, reducer);
4316 >        public Iterator<K> iterator() {
4317 >            Node<K,V>[] t;
4318 >            ConcurrentHashMapV8<K,V> m = map;
4319 >            int f = (t = m.table) == null ? 0 : t.length;
4320 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4321          }
4322  
4323          /**
4324 <         * Returns a task that when invoked, returns the result of
4325 <         * accumulating the given transformation of all values using the
4550 <         * given reducer to combine values, or null if none.
4324 >         * Adds the specified key to this set view by mapping the key to
4325 >         * the default mapped value in the backing map, if defined.
4326           *
4327 <         * @param map the map
4328 <         * @param transformer a function returning the transformation
4329 <         * for an element, or null of there is no transformation (in
4330 <         * which case it is not combined).
4331 <         * @param reducer a commutative associative combining function
4557 <         * @return the task
4327 >         * @param e key to be added
4328 >         * @return {@code true} if this set changed as a result of the call
4329 >         * @throws NullPointerException if the specified key is null
4330 >         * @throws UnsupportedOperationException if no default mapped value
4331 >         * for additions was provided
4332           */
4333 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4334 <            (ConcurrentHashMapV8<K,V> map,
4335 <             Fun<? super V, ? extends U> transformer,
4336 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4337 <            if (transformer == null || reducer == null)
4564 <                throw new NullPointerException();
4565 <            return new MapReduceValuesTask<K,V,U>
4566 <                (map, transformer, reducer);
4333 >        public boolean add(K e) {
4334 >            V v;
4335 >            if ((v = value) == null)
4336 >                throw new UnsupportedOperationException();
4337 >            return map.putVal(e, v, true) == null;
4338          }
4339  
4340          /**
4341 <         * Returns a task that when invoked, returns the result of
4342 <         * accumulating the given transformation of all values using the
4572 <         * given reducer to combine values, and the given basis as an
4573 <         * identity value.
4341 >         * Adds all of the elements in the specified collection to this set,
4342 >         * as if by calling {@link #add} on each one.
4343           *
4344 <         * @param map the map
4345 <         * @param transformer a function returning the transformation
4346 <         * for an element
4347 <         * @param basis the identity (initial default value) for the reduction
4348 <         * @param reducer a commutative associative combining function
4349 <         * @return the task
4344 >         * @param c the elements to be inserted into this set
4345 >         * @return {@code true} if this set changed as a result of the call
4346 >         * @throws NullPointerException if the collection or any of its
4347 >         * elements are {@code null}
4348 >         * @throws UnsupportedOperationException if no default mapped value
4349 >         * for additions was provided
4350           */
4351 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4352 <            (ConcurrentHashMapV8<K,V> map,
4353 <             ObjectToDouble<? super V> transformer,
4354 <             double basis,
4355 <             DoubleByDoubleToDouble reducer) {
4356 <            if (transformer == null || reducer == null)
4357 <                throw new NullPointerException();
4358 <            return new MapReduceValuesToDoubleTask<K,V>
4359 <                (map, transformer, basis, reducer);
4351 >        public boolean addAll(Collection<? extends K> c) {
4352 >            boolean added = false;
4353 >            V v;
4354 >            if ((v = value) == null)
4355 >                throw new UnsupportedOperationException();
4356 >            for (K e : c) {
4357 >                if (map.putVal(e, v, true) == null)
4358 >                    added = true;
4359 >            }
4360 >            return added;
4361          }
4362  
4363 <        /**
4364 <         * Returns a task that when invoked, returns the result of
4365 <         * accumulating the given transformation of all values using the
4366 <         * given reducer to combine values, and the given basis as an
4367 <         * identity value.
4598 <         *
4599 <         * @param map the map
4600 <         * @param transformer a function returning the transformation
4601 <         * for an element
4602 <         * @param basis the identity (initial default value) for the reduction
4603 <         * @param reducer a commutative associative combining function
4604 <         * @return the task
4605 <         */
4606 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
4607 <            (ConcurrentHashMapV8<K,V> map,
4608 <             ObjectToLong<? super V> transformer,
4609 <             long basis,
4610 <             LongByLongToLong reducer) {
4611 <            if (transformer == null || reducer == null)
4612 <                throw new NullPointerException();
4613 <            return new MapReduceValuesToLongTask<K,V>
4614 <                (map, transformer, basis, reducer);
4363 >        public int hashCode() {
4364 >            int h = 0;
4365 >            for (K e : this)
4366 >                h += e.hashCode();
4367 >            return h;
4368          }
4369  
4370 <        /**
4371 <         * Returns a task that when invoked, returns the result of
4372 <         * accumulating the given transformation of all values using the
4373 <         * given reducer to combine values, and the given basis as an
4374 <         * identity value.
4622 <         *
4623 <         * @param map the map
4624 <         * @param transformer a function returning the transformation
4625 <         * for an element
4626 <         * @param basis the identity (initial default value) for the reduction
4627 <         * @param reducer a commutative associative combining function
4628 <         * @return the task
4629 <         */
4630 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
4631 <            (ConcurrentHashMapV8<K,V> map,
4632 <             ObjectToInt<? super V> transformer,
4633 <             int basis,
4634 <             IntByIntToInt reducer) {
4635 <            if (transformer == null || reducer == null)
4636 <                throw new NullPointerException();
4637 <            return new MapReduceValuesToIntTask<K,V>
4638 <                (map, transformer, basis, reducer);
4370 >        public boolean equals(Object o) {
4371 >            Set<?> c;
4372 >            return ((o instanceof Set) &&
4373 >                    ((c = (Set<?>)o) == this ||
4374 >                     (containsAll(c) && c.containsAll(this))));
4375          }
4376  
4377 <        /**
4378 <         * Returns a task that when invoked, perform the given action
4379 <         * for each entry
4380 <         *
4381 <         * @param map the map
4382 <         * @param action the action
4647 <         */
4648 <        public static <K,V> ForkJoinTask<Void> forEachEntry
4649 <            (ConcurrentHashMapV8<K,V> map,
4650 <             Action<Map.Entry<K,V>> action) {
4651 <            if (action == null) throw new NullPointerException();
4652 <            return new ForEachEntryTask<K,V>(map, action);
4377 >        public ConcurrentHashMapSpliterator<K> spliterator() {
4378 >            Node<K,V>[] t;
4379 >            ConcurrentHashMapV8<K,V> m = map;
4380 >            long n = m.sumCount();
4381 >            int f = (t = m.table) == null ? 0 : t.length;
4382 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4383          }
4384  
4385 <        /**
4386 <         * Returns a task that when invoked, perform the given action
4387 <         * for each non-null transformation of each entry
4388 <         *
4389 <         * @param map the map
4390 <         * @param transformer a function returning the transformation
4391 <         * for an element, or null of there is no transformation (in
4392 <         * which case the action is not applied).
4663 <         * @param action the action
4664 <         */
4665 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
4666 <            (ConcurrentHashMapV8<K,V> map,
4667 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4668 <             Action<U> action) {
4669 <            if (transformer == null || action == null)
4670 <                throw new NullPointerException();
4671 <            return new ForEachTransformedEntryTask<K,V,U>
4672 <                (map, transformer, action);
4385 >        public void forEach(Action<? super K> action) {
4386 >            if (action == null) throw new NullPointerException();
4387 >            Node<K,V>[] t;
4388 >            if ((t = map.table) != null) {
4389 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4390 >                for (Node<K,V> p; (p = it.advance()) != null; )
4391 >                    action.apply(p.key);
4392 >            }
4393          }
4394 +    }
4395  
4396 <        /**
4397 <         * Returns a task that when invoked, returns a non-null result
4398 <         * from applying the given search function on each entry, or
4399 <         * null if none.  Further element processing is suppressed
4400 <         * upon success. However, this method does not return until
4401 <         * other in-progress parallel invocations of the search
4402 <         * function also complete.
4403 <         *
4404 <         * @param map the map
4405 <         * @param searchFunction a function returning a non-null
4406 <         * result on success, else null
4686 <         * @return the task
4687 <         *
4688 <         */
4689 <        public static <K,V,U> ForkJoinTask<U> searchEntries
4690 <            (ConcurrentHashMapV8<K,V> map,
4691 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4692 <            if (searchFunction == null) throw new NullPointerException();
4693 <            return new SearchEntriesTask<K,V,U>
4694 <                (map, searchFunction,
4695 <                 new AtomicReference<U>());
4396 >    /**
4397 >     * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4398 >     * values, in which additions are disabled. This class cannot be
4399 >     * directly instantiated. See {@link #values()}.
4400 >     */
4401 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4402 >        implements Collection<V>, java.io.Serializable {
4403 >        private static final long serialVersionUID = 2249069246763182397L;
4404 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4405 >        public final boolean contains(Object o) {
4406 >            return map.containsValue(o);
4407          }
4408  
4409 <        /**
4410 <         * Returns a task that when invoked, returns the result of
4411 <         * accumulating all entries using the given reducer to combine
4412 <         * values, or null if none.
4413 <         *
4414 <         * @param map the map
4415 <         * @param reducer a commutative associative combining function
4416 <         * @return the task
4417 <         */
4418 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
4708 <            (ConcurrentHashMapV8<K,V> map,
4709 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4710 <            if (reducer == null) throw new NullPointerException();
4711 <            return new ReduceEntriesTask<K,V>
4712 <                (map, reducer);
4409 >        public final boolean remove(Object o) {
4410 >            if (o != null) {
4411 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4412 >                    if (o.equals(it.next())) {
4413 >                        it.remove();
4414 >                        return true;
4415 >                    }
4416 >                }
4417 >            }
4418 >            return false;
4419          }
4420  
4421 <        /**
4422 <         * Returns a task that when invoked, returns the result of
4423 <         * accumulating the given transformation of all entries using the
4424 <         * given reducer to combine values, or null if none.
4425 <         *
4720 <         * @param map the map
4721 <         * @param transformer a function returning the transformation
4722 <         * for an element, or null of there is no transformation (in
4723 <         * which case it is not combined).
4724 <         * @param reducer a commutative associative combining function
4725 <         * @return the task
4726 <         */
4727 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
4728 <            (ConcurrentHashMapV8<K,V> map,
4729 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4730 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4731 <            if (transformer == null || reducer == null)
4732 <                throw new NullPointerException();
4733 <            return new MapReduceEntriesTask<K,V,U>
4734 <                (map, transformer, reducer);
4421 >        public final Iterator<V> iterator() {
4422 >            ConcurrentHashMapV8<K,V> m = map;
4423 >            Node<K,V>[] t;
4424 >            int f = (t = m.table) == null ? 0 : t.length;
4425 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4426          }
4427  
4428 <        /**
4429 <         * Returns a task that when invoked, returns the result of
4430 <         * accumulating the given transformation of all entries using the
4431 <         * given reducer to combine values, and the given basis as an
4432 <         * identity value.
4742 <         *
4743 <         * @param map the map
4744 <         * @param transformer a function returning the transformation
4745 <         * for an element
4746 <         * @param basis the identity (initial default value) for the reduction
4747 <         * @param reducer a commutative associative combining function
4748 <         * @return the task
4749 <         */
4750 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4751 <            (ConcurrentHashMapV8<K,V> map,
4752 <             ObjectToDouble<Map.Entry<K,V>> transformer,
4753 <             double basis,
4754 <             DoubleByDoubleToDouble reducer) {
4755 <            if (transformer == null || reducer == null)
4756 <                throw new NullPointerException();
4757 <            return new MapReduceEntriesToDoubleTask<K,V>
4758 <                (map, transformer, basis, reducer);
4428 >        public final boolean add(V e) {
4429 >            throw new UnsupportedOperationException();
4430 >        }
4431 >        public final boolean addAll(Collection<? extends V> c) {
4432 >            throw new UnsupportedOperationException();
4433          }
4434  
4435 <        /**
4436 <         * Returns a task that when invoked, returns the result of
4437 <         * accumulating the given transformation of all entries using the
4438 <         * given reducer to combine values, and the given basis as an
4439 <         * identity value.
4440 <         *
4767 <         * @param map the map
4768 <         * @param transformer a function returning the transformation
4769 <         * for an element
4770 <         * @param basis the identity (initial default value) for the reduction
4771 <         * @param reducer a commutative associative combining function
4772 <         * @return the task
4773 <         */
4774 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4775 <            (ConcurrentHashMapV8<K,V> map,
4776 <             ObjectToLong<Map.Entry<K,V>> transformer,
4777 <             long basis,
4778 <             LongByLongToLong reducer) {
4779 <            if (transformer == null || reducer == null)
4780 <                throw new NullPointerException();
4781 <            return new MapReduceEntriesToLongTask<K,V>
4782 <                (map, transformer, basis, reducer);
4435 >        public ConcurrentHashMapSpliterator<V> spliterator() {
4436 >            Node<K,V>[] t;
4437 >            ConcurrentHashMapV8<K,V> m = map;
4438 >            long n = m.sumCount();
4439 >            int f = (t = m.table) == null ? 0 : t.length;
4440 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4441          }
4442  
4443 <        /**
4444 <         * Returns a task that when invoked, returns the result of
4445 <         * accumulating the given transformation of all entries using the
4446 <         * given reducer to combine values, and the given basis as an
4447 <         * identity value.
4448 <         *
4449 <         * @param map the map
4450 <         * @param transformer a function returning the transformation
4793 <         * for an element
4794 <         * @param basis the identity (initial default value) for the reduction
4795 <         * @param reducer a commutative associative combining function
4796 <         * @return the task
4797 <         */
4798 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4799 <            (ConcurrentHashMapV8<K,V> map,
4800 <             ObjectToInt<Map.Entry<K,V>> transformer,
4801 <             int basis,
4802 <             IntByIntToInt reducer) {
4803 <            if (transformer == null || reducer == null)
4804 <                throw new NullPointerException();
4805 <            return new MapReduceEntriesToIntTask<K,V>
4806 <                (map, transformer, basis, reducer);
4443 >        public void forEach(Action<? super V> action) {
4444 >            if (action == null) throw new NullPointerException();
4445 >            Node<K,V>[] t;
4446 >            if ((t = map.table) != null) {
4447 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4448 >                for (Node<K,V> p; (p = it.advance()) != null; )
4449 >                    action.apply(p.val);
4450 >            }
4451          }
4452      }
4453  
4810    // -------------------------------------------------------
4811
4454      /**
4455 <     * Base for FJ tasks for bulk operations. This adds a variant of
4456 <     * CountedCompleters and some split and merge bookeeping to
4457 <     * iterator functionality. The forEach and reduce methods are
4458 <     * similar to those illustrated in CountedCompleter documentation,
4459 <     * except that bottom-up reduction completions perform them within
4460 <     * their compute methods. The search methods are like forEach
4461 <     * except they continually poll for success and exit early.  Also,
4462 <     * exceptions are handled in a simpler manner, by just trying to
4821 <     * complete root task exceptionally.
4822 <     */
4823 <    static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4824 <        final BulkTask<K,V,?> parent;  // completion target
4825 <        int batch;                     // split control
4826 <        int pending;                   // completion control
4455 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4456 >     * entries.  This class cannot be directly instantiated. See
4457 >     * {@link #entrySet()}.
4458 >     */
4459 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4460 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4461 >        private static final long serialVersionUID = 2249069246763182397L;
4462 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4463  
4464 <        /** Constructor for root tasks */
4465 <        BulkTask(ConcurrentHashMapV8<K,V> map) {
4466 <            super(map);
4467 <            this.parent = null;
4468 <            this.batch = -1; // force call to batch() on execution
4464 >        public boolean contains(Object o) {
4465 >            Object k, v, r; Map.Entry<?,?> e;
4466 >            return ((o instanceof Map.Entry) &&
4467 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4468 >                    (r = map.get(k)) != null &&
4469 >                    (v = e.getValue()) != null &&
4470 >                    (v == r || v.equals(r)));
4471          }
4472  
4473 <        /** Constructor for subtasks */
4474 <        BulkTask(BulkTask<K,V,?> parent, int batch, boolean split) {
4475 <            super(parent, split);
4476 <            this.parent = parent;
4477 <            this.batch = batch;
4473 >        public boolean remove(Object o) {
4474 >            Object k, v; Map.Entry<?,?> e;
4475 >            return ((o instanceof Map.Entry) &&
4476 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4477 >                    (v = e.getValue()) != null &&
4478 >                    map.remove(k, v));
4479          }
4480  
4842        // FJ methods
4843
4481          /**
4482 <         * Propagate completion. Note that all reduce actions
4846 <         * bypass this method to combine while completing.
4482 >         * @return an iterator over the entries of the backing map
4483           */
4484 <        final void tryComplete() {
4485 <            BulkTask<K,V,?> a = this, s = a;
4486 <            for (int c;;) {
4487 <                if ((c = a.pending) == 0) {
4488 <                    if ((a = (s = a).parent) == null) {
4853 <                        s.quietlyComplete();
4854 <                        break;
4855 <                    }
4856 <                }
4857 <                else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
4858 <                    break;
4859 <            }
4484 >        public Iterator<Map.Entry<K,V>> iterator() {
4485 >            ConcurrentHashMapV8<K,V> m = map;
4486 >            Node<K,V>[] t;
4487 >            int f = (t = m.table) == null ? 0 : t.length;
4488 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4489          }
4490  
4491 <        /**
4492 <         * Force root task to throw exception unless already complete.
4864 <         */
4865 <        final void tryAbortComputation(Throwable ex) {
4866 <            for (BulkTask<K,V,?> a = this;;) {
4867 <                BulkTask<K,V,?> p = a.parent;
4868 <                if (p == null) {
4869 <                    a.completeExceptionally(ex);
4870 <                    break;
4871 <                }
4872 <                a = p;
4873 <            }
4491 >        public boolean add(Entry<K,V> e) {
4492 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4493          }
4494  
4495 <        public final boolean exec() {
4496 <            try {
4497 <                compute();
4498 <            }
4499 <            catch(Throwable ex) {
4881 <                tryAbortComputation(ex);
4495 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4496 >            boolean added = false;
4497 >            for (Entry<K,V> e : c) {
4498 >                if (add(e))
4499 >                    added = true;
4500              }
4501 <            return false;
4501 >            return added;
4502          }
4503  
4504 <        public abstract void compute();
4504 >        public final int hashCode() {
4505 >            int h = 0;
4506 >            Node<K,V>[] t;
4507 >            if ((t = map.table) != null) {
4508 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4509 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4510 >                    h += p.hashCode();
4511 >                }
4512 >            }
4513 >            return h;
4514 >        }
4515  
4516 <        // utilities
4516 >        public final boolean equals(Object o) {
4517 >            Set<?> c;
4518 >            return ((o instanceof Set) &&
4519 >                    ((c = (Set<?>)o) == this ||
4520 >                     (containsAll(c) && c.containsAll(this))));
4521 >        }
4522  
4523 <        /** CompareAndSet pending count */
4524 <        final boolean casPending(int cmp, int val) {
4525 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4523 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4524 >            Node<K,V>[] t;
4525 >            ConcurrentHashMapV8<K,V> m = map;
4526 >            long n = m.sumCount();
4527 >            int f = (t = m.table) == null ? 0 : t.length;
4528 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4529          }
4530  
4531 <        /**
4532 <         * Return approx exp2 of the number of times (minus one) to
4533 <         * split task by two before executing leaf action. This value
4534 <         * is faster to compute and more convenient to use as a guide
4535 <         * to splitting than is the depth, since it is used while
4536 <         * dividing by two anyway.
4537 <         */
4902 <        final int batch() {
4903 <            int b = batch;
4904 <            if (b < 0) {
4905 <                long n = map.counter.sum();
4906 <                int sp = getPool().getParallelism() << 3; // slack of 8
4907 <                b = batch = (n <= 0L)? 0 : (n < (long)sp) ? (int)n : sp;
4531 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4532 >            if (action == null) throw new NullPointerException();
4533 >            Node<K,V>[] t;
4534 >            if ((t = map.table) != null) {
4535 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4536 >                for (Node<K,V> p; (p = it.advance()) != null; )
4537 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4538              }
4909            return b;
4539          }
4540  
4541 <        /**
4913 <         * Error message for hoisted null checks of functions
4914 <         */
4915 <        static final String NullFunctionMessage =
4916 <            "Unexpected null function";
4541 >    }
4542  
4543 <        /**
4544 <         * Return exportable snapshot entry
4545 <         */
4546 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4547 <            return new AbstractMap.SimpleEntry(k, v);
4543 >    // -------------------------------------------------------
4544 >
4545 >    /**
4546 >     * Base class for bulk tasks. Repeats some fields and code from
4547 >     * class Traverser, because we need to subclass CountedCompleter.
4548 >     */
4549 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4550 >        Node<K,V>[] tab;        // same as Traverser
4551 >        Node<K,V> next;
4552 >        int index;
4553 >        int baseIndex;
4554 >        int baseLimit;
4555 >        final int baseSize;
4556 >        int batch;              // split control
4557 >
4558 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4559 >            super(par);
4560 >            this.batch = b;
4561 >            this.index = this.baseIndex = i;
4562 >            if ((this.tab = t) == null)
4563 >                this.baseSize = this.baseLimit = 0;
4564 >            else if (par == null)
4565 >                this.baseSize = this.baseLimit = t.length;
4566 >            else {
4567 >                this.baseLimit = f;
4568 >                this.baseSize = par.baseSize;
4569 >            }
4570          }
4571  
4572 <        // Unsafe mechanics
4573 <        private static final sun.misc.Unsafe U;
4574 <        private static final long PENDING;
4575 <        static {
4576 <            try {
4577 <                U = sun.misc.Unsafe.getUnsafe();
4578 <                PENDING = U.objectFieldOffset
4579 <                    (BulkTask.class.getDeclaredField("pending"));
4580 <            } catch (Exception e) {
4581 <                throw new Error(e);
4572 >        /**
4573 >         * Same as Traverser version
4574 >         */
4575 >        final Node<K,V> advance() {
4576 >            Node<K,V> e;
4577 >            if ((e = next) != null)
4578 >                e = e.next;
4579 >            for (;;) {
4580 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4581 >                if (e != null)
4582 >                    return next = e;
4583 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4584 >                    (n = t.length) <= (i = index) || i < 0)
4585 >                    return next = null;
4586 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4587 >                    if (e instanceof ForwardingNode) {
4588 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4589 >                        e = null;
4590 >                        continue;
4591 >                    }
4592 >                    else if (e instanceof TreeBin)
4593 >                        e = ((TreeBin<K,V>)e).first;
4594 >                    else
4595 >                        e = null;
4596 >                }
4597 >                if ((index += baseSize) >= n)
4598 >                    index = ++baseIndex;    // visit upper slots if present
4599              }
4600          }
4601      }
# Line 4939 | Line 4603 | public class ConcurrentHashMapV8<K, V>
4603      /*
4604       * Task classes. Coded in a regular but ugly format/style to
4605       * simplify checks that each variant differs in the right way from
4606 <     * others.
4606 >     * others. The null screenings exist because compilers cannot tell
4607 >     * that we've already null-checked task arguments, so we force
4608 >     * simplest hoisted bypass to help avoid convoluted traps.
4609       */
4610 <
4610 >    @SuppressWarnings("serial")
4611      static final class ForEachKeyTask<K,V>
4612          extends BulkTask<K,V,Void> {
4613 <        final Action<K> action;
4948 <        ForEachKeyTask
4949 <            (ConcurrentHashMapV8<K,V> m,
4950 <             Action<K> action) {
4951 <            super(m);
4952 <            this.action = action;
4953 <        }
4613 >        final Action<? super K> action;
4614          ForEachKeyTask
4615 <            (BulkTask<K,V,?> p, int b, boolean split,
4616 <             Action<K> action) {
4617 <            super(p, b, split);
4615 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4616 >             Action<? super K> action) {
4617 >            super(p, b, i, f, t);
4618              this.action = action;
4619          }
4620          public final void compute() {
4621 <            final Action<K> action = this.action;
4622 <            if (action == null)
4623 <                throw new Error(NullFunctionMessage);
4624 <            int b = batch(), c;
4625 <            while (b > 1 && baseIndex != baseLimit) {
4626 <                do {} while (!casPending(c = pending, c+1));
4627 <                new ForEachKeyTask<K,V>(this, b >>>= 1, true, action).fork();
4628 <            }
4629 <            while (advance() != null)
4630 <                action.apply((K)nextKey);
4631 <            tryComplete();
4621 >            final Action<? super K> action;
4622 >            if ((action = this.action) != null) {
4623 >                for (int i = baseIndex, f, h; batch > 0 &&
4624 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4625 >                    addToPendingCount(1);
4626 >                    new ForEachKeyTask<K,V>
4627 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4628 >                         action).fork();
4629 >                }
4630 >                for (Node<K,V> p; (p = advance()) != null;)
4631 >                    action.apply(p.key);
4632 >                propagateCompletion();
4633 >            }
4634          }
4635      }
4636  
4637 +    @SuppressWarnings("serial")
4638      static final class ForEachValueTask<K,V>
4639          extends BulkTask<K,V,Void> {
4640 <        final Action<V> action;
4978 <        ForEachValueTask
4979 <            (ConcurrentHashMapV8<K,V> m,
4980 <             Action<V> action) {
4981 <            super(m);
4982 <            this.action = action;
4983 <        }
4640 >        final Action<? super V> action;
4641          ForEachValueTask
4642 <            (BulkTask<K,V,?> p, int b, boolean split,
4643 <             Action<V> action) {
4644 <            super(p, b, split);
4642 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4643 >             Action<? super V> action) {
4644 >            super(p, b, i, f, t);
4645              this.action = action;
4646          }
4647          public final void compute() {
4648 <            final Action<V> action = this.action;
4649 <            if (action == null)
4650 <                throw new Error(NullFunctionMessage);
4651 <            int b = batch(), c;
4652 <            while (b > 1 && baseIndex != baseLimit) {
4653 <                do {} while (!casPending(c = pending, c+1));
4654 <                new ForEachValueTask<K,V>(this, b >>>= 1, true, action).fork();
4655 <            }
4656 <            Object v;
4657 <            while ((v = advance()) != null)
4658 <                action.apply((V)v);
4659 <            tryComplete();
4648 >            final Action<? super V> action;
4649 >            if ((action = this.action) != null) {
4650 >                for (int i = baseIndex, f, h; batch > 0 &&
4651 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4652 >                    addToPendingCount(1);
4653 >                    new ForEachValueTask<K,V>
4654 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4655 >                         action).fork();
4656 >                }
4657 >                for (Node<K,V> p; (p = advance()) != null;)
4658 >                    action.apply(p.val);
4659 >                propagateCompletion();
4660 >            }
4661          }
4662      }
4663  
4664 +    @SuppressWarnings("serial")
4665      static final class ForEachEntryTask<K,V>
4666          extends BulkTask<K,V,Void> {
4667 <        final Action<Entry<K,V>> action;
5009 <        ForEachEntryTask
5010 <            (ConcurrentHashMapV8<K,V> m,
5011 <             Action<Entry<K,V>> action) {
5012 <            super(m);
5013 <            this.action = action;
5014 <        }
4667 >        final Action<? super Entry<K,V>> action;
4668          ForEachEntryTask
4669 <            (BulkTask<K,V,?> p, int b, boolean split,
4670 <             Action<Entry<K,V>> action) {
4671 <            super(p, b, split);
4669 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4670 >             Action<? super Entry<K,V>> action) {
4671 >            super(p, b, i, f, t);
4672              this.action = action;
4673          }
4674          public final void compute() {
4675 <            final Action<Entry<K,V>> action = this.action;
4676 <            if (action == null)
4677 <                throw new Error(NullFunctionMessage);
4678 <            int b = batch(), c;
4679 <            while (b > 1 && baseIndex != baseLimit) {
4680 <                do {} while (!casPending(c = pending, c+1));
4681 <                new ForEachEntryTask<K,V>(this, b >>>= 1, true, action).fork();
4682 <            }
4683 <            Object v;
4684 <            while ((v = advance()) != null)
4685 <                action.apply(entryFor((K)nextKey, (V)v));
4686 <            tryComplete();
4675 >            final Action<? super Entry<K,V>> action;
4676 >            if ((action = this.action) != null) {
4677 >                for (int i = baseIndex, f, h; batch > 0 &&
4678 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4679 >                    addToPendingCount(1);
4680 >                    new ForEachEntryTask<K,V>
4681 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4682 >                         action).fork();
4683 >                }
4684 >                for (Node<K,V> p; (p = advance()) != null; )
4685 >                    action.apply(p);
4686 >                propagateCompletion();
4687 >            }
4688          }
4689      }
4690  
4691 +    @SuppressWarnings("serial")
4692      static final class ForEachMappingTask<K,V>
4693          extends BulkTask<K,V,Void> {
4694 <        final BiAction<K,V> action;
5040 <        ForEachMappingTask
5041 <            (ConcurrentHashMapV8<K,V> m,
5042 <             BiAction<K,V> action) {
5043 <            super(m);
5044 <            this.action = action;
5045 <        }
4694 >        final BiAction<? super K, ? super V> action;
4695          ForEachMappingTask
4696 <            (BulkTask<K,V,?> p, int b, boolean split,
4697 <             BiAction<K,V> action) {
4698 <            super(p, b, split);
4696 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4697 >             BiAction<? super K,? super V> action) {
4698 >            super(p, b, i, f, t);
4699              this.action = action;
4700          }
5052
4701          public final void compute() {
4702 <            final BiAction<K,V> action = this.action;
4703 <            if (action == null)
4704 <                throw new Error(NullFunctionMessage);
4705 <            int b = batch(), c;
4706 <            while (b > 1 && baseIndex != baseLimit) {
4707 <                do {} while (!casPending(c = pending, c+1));
4708 <                new ForEachMappingTask<K,V>(this, b >>>= 1, true,
4709 <                                            action).fork();
4710 <            }
4711 <            Object v;
4712 <            while ((v = advance()) != null)
4713 <                action.apply((K)nextKey, (V)v);
4714 <            tryComplete();
4702 >            final BiAction<? super K, ? super V> action;
4703 >            if ((action = this.action) != null) {
4704 >                for (int i = baseIndex, f, h; batch > 0 &&
4705 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4706 >                    addToPendingCount(1);
4707 >                    new ForEachMappingTask<K,V>
4708 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4709 >                         action).fork();
4710 >                }
4711 >                for (Node<K,V> p; (p = advance()) != null; )
4712 >                    action.apply(p.key, p.val);
4713 >                propagateCompletion();
4714 >            }
4715          }
4716      }
4717  
4718 +    @SuppressWarnings("serial")
4719      static final class ForEachTransformedKeyTask<K,V,U>
4720          extends BulkTask<K,V,Void> {
4721          final Fun<? super K, ? extends U> transformer;
4722 <        final Action<U> action;
4722 >        final Action<? super U> action;
4723          ForEachTransformedKeyTask
4724 <            (ConcurrentHashMapV8<K,V> m,
4725 <             Fun<? super K, ? extends U> transformer,
4726 <             Action<U> action) {
4727 <            super(m);
5079 <            this.transformer = transformer;
5080 <            this.action = action;
5081 <
5082 <        }
5083 <        ForEachTransformedKeyTask
5084 <            (BulkTask<K,V,?> p, int b, boolean split,
5085 <             Fun<? super K, ? extends U> transformer,
5086 <             Action<U> action) {
5087 <            super(p, b, split);
5088 <            this.transformer = transformer;
5089 <            this.action = action;
4724 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4725 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4726 >            super(p, b, i, f, t);
4727 >            this.transformer = transformer; this.action = action;
4728          }
4729          public final void compute() {
4730 <            final Fun<? super K, ? extends U> transformer =
4731 <                this.transformer;
4732 <            final Action<U> action = this.action;
4733 <            if (transformer == null || action == null)
4734 <                throw new Error(NullFunctionMessage);
4735 <            int b = batch(), c;
4736 <            while (b > 1 && baseIndex != baseLimit) {
4737 <                do {} while (!casPending(c = pending, c+1));
4738 <                new ForEachTransformedKeyTask<K,V,U>
4739 <                    (this, b >>>= 1, true, transformer, action).fork();
4740 <            }
4741 <            U u;
4742 <            while (advance() != null) {
4743 <                if ((u = transformer.apply((K)nextKey)) != null)
4744 <                    action.apply(u);
4730 >            final Fun<? super K, ? extends U> transformer;
4731 >            final Action<? super U> action;
4732 >            if ((transformer = this.transformer) != null &&
4733 >                (action = this.action) != null) {
4734 >                for (int i = baseIndex, f, h; batch > 0 &&
4735 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4736 >                    addToPendingCount(1);
4737 >                    new ForEachTransformedKeyTask<K,V,U>
4738 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4739 >                         transformer, action).fork();
4740 >                }
4741 >                for (Node<K,V> p; (p = advance()) != null; ) {
4742 >                    U u;
4743 >                    if ((u = transformer.apply(p.key)) != null)
4744 >                        action.apply(u);
4745 >                }
4746 >                propagateCompletion();
4747              }
5108            tryComplete();
4748          }
4749      }
4750  
4751 +    @SuppressWarnings("serial")
4752      static final class ForEachTransformedValueTask<K,V,U>
4753          extends BulkTask<K,V,Void> {
4754          final Fun<? super V, ? extends U> transformer;
4755 <        final Action<U> action;
5116 <        ForEachTransformedValueTask
5117 <            (ConcurrentHashMapV8<K,V> m,
5118 <             Fun<? super V, ? extends U> transformer,
5119 <             Action<U> action) {
5120 <            super(m);
5121 <            this.transformer = transformer;
5122 <            this.action = action;
5123 <
5124 <        }
4755 >        final Action<? super U> action;
4756          ForEachTransformedValueTask
4757 <            (BulkTask<K,V,?> p, int b, boolean split,
4758 <             Fun<? super V, ? extends U> transformer,
4759 <             Action<U> action) {
4760 <            super(p, b, split);
5130 <            this.transformer = transformer;
5131 <            this.action = action;
4757 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4758 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4759 >            super(p, b, i, f, t);
4760 >            this.transformer = transformer; this.action = action;
4761          }
4762          public final void compute() {
4763 <            final Fun<? super V, ? extends U> transformer =
4764 <                this.transformer;
4765 <            final Action<U> action = this.action;
4766 <            if (transformer == null || action == null)
4767 <                throw new Error(NullFunctionMessage);
4768 <            int b = batch(), c;
4769 <            while (b > 1 && baseIndex != baseLimit) {
4770 <                do {} while (!casPending(c = pending, c+1));
4771 <                new ForEachTransformedValueTask<K,V,U>
4772 <                    (this, b >>>= 1, true, transformer, action).fork();
4773 <            }
4774 <            Object v; U u;
4775 <            while ((v = advance()) != null) {
4776 <                if ((u = transformer.apply((V)v)) != null)
4777 <                    action.apply(u);
4763 >            final Fun<? super V, ? extends U> transformer;
4764 >            final Action<? super U> action;
4765 >            if ((transformer = this.transformer) != null &&
4766 >                (action = this.action) != null) {
4767 >                for (int i = baseIndex, f, h; batch > 0 &&
4768 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4769 >                    addToPendingCount(1);
4770 >                    new ForEachTransformedValueTask<K,V,U>
4771 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4772 >                         transformer, action).fork();
4773 >                }
4774 >                for (Node<K,V> p; (p = advance()) != null; ) {
4775 >                    U u;
4776 >                    if ((u = transformer.apply(p.val)) != null)
4777 >                        action.apply(u);
4778 >                }
4779 >                propagateCompletion();
4780              }
5150            tryComplete();
4781          }
4782      }
4783  
4784 +    @SuppressWarnings("serial")
4785      static final class ForEachTransformedEntryTask<K,V,U>
4786          extends BulkTask<K,V,Void> {
4787          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4788 <        final Action<U> action;
4788 >        final Action<? super U> action;
4789          ForEachTransformedEntryTask
4790 <            (ConcurrentHashMapV8<K,V> m,
4791 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4792 <             Action<U> action) {
4793 <            super(m);
5163 <            this.transformer = transformer;
5164 <            this.action = action;
5165 <
5166 <        }
5167 <        ForEachTransformedEntryTask
5168 <            (BulkTask<K,V,?> p, int b, boolean split,
5169 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5170 <             Action<U> action) {
5171 <            super(p, b, split);
5172 <            this.transformer = transformer;
5173 <            this.action = action;
4790 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4791 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4792 >            super(p, b, i, f, t);
4793 >            this.transformer = transformer; this.action = action;
4794          }
4795          public final void compute() {
4796 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4797 <                this.transformer;
4798 <            final Action<U> action = this.action;
4799 <            if (transformer == null || action == null)
4800 <                throw new Error(NullFunctionMessage);
4801 <            int b = batch(), c;
4802 <            while (b > 1 && baseIndex != baseLimit) {
4803 <                do {} while (!casPending(c = pending, c+1));
4804 <                new ForEachTransformedEntryTask<K,V,U>
4805 <                    (this, b >>>= 1, true, transformer, action).fork();
4806 <            }
4807 <            Object v; U u;
4808 <            while ((v = advance()) != null) {
4809 <                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
4810 <                    action.apply(u);
4796 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
4797 >            final Action<? super U> action;
4798 >            if ((transformer = this.transformer) != null &&
4799 >                (action = this.action) != null) {
4800 >                for (int i = baseIndex, f, h; batch > 0 &&
4801 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4802 >                    addToPendingCount(1);
4803 >                    new ForEachTransformedEntryTask<K,V,U>
4804 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4805 >                         transformer, action).fork();
4806 >                }
4807 >                for (Node<K,V> p; (p = advance()) != null; ) {
4808 >                    U u;
4809 >                    if ((u = transformer.apply(p)) != null)
4810 >                        action.apply(u);
4811 >                }
4812 >                propagateCompletion();
4813              }
5192            tryComplete();
4814          }
4815      }
4816  
4817 +    @SuppressWarnings("serial")
4818      static final class ForEachTransformedMappingTask<K,V,U>
4819          extends BulkTask<K,V,Void> {
4820          final BiFun<? super K, ? super V, ? extends U> transformer;
4821 <        final Action<U> action;
4821 >        final Action<? super U> action;
4822          ForEachTransformedMappingTask
4823 <            (ConcurrentHashMapV8<K,V> m,
4823 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4824               BiFun<? super K, ? super V, ? extends U> transformer,
4825 <             Action<U> action) {
4826 <            super(m);
4827 <            this.transformer = transformer;
5206 <            this.action = action;
5207 <
5208 <        }
5209 <        ForEachTransformedMappingTask
5210 <            (BulkTask<K,V,?> p, int b, boolean split,
5211 <             BiFun<? super K, ? super V, ? extends U> transformer,
5212 <             Action<U> action) {
5213 <            super(p, b, split);
5214 <            this.transformer = transformer;
5215 <            this.action = action;
4825 >             Action<? super U> action) {
4826 >            super(p, b, i, f, t);
4827 >            this.transformer = transformer; this.action = action;
4828          }
4829          public final void compute() {
4830 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4831 <                this.transformer;
4832 <            final Action<U> action = this.action;
4833 <            if (transformer == null || action == null)
4834 <                throw new Error(NullFunctionMessage);
4835 <            int b = batch(), c;
4836 <            while (b > 1 && baseIndex != baseLimit) {
4837 <                do {} while (!casPending(c = pending, c+1));
4838 <                new ForEachTransformedMappingTask<K,V,U>
4839 <                    (this, b >>>= 1, true, transformer, action).fork();
4840 <            }
4841 <            Object v; U u;
4842 <            while ((v = advance()) != null) {
4843 <                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
4844 <                    action.apply(u);
4830 >            final BiFun<? super K, ? super V, ? extends U> transformer;
4831 >            final Action<? super U> action;
4832 >            if ((transformer = this.transformer) != null &&
4833 >                (action = this.action) != null) {
4834 >                for (int i = baseIndex, f, h; batch > 0 &&
4835 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4836 >                    addToPendingCount(1);
4837 >                    new ForEachTransformedMappingTask<K,V,U>
4838 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4839 >                         transformer, action).fork();
4840 >                }
4841 >                for (Node<K,V> p; (p = advance()) != null; ) {
4842 >                    U u;
4843 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4844 >                        action.apply(u);
4845 >                }
4846 >                propagateCompletion();
4847              }
5234            tryComplete();
4848          }
4849      }
4850  
4851 +    @SuppressWarnings("serial")
4852      static final class SearchKeysTask<K,V,U>
4853          extends BulkTask<K,V,U> {
4854          final Fun<? super K, ? extends U> searchFunction;
4855          final AtomicReference<U> result;
4856          SearchKeysTask
4857 <            (ConcurrentHashMapV8<K,V> m,
5244 <             Fun<? super K, ? extends U> searchFunction,
5245 <             AtomicReference<U> result) {
5246 <            super(m);
5247 <            this.searchFunction = searchFunction; this.result = result;
5248 <        }
5249 <        SearchKeysTask
5250 <            (BulkTask<K,V,?> p, int b, boolean split,
4857 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4858               Fun<? super K, ? extends U> searchFunction,
4859               AtomicReference<U> result) {
4860 <            super(p, b, split);
4860 >            super(p, b, i, f, t);
4861              this.searchFunction = searchFunction; this.result = result;
4862          }
4863 +        public final U getRawResult() { return result.get(); }
4864          public final void compute() {
4865 <            AtomicReference<U> result = this.result;
4866 <            final Fun<? super K, ? extends U> searchFunction =
4867 <                this.searchFunction;
4868 <            if (searchFunction == null || result == null)
4869 <                throw new Error(NullFunctionMessage);
4870 <            int b = batch(), c;
4871 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4872 <                do {} while (!casPending(c = pending, c+1));
4873 <                new SearchKeysTask<K,V,U>(this, b >>>= 1, true,
4874 <                                          searchFunction, result).fork();
4875 <            }
4876 <            U u;
4877 <            while (result.get() == null && advance() != null) {
4878 <                if ((u = searchFunction.apply((K)nextKey)) != null) {
4879 <                    result.compareAndSet(null, u);
4880 <                    break;
4865 >            final Fun<? super K, ? extends U> searchFunction;
4866 >            final AtomicReference<U> result;
4867 >            if ((searchFunction = this.searchFunction) != null &&
4868 >                (result = this.result) != null) {
4869 >                for (int i = baseIndex, f, h; batch > 0 &&
4870 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4871 >                    if (result.get() != null)
4872 >                        return;
4873 >                    addToPendingCount(1);
4874 >                    new SearchKeysTask<K,V,U>
4875 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4876 >                         searchFunction, result).fork();
4877 >                }
4878 >                while (result.get() == null) {
4879 >                    U u;
4880 >                    Node<K,V> p;
4881 >                    if ((p = advance()) == null) {
4882 >                        propagateCompletion();
4883 >                        break;
4884 >                    }
4885 >                    if ((u = searchFunction.apply(p.key)) != null) {
4886 >                        if (result.compareAndSet(null, u))
4887 >                            quietlyCompleteRoot();
4888 >                        break;
4889 >                    }
4890                  }
4891              }
5275            tryComplete();
4892          }
5277        public final U getRawResult() { return result.get(); }
4893      }
4894  
4895 +    @SuppressWarnings("serial")
4896      static final class SearchValuesTask<K,V,U>
4897          extends BulkTask<K,V,U> {
4898          final Fun<? super V, ? extends U> searchFunction;
4899          final AtomicReference<U> result;
4900          SearchValuesTask
4901 <            (ConcurrentHashMapV8<K,V> m,
4901 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4902               Fun<? super V, ? extends U> searchFunction,
4903               AtomicReference<U> result) {
4904 <            super(m);
5289 <            this.searchFunction = searchFunction; this.result = result;
5290 <        }
5291 <        SearchValuesTask
5292 <            (BulkTask<K,V,?> p, int b, boolean split,
5293 <             Fun<? super V, ? extends U> searchFunction,
5294 <             AtomicReference<U> result) {
5295 <            super(p, b, split);
4904 >            super(p, b, i, f, t);
4905              this.searchFunction = searchFunction; this.result = result;
4906          }
4907 +        public final U getRawResult() { return result.get(); }
4908          public final void compute() {
4909 <            AtomicReference<U> result = this.result;
4910 <            final Fun<? super V, ? extends U> searchFunction =
4911 <                this.searchFunction;
4912 <            if (searchFunction == null || result == null)
4913 <                throw new Error(NullFunctionMessage);
4914 <            int b = batch(), c;
4915 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4916 <                do {} while (!casPending(c = pending, c+1));
4917 <                new SearchValuesTask<K,V,U>(this, b >>>= 1, true,
4918 <                                            searchFunction, result).fork();
4919 <            }
4920 <            Object v; U u;
4921 <            while (result.get() == null && (v = advance()) != null) {
4922 <                if ((u = searchFunction.apply((V)v)) != null) {
4923 <                    result.compareAndSet(null, u);
4924 <                    break;
4909 >            final Fun<? super V, ? extends U> searchFunction;
4910 >            final AtomicReference<U> result;
4911 >            if ((searchFunction = this.searchFunction) != null &&
4912 >                (result = this.result) != null) {
4913 >                for (int i = baseIndex, f, h; batch > 0 &&
4914 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4915 >                    if (result.get() != null)
4916 >                        return;
4917 >                    addToPendingCount(1);
4918 >                    new SearchValuesTask<K,V,U>
4919 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4920 >                         searchFunction, result).fork();
4921 >                }
4922 >                while (result.get() == null) {
4923 >                    U u;
4924 >                    Node<K,V> p;
4925 >                    if ((p = advance()) == null) {
4926 >                        propagateCompletion();
4927 >                        break;
4928 >                    }
4929 >                    if ((u = searchFunction.apply(p.val)) != null) {
4930 >                        if (result.compareAndSet(null, u))
4931 >                            quietlyCompleteRoot();
4932 >                        break;
4933 >                    }
4934                  }
4935              }
5317            tryComplete();
4936          }
5319        public final U getRawResult() { return result.get(); }
4937      }
4938  
4939 +    @SuppressWarnings("serial")
4940      static final class SearchEntriesTask<K,V,U>
4941          extends BulkTask<K,V,U> {
4942          final Fun<Entry<K,V>, ? extends U> searchFunction;
4943          final AtomicReference<U> result;
4944          SearchEntriesTask
4945 <            (ConcurrentHashMapV8<K,V> m,
4945 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4946               Fun<Entry<K,V>, ? extends U> searchFunction,
4947               AtomicReference<U> result) {
4948 <            super(m);
5331 <            this.searchFunction = searchFunction; this.result = result;
5332 <        }
5333 <        SearchEntriesTask
5334 <            (BulkTask<K,V,?> p, int b, boolean split,
5335 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5336 <             AtomicReference<U> result) {
5337 <            super(p, b, split);
4948 >            super(p, b, i, f, t);
4949              this.searchFunction = searchFunction; this.result = result;
4950          }
4951 +        public final U getRawResult() { return result.get(); }
4952          public final void compute() {
4953 <            AtomicReference<U> result = this.result;
4954 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
4955 <                this.searchFunction;
4956 <            if (searchFunction == null || result == null)
4957 <                throw new Error(NullFunctionMessage);
4958 <            int b = batch(), c;
4959 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4960 <                do {} while (!casPending(c = pending, c+1));
4961 <                new SearchEntriesTask<K,V,U>(this, b >>>= 1, true,
4962 <                                             searchFunction, result).fork();
4963 <            }
4964 <            Object v; U u;
4965 <            while (result.get() == null && (v = advance()) != null) {
4966 <                if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
4967 <                    result.compareAndSet(null, u);
4968 <                    break;
4953 >            final Fun<Entry<K,V>, ? extends U> searchFunction;
4954 >            final AtomicReference<U> result;
4955 >            if ((searchFunction = this.searchFunction) != null &&
4956 >                (result = this.result) != null) {
4957 >                for (int i = baseIndex, f, h; batch > 0 &&
4958 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4959 >                    if (result.get() != null)
4960 >                        return;
4961 >                    addToPendingCount(1);
4962 >                    new SearchEntriesTask<K,V,U>
4963 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4964 >                         searchFunction, result).fork();
4965 >                }
4966 >                while (result.get() == null) {
4967 >                    U u;
4968 >                    Node<K,V> p;
4969 >                    if ((p = advance()) == null) {
4970 >                        propagateCompletion();
4971 >                        break;
4972 >                    }
4973 >                    if ((u = searchFunction.apply(p)) != null) {
4974 >                        if (result.compareAndSet(null, u))
4975 >                            quietlyCompleteRoot();
4976 >                        return;
4977 >                    }
4978                  }
4979              }
5359            tryComplete();
4980          }
5361        public final U getRawResult() { return result.get(); }
4981      }
4982  
4983 +    @SuppressWarnings("serial")
4984      static final class SearchMappingsTask<K,V,U>
4985          extends BulkTask<K,V,U> {
4986          final BiFun<? super K, ? super V, ? extends U> searchFunction;
4987          final AtomicReference<U> result;
4988          SearchMappingsTask
4989 <            (ConcurrentHashMapV8<K,V> m,
4989 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4990               BiFun<? super K, ? super V, ? extends U> searchFunction,
4991               AtomicReference<U> result) {
4992 <            super(m);
5373 <            this.searchFunction = searchFunction; this.result = result;
5374 <        }
5375 <        SearchMappingsTask
5376 <            (BulkTask<K,V,?> p, int b, boolean split,
5377 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5378 <             AtomicReference<U> result) {
5379 <            super(p, b, split);
4992 >            super(p, b, i, f, t);
4993              this.searchFunction = searchFunction; this.result = result;
4994          }
4995 +        public final U getRawResult() { return result.get(); }
4996          public final void compute() {
4997 <            AtomicReference<U> result = this.result;
4998 <            final BiFun<? super K, ? super V, ? extends U> searchFunction =
4999 <                this.searchFunction;
5000 <            if (searchFunction == null || result == null)
5001 <                throw new Error(NullFunctionMessage);
5002 <            int b = batch(), c;
5003 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5004 <                do {} while (!casPending(c = pending, c+1));
5005 <                new SearchMappingsTask<K,V,U>(this, b >>>= 1, true,
5006 <                                              searchFunction, result).fork();
5007 <            }
5008 <            Object v; U u;
5009 <            while (result.get() == null && (v = advance()) != null) {
5010 <                if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5011 <                    result.compareAndSet(null, u);
5012 <                    break;
4997 >            final BiFun<? super K, ? super V, ? extends U> searchFunction;
4998 >            final AtomicReference<U> result;
4999 >            if ((searchFunction = this.searchFunction) != null &&
5000 >                (result = this.result) != null) {
5001 >                for (int i = baseIndex, f, h; batch > 0 &&
5002 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5003 >                    if (result.get() != null)
5004 >                        return;
5005 >                    addToPendingCount(1);
5006 >                    new SearchMappingsTask<K,V,U>
5007 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5008 >                         searchFunction, result).fork();
5009 >                }
5010 >                while (result.get() == null) {
5011 >                    U u;
5012 >                    Node<K,V> p;
5013 >                    if ((p = advance()) == null) {
5014 >                        propagateCompletion();
5015 >                        break;
5016 >                    }
5017 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5018 >                        if (result.compareAndSet(null, u))
5019 >                            quietlyCompleteRoot();
5020 >                        break;
5021 >                    }
5022                  }
5023              }
5401            tryComplete();
5024          }
5403        public final U getRawResult() { return result.get(); }
5025      }
5026  
5027 +    @SuppressWarnings("serial")
5028      static final class ReduceKeysTask<K,V>
5029          extends BulkTask<K,V,K> {
5030          final BiFun<? super K, ? super K, ? extends K> reducer;
5031          K result;
5032 <        ReduceKeysTask<K,V> sibling;
5032 >        ReduceKeysTask<K,V> rights, nextRight;
5033          ReduceKeysTask
5034 <            (ConcurrentHashMapV8<K,V> m,
5034 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5035 >             ReduceKeysTask<K,V> nextRight,
5036               BiFun<? super K, ? super K, ? extends K> reducer) {
5037 <            super(m);
5037 >            super(p, b, i, f, t); this.nextRight = nextRight;
5038              this.reducer = reducer;
5039          }
5040 <        ReduceKeysTask
5418 <            (BulkTask<K,V,?> p, int b, boolean split,
5419 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5420 <            super(p, b, split);
5421 <            this.reducer = reducer;
5422 <        }
5423 <
5040 >        public final K getRawResult() { return result; }
5041          public final void compute() {
5042 <            ReduceKeysTask<K,V> t = this;
5043 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5044 <                this.reducer;
5045 <            if (reducer == null)
5046 <                throw new Error(NullFunctionMessage);
5047 <            int b = batch();
5048 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5049 <                b >>>= 1;
5050 <                t.pending = 1;
5051 <                ReduceKeysTask<K,V> rt =
5052 <                    new ReduceKeysTask<K,V>
5053 <                    (t, b, true, reducer);
5054 <                t = new ReduceKeysTask<K,V>
5055 <                    (t, b, false, reducer);
5056 <                t.sibling = rt;
5057 <                rt.sibling = t;
5058 <                rt.fork();
5059 <            }
5060 <            K r = null;
5061 <            while (t.advance() != null) {
5062 <                K u = (K)t.nextKey;
5063 <                r = (r == null) ? u : reducer.apply(r, u);
5064 <            }
5065 <            t.result = r;
5066 <            for (;;) {
5067 <                int c; BulkTask<K,V,?> par; ReduceKeysTask<K,V> s, p; K u;
5068 <                if ((par = t.parent) == null ||
5452 <                    !(par instanceof ReduceKeysTask)) {
5453 <                    t.quietlyComplete();
5454 <                    break;
5455 <                }
5456 <                else if ((c = (p = (ReduceKeysTask<K,V>)par).pending) == 0) {
5457 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5458 <                        r = (r == null) ? u : reducer.apply(r, u);
5459 <                    (t = p).result = r;
5042 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5043 >            if ((reducer = this.reducer) != null) {
5044 >                for (int i = baseIndex, f, h; batch > 0 &&
5045 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5046 >                    addToPendingCount(1);
5047 >                    (rights = new ReduceKeysTask<K,V>
5048 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5049 >                      rights, reducer)).fork();
5050 >                }
5051 >                K r = null;
5052 >                for (Node<K,V> p; (p = advance()) != null; ) {
5053 >                    K u = p.key;
5054 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5055 >                }
5056 >                result = r;
5057 >                CountedCompleter<?> c;
5058 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5059 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5060 >                        t = (ReduceKeysTask<K,V>)c,
5061 >                        s = t.rights;
5062 >                    while (s != null) {
5063 >                        K tr, sr;
5064 >                        if ((sr = s.result) != null)
5065 >                            t.result = (((tr = t.result) == null) ? sr :
5066 >                                        reducer.apply(tr, sr));
5067 >                        s = t.rights = s.nextRight;
5068 >                    }
5069                  }
5461                else if (p.casPending(c, 0))
5462                    break;
5070              }
5071          }
5465        public final K getRawResult() { return result; }
5072      }
5073  
5074 +    @SuppressWarnings("serial")
5075      static final class ReduceValuesTask<K,V>
5076          extends BulkTask<K,V,V> {
5077          final BiFun<? super V, ? super V, ? extends V> reducer;
5078          V result;
5079 <        ReduceValuesTask<K,V> sibling;
5473 <        ReduceValuesTask
5474 <            (ConcurrentHashMapV8<K,V> m,
5475 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5476 <            super(m);
5477 <            this.reducer = reducer;
5478 <        }
5079 >        ReduceValuesTask<K,V> rights, nextRight;
5080          ReduceValuesTask
5081 <            (BulkTask<K,V,?> p, int b, boolean split,
5081 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5082 >             ReduceValuesTask<K,V> nextRight,
5083               BiFun<? super V, ? super V, ? extends V> reducer) {
5084 <            super(p, b, split);
5084 >            super(p, b, i, f, t); this.nextRight = nextRight;
5085              this.reducer = reducer;
5086          }
5087 <
5087 >        public final V getRawResult() { return result; }
5088          public final void compute() {
5089 <            ReduceValuesTask<K,V> t = this;
5090 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5091 <                this.reducer;
5092 <            if (reducer == null)
5093 <                throw new Error(NullFunctionMessage);
5094 <            int b = batch();
5095 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5096 <                b >>>= 1;
5097 <                t.pending = 1;
5098 <                ReduceValuesTask<K,V> rt =
5099 <                    new ReduceValuesTask<K,V>
5100 <                    (t, b, true, reducer);
5101 <                t = new ReduceValuesTask<K,V>
5102 <                    (t, b, false, reducer);
5103 <                t.sibling = rt;
5104 <                rt.sibling = t;
5105 <                rt.fork();
5106 <            }
5107 <            V r = null;
5108 <            Object v;
5109 <            while ((v = t.advance()) != null) {
5110 <                V u = (V)v;
5111 <                r = (r == null) ? u : reducer.apply(r, u);
5112 <            }
5113 <            t.result = r;
5114 <            for (;;) {
5115 <                int c; BulkTask<K,V,?> par; ReduceValuesTask<K,V> s, p; V u;
5514 <                if ((par = t.parent) == null ||
5515 <                    !(par instanceof ReduceValuesTask)) {
5516 <                    t.quietlyComplete();
5517 <                    break;
5518 <                }
5519 <                else if ((c = (p = (ReduceValuesTask<K,V>)par).pending) == 0) {
5520 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5521 <                        r = (r == null) ? u : reducer.apply(r, u);
5522 <                    (t = p).result = r;
5089 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5090 >            if ((reducer = this.reducer) != null) {
5091 >                for (int i = baseIndex, f, h; batch > 0 &&
5092 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5093 >                    addToPendingCount(1);
5094 >                    (rights = new ReduceValuesTask<K,V>
5095 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5096 >                      rights, reducer)).fork();
5097 >                }
5098 >                V r = null;
5099 >                for (Node<K,V> p; (p = advance()) != null; ) {
5100 >                    V v = p.val;
5101 >                    r = (r == null) ? v : reducer.apply(r, v);
5102 >                }
5103 >                result = r;
5104 >                CountedCompleter<?> c;
5105 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5106 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5107 >                        t = (ReduceValuesTask<K,V>)c,
5108 >                        s = t.rights;
5109 >                    while (s != null) {
5110 >                        V tr, sr;
5111 >                        if ((sr = s.result) != null)
5112 >                            t.result = (((tr = t.result) == null) ? sr :
5113 >                                        reducer.apply(tr, sr));
5114 >                        s = t.rights = s.nextRight;
5115 >                    }
5116                  }
5524                else if (p.casPending(c, 0))
5525                    break;
5117              }
5118          }
5528        public final V getRawResult() { return result; }
5119      }
5120  
5121 +    @SuppressWarnings("serial")
5122      static final class ReduceEntriesTask<K,V>
5123          extends BulkTask<K,V,Map.Entry<K,V>> {
5124          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5125          Map.Entry<K,V> result;
5126 <        ReduceEntriesTask<K,V> sibling;
5126 >        ReduceEntriesTask<K,V> rights, nextRight;
5127          ReduceEntriesTask
5128 <            (ConcurrentHashMapV8<K,V> m,
5128 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5129 >             ReduceEntriesTask<K,V> nextRight,
5130               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5131 <            super(m);
5540 <            this.reducer = reducer;
5541 <        }
5542 <        ReduceEntriesTask
5543 <            (BulkTask<K,V,?> p, int b, boolean split,
5544 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5545 <            super(p, b, split);
5131 >            super(p, b, i, f, t); this.nextRight = nextRight;
5132              this.reducer = reducer;
5133          }
5134 <
5134 >        public final Map.Entry<K,V> getRawResult() { return result; }
5135          public final void compute() {
5136 <            ReduceEntriesTask<K,V> t = this;
5137 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5138 <                this.reducer;
5139 <            if (reducer == null)
5140 <                throw new Error(NullFunctionMessage);
5141 <            int b = batch();
5142 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5143 <                b >>>= 1;
5144 <                t.pending = 1;
5145 <                ReduceEntriesTask<K,V> rt =
5146 <                    new ReduceEntriesTask<K,V>
5147 <                    (t, b, true, reducer);
5148 <                t = new ReduceEntriesTask<K,V>
5149 <                    (t, b, false, reducer);
5150 <                t.sibling = rt;
5151 <                rt.sibling = t;
5152 <                rt.fork();
5153 <            }
5154 <            Map.Entry<K,V> r = null;
5155 <            Object v;
5156 <            while ((v = t.advance()) != null) {
5157 <                Map.Entry<K,V> u = entryFor((K)t.nextKey, (V)v);
5158 <                r = (r == null) ? u : reducer.apply(r, u);
5159 <            }
5160 <            t.result = r;
5575 <            for (;;) {
5576 <                int c; BulkTask<K,V,?> par; ReduceEntriesTask<K,V> s, p;
5577 <                Map.Entry<K,V> u;
5578 <                if ((par = t.parent) == null ||
5579 <                    !(par instanceof ReduceEntriesTask)) {
5580 <                    t.quietlyComplete();
5581 <                    break;
5582 <                }
5583 <                else if ((c = (p = (ReduceEntriesTask<K,V>)par).pending) == 0) {
5584 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5585 <                        r = (r == null) ? u : reducer.apply(r, u);
5586 <                    (t = p).result = r;
5136 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5137 >            if ((reducer = this.reducer) != null) {
5138 >                for (int i = baseIndex, f, h; batch > 0 &&
5139 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5140 >                    addToPendingCount(1);
5141 >                    (rights = new ReduceEntriesTask<K,V>
5142 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5143 >                      rights, reducer)).fork();
5144 >                }
5145 >                Map.Entry<K,V> r = null;
5146 >                for (Node<K,V> p; (p = advance()) != null; )
5147 >                    r = (r == null) ? p : reducer.apply(r, p);
5148 >                result = r;
5149 >                CountedCompleter<?> c;
5150 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5151 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5152 >                        t = (ReduceEntriesTask<K,V>)c,
5153 >                        s = t.rights;
5154 >                    while (s != null) {
5155 >                        Map.Entry<K,V> tr, sr;
5156 >                        if ((sr = s.result) != null)
5157 >                            t.result = (((tr = t.result) == null) ? sr :
5158 >                                        reducer.apply(tr, sr));
5159 >                        s = t.rights = s.nextRight;
5160 >                    }
5161                  }
5588                else if (p.casPending(c, 0))
5589                    break;
5162              }
5163          }
5592        public final Map.Entry<K,V> getRawResult() { return result; }
5164      }
5165  
5166 +    @SuppressWarnings("serial")
5167      static final class MapReduceKeysTask<K,V,U>
5168          extends BulkTask<K,V,U> {
5169          final Fun<? super K, ? extends U> transformer;
5170          final BiFun<? super U, ? super U, ? extends U> reducer;
5171          U result;
5172 <        MapReduceKeysTask<K,V,U> sibling;
5601 <        MapReduceKeysTask
5602 <            (ConcurrentHashMapV8<K,V> m,
5603 <             Fun<? super K, ? extends U> transformer,
5604 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5605 <            super(m);
5606 <            this.transformer = transformer;
5607 <            this.reducer = reducer;
5608 <        }
5172 >        MapReduceKeysTask<K,V,U> rights, nextRight;
5173          MapReduceKeysTask
5174 <            (BulkTask<K,V,?> p, int b, boolean split,
5174 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5175 >             MapReduceKeysTask<K,V,U> nextRight,
5176               Fun<? super K, ? extends U> transformer,
5177               BiFun<? super U, ? super U, ? extends U> reducer) {
5178 <            super(p, b, split);
5178 >            super(p, b, i, f, t); this.nextRight = nextRight;
5179              this.transformer = transformer;
5180              this.reducer = reducer;
5181          }
5182 +        public final U getRawResult() { return result; }
5183          public final void compute() {
5184 <            MapReduceKeysTask<K,V,U> t = this;
5185 <            final Fun<? super K, ? extends U> transformer =
5186 <                this.transformer;
5187 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5188 <                this.reducer;
5189 <            if (transformer == null || reducer == null)
5190 <                throw new Error(NullFunctionMessage);
5191 <            int b = batch();
5192 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5193 <                b >>>= 1;
5194 <                t.pending = 1;
5195 <                MapReduceKeysTask<K,V,U> rt =
5196 <                    new MapReduceKeysTask<K,V,U>
5197 <                    (t, b, true, transformer, reducer);
5198 <                t = new MapReduceKeysTask<K,V,U>
5633 <                    (t, b, false, transformer, reducer);
5634 <                t.sibling = rt;
5635 <                rt.sibling = t;
5636 <                rt.fork();
5637 <            }
5638 <            U r = null, u;
5639 <            while (t.advance() != null) {
5640 <                if ((u = transformer.apply((K)t.nextKey)) != null)
5641 <                    r = (r == null) ? u : reducer.apply(r, u);
5642 <            }
5643 <            t.result = r;
5644 <            for (;;) {
5645 <                int c; BulkTask<K,V,?> par; MapReduceKeysTask<K,V,U> s, p;
5646 <                if ((par = t.parent) == null ||
5647 <                    !(par instanceof MapReduceKeysTask)) {
5648 <                    t.quietlyComplete();
5649 <                    break;
5650 <                }
5651 <                else if ((c = (p = (MapReduceKeysTask<K,V,U>)par).pending) == 0) {
5652 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5184 >            final Fun<? super K, ? extends U> transformer;
5185 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5186 >            if ((transformer = this.transformer) != null &&
5187 >                (reducer = this.reducer) != null) {
5188 >                for (int i = baseIndex, f, h; batch > 0 &&
5189 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5190 >                    addToPendingCount(1);
5191 >                    (rights = new MapReduceKeysTask<K,V,U>
5192 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5193 >                      rights, transformer, reducer)).fork();
5194 >                }
5195 >                U r = null;
5196 >                for (Node<K,V> p; (p = advance()) != null; ) {
5197 >                    U u;
5198 >                    if ((u = transformer.apply(p.key)) != null)
5199                          r = (r == null) ? u : reducer.apply(r, u);
5654                    (t = p).result = r;
5200                  }
5201 <                else if (p.casPending(c, 0))
5202 <                    break;
5201 >                result = r;
5202 >                CountedCompleter<?> c;
5203 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5204 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5205 >                        t = (MapReduceKeysTask<K,V,U>)c,
5206 >                        s = t.rights;
5207 >                    while (s != null) {
5208 >                        U tr, sr;
5209 >                        if ((sr = s.result) != null)
5210 >                            t.result = (((tr = t.result) == null) ? sr :
5211 >                                        reducer.apply(tr, sr));
5212 >                        s = t.rights = s.nextRight;
5213 >                    }
5214 >                }
5215              }
5216          }
5660        public final U getRawResult() { return result; }
5217      }
5218  
5219 +    @SuppressWarnings("serial")
5220      static final class MapReduceValuesTask<K,V,U>
5221          extends BulkTask<K,V,U> {
5222          final Fun<? super V, ? extends U> transformer;
5223          final BiFun<? super U, ? super U, ? extends U> reducer;
5224          U result;
5225 <        MapReduceValuesTask<K,V,U> sibling;
5225 >        MapReduceValuesTask<K,V,U> rights, nextRight;
5226          MapReduceValuesTask
5227 <            (ConcurrentHashMapV8<K,V> m,
5227 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5228 >             MapReduceValuesTask<K,V,U> nextRight,
5229               Fun<? super V, ? extends U> transformer,
5230               BiFun<? super U, ? super U, ? extends U> reducer) {
5231 <            super(m);
5674 <            this.transformer = transformer;
5675 <            this.reducer = reducer;
5676 <        }
5677 <        MapReduceValuesTask
5678 <            (BulkTask<K,V,?> p, int b, boolean split,
5679 <             Fun<? super V, ? extends U> transformer,
5680 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5681 <            super(p, b, split);
5231 >            super(p, b, i, f, t); this.nextRight = nextRight;
5232              this.transformer = transformer;
5233              this.reducer = reducer;
5234          }
5235 +        public final U getRawResult() { return result; }
5236          public final void compute() {
5237 <            MapReduceValuesTask<K,V,U> t = this;
5238 <            final Fun<? super V, ? extends U> transformer =
5239 <                this.transformer;
5240 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5241 <                this.reducer;
5242 <            if (transformer == null || reducer == null)
5243 <                throw new Error(NullFunctionMessage);
5244 <            int b = batch();
5245 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5246 <                b >>>= 1;
5247 <                t.pending = 1;
5248 <                MapReduceValuesTask<K,V,U> rt =
5249 <                    new MapReduceValuesTask<K,V,U>
5250 <                    (t, b, true, transformer, reducer);
5251 <                t = new MapReduceValuesTask<K,V,U>
5701 <                    (t, b, false, transformer, reducer);
5702 <                t.sibling = rt;
5703 <                rt.sibling = t;
5704 <                rt.fork();
5705 <            }
5706 <            U r = null, u;
5707 <            Object v;
5708 <            while ((v = t.advance()) != null) {
5709 <                if ((u = transformer.apply((V)v)) != null)
5710 <                    r = (r == null) ? u : reducer.apply(r, u);
5711 <            }
5712 <            t.result = r;
5713 <            for (;;) {
5714 <                int c; BulkTask<K,V,?> par; MapReduceValuesTask<K,V,U> s, p;
5715 <                if ((par = t.parent) == null ||
5716 <                    !(par instanceof MapReduceValuesTask)) {
5717 <                    t.quietlyComplete();
5718 <                    break;
5719 <                }
5720 <                else if ((c = (p = (MapReduceValuesTask<K,V,U>)par).pending) == 0) {
5721 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5237 >            final Fun<? super V, ? extends U> transformer;
5238 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5239 >            if ((transformer = this.transformer) != null &&
5240 >                (reducer = this.reducer) != null) {
5241 >                for (int i = baseIndex, f, h; batch > 0 &&
5242 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5243 >                    addToPendingCount(1);
5244 >                    (rights = new MapReduceValuesTask<K,V,U>
5245 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5246 >                      rights, transformer, reducer)).fork();
5247 >                }
5248 >                U r = null;
5249 >                for (Node<K,V> p; (p = advance()) != null; ) {
5250 >                    U u;
5251 >                    if ((u = transformer.apply(p.val)) != null)
5252                          r = (r == null) ? u : reducer.apply(r, u);
5723                    (t = p).result = r;
5253                  }
5254 <                else if (p.casPending(c, 0))
5255 <                    break;
5254 >                result = r;
5255 >                CountedCompleter<?> c;
5256 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5257 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5258 >                        t = (MapReduceValuesTask<K,V,U>)c,
5259 >                        s = t.rights;
5260 >                    while (s != null) {
5261 >                        U tr, sr;
5262 >                        if ((sr = s.result) != null)
5263 >                            t.result = (((tr = t.result) == null) ? sr :
5264 >                                        reducer.apply(tr, sr));
5265 >                        s = t.rights = s.nextRight;
5266 >                    }
5267 >                }
5268              }
5269          }
5729        public final U getRawResult() { return result; }
5270      }
5271  
5272 +    @SuppressWarnings("serial")
5273      static final class MapReduceEntriesTask<K,V,U>
5274          extends BulkTask<K,V,U> {
5275          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5276          final BiFun<? super U, ? super U, ? extends U> reducer;
5277          U result;
5278 <        MapReduceEntriesTask<K,V,U> sibling;
5278 >        MapReduceEntriesTask<K,V,U> rights, nextRight;
5279          MapReduceEntriesTask
5280 <            (ConcurrentHashMapV8<K,V> m,
5280 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5281 >             MapReduceEntriesTask<K,V,U> nextRight,
5282               Fun<Map.Entry<K,V>, ? extends U> transformer,
5283               BiFun<? super U, ? super U, ? extends U> reducer) {
5284 <            super(m);
5743 <            this.transformer = transformer;
5744 <            this.reducer = reducer;
5745 <        }
5746 <        MapReduceEntriesTask
5747 <            (BulkTask<K,V,?> p, int b, boolean split,
5748 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5749 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5750 <            super(p, b, split);
5284 >            super(p, b, i, f, t); this.nextRight = nextRight;
5285              this.transformer = transformer;
5286              this.reducer = reducer;
5287          }
5288 +        public final U getRawResult() { return result; }
5289          public final void compute() {
5290 <            MapReduceEntriesTask<K,V,U> t = this;
5291 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5292 <                this.transformer;
5293 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5294 <                this.reducer;
5295 <            if (transformer == null || reducer == null)
5296 <                throw new Error(NullFunctionMessage);
5297 <            int b = batch();
5298 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5299 <                b >>>= 1;
5300 <                t.pending = 1;
5301 <                MapReduceEntriesTask<K,V,U> rt =
5302 <                    new MapReduceEntriesTask<K,V,U>
5303 <                    (t, b, true, transformer, reducer);
5304 <                t = new MapReduceEntriesTask<K,V,U>
5770 <                    (t, b, false, transformer, reducer);
5771 <                t.sibling = rt;
5772 <                rt.sibling = t;
5773 <                rt.fork();
5774 <            }
5775 <            U r = null, u;
5776 <            Object v;
5777 <            while ((v = t.advance()) != null) {
5778 <                if ((u = transformer.apply(entryFor((K)t.nextKey, (V)v))) != null)
5779 <                    r = (r == null) ? u : reducer.apply(r, u);
5780 <            }
5781 <            t.result = r;
5782 <            for (;;) {
5783 <                int c; BulkTask<K,V,?> par; MapReduceEntriesTask<K,V,U> s, p;
5784 <                if ((par = t.parent) == null ||
5785 <                    !(par instanceof MapReduceEntriesTask)) {
5786 <                    t.quietlyComplete();
5787 <                    break;
5788 <                }
5789 <                else if ((c = (p = (MapReduceEntriesTask<K,V,U>)par).pending) == 0) {
5790 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5290 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5291 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5292 >            if ((transformer = this.transformer) != null &&
5293 >                (reducer = this.reducer) != null) {
5294 >                for (int i = baseIndex, f, h; batch > 0 &&
5295 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5296 >                    addToPendingCount(1);
5297 >                    (rights = new MapReduceEntriesTask<K,V,U>
5298 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5299 >                      rights, transformer, reducer)).fork();
5300 >                }
5301 >                U r = null;
5302 >                for (Node<K,V> p; (p = advance()) != null; ) {
5303 >                    U u;
5304 >                    if ((u = transformer.apply(p)) != null)
5305                          r = (r == null) ? u : reducer.apply(r, u);
5792                    (t = p).result = r;
5306                  }
5307 <                else if (p.casPending(c, 0))
5308 <                    break;
5307 >                result = r;
5308 >                CountedCompleter<?> c;
5309 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5310 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5311 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5312 >                        s = t.rights;
5313 >                    while (s != null) {
5314 >                        U tr, sr;
5315 >                        if ((sr = s.result) != null)
5316 >                            t.result = (((tr = t.result) == null) ? sr :
5317 >                                        reducer.apply(tr, sr));
5318 >                        s = t.rights = s.nextRight;
5319 >                    }
5320 >                }
5321              }
5322          }
5798        public final U getRawResult() { return result; }
5323      }
5324  
5325 +    @SuppressWarnings("serial")
5326      static final class MapReduceMappingsTask<K,V,U>
5327          extends BulkTask<K,V,U> {
5328          final BiFun<? super K, ? super V, ? extends U> transformer;
5329          final BiFun<? super U, ? super U, ? extends U> reducer;
5330          U result;
5331 <        MapReduceMappingsTask<K,V,U> sibling;
5807 <        MapReduceMappingsTask
5808 <            (ConcurrentHashMapV8<K,V> m,
5809 <             BiFun<? super K, ? super V, ? extends U> transformer,
5810 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5811 <            super(m);
5812 <            this.transformer = transformer;
5813 <            this.reducer = reducer;
5814 <        }
5331 >        MapReduceMappingsTask<K,V,U> rights, nextRight;
5332          MapReduceMappingsTask
5333 <            (BulkTask<K,V,?> p, int b, boolean split,
5333 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5334 >             MapReduceMappingsTask<K,V,U> nextRight,
5335               BiFun<? super K, ? super V, ? extends U> transformer,
5336               BiFun<? super U, ? super U, ? extends U> reducer) {
5337 <            super(p, b, split);
5337 >            super(p, b, i, f, t); this.nextRight = nextRight;
5338              this.transformer = transformer;
5339              this.reducer = reducer;
5340          }
5341 +        public final U getRawResult() { return result; }
5342          public final void compute() {
5343 <            MapReduceMappingsTask<K,V,U> t = this;
5344 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5345 <                this.transformer;
5346 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5347 <                this.reducer;
5348 <            if (transformer == null || reducer == null)
5349 <                throw new Error(NullFunctionMessage);
5350 <            int b = batch();
5351 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5352 <                b >>>= 1;
5353 <                t.pending = 1;
5354 <                MapReduceMappingsTask<K,V,U> rt =
5355 <                    new MapReduceMappingsTask<K,V,U>
5356 <                    (t, b, true, transformer, reducer);
5357 <                t = new MapReduceMappingsTask<K,V,U>
5839 <                    (t, b, false, transformer, reducer);
5840 <                t.sibling = rt;
5841 <                rt.sibling = t;
5842 <                rt.fork();
5843 <            }
5844 <            U r = null, u;
5845 <            Object v;
5846 <            while ((v = t.advance()) != null) {
5847 <                if ((u = transformer.apply((K)t.nextKey, (V)v)) != null)
5848 <                    r = (r == null) ? u : reducer.apply(r, u);
5849 <            }
5850 <            for (;;) {
5851 <                int c; BulkTask<K,V,?> par; MapReduceMappingsTask<K,V,U> s, p;
5852 <                if ((par = t.parent) == null ||
5853 <                    !(par instanceof MapReduceMappingsTask)) {
5854 <                    t.quietlyComplete();
5855 <                    break;
5856 <                }
5857 <                else if ((c = (p = (MapReduceMappingsTask<K,V,U>)par).pending) == 0) {
5858 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5343 >            final BiFun<? super K, ? super V, ? extends U> transformer;
5344 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5345 >            if ((transformer = this.transformer) != null &&
5346 >                (reducer = this.reducer) != null) {
5347 >                for (int i = baseIndex, f, h; batch > 0 &&
5348 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5349 >                    addToPendingCount(1);
5350 >                    (rights = new MapReduceMappingsTask<K,V,U>
5351 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5352 >                      rights, transformer, reducer)).fork();
5353 >                }
5354 >                U r = null;
5355 >                for (Node<K,V> p; (p = advance()) != null; ) {
5356 >                    U u;
5357 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5358                          r = (r == null) ? u : reducer.apply(r, u);
5860                    (t = p).result = r;
5359                  }
5360 <                else if (p.casPending(c, 0))
5361 <                    break;
5360 >                result = r;
5361 >                CountedCompleter<?> c;
5362 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5363 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5364 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5365 >                        s = t.rights;
5366 >                    while (s != null) {
5367 >                        U tr, sr;
5368 >                        if ((sr = s.result) != null)
5369 >                            t.result = (((tr = t.result) == null) ? sr :
5370 >                                        reducer.apply(tr, sr));
5371 >                        s = t.rights = s.nextRight;
5372 >                    }
5373 >                }
5374              }
5375          }
5866        public final U getRawResult() { return result; }
5376      }
5377  
5378 +    @SuppressWarnings("serial")
5379      static final class MapReduceKeysToDoubleTask<K,V>
5380          extends BulkTask<K,V,Double> {
5381          final ObjectToDouble<? super K> transformer;
5382          final DoubleByDoubleToDouble reducer;
5383          final double basis;
5384          double result;
5385 <        MapReduceKeysToDoubleTask<K,V> sibling;
5876 <        MapReduceKeysToDoubleTask
5877 <            (ConcurrentHashMapV8<K,V> m,
5878 <             ObjectToDouble<? super K> transformer,
5879 <             double basis,
5880 <             DoubleByDoubleToDouble reducer) {
5881 <            super(m);
5882 <            this.transformer = transformer;
5883 <            this.basis = basis; this.reducer = reducer;
5884 <        }
5385 >        MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5386          MapReduceKeysToDoubleTask
5387 <            (BulkTask<K,V,?> p, int b, boolean split,
5387 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5388 >             MapReduceKeysToDoubleTask<K,V> nextRight,
5389               ObjectToDouble<? super K> transformer,
5390               double basis,
5391               DoubleByDoubleToDouble reducer) {
5392 <            super(p, b, split);
5392 >            super(p, b, i, f, t); this.nextRight = nextRight;
5393              this.transformer = transformer;
5394              this.basis = basis; this.reducer = reducer;
5395          }
5396 +        public final Double getRawResult() { return result; }
5397          public final void compute() {
5398 <            MapReduceKeysToDoubleTask<K,V> t = this;
5399 <            final ObjectToDouble<? super K> transformer =
5400 <                this.transformer;
5401 <            final DoubleByDoubleToDouble reducer = this.reducer;
5402 <            if (transformer == null || reducer == null)
5403 <                throw new Error(NullFunctionMessage);
5404 <            final double id = this.basis;
5405 <            int b = batch();
5406 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5407 <                b >>>= 1;
5408 <                t.pending = 1;
5409 <                MapReduceKeysToDoubleTask<K,V> rt =
5410 <                    new MapReduceKeysToDoubleTask<K,V>
5411 <                    (t, b, true, transformer, id, reducer);
5412 <                t = new MapReduceKeysToDoubleTask<K,V>
5413 <                    (t, b, false, transformer, id, reducer);
5414 <                t.sibling = rt;
5415 <                rt.sibling = t;
5416 <                rt.fork();
5417 <            }
5418 <            double r = id;
5419 <            while (t.advance() != null)
5420 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5421 <            t.result = r;
5919 <            for (;;) {
5920 <                int c; BulkTask<K,V,?> par; MapReduceKeysToDoubleTask<K,V> s, p;
5921 <                if ((par = t.parent) == null ||
5922 <                    !(par instanceof MapReduceKeysToDoubleTask)) {
5923 <                    t.quietlyComplete();
5924 <                    break;
5925 <                }
5926 <                else if ((c = (p = (MapReduceKeysToDoubleTask<K,V>)par).pending) == 0) {
5927 <                    if ((s = t.sibling) != null)
5928 <                        r = reducer.apply(r, s.result);
5929 <                    (t = p).result = r;
5398 >            final ObjectToDouble<? super K> transformer;
5399 >            final DoubleByDoubleToDouble reducer;
5400 >            if ((transformer = this.transformer) != null &&
5401 >                (reducer = this.reducer) != null) {
5402 >                double r = this.basis;
5403 >                for (int i = baseIndex, f, h; batch > 0 &&
5404 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5405 >                    addToPendingCount(1);
5406 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
5407 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5408 >                      rights, transformer, r, reducer)).fork();
5409 >                }
5410 >                for (Node<K,V> p; (p = advance()) != null; )
5411 >                    r = reducer.apply(r, transformer.apply(p.key));
5412 >                result = r;
5413 >                CountedCompleter<?> c;
5414 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5415 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5416 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5417 >                        s = t.rights;
5418 >                    while (s != null) {
5419 >                        t.result = reducer.apply(t.result, s.result);
5420 >                        s = t.rights = s.nextRight;
5421 >                    }
5422                  }
5931                else if (p.casPending(c, 0))
5932                    break;
5423              }
5424          }
5935        public final Double getRawResult() { return result; }
5425      }
5426  
5427 +    @SuppressWarnings("serial")
5428      static final class MapReduceValuesToDoubleTask<K,V>
5429          extends BulkTask<K,V,Double> {
5430          final ObjectToDouble<? super V> transformer;
5431          final DoubleByDoubleToDouble reducer;
5432          final double basis;
5433          double result;
5434 <        MapReduceValuesToDoubleTask<K,V> sibling;
5434 >        MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5435          MapReduceValuesToDoubleTask
5436 <            (ConcurrentHashMapV8<K,V> m,
5436 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5437 >             MapReduceValuesToDoubleTask<K,V> nextRight,
5438               ObjectToDouble<? super V> transformer,
5439               double basis,
5440               DoubleByDoubleToDouble reducer) {
5441 <            super(m);
5951 <            this.transformer = transformer;
5952 <            this.basis = basis; this.reducer = reducer;
5953 <        }
5954 <        MapReduceValuesToDoubleTask
5955 <            (BulkTask<K,V,?> p, int b, boolean split,
5956 <             ObjectToDouble<? super V> transformer,
5957 <             double basis,
5958 <             DoubleByDoubleToDouble reducer) {
5959 <            super(p, b, split);
5441 >            super(p, b, i, f, t); this.nextRight = nextRight;
5442              this.transformer = transformer;
5443              this.basis = basis; this.reducer = reducer;
5444          }
5445 +        public final Double getRawResult() { return result; }
5446          public final void compute() {
5447 <            MapReduceValuesToDoubleTask<K,V> t = this;
5448 <            final ObjectToDouble<? super V> transformer =
5449 <                this.transformer;
5450 <            final DoubleByDoubleToDouble reducer = this.reducer;
5451 <            if (transformer == null || reducer == null)
5452 <                throw new Error(NullFunctionMessage);
5453 <            final double id = this.basis;
5454 <            int b = batch();
5455 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5456 <                b >>>= 1;
5457 <                t.pending = 1;
5458 <                MapReduceValuesToDoubleTask<K,V> rt =
5459 <                    new MapReduceValuesToDoubleTask<K,V>
5460 <                    (t, b, true, transformer, id, reducer);
5461 <                t = new MapReduceValuesToDoubleTask<K,V>
5462 <                    (t, b, false, transformer, id, reducer);
5463 <                t.sibling = rt;
5464 <                rt.sibling = t;
5465 <                rt.fork();
5466 <            }
5467 <            double r = id;
5468 <            Object v;
5469 <            while ((v = t.advance()) != null)
5470 <                r = reducer.apply(r, transformer.apply((V)v));
5988 <            t.result = r;
5989 <            for (;;) {
5990 <                int c; BulkTask<K,V,?> par; MapReduceValuesToDoubleTask<K,V> s, p;
5991 <                if ((par = t.parent) == null ||
5992 <                    !(par instanceof MapReduceValuesToDoubleTask)) {
5993 <                    t.quietlyComplete();
5994 <                    break;
5995 <                }
5996 <                else if ((c = (p = (MapReduceValuesToDoubleTask<K,V>)par).pending) == 0) {
5997 <                    if ((s = t.sibling) != null)
5998 <                        r = reducer.apply(r, s.result);
5999 <                    (t = p).result = r;
5447 >            final ObjectToDouble<? super V> transformer;
5448 >            final DoubleByDoubleToDouble reducer;
5449 >            if ((transformer = this.transformer) != null &&
5450 >                (reducer = this.reducer) != null) {
5451 >                double r = this.basis;
5452 >                for (int i = baseIndex, f, h; batch > 0 &&
5453 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5454 >                    addToPendingCount(1);
5455 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
5456 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5457 >                      rights, transformer, r, reducer)).fork();
5458 >                }
5459 >                for (Node<K,V> p; (p = advance()) != null; )
5460 >                    r = reducer.apply(r, transformer.apply(p.val));
5461 >                result = r;
5462 >                CountedCompleter<?> c;
5463 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5464 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5465 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5466 >                        s = t.rights;
5467 >                    while (s != null) {
5468 >                        t.result = reducer.apply(t.result, s.result);
5469 >                        s = t.rights = s.nextRight;
5470 >                    }
5471                  }
6001                else if (p.casPending(c, 0))
6002                    break;
5472              }
5473          }
6005        public final Double getRawResult() { return result; }
5474      }
5475  
5476 +    @SuppressWarnings("serial")
5477      static final class MapReduceEntriesToDoubleTask<K,V>
5478          extends BulkTask<K,V,Double> {
5479          final ObjectToDouble<Map.Entry<K,V>> transformer;
5480          final DoubleByDoubleToDouble reducer;
5481          final double basis;
5482          double result;
5483 <        MapReduceEntriesToDoubleTask<K,V> sibling;
5483 >        MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5484          MapReduceEntriesToDoubleTask
5485 <            (ConcurrentHashMapV8<K,V> m,
5485 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5486 >             MapReduceEntriesToDoubleTask<K,V> nextRight,
5487               ObjectToDouble<Map.Entry<K,V>> transformer,
5488               double basis,
5489               DoubleByDoubleToDouble reducer) {
5490 <            super(m);
6021 <            this.transformer = transformer;
6022 <            this.basis = basis; this.reducer = reducer;
6023 <        }
6024 <        MapReduceEntriesToDoubleTask
6025 <            (BulkTask<K,V,?> p, int b, boolean split,
6026 <             ObjectToDouble<Map.Entry<K,V>> transformer,
6027 <             double basis,
6028 <             DoubleByDoubleToDouble reducer) {
6029 <            super(p, b, split);
5490 >            super(p, b, i, f, t); this.nextRight = nextRight;
5491              this.transformer = transformer;
5492              this.basis = basis; this.reducer = reducer;
5493          }
5494 +        public final Double getRawResult() { return result; }
5495          public final void compute() {
5496 <            MapReduceEntriesToDoubleTask<K,V> t = this;
5497 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5498 <                this.transformer;
5499 <            final DoubleByDoubleToDouble reducer = this.reducer;
5500 <            if (transformer == null || reducer == null)
5501 <                throw new Error(NullFunctionMessage);
5502 <            final double id = this.basis;
5503 <            int b = batch();
5504 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5505 <                b >>>= 1;
5506 <                t.pending = 1;
5507 <                MapReduceEntriesToDoubleTask<K,V> rt =
5508 <                    new MapReduceEntriesToDoubleTask<K,V>
5509 <                    (t, b, true, transformer, id, reducer);
5510 <                t = new MapReduceEntriesToDoubleTask<K,V>
5511 <                    (t, b, false, transformer, id, reducer);
5512 <                t.sibling = rt;
5513 <                rt.sibling = t;
5514 <                rt.fork();
5515 <            }
5516 <            double r = id;
5517 <            Object v;
5518 <            while ((v = t.advance()) != null)
5519 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6058 <            t.result = r;
6059 <            for (;;) {
6060 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToDoubleTask<K,V> s, p;
6061 <                if ((par = t.parent) == null ||
6062 <                    !(par instanceof MapReduceEntriesToDoubleTask)) {
6063 <                    t.quietlyComplete();
6064 <                    break;
6065 <                }
6066 <                else if ((c = (p = (MapReduceEntriesToDoubleTask<K,V>)par).pending) == 0) {
6067 <                    if ((s = t.sibling) != null)
6068 <                        r = reducer.apply(r, s.result);
6069 <                    (t = p).result = r;
5496 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
5497 >            final DoubleByDoubleToDouble reducer;
5498 >            if ((transformer = this.transformer) != null &&
5499 >                (reducer = this.reducer) != null) {
5500 >                double r = this.basis;
5501 >                for (int i = baseIndex, f, h; batch > 0 &&
5502 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5503 >                    addToPendingCount(1);
5504 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
5505 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5506 >                      rights, transformer, r, reducer)).fork();
5507 >                }
5508 >                for (Node<K,V> p; (p = advance()) != null; )
5509 >                    r = reducer.apply(r, transformer.apply(p));
5510 >                result = r;
5511 >                CountedCompleter<?> c;
5512 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5513 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5514 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5515 >                        s = t.rights;
5516 >                    while (s != null) {
5517 >                        t.result = reducer.apply(t.result, s.result);
5518 >                        s = t.rights = s.nextRight;
5519 >                    }
5520                  }
6071                else if (p.casPending(c, 0))
6072                    break;
5521              }
5522          }
6075        public final Double getRawResult() { return result; }
5523      }
5524  
5525 +    @SuppressWarnings("serial")
5526      static final class MapReduceMappingsToDoubleTask<K,V>
5527          extends BulkTask<K,V,Double> {
5528          final ObjectByObjectToDouble<? super K, ? super V> transformer;
5529          final DoubleByDoubleToDouble reducer;
5530          final double basis;
5531          double result;
5532 <        MapReduceMappingsToDoubleTask<K,V> sibling;
6085 <        MapReduceMappingsToDoubleTask
6086 <            (ConcurrentHashMapV8<K,V> m,
6087 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
6088 <             double basis,
6089 <             DoubleByDoubleToDouble reducer) {
6090 <            super(m);
6091 <            this.transformer = transformer;
6092 <            this.basis = basis; this.reducer = reducer;
6093 <        }
5532 >        MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5533          MapReduceMappingsToDoubleTask
5534 <            (BulkTask<K,V,?> p, int b, boolean split,
5534 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5535 >             MapReduceMappingsToDoubleTask<K,V> nextRight,
5536               ObjectByObjectToDouble<? super K, ? super V> transformer,
5537               double basis,
5538               DoubleByDoubleToDouble reducer) {
5539 <            super(p, b, split);
5539 >            super(p, b, i, f, t); this.nextRight = nextRight;
5540              this.transformer = transformer;
5541              this.basis = basis; this.reducer = reducer;
5542          }
5543 +        public final Double getRawResult() { return result; }
5544          public final void compute() {
5545 <            MapReduceMappingsToDoubleTask<K,V> t = this;
5546 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5547 <                this.transformer;
5548 <            final DoubleByDoubleToDouble reducer = this.reducer;
5549 <            if (transformer == null || reducer == null)
5550 <                throw new Error(NullFunctionMessage);
5551 <            final double id = this.basis;
5552 <            int b = batch();
5553 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5554 <                b >>>= 1;
5555 <                t.pending = 1;
5556 <                MapReduceMappingsToDoubleTask<K,V> rt =
5557 <                    new MapReduceMappingsToDoubleTask<K,V>
5558 <                    (t, b, true, transformer, id, reducer);
5559 <                t = new MapReduceMappingsToDoubleTask<K,V>
5560 <                    (t, b, false, transformer, id, reducer);
5561 <                t.sibling = rt;
5562 <                rt.sibling = t;
5563 <                rt.fork();
5564 <            }
5565 <            double r = id;
5566 <            Object v;
5567 <            while ((v = t.advance()) != null)
5568 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6128 <            t.result = r;
6129 <            for (;;) {
6130 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToDoubleTask<K,V> s, p;
6131 <                if ((par = t.parent) == null ||
6132 <                    !(par instanceof MapReduceMappingsToDoubleTask)) {
6133 <                    t.quietlyComplete();
6134 <                    break;
6135 <                }
6136 <                else if ((c = (p = (MapReduceMappingsToDoubleTask<K,V>)par).pending) == 0) {
6137 <                    if ((s = t.sibling) != null)
6138 <                        r = reducer.apply(r, s.result);
6139 <                    (t = p).result = r;
5545 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
5546 >            final DoubleByDoubleToDouble reducer;
5547 >            if ((transformer = this.transformer) != null &&
5548 >                (reducer = this.reducer) != null) {
5549 >                double r = this.basis;
5550 >                for (int i = baseIndex, f, h; batch > 0 &&
5551 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5552 >                    addToPendingCount(1);
5553 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
5554 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5555 >                      rights, transformer, r, reducer)).fork();
5556 >                }
5557 >                for (Node<K,V> p; (p = advance()) != null; )
5558 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5559 >                result = r;
5560 >                CountedCompleter<?> c;
5561 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5562 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5563 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5564 >                        s = t.rights;
5565 >                    while (s != null) {
5566 >                        t.result = reducer.apply(t.result, s.result);
5567 >                        s = t.rights = s.nextRight;
5568 >                    }
5569                  }
6141                else if (p.casPending(c, 0))
6142                    break;
5570              }
5571          }
6145        public final Double getRawResult() { return result; }
5572      }
5573  
5574 +    @SuppressWarnings("serial")
5575      static final class MapReduceKeysToLongTask<K,V>
5576          extends BulkTask<K,V,Long> {
5577          final ObjectToLong<? super K> transformer;
5578          final LongByLongToLong reducer;
5579          final long basis;
5580          long result;
5581 <        MapReduceKeysToLongTask<K,V> sibling;
6155 <        MapReduceKeysToLongTask
6156 <            (ConcurrentHashMapV8<K,V> m,
6157 <             ObjectToLong<? super K> transformer,
6158 <             long basis,
6159 <             LongByLongToLong reducer) {
6160 <            super(m);
6161 <            this.transformer = transformer;
6162 <            this.basis = basis; this.reducer = reducer;
6163 <        }
5581 >        MapReduceKeysToLongTask<K,V> rights, nextRight;
5582          MapReduceKeysToLongTask
5583 <            (BulkTask<K,V,?> p, int b, boolean split,
5583 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5584 >             MapReduceKeysToLongTask<K,V> nextRight,
5585               ObjectToLong<? super K> transformer,
5586               long basis,
5587               LongByLongToLong reducer) {
5588 <            super(p, b, split);
5588 >            super(p, b, i, f, t); this.nextRight = nextRight;
5589              this.transformer = transformer;
5590              this.basis = basis; this.reducer = reducer;
5591          }
5592 +        public final Long getRawResult() { return result; }
5593          public final void compute() {
5594 <            MapReduceKeysToLongTask<K,V> t = this;
5595 <            final ObjectToLong<? super K> transformer =
5596 <                this.transformer;
5597 <            final LongByLongToLong reducer = this.reducer;
5598 <            if (transformer == null || reducer == null)
5599 <                throw new Error(NullFunctionMessage);
5600 <            final long id = this.basis;
5601 <            int b = batch();
5602 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5603 <                b >>>= 1;
5604 <                t.pending = 1;
5605 <                MapReduceKeysToLongTask<K,V> rt =
5606 <                    new MapReduceKeysToLongTask<K,V>
5607 <                    (t, b, true, transformer, id, reducer);
5608 <                t = new MapReduceKeysToLongTask<K,V>
5609 <                    (t, b, false, transformer, id, reducer);
5610 <                t.sibling = rt;
5611 <                rt.sibling = t;
5612 <                rt.fork();
5613 <            }
5614 <            long r = id;
5615 <            while (t.advance() != null)
5616 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5617 <            t.result = r;
6198 <            for (;;) {
6199 <                int c; BulkTask<K,V,?> par; MapReduceKeysToLongTask<K,V> s, p;
6200 <                if ((par = t.parent) == null ||
6201 <                    !(par instanceof MapReduceKeysToLongTask)) {
6202 <                    t.quietlyComplete();
6203 <                    break;
6204 <                }
6205 <                else if ((c = (p = (MapReduceKeysToLongTask<K,V>)par).pending) == 0) {
6206 <                    if ((s = t.sibling) != null)
6207 <                        r = reducer.apply(r, s.result);
6208 <                    (t = p).result = r;
5594 >            final ObjectToLong<? super K> transformer;
5595 >            final LongByLongToLong reducer;
5596 >            if ((transformer = this.transformer) != null &&
5597 >                (reducer = this.reducer) != null) {
5598 >                long r = this.basis;
5599 >                for (int i = baseIndex, f, h; batch > 0 &&
5600 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5601 >                    addToPendingCount(1);
5602 >                    (rights = new MapReduceKeysToLongTask<K,V>
5603 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5604 >                      rights, transformer, r, reducer)).fork();
5605 >                }
5606 >                for (Node<K,V> p; (p = advance()) != null; )
5607 >                    r = reducer.apply(r, transformer.apply(p.key));
5608 >                result = r;
5609 >                CountedCompleter<?> c;
5610 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5611 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5612 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5613 >                        s = t.rights;
5614 >                    while (s != null) {
5615 >                        t.result = reducer.apply(t.result, s.result);
5616 >                        s = t.rights = s.nextRight;
5617 >                    }
5618                  }
6210                else if (p.casPending(c, 0))
6211                    break;
5619              }
5620          }
6214        public final Long getRawResult() { return result; }
5621      }
5622  
5623 +    @SuppressWarnings("serial")
5624      static final class MapReduceValuesToLongTask<K,V>
5625          extends BulkTask<K,V,Long> {
5626          final ObjectToLong<? super V> transformer;
5627          final LongByLongToLong reducer;
5628          final long basis;
5629          long result;
5630 <        MapReduceValuesToLongTask<K,V> sibling;
5630 >        MapReduceValuesToLongTask<K,V> rights, nextRight;
5631          MapReduceValuesToLongTask
5632 <            (ConcurrentHashMapV8<K,V> m,
5632 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5633 >             MapReduceValuesToLongTask<K,V> nextRight,
5634               ObjectToLong<? super V> transformer,
5635               long basis,
5636               LongByLongToLong reducer) {
5637 <            super(m);
6230 <            this.transformer = transformer;
6231 <            this.basis = basis; this.reducer = reducer;
6232 <        }
6233 <        MapReduceValuesToLongTask
6234 <            (BulkTask<K,V,?> p, int b, boolean split,
6235 <             ObjectToLong<? super V> transformer,
6236 <             long basis,
6237 <             LongByLongToLong reducer) {
6238 <            super(p, b, split);
5637 >            super(p, b, i, f, t); this.nextRight = nextRight;
5638              this.transformer = transformer;
5639              this.basis = basis; this.reducer = reducer;
5640          }
5641 +        public final Long getRawResult() { return result; }
5642          public final void compute() {
5643 <            MapReduceValuesToLongTask<K,V> t = this;
5644 <            final ObjectToLong<? super V> transformer =
5645 <                this.transformer;
5646 <            final LongByLongToLong reducer = this.reducer;
5647 <            if (transformer == null || reducer == null)
5648 <                throw new Error(NullFunctionMessage);
5649 <            final long id = this.basis;
5650 <            int b = batch();
5651 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5652 <                b >>>= 1;
5653 <                t.pending = 1;
5654 <                MapReduceValuesToLongTask<K,V> rt =
5655 <                    new MapReduceValuesToLongTask<K,V>
5656 <                    (t, b, true, transformer, id, reducer);
5657 <                t = new MapReduceValuesToLongTask<K,V>
5658 <                    (t, b, false, transformer, id, reducer);
5659 <                t.sibling = rt;
5660 <                rt.sibling = t;
5661 <                rt.fork();
5662 <            }
5663 <            long r = id;
5664 <            Object v;
5665 <            while ((v = t.advance()) != null)
5666 <                r = reducer.apply(r, transformer.apply((V)v));
6267 <            t.result = r;
6268 <            for (;;) {
6269 <                int c; BulkTask<K,V,?> par; MapReduceValuesToLongTask<K,V> s, p;
6270 <                if ((par = t.parent) == null ||
6271 <                    !(par instanceof MapReduceValuesToLongTask)) {
6272 <                    t.quietlyComplete();
6273 <                    break;
6274 <                }
6275 <                else if ((c = (p = (MapReduceValuesToLongTask<K,V>)par).pending) == 0) {
6276 <                    if ((s = t.sibling) != null)
6277 <                        r = reducer.apply(r, s.result);
6278 <                    (t = p).result = r;
5643 >            final ObjectToLong<? super V> transformer;
5644 >            final LongByLongToLong reducer;
5645 >            if ((transformer = this.transformer) != null &&
5646 >                (reducer = this.reducer) != null) {
5647 >                long r = this.basis;
5648 >                for (int i = baseIndex, f, h; batch > 0 &&
5649 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5650 >                    addToPendingCount(1);
5651 >                    (rights = new MapReduceValuesToLongTask<K,V>
5652 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5653 >                      rights, transformer, r, reducer)).fork();
5654 >                }
5655 >                for (Node<K,V> p; (p = advance()) != null; )
5656 >                    r = reducer.apply(r, transformer.apply(p.val));
5657 >                result = r;
5658 >                CountedCompleter<?> c;
5659 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5660 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5661 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5662 >                        s = t.rights;
5663 >                    while (s != null) {
5664 >                        t.result = reducer.apply(t.result, s.result);
5665 >                        s = t.rights = s.nextRight;
5666 >                    }
5667                  }
6280                else if (p.casPending(c, 0))
6281                    break;
5668              }
5669          }
6284        public final Long getRawResult() { return result; }
5670      }
5671  
5672 +    @SuppressWarnings("serial")
5673      static final class MapReduceEntriesToLongTask<K,V>
5674          extends BulkTask<K,V,Long> {
5675          final ObjectToLong<Map.Entry<K,V>> transformer;
5676          final LongByLongToLong reducer;
5677          final long basis;
5678          long result;
5679 <        MapReduceEntriesToLongTask<K,V> sibling;
5679 >        MapReduceEntriesToLongTask<K,V> rights, nextRight;
5680          MapReduceEntriesToLongTask
5681 <            (ConcurrentHashMapV8<K,V> m,
5681 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5682 >             MapReduceEntriesToLongTask<K,V> nextRight,
5683               ObjectToLong<Map.Entry<K,V>> transformer,
5684               long basis,
5685               LongByLongToLong reducer) {
5686 <            super(m);
6300 <            this.transformer = transformer;
6301 <            this.basis = basis; this.reducer = reducer;
6302 <        }
6303 <        MapReduceEntriesToLongTask
6304 <            (BulkTask<K,V,?> p, int b, boolean split,
6305 <             ObjectToLong<Map.Entry<K,V>> transformer,
6306 <             long basis,
6307 <             LongByLongToLong reducer) {
6308 <            super(p, b, split);
5686 >            super(p, b, i, f, t); this.nextRight = nextRight;
5687              this.transformer = transformer;
5688              this.basis = basis; this.reducer = reducer;
5689          }
5690 +        public final Long getRawResult() { return result; }
5691          public final void compute() {
5692 <            MapReduceEntriesToLongTask<K,V> t = this;
5693 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5694 <                this.transformer;
5695 <            final LongByLongToLong reducer = this.reducer;
5696 <            if (transformer == null || reducer == null)
5697 <                throw new Error(NullFunctionMessage);
5698 <            final long id = this.basis;
5699 <            int b = batch();
5700 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5701 <                b >>>= 1;
5702 <                t.pending = 1;
5703 <                MapReduceEntriesToLongTask<K,V> rt =
5704 <                    new MapReduceEntriesToLongTask<K,V>
5705 <                    (t, b, true, transformer, id, reducer);
5706 <                t = new MapReduceEntriesToLongTask<K,V>
5707 <                    (t, b, false, transformer, id, reducer);
5708 <                t.sibling = rt;
5709 <                rt.sibling = t;
5710 <                rt.fork();
5711 <            }
5712 <            long r = id;
5713 <            Object v;
5714 <            while ((v = t.advance()) != null)
5715 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6337 <            t.result = r;
6338 <            for (;;) {
6339 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToLongTask<K,V> s, p;
6340 <                if ((par = t.parent) == null ||
6341 <                    !(par instanceof MapReduceEntriesToLongTask)) {
6342 <                    t.quietlyComplete();
6343 <                    break;
6344 <                }
6345 <                else if ((c = (p = (MapReduceEntriesToLongTask<K,V>)par).pending) == 0) {
6346 <                    if ((s = t.sibling) != null)
6347 <                        r = reducer.apply(r, s.result);
6348 <                    (t = p).result = r;
5692 >            final ObjectToLong<Map.Entry<K,V>> transformer;
5693 >            final LongByLongToLong reducer;
5694 >            if ((transformer = this.transformer) != null &&
5695 >                (reducer = this.reducer) != null) {
5696 >                long r = this.basis;
5697 >                for (int i = baseIndex, f, h; batch > 0 &&
5698 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5699 >                    addToPendingCount(1);
5700 >                    (rights = new MapReduceEntriesToLongTask<K,V>
5701 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5702 >                      rights, transformer, r, reducer)).fork();
5703 >                }
5704 >                for (Node<K,V> p; (p = advance()) != null; )
5705 >                    r = reducer.apply(r, transformer.apply(p));
5706 >                result = r;
5707 >                CountedCompleter<?> c;
5708 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5709 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5710 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5711 >                        s = t.rights;
5712 >                    while (s != null) {
5713 >                        t.result = reducer.apply(t.result, s.result);
5714 >                        s = t.rights = s.nextRight;
5715 >                    }
5716                  }
6350                else if (p.casPending(c, 0))
6351                    break;
5717              }
5718          }
6354        public final Long getRawResult() { return result; }
5719      }
5720  
5721 +    @SuppressWarnings("serial")
5722      static final class MapReduceMappingsToLongTask<K,V>
5723          extends BulkTask<K,V,Long> {
5724          final ObjectByObjectToLong<? super K, ? super V> transformer;
5725          final LongByLongToLong reducer;
5726          final long basis;
5727          long result;
5728 <        MapReduceMappingsToLongTask<K,V> sibling;
5728 >        MapReduceMappingsToLongTask<K,V> rights, nextRight;
5729          MapReduceMappingsToLongTask
5730 <            (ConcurrentHashMapV8<K,V> m,
5730 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5731 >             MapReduceMappingsToLongTask<K,V> nextRight,
5732               ObjectByObjectToLong<? super K, ? super V> transformer,
5733               long basis,
5734               LongByLongToLong reducer) {
5735 <            super(m);
6370 <            this.transformer = transformer;
6371 <            this.basis = basis; this.reducer = reducer;
6372 <        }
6373 <        MapReduceMappingsToLongTask
6374 <            (BulkTask<K,V,?> p, int b, boolean split,
6375 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6376 <             long basis,
6377 <             LongByLongToLong reducer) {
6378 <            super(p, b, split);
5735 >            super(p, b, i, f, t); this.nextRight = nextRight;
5736              this.transformer = transformer;
5737              this.basis = basis; this.reducer = reducer;
5738          }
5739 +        public final Long getRawResult() { return result; }
5740          public final void compute() {
5741 <            MapReduceMappingsToLongTask<K,V> t = this;
5742 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5743 <                this.transformer;
5744 <            final LongByLongToLong reducer = this.reducer;
5745 <            if (transformer == null || reducer == null)
5746 <                throw new Error(NullFunctionMessage);
5747 <            final long id = this.basis;
5748 <            int b = batch();
5749 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5750 <                b >>>= 1;
5751 <                t.pending = 1;
5752 <                MapReduceMappingsToLongTask<K,V> rt =
5753 <                    new MapReduceMappingsToLongTask<K,V>
5754 <                    (t, b, true, transformer, id, reducer);
5755 <                t = new MapReduceMappingsToLongTask<K,V>
5756 <                    (t, b, false, transformer, id, reducer);
5757 <                t.sibling = rt;
5758 <                rt.sibling = t;
5759 <                rt.fork();
5760 <            }
5761 <            long r = id;
5762 <            Object v;
5763 <            while ((v = t.advance()) != null)
5764 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6407 <            t.result = r;
6408 <            for (;;) {
6409 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToLongTask<K,V> s, p;
6410 <                if ((par = t.parent) == null ||
6411 <                    !(par instanceof MapReduceMappingsToLongTask)) {
6412 <                    t.quietlyComplete();
6413 <                    break;
6414 <                }
6415 <                else if ((c = (p = (MapReduceMappingsToLongTask<K,V>)par).pending) == 0) {
6416 <                    if ((s = t.sibling) != null)
6417 <                        r = reducer.apply(r, s.result);
6418 <                    (t = p).result = r;
5741 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
5742 >            final LongByLongToLong reducer;
5743 >            if ((transformer = this.transformer) != null &&
5744 >                (reducer = this.reducer) != null) {
5745 >                long r = this.basis;
5746 >                for (int i = baseIndex, f, h; batch > 0 &&
5747 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5748 >                    addToPendingCount(1);
5749 >                    (rights = new MapReduceMappingsToLongTask<K,V>
5750 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5751 >                      rights, transformer, r, reducer)).fork();
5752 >                }
5753 >                for (Node<K,V> p; (p = advance()) != null; )
5754 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5755 >                result = r;
5756 >                CountedCompleter<?> c;
5757 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5758 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5759 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5760 >                        s = t.rights;
5761 >                    while (s != null) {
5762 >                        t.result = reducer.apply(t.result, s.result);
5763 >                        s = t.rights = s.nextRight;
5764 >                    }
5765                  }
6420                else if (p.casPending(c, 0))
6421                    break;
5766              }
5767          }
6424        public final Long getRawResult() { return result; }
5768      }
5769  
5770 +    @SuppressWarnings("serial")
5771      static final class MapReduceKeysToIntTask<K,V>
5772          extends BulkTask<K,V,Integer> {
5773          final ObjectToInt<? super K> transformer;
5774          final IntByIntToInt reducer;
5775          final int basis;
5776          int result;
5777 <        MapReduceKeysToIntTask<K,V> sibling;
5777 >        MapReduceKeysToIntTask<K,V> rights, nextRight;
5778          MapReduceKeysToIntTask
5779 <            (ConcurrentHashMapV8<K,V> m,
5779 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5780 >             MapReduceKeysToIntTask<K,V> nextRight,
5781               ObjectToInt<? super K> transformer,
5782               int basis,
5783               IntByIntToInt reducer) {
5784 <            super(m);
6440 <            this.transformer = transformer;
6441 <            this.basis = basis; this.reducer = reducer;
6442 <        }
6443 <        MapReduceKeysToIntTask
6444 <            (BulkTask<K,V,?> p, int b, boolean split,
6445 <             ObjectToInt<? super K> transformer,
6446 <             int basis,
6447 <             IntByIntToInt reducer) {
6448 <            super(p, b, split);
5784 >            super(p, b, i, f, t); this.nextRight = nextRight;
5785              this.transformer = transformer;
5786              this.basis = basis; this.reducer = reducer;
5787          }
5788 +        public final Integer getRawResult() { return result; }
5789          public final void compute() {
5790 <            MapReduceKeysToIntTask<K,V> t = this;
5791 <            final ObjectToInt<? super K> transformer =
5792 <                this.transformer;
5793 <            final IntByIntToInt reducer = this.reducer;
5794 <            if (transformer == null || reducer == null)
5795 <                throw new Error(NullFunctionMessage);
5796 <            final int id = this.basis;
5797 <            int b = batch();
5798 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5799 <                b >>>= 1;
5800 <                t.pending = 1;
5801 <                MapReduceKeysToIntTask<K,V> rt =
5802 <                    new MapReduceKeysToIntTask<K,V>
5803 <                    (t, b, true, transformer, id, reducer);
5804 <                t = new MapReduceKeysToIntTask<K,V>
5805 <                    (t, b, false, transformer, id, reducer);
5806 <                t.sibling = rt;
5807 <                rt.sibling = t;
5808 <                rt.fork();
5809 <            }
5810 <            int r = id;
5811 <            while (t.advance() != null)
5812 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5813 <            t.result = r;
6477 <            for (;;) {
6478 <                int c; BulkTask<K,V,?> par; MapReduceKeysToIntTask<K,V> s, p;
6479 <                if ((par = t.parent) == null ||
6480 <                    !(par instanceof MapReduceKeysToIntTask)) {
6481 <                    t.quietlyComplete();
6482 <                    break;
6483 <                }
6484 <                else if ((c = (p = (MapReduceKeysToIntTask<K,V>)par).pending) == 0) {
6485 <                    if ((s = t.sibling) != null)
6486 <                        r = reducer.apply(r, s.result);
6487 <                    (t = p).result = r;
5790 >            final ObjectToInt<? super K> transformer;
5791 >            final IntByIntToInt reducer;
5792 >            if ((transformer = this.transformer) != null &&
5793 >                (reducer = this.reducer) != null) {
5794 >                int r = this.basis;
5795 >                for (int i = baseIndex, f, h; batch > 0 &&
5796 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5797 >                    addToPendingCount(1);
5798 >                    (rights = new MapReduceKeysToIntTask<K,V>
5799 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5800 >                      rights, transformer, r, reducer)).fork();
5801 >                }
5802 >                for (Node<K,V> p; (p = advance()) != null; )
5803 >                    r = reducer.apply(r, transformer.apply(p.key));
5804 >                result = r;
5805 >                CountedCompleter<?> c;
5806 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5807 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5808 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5809 >                        s = t.rights;
5810 >                    while (s != null) {
5811 >                        t.result = reducer.apply(t.result, s.result);
5812 >                        s = t.rights = s.nextRight;
5813 >                    }
5814                  }
6489                else if (p.casPending(c, 0))
6490                    break;
5815              }
5816          }
6493        public final Integer getRawResult() { return result; }
5817      }
5818  
5819 +    @SuppressWarnings("serial")
5820      static final class MapReduceValuesToIntTask<K,V>
5821          extends BulkTask<K,V,Integer> {
5822          final ObjectToInt<? super V> transformer;
5823          final IntByIntToInt reducer;
5824          final int basis;
5825          int result;
5826 <        MapReduceValuesToIntTask<K,V> sibling;
6503 <        MapReduceValuesToIntTask
6504 <            (ConcurrentHashMapV8<K,V> m,
6505 <             ObjectToInt<? super V> transformer,
6506 <             int basis,
6507 <             IntByIntToInt reducer) {
6508 <            super(m);
6509 <            this.transformer = transformer;
6510 <            this.basis = basis; this.reducer = reducer;
6511 <        }
5826 >        MapReduceValuesToIntTask<K,V> rights, nextRight;
5827          MapReduceValuesToIntTask
5828 <            (BulkTask<K,V,?> p, int b, boolean split,
5828 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5829 >             MapReduceValuesToIntTask<K,V> nextRight,
5830               ObjectToInt<? super V> transformer,
5831               int basis,
5832               IntByIntToInt reducer) {
5833 <            super(p, b, split);
5833 >            super(p, b, i, f, t); this.nextRight = nextRight;
5834              this.transformer = transformer;
5835              this.basis = basis; this.reducer = reducer;
5836          }
5837 +        public final Integer getRawResult() { return result; }
5838          public final void compute() {
5839 <            MapReduceValuesToIntTask<K,V> t = this;
5840 <            final ObjectToInt<? super V> transformer =
5841 <                this.transformer;
5842 <            final IntByIntToInt reducer = this.reducer;
5843 <            if (transformer == null || reducer == null)
5844 <                throw new Error(NullFunctionMessage);
5845 <            final int id = this.basis;
5846 <            int b = batch();
5847 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5848 <                b >>>= 1;
5849 <                t.pending = 1;
5850 <                MapReduceValuesToIntTask<K,V> rt =
5851 <                    new MapReduceValuesToIntTask<K,V>
5852 <                    (t, b, true, transformer, id, reducer);
5853 <                t = new MapReduceValuesToIntTask<K,V>
5854 <                    (t, b, false, transformer, id, reducer);
5855 <                t.sibling = rt;
5856 <                rt.sibling = t;
5857 <                rt.fork();
5858 <            }
5859 <            int r = id;
5860 <            Object v;
5861 <            while ((v = t.advance()) != null)
5862 <                r = reducer.apply(r, transformer.apply((V)v));
6546 <            t.result = r;
6547 <            for (;;) {
6548 <                int c; BulkTask<K,V,?> par; MapReduceValuesToIntTask<K,V> s, p;
6549 <                if ((par = t.parent) == null ||
6550 <                    !(par instanceof MapReduceValuesToIntTask)) {
6551 <                    t.quietlyComplete();
6552 <                    break;
6553 <                }
6554 <                else if ((c = (p = (MapReduceValuesToIntTask<K,V>)par).pending) == 0) {
6555 <                    if ((s = t.sibling) != null)
6556 <                        r = reducer.apply(r, s.result);
6557 <                    (t = p).result = r;
5839 >            final ObjectToInt<? super V> transformer;
5840 >            final IntByIntToInt reducer;
5841 >            if ((transformer = this.transformer) != null &&
5842 >                (reducer = this.reducer) != null) {
5843 >                int r = this.basis;
5844 >                for (int i = baseIndex, f, h; batch > 0 &&
5845 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5846 >                    addToPendingCount(1);
5847 >                    (rights = new MapReduceValuesToIntTask<K,V>
5848 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5849 >                      rights, transformer, r, reducer)).fork();
5850 >                }
5851 >                for (Node<K,V> p; (p = advance()) != null; )
5852 >                    r = reducer.apply(r, transformer.apply(p.val));
5853 >                result = r;
5854 >                CountedCompleter<?> c;
5855 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5856 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5857 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5858 >                        s = t.rights;
5859 >                    while (s != null) {
5860 >                        t.result = reducer.apply(t.result, s.result);
5861 >                        s = t.rights = s.nextRight;
5862 >                    }
5863                  }
6559                else if (p.casPending(c, 0))
6560                    break;
5864              }
5865          }
6563        public final Integer getRawResult() { return result; }
5866      }
5867  
5868 +    @SuppressWarnings("serial")
5869      static final class MapReduceEntriesToIntTask<K,V>
5870          extends BulkTask<K,V,Integer> {
5871          final ObjectToInt<Map.Entry<K,V>> transformer;
5872          final IntByIntToInt reducer;
5873          final int basis;
5874          int result;
5875 <        MapReduceEntriesToIntTask<K,V> sibling;
5875 >        MapReduceEntriesToIntTask<K,V> rights, nextRight;
5876          MapReduceEntriesToIntTask
5877 <            (ConcurrentHashMapV8<K,V> m,
5877 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5878 >             MapReduceEntriesToIntTask<K,V> nextRight,
5879               ObjectToInt<Map.Entry<K,V>> transformer,
5880               int basis,
5881               IntByIntToInt reducer) {
5882 <            super(m);
6579 <            this.transformer = transformer;
6580 <            this.basis = basis; this.reducer = reducer;
6581 <        }
6582 <        MapReduceEntriesToIntTask
6583 <            (BulkTask<K,V,?> p, int b, boolean split,
6584 <             ObjectToInt<Map.Entry<K,V>> transformer,
6585 <             int basis,
6586 <             IntByIntToInt reducer) {
6587 <            super(p, b, split);
5882 >            super(p, b, i, f, t); this.nextRight = nextRight;
5883              this.transformer = transformer;
5884              this.basis = basis; this.reducer = reducer;
5885          }
5886 +        public final Integer getRawResult() { return result; }
5887          public final void compute() {
5888 <            MapReduceEntriesToIntTask<K,V> t = this;
5889 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5890 <                this.transformer;
5891 <            final IntByIntToInt reducer = this.reducer;
5892 <            if (transformer == null || reducer == null)
5893 <                throw new Error(NullFunctionMessage);
5894 <            final int id = this.basis;
5895 <            int b = batch();
5896 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5897 <                b >>>= 1;
5898 <                t.pending = 1;
5899 <                MapReduceEntriesToIntTask<K,V> rt =
5900 <                    new MapReduceEntriesToIntTask<K,V>
5901 <                    (t, b, true, transformer, id, reducer);
5902 <                t = new MapReduceEntriesToIntTask<K,V>
5903 <                    (t, b, false, transformer, id, reducer);
5904 <                t.sibling = rt;
5905 <                rt.sibling = t;
5906 <                rt.fork();
5907 <            }
5908 <            int r = id;
5909 <            Object v;
5910 <            while ((v = t.advance()) != null)
5911 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6616 <            t.result = r;
6617 <            for (;;) {
6618 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToIntTask<K,V> s, p;
6619 <                if ((par = t.parent) == null ||
6620 <                    !(par instanceof MapReduceEntriesToIntTask)) {
6621 <                    t.quietlyComplete();
6622 <                    break;
6623 <                }
6624 <                else if ((c = (p = (MapReduceEntriesToIntTask<K,V>)par).pending) == 0) {
6625 <                    if ((s = t.sibling) != null)
6626 <                        r = reducer.apply(r, s.result);
6627 <                    (t = p).result = r;
5888 >            final ObjectToInt<Map.Entry<K,V>> transformer;
5889 >            final IntByIntToInt reducer;
5890 >            if ((transformer = this.transformer) != null &&
5891 >                (reducer = this.reducer) != null) {
5892 >                int r = this.basis;
5893 >                for (int i = baseIndex, f, h; batch > 0 &&
5894 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5895 >                    addToPendingCount(1);
5896 >                    (rights = new MapReduceEntriesToIntTask<K,V>
5897 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5898 >                      rights, transformer, r, reducer)).fork();
5899 >                }
5900 >                for (Node<K,V> p; (p = advance()) != null; )
5901 >                    r = reducer.apply(r, transformer.apply(p));
5902 >                result = r;
5903 >                CountedCompleter<?> c;
5904 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5905 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5906 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5907 >                        s = t.rights;
5908 >                    while (s != null) {
5909 >                        t.result = reducer.apply(t.result, s.result);
5910 >                        s = t.rights = s.nextRight;
5911 >                    }
5912                  }
6629                else if (p.casPending(c, 0))
6630                    break;
5913              }
5914          }
6633        public final Integer getRawResult() { return result; }
5915      }
5916  
5917 +    @SuppressWarnings("serial")
5918      static final class MapReduceMappingsToIntTask<K,V>
5919          extends BulkTask<K,V,Integer> {
5920          final ObjectByObjectToInt<? super K, ? super V> transformer;
5921          final IntByIntToInt reducer;
5922          final int basis;
5923          int result;
5924 <        MapReduceMappingsToIntTask<K,V> sibling;
5924 >        MapReduceMappingsToIntTask<K,V> rights, nextRight;
5925          MapReduceMappingsToIntTask
5926 <            (ConcurrentHashMapV8<K,V> m,
5926 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5927 >             MapReduceMappingsToIntTask<K,V> nextRight,
5928               ObjectByObjectToInt<? super K, ? super V> transformer,
5929               int basis,
5930               IntByIntToInt reducer) {
5931 <            super(m);
6649 <            this.transformer = transformer;
6650 <            this.basis = basis; this.reducer = reducer;
6651 <        }
6652 <        MapReduceMappingsToIntTask
6653 <            (BulkTask<K,V,?> p, int b, boolean split,
6654 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6655 <             int basis,
6656 <             IntByIntToInt reducer) {
6657 <            super(p, b, split);
5931 >            super(p, b, i, f, t); this.nextRight = nextRight;
5932              this.transformer = transformer;
5933              this.basis = basis; this.reducer = reducer;
5934          }
5935 +        public final Integer getRawResult() { return result; }
5936          public final void compute() {
5937 <            MapReduceMappingsToIntTask<K,V> t = this;
5938 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
5939 <                this.transformer;
5940 <            final IntByIntToInt reducer = this.reducer;
5941 <            if (transformer == null || reducer == null)
5942 <                throw new Error(NullFunctionMessage);
5943 <            final int id = this.basis;
5944 <            int b = batch();
5945 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5946 <                b >>>= 1;
5947 <                t.pending = 1;
5948 <                MapReduceMappingsToIntTask<K,V> rt =
5949 <                    new MapReduceMappingsToIntTask<K,V>
5950 <                    (t, b, true, transformer, id, reducer);
5951 <                t = new MapReduceMappingsToIntTask<K,V>
5952 <                    (t, b, false, transformer, id, reducer);
5953 <                t.sibling = rt;
5954 <                rt.sibling = t;
5955 <                rt.fork();
5956 <            }
5957 <            int r = id;
5958 <            Object v;
5959 <            while ((v = t.advance()) != null)
5960 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
5961 <            t.result = r;
5962 <            for (;;) {
5963 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToIntTask<K,V> s, p;
5964 <                if ((par = t.parent) == null ||
5965 <                    !(par instanceof MapReduceMappingsToIntTask)) {
5966 <                    t.quietlyComplete();
5937 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
5938 >            final IntByIntToInt reducer;
5939 >            if ((transformer = this.transformer) != null &&
5940 >                (reducer = this.reducer) != null) {
5941 >                int r = this.basis;
5942 >                for (int i = baseIndex, f, h; batch > 0 &&
5943 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5944 >                    addToPendingCount(1);
5945 >                    (rights = new MapReduceMappingsToIntTask<K,V>
5946 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5947 >                      rights, transformer, r, reducer)).fork();
5948 >                }
5949 >                for (Node<K,V> p; (p = advance()) != null; )
5950 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5951 >                result = r;
5952 >                CountedCompleter<?> c;
5953 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5954 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
5955 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
5956 >                        s = t.rights;
5957 >                    while (s != null) {
5958 >                        t.result = reducer.apply(t.result, s.result);
5959 >                        s = t.rights = s.nextRight;
5960 >                    }
5961 >                }
5962 >            }
5963 >        }
5964 >    }
5965 >
5966 >    /* ---------------- Counters -------------- */
5967 >
5968 >    // Adapted from LongAdder and Striped64.
5969 >    // See their internal docs for explanation.
5970 >
5971 >    // A padded cell for distributing counts
5972 >    static final class CounterCell {
5973 >        volatile long p0, p1, p2, p3, p4, p5, p6;
5974 >        volatile long value;
5975 >        volatile long q0, q1, q2, q3, q4, q5, q6;
5976 >        CounterCell(long x) { value = x; }
5977 >    }
5978 >
5979 >    /**
5980 >     * Holder for the thread-local hash code determining which
5981 >     * CounterCell to use. The code is initialized via the
5982 >     * counterHashCodeGenerator, but may be moved upon collisions.
5983 >     */
5984 >    static final class CounterHashCode {
5985 >        int code;
5986 >    }
5987 >
5988 >    /**
5989 >     * Generates initial value for per-thread CounterHashCodes.
5990 >     */
5991 >    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
5992 >
5993 >    /**
5994 >     * Increment for counterHashCodeGenerator. See class ThreadLocal
5995 >     * for explanation.
5996 >     */
5997 >    static final int SEED_INCREMENT = 0x61c88647;
5998 >
5999 >    /**
6000 >     * Per-thread counter hash codes. Shared across all instances.
6001 >     */
6002 >    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6003 >        new ThreadLocal<CounterHashCode>();
6004 >
6005 >
6006 >    final long sumCount() {
6007 >        CounterCell[] as = counterCells; CounterCell a;
6008 >        long sum = baseCount;
6009 >        if (as != null) {
6010 >            for (int i = 0; i < as.length; ++i) {
6011 >                if ((a = as[i]) != null)
6012 >                    sum += a.value;
6013 >            }
6014 >        }
6015 >        return sum;
6016 >    }
6017 >
6018 >    // See LongAdder version for explanation
6019 >    private final void fullAddCount(long x, CounterHashCode hc,
6020 >                                    boolean wasUncontended) {
6021 >        int h;
6022 >        if (hc == null) {
6023 >            hc = new CounterHashCode();
6024 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6025 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6026 >            threadCounterHashCode.set(hc);
6027 >        }
6028 >        else
6029 >            h = hc.code;
6030 >        boolean collide = false;                // True if last slot nonempty
6031 >        for (;;) {
6032 >            CounterCell[] as; CounterCell a; int n; long v;
6033 >            if ((as = counterCells) != null && (n = as.length) > 0) {
6034 >                if ((a = as[(n - 1) & h]) == null) {
6035 >                    if (cellsBusy == 0) {            // Try to attach new Cell
6036 >                        CounterCell r = new CounterCell(x); // Optimistic create
6037 >                        if (cellsBusy == 0 &&
6038 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6039 >                            boolean created = false;
6040 >                            try {               // Recheck under lock
6041 >                                CounterCell[] rs; int m, j;
6042 >                                if ((rs = counterCells) != null &&
6043 >                                    (m = rs.length) > 0 &&
6044 >                                    rs[j = (m - 1) & h] == null) {
6045 >                                    rs[j] = r;
6046 >                                    created = true;
6047 >                                }
6048 >                            } finally {
6049 >                                cellsBusy = 0;
6050 >                            }
6051 >                            if (created)
6052 >                                break;
6053 >                            continue;           // Slot is now non-empty
6054 >                        }
6055 >                    }
6056 >                    collide = false;
6057 >                }
6058 >                else if (!wasUncontended)       // CAS already known to fail
6059 >                    wasUncontended = true;      // Continue after rehash
6060 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6061                      break;
6062 +                else if (counterCells != as || n >= NCPU)
6063 +                    collide = false;            // At max size or stale
6064 +                else if (!collide)
6065 +                    collide = true;
6066 +                else if (cellsBusy == 0 &&
6067 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6068 +                    try {
6069 +                        if (counterCells == as) {// Expand table unless stale
6070 +                            CounterCell[] rs = new CounterCell[n << 1];
6071 +                            for (int i = 0; i < n; ++i)
6072 +                                rs[i] = as[i];
6073 +                            counterCells = rs;
6074 +                        }
6075 +                    } finally {
6076 +                        cellsBusy = 0;
6077 +                    }
6078 +                    collide = false;
6079 +                    continue;                   // Retry with expanded table
6080                  }
6081 <                else if ((c = (p = (MapReduceMappingsToIntTask<K,V>)par).pending) == 0) {
6082 <                    if ((s = t.sibling) != null)
6083 <                        r = reducer.apply(r, s.result);
6084 <                    (t = p).result = r;
6081 >                h ^= h << 13;                   // Rehash
6082 >                h ^= h >>> 17;
6083 >                h ^= h << 5;
6084 >            }
6085 >            else if (cellsBusy == 0 && counterCells == as &&
6086 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6087 >                boolean init = false;
6088 >                try {                           // Initialize table
6089 >                    if (counterCells == as) {
6090 >                        CounterCell[] rs = new CounterCell[2];
6091 >                        rs[h & 1] = new CounterCell(x);
6092 >                        counterCells = rs;
6093 >                        init = true;
6094 >                    }
6095 >                } finally {
6096 >                    cellsBusy = 0;
6097                  }
6098 <                else if (p.casPending(c, 0))
6098 >                if (init)
6099                      break;
6100              }
6101 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6102 +                break;                          // Fall back on using base
6103          }
6104 <        public final Integer getRawResult() { return result; }
6104 >        hc.code = h;                            // Record index for next time
6105      }
6106  
6706
6107      // Unsafe mechanics
6108 <    private static final sun.misc.Unsafe UNSAFE;
6109 <    private static final long counterOffset;
6110 <    private static final long sizeCtlOffset;
6108 >    private static final sun.misc.Unsafe U;
6109 >    private static final long SIZECTL;
6110 >    private static final long TRANSFERINDEX;
6111 >    private static final long TRANSFERORIGIN;
6112 >    private static final long BASECOUNT;
6113 >    private static final long CELLSBUSY;
6114 >    private static final long CELLVALUE;
6115      private static final long ABASE;
6116      private static final int ASHIFT;
6117  
6118      static {
6715        int ss;
6119          try {
6120 <            UNSAFE = getUnsafe();
6120 >            U = getUnsafe();
6121              Class<?> k = ConcurrentHashMapV8.class;
6122 <            counterOffset = UNSAFE.objectFieldOffset
6720 <                (k.getDeclaredField("counter"));
6721 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6122 >            SIZECTL = U.objectFieldOffset
6123                  (k.getDeclaredField("sizeCtl"));
6124 <            Class<?> sc = Node[].class;
6125 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6126 <            ss = UNSAFE.arrayIndexScale(sc);
6124 >            TRANSFERINDEX = U.objectFieldOffset
6125 >                (k.getDeclaredField("transferIndex"));
6126 >            TRANSFERORIGIN = U.objectFieldOffset
6127 >                (k.getDeclaredField("transferOrigin"));
6128 >            BASECOUNT = U.objectFieldOffset
6129 >                (k.getDeclaredField("baseCount"));
6130 >            CELLSBUSY = U.objectFieldOffset
6131 >                (k.getDeclaredField("cellsBusy"));
6132 >            Class<?> ck = CounterCell.class;
6133 >            CELLVALUE = U.objectFieldOffset
6134 >                (ck.getDeclaredField("value"));
6135 >            Class<?> ak = Node[].class;
6136 >            ABASE = U.arrayBaseOffset(ak);
6137 >            int scale = U.arrayIndexScale(ak);
6138 >            if ((scale & (scale - 1)) != 0)
6139 >                throw new Error("data type scale not a power of two");
6140 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6141          } catch (Exception e) {
6142              throw new Error(e);
6143          }
6729        if ((ss & (ss-1)) != 0)
6730            throw new Error("data type scale not a power of two");
6731        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6144      }
6145  
6146      /**
# Line 6741 | Line 6153 | public class ConcurrentHashMapV8<K, V>
6153      private static sun.misc.Unsafe getUnsafe() {
6154          try {
6155              return sun.misc.Unsafe.getUnsafe();
6156 <        } catch (SecurityException se) {
6157 <            try {
6158 <                return java.security.AccessController.doPrivileged
6159 <                    (new java.security
6160 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6161 <                        public sun.misc.Unsafe run() throws Exception {
6162 <                            java.lang.reflect.Field f = sun.misc
6163 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6164 <                            f.setAccessible(true);
6165 <                            return (sun.misc.Unsafe) f.get(null);
6166 <                        }});
6167 <            } catch (java.security.PrivilegedActionException e) {
6168 <                throw new RuntimeException("Could not initialize intrinsics",
6169 <                                           e.getCause());
6170 <            }
6156 >        } catch (SecurityException tryReflectionInstead) {}
6157 >        try {
6158 >            return java.security.AccessController.doPrivileged
6159 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6160 >                public sun.misc.Unsafe run() throws Exception {
6161 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6162 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6163 >                        f.setAccessible(true);
6164 >                        Object x = f.get(null);
6165 >                        if (k.isInstance(x))
6166 >                            return k.cast(x);
6167 >                    }
6168 >                    throw new NoSuchFieldError("the Unsafe");
6169 >                }});
6170 >        } catch (java.security.PrivilegedActionException e) {
6171 >            throw new RuntimeException("Could not initialize intrinsics",
6172 >                                       e.getCause());
6173          }
6174      }
6175   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines