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.123 by jsr166, Fri Feb 27 21:08:53 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines