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.59 by dl, Tue Aug 14 13:16:50 2012 UTC vs.
Revision 1.116 by dl, Wed Sep 11 14:53:38 2013 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166e;
8 < import jsr166e.LongAdder;
8 >
9   import jsr166e.ForkJoinPool;
10 import jsr166e.ForkJoinTask;
10  
11 < import java.util.Comparator;
11 > import java.io.ObjectStreamField;
12 > import java.io.Serializable;
13 > import java.lang.reflect.ParameterizedType;
14 > import java.lang.reflect.Type;
15 > import java.util.AbstractMap;
16   import java.util.Arrays;
14 import java.util.Map;
15 import java.util.Set;
17   import java.util.Collection;
18 < import java.util.AbstractMap;
19 < import java.util.AbstractSet;
20 < import java.util.AbstractCollection;
20 < import java.util.Hashtable;
18 > import java.util.Comparator;
19 > import java.util.ConcurrentModificationException;
20 > import java.util.Enumeration;
21   import java.util.HashMap;
22 + import java.util.Hashtable;
23   import java.util.Iterator;
24 < import java.util.Enumeration;
24 < import java.util.ConcurrentModificationException;
24 > import java.util.Map;
25   import java.util.NoSuchElementException;
26 + import java.util.Set;
27   import java.util.concurrent.ConcurrentMap;
27 import java.util.concurrent.ThreadLocalRandom;
28 import java.util.concurrent.locks.LockSupport;
29 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
28   import java.util.concurrent.atomic.AtomicReference;
29 <
30 < import java.io.Serializable;
29 > import java.util.concurrent.atomic.AtomicInteger;
30 > import java.util.concurrent.locks.LockSupport;
31 > import java.util.concurrent.locks.ReentrantLock;
32  
33   /**
34   * A hash table supporting full concurrency of retrievals and
# Line 43 | Line 42 | import java.io.Serializable;
42   * interoperable with {@code Hashtable} in programs that rely on its
43   * thread safety but not on its synchronization details.
44   *
45 < * <p> Retrieval operations (including {@code get}) generally do not
45 > * <p>Retrieval operations (including {@code get}) generally do not
46   * block, so may overlap with update operations (including {@code put}
47   * and {@code remove}). Retrievals reflect the results of the most
48   * recently <em>completed</em> update operations holding upon their
# Line 64 | Line 63 | import java.io.Serializable;
63   * that may be adequate for monitoring or estimation purposes, but not
64   * for program control.
65   *
66 < * <p> The table is dynamically expanded when there are too many
66 > * <p>The table is dynamically expanded when there are too many
67   * collisions (i.e., keys that have distinct hash codes but fall into
68   * the same slot modulo the table size), with the expected average
69   * effect of maintaining roughly two bins per mapping (corresponding
# Line 83 | Line 82 | import java.io.Serializable;
82   * expected {@code concurrencyLevel} as an additional hint for
83   * internal sizing.  Note that using many keys with exactly the same
84   * {@code hashCode()} is a sure way to slow down performance of any
85 < * hash table.
85 > * hash table. To ameliorate impact, when keys are {@link Comparable},
86 > * this class may use comparison order among keys to help break ties.
87 > *
88 > * <p>A {@link Set} projection of a ConcurrentHashMapV8 may be created
89 > * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
90 > * (using {@link #keySet(Object)} when only keys are of interest, and the
91 > * mapped values are (perhaps transiently) not used or all take the
92 > * same mapping value.
93   *
94   * <p>This class and its views and iterators implement all of the
95   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
96   * interfaces.
97   *
98 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
98 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
99   * does <em>not</em> allow {@code null} to be used as a key or value.
100   *
101 + * <p>ConcurrentHashMapV8s support a set of sequential and parallel bulk
102 + * operations that are designed
103 + * to be safely, and often sensibly, applied even with maps that are
104 + * being concurrently updated by other threads; for example, when
105 + * computing a snapshot summary of the values in a shared registry.
106 + * There are three kinds of operation, each with four forms, accepting
107 + * functions with Keys, Values, Entries, and (Key, Value) arguments
108 + * and/or return values. Because the elements of a ConcurrentHashMapV8
109 + * are not ordered in any particular way, and may be processed in
110 + * different orders in different parallel executions, the correctness
111 + * of supplied functions should not depend on any ordering, or on any
112 + * other objects or values that may transiently change while
113 + * computation is in progress; and except for forEach actions, should
114 + * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
115 + * objects do not support method {@code setValue}.
116 + *
117 + * <ul>
118 + * <li> forEach: Perform a given action on each element.
119 + * A variant form applies a given transformation on each element
120 + * before performing the action.</li>
121 + *
122 + * <li> search: Return the first available non-null result of
123 + * applying a given function on each element; skipping further
124 + * search when a result is found.</li>
125 + *
126 + * <li> reduce: Accumulate each element.  The supplied reduction
127 + * function cannot rely on ordering (more formally, it should be
128 + * both associative and commutative).  There are five variants:
129 + *
130 + * <ul>
131 + *
132 + * <li> Plain reductions. (There is not a form of this method for
133 + * (key, value) function arguments since there is no corresponding
134 + * return type.)</li>
135 + *
136 + * <li> Mapped reductions that accumulate the results of a given
137 + * function applied to each element.</li>
138 + *
139 + * <li> Reductions to scalar doubles, longs, and ints, using a
140 + * given basis value.</li>
141 + *
142 + * </ul>
143 + * </li>
144 + * </ul>
145 + *
146 + * <p>These bulk operations accept a {@code parallelismThreshold}
147 + * argument. Methods proceed sequentially if the current map size is
148 + * estimated to be less than the given threshold. Using a value of
149 + * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
150 + * of {@code 1} results in maximal parallelism by partitioning into
151 + * enough subtasks to fully utilize the {@link
152 + * ForkJoinPool#commonPool()} that is used for all parallel
153 + * computations. Normally, you would initially choose one of these
154 + * extreme values, and then measure performance of using in-between
155 + * values that trade off overhead versus throughput.
156 + *
157 + * <p>The concurrency properties of bulk operations follow
158 + * from those of ConcurrentHashMapV8: Any non-null result returned
159 + * from {@code get(key)} and related access methods bears a
160 + * happens-before relation with the associated insertion or
161 + * update.  The result of any bulk operation reflects the
162 + * composition of these per-element relations (but is not
163 + * necessarily atomic with respect to the map as a whole unless it
164 + * is somehow known to be quiescent).  Conversely, because keys
165 + * and values in the map are never null, null serves as a reliable
166 + * atomic indicator of the current lack of any result.  To
167 + * maintain this property, null serves as an implicit basis for
168 + * all non-scalar reduction operations. For the double, long, and
169 + * int versions, the basis should be one that, when combined with
170 + * any other value, returns that other value (more formally, it
171 + * should be the identity element for the reduction). Most common
172 + * reductions have these properties; for example, computing a sum
173 + * with basis 0 or a minimum with basis MAX_VALUE.
174 + *
175 + * <p>Search and transformation functions provided as arguments
176 + * should similarly return null to indicate the lack of any result
177 + * (in which case it is not used). In the case of mapped
178 + * reductions, this also enables transformations to serve as
179 + * filters, returning null (or, in the case of primitive
180 + * specializations, the identity basis) if the element should not
181 + * be combined. You can create compound transformations and
182 + * filterings by composing them yourself under this "null means
183 + * there is nothing there now" rule before using them in search or
184 + * reduce operations.
185 + *
186 + * <p>Methods accepting and/or returning Entry arguments maintain
187 + * key-value associations. They may be useful for example when
188 + * finding the key for the greatest value. Note that "plain" Entry
189 + * arguments can be supplied using {@code new
190 + * AbstractMap.SimpleEntry(k,v)}.
191 + *
192 + * <p>Bulk operations may complete abruptly, throwing an
193 + * exception encountered in the application of a supplied
194 + * function. Bear in mind when handling such exceptions that other
195 + * concurrently executing functions could also have thrown
196 + * exceptions, or would have done so if the first exception had
197 + * not occurred.
198 + *
199 + * <p>Speedups for parallel compared to sequential forms are common
200 + * but not guaranteed.  Parallel operations involving brief functions
201 + * on small maps may execute more slowly than sequential forms if the
202 + * underlying work to parallelize the computation is more expensive
203 + * than the computation itself.  Similarly, parallelization may not
204 + * lead to much actual parallelism if all processors are busy
205 + * performing unrelated tasks.
206 + *
207 + * <p>All arguments to all task methods must be non-null.
208 + *
209 + * <p><em>jsr166e note: During transition, this class
210 + * uses nested functional interfaces with different names but the
211 + * same forms as those expected for JDK8.</em>
212 + *
213   * <p>This class is a member of the
214   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
215   * Java Collections Framework</a>.
216   *
99 * <p><em>jsr166e note: This class is a candidate replacement for
100 * java.util.concurrent.ConcurrentHashMap.  During transition, this
101 * class declares and uses nested functional interfaces with different
102 * names but the same forms as those expected for JDK8.<em>
103 *
217   * @since 1.5
218   * @author Doug Lea
219   * @param <K> the type of keys maintained by this map
220   * @param <V> the type of mapped values
221   */
222 < public class ConcurrentHashMapV8<K, V>
223 <    implements ConcurrentMap<K, V>, Serializable {
222 > public class ConcurrentHashMapV8<K,V> extends AbstractMap<K,V>
223 >    implements ConcurrentMap<K,V>, Serializable {
224      private static final long serialVersionUID = 7249069246763182397L;
225  
226      /**
227 <     * A partitionable iterator. A Spliterator can be traversed
228 <     * directly, but can also be partitioned (before traversal) by
229 <     * creating another Spliterator that covers a non-overlapping
117 <     * portion of the elements, and so may be amenable to parallel
118 <     * execution.
119 <     *
120 <     * <p> This interface exports a subset of expected JDK8
121 <     * functionality.
122 <     *
123 <     * <p>Sample usage: Here is one (of the several) ways to compute
124 <     * the sum of the values held in a map using the ForkJoin
125 <     * framework. As illustrated here, Spliterators are well suited to
126 <     * designs in which a task repeatedly splits off half its work
127 <     * into forked subtasks until small enough to process directly,
128 <     * and then joins these subtasks. Variants of this style can also
129 <     * be used in completion-based designs.
130 <     *
131 <     * <pre>
132 <     * {@code ConcurrentHashMapV8<String, Long> m = ...
133 <     * // split as if have 8 * parallelism, for load balance
134 <     * int n = m.size();
135 <     * int p = aForkJoinPool.getParallelism() * 8;
136 <     * int split = (n < p)? n : p;
137 <     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
138 <     * // ...
139 <     * static class SumValues extends RecursiveTask<Long> {
140 <     *   final Spliterator<Long> s;
141 <     *   final int split;             // split while > 1
142 <     *   final SumValues nextJoin;    // records forked subtasks to join
143 <     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
144 <     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
145 <     *   }
146 <     *   public Long compute() {
147 <     *     long sum = 0;
148 <     *     SumValues subtasks = null; // fork subtasks
149 <     *     for (int s = split >>> 1; s > 0; s >>>= 1)
150 <     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
151 <     *     while (s.hasNext())        // directly process remaining elements
152 <     *       sum += s.next();
153 <     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
154 <     *       sum += t.join();         // collect subtask results
155 <     *     return sum;
156 <     *   }
157 <     * }
158 <     * }</pre>
227 >     * An object for traversing and partitioning elements of a source.
228 >     * This interface provides a subset of the functionality of JDK8
229 >     * java.util.Spliterator.
230       */
231 <    public static interface Spliterator<T> extends Iterator<T> {
231 >    public static interface ConcurrentHashMapSpliterator<T> {
232          /**
233 <         * Returns a Spliterator covering approximately half of the
234 <         * elements, guaranteed not to overlap with those subsequently
235 <         * returned by this Spliterator.  After invoking this method,
236 <         * the current Spliterator will <em>not</em> produce any of
237 <         * the elements of the returned Spliterator, but the two
238 <         * Spliterators together will produce all of the elements that
239 <         * would have been produced by this Spliterator had this
240 <         * method not been called. The exact number of elements
241 <         * produced by the returned Spliterator is not guaranteed, and
171 <         * may be zero (i.e., with {@code hasNext()} reporting {@code
172 <         * false}) if this Spliterator cannot be further split.
173 <         *
174 <         * @return a Spliterator covering approximately half of the
175 <         * elements
176 <         * @throws IllegalStateException if this Spliterator has
177 <         * already commenced traversing elements
233 >         * If possible, returns a new spliterator covering
234 >         * approximately one half of the elements, which will not be
235 >         * covered by this spliterator. Returns null if cannot be
236 >         * split.
237 >         */
238 >        ConcurrentHashMapSpliterator<T> trySplit();
239 >        /**
240 >         * Returns an estimate of the number of elements covered by
241 >         * this Spliterator.
242           */
243 <        Spliterator<T> split();
243 >        long estimateSize();
244 >
245 >        /** Applies the action to each untraversed element */
246 >        void forEachRemaining(Action<? super T> action);
247 >        /** If an element remains, applies the action and returns true. */
248 >        boolean tryAdvance(Action<? super T> action);
249      }
250  
251 +    // Sams
252 +    /** Interface describing a void action of one argument */
253 +    public interface Action<A> { void apply(A a); }
254 +    /** Interface describing a void action of two arguments */
255 +    public interface BiAction<A,B> { void apply(A a, B b); }
256 +    /** Interface describing a function of one argument */
257 +    public interface Fun<A,T> { T apply(A a); }
258 +    /** Interface describing a function of two arguments */
259 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
260 +    /** Interface describing a function mapping its argument to a double */
261 +    public interface ObjectToDouble<A> { double apply(A a); }
262 +    /** Interface describing a function mapping its argument to a long */
263 +    public interface ObjectToLong<A> { long apply(A a); }
264 +    /** Interface describing a function mapping its argument to an int */
265 +    public interface ObjectToInt<A> {int apply(A a); }
266 +    /** Interface describing a function mapping two arguments to a double */
267 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
268 +    /** Interface describing a function mapping two arguments to a long */
269 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
270 +    /** Interface describing a function mapping two arguments to an int */
271 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
272 +    /** Interface describing a function mapping two doubles to a double */
273 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
274 +    /** Interface describing a function mapping two longs to a long */
275 +    public interface LongByLongToLong { long apply(long a, long b); }
276 +    /** Interface describing a function mapping two ints to an int */
277 +    public interface IntByIntToInt { int apply(int a, int b); }
278 +
279 +
280      /*
281       * Overview:
282       *
# Line 189 | Line 287 | public class ConcurrentHashMapV8<K, V>
287       * the same or better than java.util.HashMap, and to support high
288       * initial insertion rates on an empty table by many threads.
289       *
290 <     * Each key-value mapping is held in a Node.  Because Node fields
291 <     * can contain special values, they are defined using plain Object
292 <     * types. Similarly in turn, all internal methods that use them
293 <     * work off Object types. And similarly, so do the internal
294 <     * methods of auxiliary iterator and view classes.  All public
295 <     * generic typed methods relay in/out of these internal methods,
296 <     * supplying null-checks and casts as needed. This also allows
297 <     * many of the public methods to be factored into a smaller number
298 <     * of internal methods (although sadly not so for the five
299 <     * variants of put-related operations). The validation-based
300 <     * approach explained below leads to a lot of code sprawl because
301 <     * retry-control precludes factoring into smaller methods.
290 >     * This map usually acts as a binned (bucketed) hash table.  Each
291 >     * key-value mapping is held in a Node.  Most nodes are instances
292 >     * of the basic Node class with hash, key, value, and next
293 >     * fields. However, various subclasses exist: TreeNodes are
294 >     * arranged in balanced trees, not lists.  TreeBins hold the roots
295 >     * of sets of TreeNodes. ForwardingNodes are placed at the heads
296 >     * of bins during resizing. ReservationNodes are used as
297 >     * placeholders while establishing values in computeIfAbsent and
298 >     * related methods.  The types TreeBin, ForwardingNode, and
299 >     * ReservationNode do not hold normal user keys, values, or
300 >     * hashes, and are readily distinguishable during search etc
301 >     * because they have negative hash fields and null key and value
302 >     * fields. (These special nodes are either uncommon or transient,
303 >     * so the impact of carrying around some unused fields is
304 >     * insignificant.)
305       *
306       * The table is lazily initialized to a power-of-two size upon the
307       * first insertion.  Each bin in the table normally contains a
# Line 208 | Line 309 | public class ConcurrentHashMapV8<K, V>
309       * Table accesses require volatile/atomic reads, writes, and
310       * CASes.  Because there is no other way to arrange this without
311       * adding further indirections, we use intrinsics
312 <     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
313 <     * are always accurately traversable under volatile reads, so long
314 <     * as lookups check hash code and non-nullness of value before
315 <     * checking key equality.
316 <     *
317 <     * We use the top two bits of Node hash fields for control
217 <     * purposes -- they are available anyway because of addressing
218 <     * constraints.  As explained further below, these top bits are
219 <     * used as follows:
220 <     *  00 - Normal
221 <     *  01 - Locked
222 <     *  11 - Locked and may have a thread waiting for lock
223 <     *  10 - Node is a forwarding node
224 <     *
225 <     * The lower 30 bits of each Node's hash field contain a
226 <     * transformation of the key's hash code, except for forwarding
227 <     * nodes, for which the lower bits are zero (and so always have
228 <     * hash field == MOVED).
312 >     * (sun.misc.Unsafe) operations.
313 >     *
314 >     * We use the top (sign) bit of Node hash fields for control
315 >     * purposes -- it is available anyway because of addressing
316 >     * constraints.  Nodes with negative hash fields are specially
317 >     * handled or ignored in map methods.
318       *
319       * Insertion (via put or its variants) of the first node in an
320       * empty bin is performed by just CASing it to the bin.  This is
# Line 234 | Line 323 | public class ConcurrentHashMapV8<K, V>
323       * delete, and replace) require locks.  We do not want to waste
324       * the space required to associate a distinct lock object with
325       * each bin, so instead use the first node of a bin list itself as
326 <     * a lock. Blocking support for these locks relies on the builtin
327 <     * "synchronized" monitors.  However, we also need a tryLock
239 <     * construction, so we overlay these by using bits of the Node
240 <     * hash field for lock control (see above), and so normally use
241 <     * builtin monitors only for blocking and signalling using
242 <     * wait/notifyAll constructions. See Node.tryAwaitLock.
326 >     * a lock. Locking support for these locks relies on builtin
327 >     * "synchronized" monitors.
328       *
329       * Using the first node of a list as a lock does not by itself
330       * suffice though: When a node is locked, any update must first
331       * validate that it is still the first node after locking it, and
332       * retry if not. Because new nodes are always appended to lists,
333       * once a node is first in a bin, it remains first until deleted
334 <     * or the bin becomes invalidated (upon resizing).  However,
250 <     * operations that only conditionally update may inspect nodes
251 <     * until the point of update. This is a converse of sorts to the
252 <     * lazy locking technique described by Herlihy & Shavit.
334 >     * or the bin becomes invalidated (upon resizing).
335       *
336       * The main disadvantage of per-bin locks is that other update
337       * operations on other nodes in a bin list protected by the same
# Line 282 | Line 364 | public class ConcurrentHashMapV8<K, V>
364       * sometimes deviate significantly from uniform randomness.  This
365       * includes the case when N > (1<<30), so some keys MUST collide.
366       * Similarly for dumb or hostile usages in which multiple keys are
367 <     * designed to have identical hash codes. Also, although we guard
368 <     * against the worst effects of this (see method spread), sets of
369 <     * hashes may differ only in bits that do not impact their bin
370 <     * index for a given power-of-two mask.  So we use a secondary
371 <     * strategy that applies when the number of nodes in a bin exceeds
372 <     * a threshold, and at least one of the keys implements
291 <     * Comparable.  These TreeBins use a balanced tree to hold nodes
292 <     * (a specialized form of red-black trees), bounding search time
293 <     * to O(log N).  Each search step in a TreeBin is around twice as
367 >     * designed to have identical hash codes or ones that differs only
368 >     * in masked-out high bits. So we use a secondary strategy that
369 >     * applies when the number of nodes in a bin exceeds a
370 >     * threshold. These TreeBins use a balanced tree to hold nodes (a
371 >     * specialized form of red-black trees), bounding search time to
372 >     * O(log N).  Each search step in a TreeBin is at least twice as
373       * slow as in a regular list, but given that N cannot exceed
374       * (1<<64) (before running out of addresses) this bounds search
375       * steps, lock hold times, etc, to reasonable constants (roughly
# Line 301 | Line 380 | public class ConcurrentHashMapV8<K, V>
380       * iterators in the same way.
381       *
382       * The table is resized when occupancy exceeds a percentage
383 <     * threshold (nominally, 0.75, but see below).  Only a single
384 <     * thread performs the resize (using field "sizeCtl", to arrange
385 <     * exclusion), but the table otherwise remains usable for reads
386 <     * and updates. Resizing proceeds by transferring bins, one by
387 <     * one, from the table to the next table.  Because we are using
383 >     * threshold (nominally, 0.75, but see below).  Any thread
384 >     * noticing an overfull bin may assist in resizing after the
385 >     * initiating thread allocates and sets up the replacement array.
386 >     * However, rather than stalling, these other threads may proceed
387 >     * with insertions etc.  The use of TreeBins shields us from the
388 >     * worst case effects of overfilling while resizes are in
389 >     * progress.  Resizing proceeds by transferring bins, one by one,
390 >     * from the table to the next table. However, threads claim small
391 >     * blocks of indices to transfer (via field transferIndex) before
392 >     * doing so, reducing contention.  Because we are using
393       * power-of-two expansion, the elements from each bin must either
394       * stay at same index, or move with a power of two offset. We
395       * eliminate unnecessary node creation by catching cases where old
# Line 319 | Line 403 | public class ConcurrentHashMapV8<K, V>
403       * its key. On encountering a forwarding node, access and update
404       * operations restart, using the new table.
405       *
406 <     * Each bin transfer requires its bin lock. However, unlike other
407 <     * cases, a transfer can skip a bin if it fails to acquire its
408 <     * lock, and revisit it later (unless it is a TreeBin). Method
409 <     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
410 <     * have been skipped because of failure to acquire a lock, and
411 <     * blocks only if none are available (i.e., only very rarely).
412 <     * The transfer operation must also ensure that all accessible
413 <     * bins in both the old and new table are usable by any traversal.
414 <     * When there are no lock acquisition failures, this is arranged
415 <     * simply by proceeding from the last bin (table.length - 1) up
416 <     * towards the first.  Upon seeing a forwarding node, traversals
417 <     * (see class Iter) arrange to move to the new table
418 <     * without revisiting nodes.  However, when any node is skipped
419 <     * during a transfer, all earlier table bins may have become
420 <     * visible, so are initialized with a reverse-forwarding node back
421 <     * to the old table until the new ones are established. (This
422 <     * sometimes requires transiently locking a forwarding node, which
423 <     * is possible under the above encoding.) These more expensive
424 <     * mechanics trigger only when necessary.
406 >     * Each bin transfer requires its bin lock, which can stall
407 >     * waiting for locks while resizing. However, because other
408 >     * threads can join in and help resize rather than contend for
409 >     * locks, average aggregate waits become shorter as resizing
410 >     * progresses.  The transfer operation must also ensure that all
411 >     * accessible bins in both the old and new table are usable by any
412 >     * traversal.  This is arranged in part by proceeding from the
413 >     * last bin (table.length - 1) up towards the first.  Upon seeing
414 >     * a forwarding node, traversals (see class Traverser) arrange to
415 >     * move to the new table without revisiting nodes.  To ensure that
416 >     * no intervening nodes are skipped even when moved out of order,
417 >     * a stack (see class TableStack) is created on first encounter of
418 >     * a forwarding node during a traversal, to maintain its place if
419 >     * later processing the current table. The need for these
420 >     * save/restore mechanics is relatively rare, but when one
421 >     * forwarding node is encountered, typically many more will be.
422 >     * So Traversers use a simple caching scheme to avoid creating so
423 >     * many new TableStack nodes. (Thanks to Peter Levart for
424 >     * suggesting use of a stack here.)
425       *
426       * The traversal scheme also applies to partial traversals of
427       * ranges of bins (via an alternate Traverser constructor)
# Line 352 | Line 436 | public class ConcurrentHashMapV8<K, V>
436       * These cases attempt to override the initial capacity settings,
437       * but harmlessly fail to take effect in cases of races.
438       *
439 <     * The element count is maintained using a LongAdder, which avoids
440 <     * contention on updates but can encounter cache thrashing if read
441 <     * too frequently during concurrent access. To avoid reading so
442 <     * often, resizing is attempted either when a bin lock is
443 <     * contended, or upon adding to a bin already holding two or more
444 <     * nodes (checked before adding in the xIfAbsent methods, after
445 <     * adding in others). Under uniform hash distributions, the
446 <     * probability of this occurring at threshold is around 13%,
447 <     * meaning that only about 1 in 8 puts check threshold (and after
448 <     * resizing, many fewer do so). But this approximation has high
449 <     * variance for small table sizes, so we check on any collision
450 <     * for sizes <= 64. The bulk putAll operation further reduces
451 <     * contention by only committing count updates upon these size
452 <     * checks.
439 >     * The element count is maintained using a specialization of
440 >     * LongAdder. We need to incorporate a specialization rather than
441 >     * just use a LongAdder in order to access implicit
442 >     * contention-sensing that leads to creation of multiple
443 >     * CounterCells.  The counter mechanics avoid contention on
444 >     * updates but can encounter cache thrashing if read too
445 >     * frequently during concurrent access. To avoid reading so often,
446 >     * resizing under contention is attempted only upon adding to a
447 >     * bin already holding two or more nodes. Under uniform hash
448 >     * distributions, the probability of this occurring at threshold
449 >     * is around 13%, meaning that only about 1 in 8 puts check
450 >     * threshold (and after resizing, many fewer do so).
451 >     *
452 >     * TreeBins use a special form of comparison for search and
453 >     * related operations (which is the main reason we cannot use
454 >     * existing collections such as TreeMaps). TreeBins contain
455 >     * Comparable elements, but may contain others, as well as
456 >     * elements that are Comparable but not necessarily Comparable for
457 >     * the same T, so we cannot invoke compareTo among them. To handle
458 >     * this, the tree is ordered primarily by hash value, then by
459 >     * Comparable.compareTo order if applicable.  On lookup at a node,
460 >     * if elements are not comparable or compare as 0 then both left
461 >     * and right children may need to be searched in the case of tied
462 >     * hash values. (This corresponds to the full list search that
463 >     * would be necessary if all elements were non-Comparable and had
464 >     * tied hashes.) On insertion, to keep a total ordering (or as
465 >     * close as is required here) across rebalancings, we compare
466 >     * classes and identityHashCodes as tie-breakers. The red-black
467 >     * balancing code is updated from pre-jdk-collections
468 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
469 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
470 >     * Algorithms" (CLR).
471 >     *
472 >     * TreeBins also require an additional locking mechanism.  While
473 >     * list traversal is always possible by readers even during
474 >     * updates, tree traversal is not, mainly because of tree-rotations
475 >     * that may change the root node and/or its linkages.  TreeBins
476 >     * include a simple read-write lock mechanism parasitic on the
477 >     * main bin-synchronization strategy: Structural adjustments
478 >     * associated with an insertion or removal are already bin-locked
479 >     * (and so cannot conflict with other writers) but must wait for
480 >     * ongoing readers to finish. Since there can be only one such
481 >     * waiter, we use a simple scheme using a single "waiter" field to
482 >     * block writers.  However, readers need never block.  If the root
483 >     * lock is held, they proceed along the slow traversal path (via
484 >     * next-pointers) until the lock becomes available or the list is
485 >     * exhausted, whichever comes first. These cases are not fast, but
486 >     * maximize aggregate expected throughput.
487       *
488       * Maintaining API and serialization compatibility with previous
489       * versions of this class introduces several oddities. Mainly: We
# Line 375 | Line 493 | public class ConcurrentHashMapV8<K, V>
493       * time that we can guarantee to honor it.) We also declare an
494       * unused "Segment" class that is instantiated in minimal form
495       * only when serializing.
496 +     *
497 +     * Also, solely for compatibility with previous versions of this
498 +     * class, it extends AbstractMap, even though all of its methods
499 +     * are overridden, so it is just useless baggage.
500 +     *
501 +     * This file is organized to make things a little easier to follow
502 +     * while reading than they might otherwise: First the main static
503 +     * declarations and utilities, then fields, then main public
504 +     * methods (with a few factorings of multiple public methods into
505 +     * internal ones), then sizing methods, trees, traversers, and
506 +     * bulk operations.
507       */
508  
509      /* ---------------- Constants -------------- */
# Line 416 | Line 545 | public class ConcurrentHashMapV8<K, V>
545      private static final float LOAD_FACTOR = 0.75f;
546  
547      /**
419     * The buffer size for skipped bins during transfers. The
420     * value is arbitrary but should be large enough to avoid
421     * most locking stalls during resizes.
422     */
423    private static final int TRANSFER_BUFFER_SIZE = 32;
424
425    /**
548       * The bin count threshold for using a tree rather than list for a
549 <     * bin.  The value reflects the approximate break-even point for
550 <     * using tree-based operations.
549 >     * bin.  Bins are converted to trees when adding an element to a
550 >     * bin with at least this many nodes. The value must be greater
551 >     * than 2, and should be at least 8 to mesh with assumptions in
552 >     * tree removal about conversion back to plain bins upon
553 >     * shrinkage.
554       */
555 <    private static final int TREE_THRESHOLD = 8;
431 <
432 <    /*
433 <     * Encodings for special uses of Node hash fields. See above for
434 <     * explanation.
435 <     */
436 <    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
437 <    static final int LOCKED    = 0x40000000; // set/tested only as a bit
438 <    static final int WAITING   = 0xc0000000; // both bits set/tested together
439 <    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
440 <
441 <    /* ---------------- Fields -------------- */
555 >    static final int TREEIFY_THRESHOLD = 8;
556  
557      /**
558 <     * The array of bins. Lazily initialized upon first insertion.
559 <     * Size is always a power of two. Accessed directly by iterators.
558 >     * The bin count threshold for untreeifying a (split) bin during a
559 >     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
560 >     * most 6 to mesh with shrinkage detection under removal.
561       */
562 <    transient volatile Node[] table;
562 >    static final int UNTREEIFY_THRESHOLD = 6;
563  
564      /**
565 <     * The counter maintaining number of elements.
565 >     * The smallest table capacity for which bins may be treeified.
566 >     * (Otherwise the table is resized if too many nodes in a bin.)
567 >     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
568 >     * conflicts between resizing and treeification thresholds.
569       */
570 <    private transient final LongAdder counter;
570 >    static final int MIN_TREEIFY_CAPACITY = 64;
571  
572      /**
573 <     * Table initialization and resizing control.  When negative, the
574 <     * table is being initialized or resized. Otherwise, when table is
575 <     * null, holds the initial table size to use upon creation, or 0
576 <     * for default. After initialization, holds the next element count
577 <     * value upon which to resize the table.
573 >     * Minimum number of rebinnings per transfer step. Ranges are
574 >     * subdivided to allow multiple resizer threads.  This value
575 >     * serves as a lower bound to avoid resizers encountering
576 >     * excessive memory contention.  The value should be at least
577 >     * DEFAULT_CAPACITY.
578       */
579 <    private transient volatile int sizeCtl;
462 <
463 <    // views
464 <    private transient KeySet<K,V> keySet;
465 <    private transient Values<K,V> values;
466 <    private transient EntrySet<K,V> entrySet;
467 <
468 <    /** For serialization compatibility. Null unless serialized; see below */
469 <    private Segment<K,V>[] segments;
470 <
471 <    /* ---------------- Table element access -------------- */
579 >    private static final int MIN_TRANSFER_STRIDE = 16;
580  
581      /*
582 <     * Volatile access methods are used for table elements as well as
475 <     * elements of in-progress next table while resizing.  Uses are
476 <     * null checked by callers, and implicitly bounds-checked, relying
477 <     * on the invariants that tab arrays have non-zero size, and all
478 <     * indices are masked with (tab.length - 1) which is never
479 <     * negative and always less than length. Note that, to be correct
480 <     * wrt arbitrary concurrency errors by users, bounds checks must
481 <     * operate on local variables, which accounts for some odd-looking
482 <     * inline assignments below.
582 >     * Encodings for Node hash fields. See above for explanation.
583       */
584 <
585 <    static final Node tabAt(Node[] tab, int i) { // used by Iter
586 <        return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
587 <    }
588 <
589 <    private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
590 <        return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
591 <    }
592 <
593 <    private static final void setTabAt(Node[] tab, int i, Node v) {
594 <        UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
595 <    }
584 >    static final int MOVED     = -1; // hash for forwarding nodes
585 >    static final int TREEBIN   = -2; // hash for roots of trees
586 >    static final int RESERVED  = -3; // hash for transient reservations
587 >    static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
588 >
589 >    /** Number of CPUS, to place bounds on some sizings */
590 >    static final int NCPU = Runtime.getRuntime().availableProcessors();
591 >
592 >    /** For serialization compatibility. */
593 >    private static final ObjectStreamField[] serialPersistentFields = {
594 >        new ObjectStreamField("segments", Segment[].class),
595 >        new ObjectStreamField("segmentMask", Integer.TYPE),
596 >        new ObjectStreamField("segmentShift", Integer.TYPE)
597 >    };
598  
599      /* ---------------- Nodes -------------- */
600  
601      /**
602 <     * Key-value entry. Note that this is never exported out as a
603 <     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
604 <     * field of MOVED are special, and do not contain user keys or
605 <     * values.  Otherwise, keys are never null, and null val fields
606 <     * indicate that a node is in the process of being deleted or
607 <     * created. For purposes of read-only access, a key may be read
608 <     * before a val, but can only be used after checking val to be
609 <     * non-null.
610 <     */
611 <    static class Node {
612 <        volatile int hash;
613 <        final Object key;
512 <        volatile Object val;
513 <        volatile Node next;
602 >     * Key-value entry.  This class is never exported out as a
603 >     * user-mutable Map.Entry (i.e., one supporting setValue; see
604 >     * MapEntry below), but can be used for read-only traversals used
605 >     * in bulk tasks.  Subclasses of Node with a negative hash field
606 >     * are special, and contain null keys and values (but are never
607 >     * exported).  Otherwise, keys and vals are never null.
608 >     */
609 >    static class Node<K,V> implements Map.Entry<K,V> {
610 >        final int hash;
611 >        final K key;
612 >        volatile V val;
613 >        volatile Node<K,V> next;
614  
615 <        Node(int hash, Object key, Object val, Node next) {
615 >        Node(int hash, K key, V val, Node<K,V> next) {
616              this.hash = hash;
617              this.key = key;
618              this.val = val;
619              this.next = next;
620          }
621  
622 <        /** CompareAndSet the hash field */
623 <        final boolean casHash(int cmp, int val) {
624 <            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
625 <        }
626 <
627 <        /** The number of spins before blocking for a lock */
528 <        static final int MAX_SPINS =
529 <            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
530 <
531 <        /**
532 <         * Spins a while if LOCKED bit set and this node is the first
533 <         * of its bin, and then sets WAITING bits on hash field and
534 <         * blocks (once) if they are still set.  It is OK for this
535 <         * method to return even if lock is not available upon exit,
536 <         * which enables these simple single-wait mechanics.
537 <         *
538 <         * The corresponding signalling operation is performed within
539 <         * callers: Upon detecting that WAITING has been set when
540 <         * unlocking lock (via a failed CAS from non-waiting LOCKED
541 <         * state), unlockers acquire the sync lock and perform a
542 <         * notifyAll.
543 <         */
544 <        final void tryAwaitLock(Node[] tab, int i) {
545 <            if (tab != null && i >= 0 && i < tab.length) { // bounds check
546 <                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
547 <                int spins = MAX_SPINS, h;
548 <                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
549 <                    if (spins >= 0) {
550 <                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
551 <                        if (r >= 0 && --spins == 0)
552 <                            Thread.yield();  // yield before block
553 <                    }
554 <                    else if (casHash(h, h | WAITING)) {
555 <                        synchronized (this) {
556 <                            if (tabAt(tab, i) == this &&
557 <                                (hash & WAITING) == WAITING) {
558 <                                try {
559 <                                    wait();
560 <                                } catch (InterruptedException ie) {
561 <                                    Thread.currentThread().interrupt();
562 <                                }
563 <                            }
564 <                            else
565 <                                notifyAll(); // possibly won race vs signaller
566 <                        }
567 <                        break;
568 <                    }
569 <                }
570 <            }
571 <        }
572 <
573 <        // Unsafe mechanics for casHash
574 <        private static final sun.misc.Unsafe UNSAFE;
575 <        private static final long hashOffset;
576 <
577 <        static {
578 <            try {
579 <                UNSAFE = getUnsafe();
580 <                Class<?> k = Node.class;
581 <                hashOffset = UNSAFE.objectFieldOffset
582 <                    (k.getDeclaredField("hash"));
583 <            } catch (Exception e) {
584 <                throw new Error(e);
585 <            }
586 <        }
587 <    }
588 <
589 <    /* ---------------- TreeBins -------------- */
590 <
591 <    /**
592 <     * Nodes for use in TreeBins
593 <     */
594 <    static final class TreeNode extends Node {
595 <        TreeNode parent;  // red-black tree links
596 <        TreeNode left;
597 <        TreeNode right;
598 <        TreeNode prev;    // needed to unlink next upon deletion
599 <        boolean red;
600 <
601 <        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
602 <            super(hash, key, val, next);
603 <            this.parent = parent;
604 <        }
605 <    }
606 <
607 <    /**
608 <     * A specialized form of red-black tree for use in bins
609 <     * whose size exceeds a threshold.
610 <     *
611 <     * TreeBins use a special form of comparison for search and
612 <     * related operations (which is the main reason we cannot use
613 <     * existing collections such as TreeMaps). TreeBins contain
614 <     * Comparable elements, but may contain others, as well as
615 <     * elements that are Comparable but not necessarily Comparable<T>
616 <     * for the same T, so we cannot invoke compareTo among them. To
617 <     * handle this, the tree is ordered primarily by hash value, then
618 <     * by getClass().getName() order, and then by Comparator order
619 <     * among elements of the same class.  On lookup at a node, if
620 <     * elements are not comparable or compare as 0, both left and
621 <     * right children may need to be searched in the case of tied hash
622 <     * values. (This corresponds to the full list search that would be
623 <     * necessary if all elements were non-Comparable and had tied
624 <     * hashes.)  The red-black balancing code is updated from
625 <     * pre-jdk-collections
626 <     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
627 <     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
628 <     * Algorithms" (CLR).
629 <     *
630 <     * TreeBins also maintain a separate locking discipline than
631 <     * regular bins. Because they are forwarded via special MOVED
632 <     * nodes at bin heads (which can never change once established),
633 <     * we cannot use those nodes as locks. Instead, TreeBin
634 <     * extends AbstractQueuedSynchronizer to support a simple form of
635 <     * read-write lock. For update operations and table validation,
636 <     * the exclusive form of lock behaves in the same way as bin-head
637 <     * locks. However, lookups use shared read-lock mechanics to allow
638 <     * multiple readers in the absence of writers.  Additionally,
639 <     * these lookups do not ever block: While the lock is not
640 <     * available, they proceed along the slow traversal path (via
641 <     * next-pointers) until the lock becomes available or the list is
642 <     * exhausted, whichever comes first. (These cases are not fast,
643 <     * but maximize aggregate expected throughput.)  The AQS mechanics
644 <     * for doing this are straightforward.  The lock state is held as
645 <     * AQS getState().  Read counts are negative; the write count (1)
646 <     * is positive.  There are no signalling preferences among readers
647 <     * and writers. Since we don't need to export full Lock API, we
648 <     * just override the minimal AQS methods and use them directly.
649 <     */
650 <    static final class TreeBin extends AbstractQueuedSynchronizer {
651 <        private static final long serialVersionUID = 2249069246763182397L;
652 <        transient TreeNode root;  // root of tree
653 <        transient TreeNode first; // head of next-pointer list
654 <
655 <        /* AQS overrides */
656 <        public final boolean isHeldExclusively() { return getState() > 0; }
657 <        public final boolean tryAcquire(int ignore) {
658 <            if (compareAndSetState(0, 1)) {
659 <                setExclusiveOwnerThread(Thread.currentThread());
660 <                return true;
661 <            }
662 <            return false;
663 <        }
664 <        public final boolean tryRelease(int ignore) {
665 <            setExclusiveOwnerThread(null);
666 <            setState(0);
667 <            return true;
668 <        }
669 <        public final int tryAcquireShared(int ignore) {
670 <            for (int c;;) {
671 <                if ((c = getState()) > 0)
672 <                    return -1;
673 <                if (compareAndSetState(c, c -1))
674 <                    return 1;
675 <            }
676 <        }
677 <        public final boolean tryReleaseShared(int ignore) {
678 <            int c;
679 <            do {} while (!compareAndSetState(c = getState(), c + 1));
680 <            return c == -1;
681 <        }
682 <
683 <        /** From CLR */
684 <        private void rotateLeft(TreeNode p) {
685 <            if (p != null) {
686 <                TreeNode r = p.right, pp, rl;
687 <                if ((rl = p.right = r.left) != null)
688 <                    rl.parent = p;
689 <                if ((pp = r.parent = p.parent) == null)
690 <                    root = r;
691 <                else if (pp.left == p)
692 <                    pp.left = r;
693 <                else
694 <                    pp.right = r;
695 <                r.left = p;
696 <                p.parent = r;
697 <            }
698 <        }
699 <
700 <        /** From CLR */
701 <        private void rotateRight(TreeNode p) {
702 <            if (p != null) {
703 <                TreeNode l = p.left, pp, lr;
704 <                if ((lr = p.left = l.right) != null)
705 <                    lr.parent = p;
706 <                if ((pp = l.parent = p.parent) == null)
707 <                    root = l;
708 <                else if (pp.right == p)
709 <                    pp.right = l;
710 <                else
711 <                    pp.left = l;
712 <                l.right = p;
713 <                p.parent = l;
714 <            }
715 <        }
716 <
717 <        /**
718 <         * Returns the TreeNode (or null if not found) for the given key
719 <         * starting at given root.
720 <         */
721 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
722 <        final TreeNode getTreeNode(int h, Object k, TreeNode p) {
723 <            Class<?> c = k.getClass();
724 <            while (p != null) {
725 <                int dir, ph;  Object pk; Class<?> pc;
726 <                if ((ph = p.hash) == h) {
727 <                    if ((pk = p.key) == k || k.equals(pk))
728 <                        return p;
729 <                    if (c != (pc = pk.getClass()) ||
730 <                        !(k instanceof Comparable) ||
731 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
732 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
733 <                        TreeNode r = null, s = null, pl, pr;
734 <                        if (dir >= 0) {
735 <                            if ((pl = p.left) != null && h <= pl.hash)
736 <                                s = pl;
737 <                        }
738 <                        else if ((pr = p.right) != null && h >= pr.hash)
739 <                            s = pr;
740 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
741 <                            return r;
742 <                    }
743 <                }
744 <                else
745 <                    dir = (h < ph) ? -1 : 1;
746 <                p = (dir > 0) ? p.right : p.left;
747 <            }
748 <            return null;
622 >        public final K getKey()       { return key; }
623 >        public final V getValue()     { return val; }
624 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
625 >        public final String toString(){ return key + "=" + val; }
626 >        public final V setValue(V value) {
627 >            throw new UnsupportedOperationException();
628          }
629  
630 <        /**
631 <         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
632 <         * read-lock to call getTreeNode, but during failure to get
633 <         * lock, searches along next links.
634 <         */
635 <        final Object getValue(int h, Object k) {
636 <            Node r = null;
758 <            int c = getState(); // Must read lock state first
759 <            for (Node e = first; e != null; e = e.next) {
760 <                if (c <= 0 && compareAndSetState(c, c - 1)) {
761 <                    try {
762 <                        r = getTreeNode(h, k, root);
763 <                    } finally {
764 <                        releaseShared(0);
765 <                    }
766 <                    break;
767 <                }
768 <                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
769 <                    r = e;
770 <                    break;
771 <                }
772 <                else
773 <                    c = getState();
774 <            }
775 <            return r == null ? null : r.val;
630 >        public final boolean equals(Object o) {
631 >            Object k, v, u; Map.Entry<?,?> e;
632 >            return ((o instanceof Map.Entry) &&
633 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
634 >                    (v = e.getValue()) != null &&
635 >                    (k == key || k.equals(key)) &&
636 >                    (v == (u = val) || v.equals(u)));
637          }
638  
639          /**
640 <         * Finds or adds a node.
780 <         * @return null if added
640 >         * Virtualized support for map.get(); overridden in subclasses.
641           */
642 <        @SuppressWarnings("unchecked") // suppress Comparable cast warning
643 <        final TreeNode putTreeNode(int h, Object k, Object v) {
644 <            Class<?> c = k.getClass();
645 <            TreeNode pp = root, p = null;
646 <            int dir = 0;
647 <            while (pp != null) { // find existing node or leaf to insert at
648 <                int ph;  Object pk; Class<?> pc;
649 <                p = pp;
650 <                if ((ph = p.hash) == h) {
791 <                    if ((pk = p.key) == k || k.equals(pk))
792 <                        return p;
793 <                    if (c != (pc = pk.getClass()) ||
794 <                        !(k instanceof Comparable) ||
795 <                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
796 <                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
797 <                        TreeNode r = null, s = null, pl, pr;
798 <                        if (dir >= 0) {
799 <                            if ((pl = p.left) != null && h <= pl.hash)
800 <                                s = pl;
801 <                        }
802 <                        else if ((pr = p.right) != null && h >= pr.hash)
803 <                            s = pr;
804 <                        if (s != null && (r = getTreeNode(h, k, s)) != null)
805 <                            return r;
806 <                    }
807 <                }
808 <                else
809 <                    dir = (h < ph) ? -1 : 1;
810 <                pp = (dir > 0) ? p.right : p.left;
811 <            }
812 <
813 <            TreeNode f = first;
814 <            TreeNode x = first = new TreeNode(h, k, v, f, p);
815 <            if (p == null)
816 <                root = x;
817 <            else { // attach and rebalance; adapted from CLR
818 <                TreeNode xp, xpp;
819 <                if (f != null)
820 <                    f.prev = x;
821 <                if (dir <= 0)
822 <                    p.left = x;
823 <                else
824 <                    p.right = x;
825 <                x.red = true;
826 <                while (x != null && (xp = x.parent) != null && xp.red &&
827 <                       (xpp = xp.parent) != null) {
828 <                    TreeNode xppl = xpp.left;
829 <                    if (xp == xppl) {
830 <                        TreeNode y = xpp.right;
831 <                        if (y != null && y.red) {
832 <                            y.red = false;
833 <                            xp.red = false;
834 <                            xpp.red = true;
835 <                            x = xpp;
836 <                        }
837 <                        else {
838 <                            if (x == xp.right) {
839 <                                rotateLeft(x = xp);
840 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
841 <                            }
842 <                            if (xp != null) {
843 <                                xp.red = false;
844 <                                if (xpp != null) {
845 <                                    xpp.red = true;
846 <                                    rotateRight(xpp);
847 <                                }
848 <                            }
849 <                        }
850 <                    }
851 <                    else {
852 <                        TreeNode y = xppl;
853 <                        if (y != null && y.red) {
854 <                            y.red = false;
855 <                            xp.red = false;
856 <                            xpp.red = true;
857 <                            x = xpp;
858 <                        }
859 <                        else {
860 <                            if (x == xp.left) {
861 <                                rotateRight(x = xp);
862 <                                xpp = (xp = x.parent) == null ? null : xp.parent;
863 <                            }
864 <                            if (xp != null) {
865 <                                xp.red = false;
866 <                                if (xpp != null) {
867 <                                    xpp.red = true;
868 <                                    rotateLeft(xpp);
869 <                                }
870 <                            }
871 <                        }
872 <                    }
873 <                }
874 <                TreeNode r = root;
875 <                if (r != null && r.red)
876 <                    r.red = false;
642 >        Node<K,V> find(int h, Object k) {
643 >            Node<K,V> e = this;
644 >            if (k != null) {
645 >                do {
646 >                    K ek;
647 >                    if (e.hash == h &&
648 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
649 >                        return e;
650 >                } while ((e = e.next) != null);
651              }
652              return null;
653          }
880
881        /**
882         * Removes the given node, that must be present before this
883         * call.  This is messier than typical red-black deletion code
884         * because we cannot swap the contents of an interior node
885         * with a leaf successor that is pinned by "next" pointers
886         * that are accessible independently of lock. So instead we
887         * swap the tree linkages.
888         */
889        final void deleteTreeNode(TreeNode p) {
890            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
891            TreeNode pred = p.prev;
892            if (pred == null)
893                first = next;
894            else
895                pred.next = next;
896            if (next != null)
897                next.prev = pred;
898            TreeNode replacement;
899            TreeNode pl = p.left;
900            TreeNode pr = p.right;
901            if (pl != null && pr != null) {
902                TreeNode s = pr, sl;
903                while ((sl = s.left) != null) // find successor
904                    s = sl;
905                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
906                TreeNode sr = s.right;
907                TreeNode pp = p.parent;
908                if (s == pr) { // p was s's direct parent
909                    p.parent = s;
910                    s.right = p;
911                }
912                else {
913                    TreeNode sp = s.parent;
914                    if ((p.parent = sp) != null) {
915                        if (s == sp.left)
916                            sp.left = p;
917                        else
918                            sp.right = p;
919                    }
920                    if ((s.right = pr) != null)
921                        pr.parent = s;
922                }
923                p.left = null;
924                if ((p.right = sr) != null)
925                    sr.parent = p;
926                if ((s.left = pl) != null)
927                    pl.parent = s;
928                if ((s.parent = pp) == null)
929                    root = s;
930                else if (p == pp.left)
931                    pp.left = s;
932                else
933                    pp.right = s;
934                replacement = sr;
935            }
936            else
937                replacement = (pl != null) ? pl : pr;
938            TreeNode pp = p.parent;
939            if (replacement == null) {
940                if (pp == null) {
941                    root = null;
942                    return;
943                }
944                replacement = p;
945            }
946            else {
947                replacement.parent = pp;
948                if (pp == null)
949                    root = replacement;
950                else if (p == pp.left)
951                    pp.left = replacement;
952                else
953                    pp.right = replacement;
954                p.left = p.right = p.parent = null;
955            }
956            if (!p.red) { // rebalance, from CLR
957                TreeNode x = replacement;
958                while (x != null) {
959                    TreeNode xp, xpl;
960                    if (x.red || (xp = x.parent) == null) {
961                        x.red = false;
962                        break;
963                    }
964                    if (x == (xpl = xp.left)) {
965                        TreeNode sib = xp.right;
966                        if (sib != null && sib.red) {
967                            sib.red = false;
968                            xp.red = true;
969                            rotateLeft(xp);
970                            sib = (xp = x.parent) == null ? null : xp.right;
971                        }
972                        if (sib == null)
973                            x = xp;
974                        else {
975                            TreeNode sl = sib.left, sr = sib.right;
976                            if ((sr == null || !sr.red) &&
977                                (sl == null || !sl.red)) {
978                                sib.red = true;
979                                x = xp;
980                            }
981                            else {
982                                if (sr == null || !sr.red) {
983                                    if (sl != null)
984                                        sl.red = false;
985                                    sib.red = true;
986                                    rotateRight(sib);
987                                    sib = (xp = x.parent) == null ? null : xp.right;
988                                }
989                                if (sib != null) {
990                                    sib.red = (xp == null) ? false : xp.red;
991                                    if ((sr = sib.right) != null)
992                                        sr.red = false;
993                                }
994                                if (xp != null) {
995                                    xp.red = false;
996                                    rotateLeft(xp);
997                                }
998                                x = root;
999                            }
1000                        }
1001                    }
1002                    else { // symmetric
1003                        TreeNode sib = xpl;
1004                        if (sib != null && sib.red) {
1005                            sib.red = false;
1006                            xp.red = true;
1007                            rotateRight(xp);
1008                            sib = (xp = x.parent) == null ? null : xp.left;
1009                        }
1010                        if (sib == null)
1011                            x = xp;
1012                        else {
1013                            TreeNode sl = sib.left, sr = sib.right;
1014                            if ((sl == null || !sl.red) &&
1015                                (sr == null || !sr.red)) {
1016                                sib.red = true;
1017                                x = xp;
1018                            }
1019                            else {
1020                                if (sl == null || !sl.red) {
1021                                    if (sr != null)
1022                                        sr.red = false;
1023                                    sib.red = true;
1024                                    rotateLeft(sib);
1025                                    sib = (xp = x.parent) == null ? null : xp.left;
1026                                }
1027                                if (sib != null) {
1028                                    sib.red = (xp == null) ? false : xp.red;
1029                                    if ((sl = sib.left) != null)
1030                                        sl.red = false;
1031                                }
1032                                if (xp != null) {
1033                                    xp.red = false;
1034                                    rotateRight(xp);
1035                                }
1036                                x = root;
1037                            }
1038                        }
1039                    }
1040                }
1041            }
1042            if (p == replacement && (pp = p.parent) != null) {
1043                if (p == pp.left) // detach pointers
1044                    pp.left = null;
1045                else if (p == pp.right)
1046                    pp.right = null;
1047                p.parent = null;
1048            }
1049        }
654      }
655  
656 <    /* ---------------- Collision reduction methods -------------- */
656 >    /* ---------------- Static utilities -------------- */
657  
658      /**
659 <     * Spreads higher bits to lower, and also forces top 2 bits to 0.
660 <     * Because the table uses power-of-two masking, sets of hashes
661 <     * that vary only in bits above the current mask will always
662 <     * collide. (Among known examples are sets of Float keys holding
663 <     * consecutive whole numbers in small tables.)  To counter this,
664 <     * we apply a transform that spreads the impact of higher bits
659 >     * Spreads (XORs) higher bits of hash to lower and also forces top
660 >     * bit to 0. Because the table uses power-of-two masking, sets of
661 >     * hashes that vary only in bits above the current mask will
662 >     * always collide. (Among known examples are sets of Float keys
663 >     * holding consecutive whole numbers in small tables.)  So we
664 >     * apply a transform that spreads the impact of higher bits
665       * downward. There is a tradeoff between speed, utility, and
666       * quality of bit-spreading. Because many common sets of hashes
667 <     * are already reasonably distributed across bits (so don't benefit
668 <     * from spreading), and because we use trees to handle large sets
669 <     * of collisions in bins, we don't need excessively high quality.
667 >     * are already reasonably distributed (so don't benefit from
668 >     * spreading), and because we use trees to handle large sets of
669 >     * collisions in bins, we just XOR some shifted bits in the
670 >     * cheapest possible way to reduce systematic lossage, as well as
671 >     * to incorporate impact of the highest bits that would otherwise
672 >     * never be used in index calculations because of table bounds.
673       */
674 <    private static final int spread(int h) {
675 <        h ^= (h >>> 18) ^ (h >>> 12);
1069 <        return (h ^ (h >>> 10)) & HASH_BITS;
674 >    static final int spread(int h) {
675 >        return (h ^ (h >>> 16)) & HASH_BITS;
676      }
677  
678      /**
679 <     * Replaces a list bin with a tree bin. Call only when locked.
680 <     * Fails to replace if the given key is non-comparable or table
1075 <     * is, or needs, resizing.
679 >     * Returns a power of two table size for the given desired capacity.
680 >     * See Hackers Delight, sec 3.2
681       */
682 <    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
683 <        if ((key instanceof Comparable) &&
684 <            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
685 <            TreeBin t = new TreeBin();
686 <            for (Node e = tabAt(tab, index); e != null; e = e.next)
687 <                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
688 <            setTabAt(tab, index, new Node(MOVED, t, null, null));
689 <        }
682 >    private static final int tableSizeFor(int c) {
683 >        int n = c - 1;
684 >        n |= n >>> 1;
685 >        n |= n >>> 2;
686 >        n |= n >>> 4;
687 >        n |= n >>> 8;
688 >        n |= n >>> 16;
689 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
690      }
691  
692 <    /* ---------------- Internal access and update methods -------------- */
693 <
694 <    /** Implementation for get and containsKey */
695 <    private final Object internalGet(Object k) {
696 <        int h = spread(k.hashCode());
697 <        retry: for (Node[] tab = table; tab != null;) {
698 <            Node e, p; Object ek, ev; int eh;      // locals to read fields once
699 <            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
700 <                if ((eh = e.hash) == MOVED) {
701 <                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
702 <                        return ((TreeBin)ek).getValue(h, k);
703 <                    else {                        // restart with new table
704 <                        tab = (Node[])ek;
705 <                        continue retry;
706 <                    }
692 >    /**
693 >     * Returns x's Class if it is of the form "class C implements
694 >     * Comparable<C>", else null.
695 >     */
696 >    static Class<?> comparableClassFor(Object x) {
697 >        if (x instanceof Comparable) {
698 >            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
699 >            if ((c = x.getClass()) == String.class) // bypass checks
700 >                return c;
701 >            if ((ts = c.getGenericInterfaces()) != null) {
702 >                for (int i = 0; i < ts.length; ++i) {
703 >                    if (((t = ts[i]) instanceof ParameterizedType) &&
704 >                        ((p = (ParameterizedType)t).getRawType() ==
705 >                         Comparable.class) &&
706 >                        (as = p.getActualTypeArguments()) != null &&
707 >                        as.length == 1 && as[0] == c) // type arg is c
708 >                        return c;
709                  }
1103                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1104                         ((ek = e.key) == k || k.equals(ek)))
1105                    return ev;
710              }
1107            break;
711          }
712          return null;
713      }
714  
715      /**
716 <     * Implementation for the four public remove/replace methods:
717 <     * Replaces node value with v, conditional upon match of cv if
1115 <     * non-null.  If resulting value is null, delete.
716 >     * Returns k.compareTo(x) if x matches kc (k's screened comparable
717 >     * class), else 0.
718       */
719 <    private final Object internalReplace(Object k, Object v, Object cv) {
720 <        int h = spread(k.hashCode());
721 <        Object oldVal = null;
722 <        for (Node[] tab = table;;) {
1121 <            Node f; int i, fh; Object fk;
1122 <            if (tab == null ||
1123 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1124 <                break;
1125 <            else if ((fh = f.hash) == MOVED) {
1126 <                if ((fk = f.key) instanceof TreeBin) {
1127 <                    TreeBin t = (TreeBin)fk;
1128 <                    boolean validated = false;
1129 <                    boolean deleted = false;
1130 <                    t.acquire(0);
1131 <                    try {
1132 <                        if (tabAt(tab, i) == f) {
1133 <                            validated = true;
1134 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1135 <                            if (p != null) {
1136 <                                Object pv = p.val;
1137 <                                if (cv == null || cv == pv || cv.equals(pv)) {
1138 <                                    oldVal = pv;
1139 <                                    if ((p.val = v) == null) {
1140 <                                        deleted = true;
1141 <                                        t.deleteTreeNode(p);
1142 <                                    }
1143 <                                }
1144 <                            }
1145 <                        }
1146 <                    } finally {
1147 <                        t.release(0);
1148 <                    }
1149 <                    if (validated) {
1150 <                        if (deleted)
1151 <                            counter.add(-1L);
1152 <                        break;
1153 <                    }
1154 <                }
1155 <                else
1156 <                    tab = (Node[])fk;
1157 <            }
1158 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1159 <                break;                          // rules out possible existence
1160 <            else if ((fh & LOCKED) != 0) {
1161 <                checkForResize();               // try resizing if can't get lock
1162 <                f.tryAwaitLock(tab, i);
1163 <            }
1164 <            else if (f.casHash(fh, fh | LOCKED)) {
1165 <                boolean validated = false;
1166 <                boolean deleted = false;
1167 <                try {
1168 <                    if (tabAt(tab, i) == f) {
1169 <                        validated = true;
1170 <                        for (Node e = f, pred = null;;) {
1171 <                            Object ek, ev;
1172 <                            if ((e.hash & HASH_BITS) == h &&
1173 <                                ((ev = e.val) != null) &&
1174 <                                ((ek = e.key) == k || k.equals(ek))) {
1175 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1176 <                                    oldVal = ev;
1177 <                                    if ((e.val = v) == null) {
1178 <                                        deleted = true;
1179 <                                        Node en = e.next;
1180 <                                        if (pred != null)
1181 <                                            pred.next = en;
1182 <                                        else
1183 <                                            setTabAt(tab, i, en);
1184 <                                    }
1185 <                                }
1186 <                                break;
1187 <                            }
1188 <                            pred = e;
1189 <                            if ((e = e.next) == null)
1190 <                                break;
1191 <                        }
1192 <                    }
1193 <                } finally {
1194 <                    if (!f.casHash(fh | LOCKED, fh)) {
1195 <                        f.hash = fh;
1196 <                        synchronized (f) { f.notifyAll(); };
1197 <                    }
1198 <                }
1199 <                if (validated) {
1200 <                    if (deleted)
1201 <                        counter.add(-1L);
1202 <                    break;
1203 <                }
1204 <            }
1205 <        }
1206 <        return oldVal;
1207 <    }
1208 <
1209 <    /*
1210 <     * Internal versions of the six insertion methods, each a
1211 <     * little more complicated than the last. All have
1212 <     * the same basic structure as the first (internalPut):
1213 <     *  1. If table uninitialized, create
1214 <     *  2. If bin empty, try to CAS new node
1215 <     *  3. If bin stale, use new table
1216 <     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1217 <     *  5. Lock and validate; if valid, scan and add or update
1218 <     *
1219 <     * The others interweave other checks and/or alternative actions:
1220 <     *  * Plain put checks for and performs resize after insertion.
1221 <     *  * putIfAbsent prescans for mapping without lock (and fails to add
1222 <     *    if present), which also makes pre-emptive resize checks worthwhile.
1223 <     *  * computeIfAbsent extends form used in putIfAbsent with additional
1224 <     *    mechanics to deal with, calls, potential exceptions and null
1225 <     *    returns from function call.
1226 <     *  * compute uses the same function-call mechanics, but without
1227 <     *    the prescans
1228 <     *  * merge acts as putIfAbsent in the absent case, but invokes the
1229 <     *    update function if present
1230 <     *  * putAll attempts to pre-allocate enough table space
1231 <     *    and more lazily performs count updates and checks.
1232 <     *
1233 <     * Someday when details settle down a bit more, it might be worth
1234 <     * some factoring to reduce sprawl.
1235 <     */
1236 <
1237 <    /** Implementation for put */
1238 <    private final Object internalPut(Object k, Object v) {
1239 <        int h = spread(k.hashCode());
1240 <        int count = 0;
1241 <        for (Node[] tab = table;;) {
1242 <            int i; Node f; int fh; Object fk;
1243 <            if (tab == null)
1244 <                tab = initTable();
1245 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1246 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1247 <                    break;                   // no lock when adding to empty bin
1248 <            }
1249 <            else if ((fh = f.hash) == MOVED) {
1250 <                if ((fk = f.key) instanceof TreeBin) {
1251 <                    TreeBin t = (TreeBin)fk;
1252 <                    Object oldVal = null;
1253 <                    t.acquire(0);
1254 <                    try {
1255 <                        if (tabAt(tab, i) == f) {
1256 <                            count = 2;
1257 <                            TreeNode p = t.putTreeNode(h, k, v);
1258 <                            if (p != null) {
1259 <                                oldVal = p.val;
1260 <                                p.val = v;
1261 <                            }
1262 <                        }
1263 <                    } finally {
1264 <                        t.release(0);
1265 <                    }
1266 <                    if (count != 0) {
1267 <                        if (oldVal != null)
1268 <                            return oldVal;
1269 <                        break;
1270 <                    }
1271 <                }
1272 <                else
1273 <                    tab = (Node[])fk;
1274 <            }
1275 <            else if ((fh & LOCKED) != 0) {
1276 <                checkForResize();
1277 <                f.tryAwaitLock(tab, i);
1278 <            }
1279 <            else if (f.casHash(fh, fh | LOCKED)) {
1280 <                Object oldVal = null;
1281 <                try {                        // needed in case equals() throws
1282 <                    if (tabAt(tab, i) == f) {
1283 <                        count = 1;
1284 <                        for (Node e = f;; ++count) {
1285 <                            Object ek, ev;
1286 <                            if ((e.hash & HASH_BITS) == h &&
1287 <                                (ev = e.val) != null &&
1288 <                                ((ek = e.key) == k || k.equals(ek))) {
1289 <                                oldVal = ev;
1290 <                                e.val = v;
1291 <                                break;
1292 <                            }
1293 <                            Node last = e;
1294 <                            if ((e = e.next) == null) {
1295 <                                last.next = new Node(h, k, v, null);
1296 <                                if (count >= TREE_THRESHOLD)
1297 <                                    replaceWithTreeBin(tab, i, k);
1298 <                                break;
1299 <                            }
1300 <                        }
1301 <                    }
1302 <                } finally {                  // unlock and signal if needed
1303 <                    if (!f.casHash(fh | LOCKED, fh)) {
1304 <                        f.hash = fh;
1305 <                        synchronized (f) { f.notifyAll(); };
1306 <                    }
1307 <                }
1308 <                if (count != 0) {
1309 <                    if (oldVal != null)
1310 <                        return oldVal;
1311 <                    if (tab.length <= 64)
1312 <                        count = 2;
1313 <                    break;
1314 <                }
1315 <            }
1316 <        }
1317 <        counter.add(1L);
1318 <        if (count > 1)
1319 <            checkForResize();
1320 <        return null;
719 >    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
720 >    static int compareComparables(Class<?> kc, Object k, Object x) {
721 >        return (x == null || x.getClass() != kc ? 0 :
722 >                ((Comparable)k).compareTo(x));
723      }
724  
725 <    /** Implementation for putIfAbsent */
1324 <    private final Object internalPutIfAbsent(Object k, Object v) {
1325 <        int h = spread(k.hashCode());
1326 <        int count = 0;
1327 <        for (Node[] tab = table;;) {
1328 <            int i; Node f; int fh; Object fk, fv;
1329 <            if (tab == null)
1330 <                tab = initTable();
1331 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1332 <                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1333 <                    break;
1334 <            }
1335 <            else if ((fh = f.hash) == MOVED) {
1336 <                if ((fk = f.key) instanceof TreeBin) {
1337 <                    TreeBin t = (TreeBin)fk;
1338 <                    Object oldVal = null;
1339 <                    t.acquire(0);
1340 <                    try {
1341 <                        if (tabAt(tab, i) == f) {
1342 <                            count = 2;
1343 <                            TreeNode p = t.putTreeNode(h, k, v);
1344 <                            if (p != null)
1345 <                                oldVal = p.val;
1346 <                        }
1347 <                    } finally {
1348 <                        t.release(0);
1349 <                    }
1350 <                    if (count != 0) {
1351 <                        if (oldVal != null)
1352 <                            return oldVal;
1353 <                        break;
1354 <                    }
1355 <                }
1356 <                else
1357 <                    tab = (Node[])fk;
1358 <            }
1359 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1360 <                     ((fk = f.key) == k || k.equals(fk)))
1361 <                return fv;
1362 <            else {
1363 <                Node g = f.next;
1364 <                if (g != null) { // at least 2 nodes -- search and maybe resize
1365 <                    for (Node e = g;;) {
1366 <                        Object ek, ev;
1367 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1368 <                            ((ek = e.key) == k || k.equals(ek)))
1369 <                            return ev;
1370 <                        if ((e = e.next) == null) {
1371 <                            checkForResize();
1372 <                            break;
1373 <                        }
1374 <                    }
1375 <                }
1376 <                if (((fh = f.hash) & LOCKED) != 0) {
1377 <                    checkForResize();
1378 <                    f.tryAwaitLock(tab, i);
1379 <                }
1380 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1381 <                    Object oldVal = null;
1382 <                    try {
1383 <                        if (tabAt(tab, i) == f) {
1384 <                            count = 1;
1385 <                            for (Node e = f;; ++count) {
1386 <                                Object ek, ev;
1387 <                                if ((e.hash & HASH_BITS) == h &&
1388 <                                    (ev = e.val) != null &&
1389 <                                    ((ek = e.key) == k || k.equals(ek))) {
1390 <                                    oldVal = ev;
1391 <                                    break;
1392 <                                }
1393 <                                Node last = e;
1394 <                                if ((e = e.next) == null) {
1395 <                                    last.next = new Node(h, k, v, null);
1396 <                                    if (count >= TREE_THRESHOLD)
1397 <                                        replaceWithTreeBin(tab, i, k);
1398 <                                    break;
1399 <                                }
1400 <                            }
1401 <                        }
1402 <                    } finally {
1403 <                        if (!f.casHash(fh | LOCKED, fh)) {
1404 <                            f.hash = fh;
1405 <                            synchronized (f) { f.notifyAll(); };
1406 <                        }
1407 <                    }
1408 <                    if (count != 0) {
1409 <                        if (oldVal != null)
1410 <                            return oldVal;
1411 <                        if (tab.length <= 64)
1412 <                            count = 2;
1413 <                        break;
1414 <                    }
1415 <                }
1416 <            }
1417 <        }
1418 <        counter.add(1L);
1419 <        if (count > 1)
1420 <            checkForResize();
1421 <        return null;
1422 <    }
725 >    /* ---------------- Table element access -------------- */
726  
727 <    /** Implementation for computeIfAbsent */
728 <    private final Object internalComputeIfAbsent(K k,
729 <                                                 Fun<? super K, ?> mf) {
730 <        int h = spread(k.hashCode());
731 <        Object val = null;
732 <        int count = 0;
733 <        for (Node[] tab = table;;) {
734 <            Node f; int i, fh; Object fk, fv;
735 <            if (tab == null)
736 <                tab = initTable();
737 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
738 <                Node node = new Node(fh = h | LOCKED, k, null, null);
739 <                if (casTabAt(tab, i, null, node)) {
740 <                    count = 1;
741 <                    try {
1439 <                        if ((val = mf.apply(k)) != null)
1440 <                            node.val = val;
1441 <                    } finally {
1442 <                        if (val == null)
1443 <                            setTabAt(tab, i, null);
1444 <                        if (!node.casHash(fh, h)) {
1445 <                            node.hash = h;
1446 <                            synchronized (node) { node.notifyAll(); };
1447 <                        }
1448 <                    }
1449 <                }
1450 <                if (count != 0)
1451 <                    break;
1452 <            }
1453 <            else if ((fh = f.hash) == MOVED) {
1454 <                if ((fk = f.key) instanceof TreeBin) {
1455 <                    TreeBin t = (TreeBin)fk;
1456 <                    boolean added = false;
1457 <                    t.acquire(0);
1458 <                    try {
1459 <                        if (tabAt(tab, i) == f) {
1460 <                            count = 1;
1461 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1462 <                            if (p != null)
1463 <                                val = p.val;
1464 <                            else if ((val = mf.apply(k)) != null) {
1465 <                                added = true;
1466 <                                count = 2;
1467 <                                t.putTreeNode(h, k, val);
1468 <                            }
1469 <                        }
1470 <                    } finally {
1471 <                        t.release(0);
1472 <                    }
1473 <                    if (count != 0) {
1474 <                        if (!added)
1475 <                            return val;
1476 <                        break;
1477 <                    }
1478 <                }
1479 <                else
1480 <                    tab = (Node[])fk;
1481 <            }
1482 <            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1483 <                     ((fk = f.key) == k || k.equals(fk)))
1484 <                return fv;
1485 <            else {
1486 <                Node g = f.next;
1487 <                if (g != null) {
1488 <                    for (Node e = g;;) {
1489 <                        Object ek, ev;
1490 <                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1491 <                            ((ek = e.key) == k || k.equals(ek)))
1492 <                            return ev;
1493 <                        if ((e = e.next) == null) {
1494 <                            checkForResize();
1495 <                            break;
1496 <                        }
1497 <                    }
1498 <                }
1499 <                if (((fh = f.hash) & LOCKED) != 0) {
1500 <                    checkForResize();
1501 <                    f.tryAwaitLock(tab, i);
1502 <                }
1503 <                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1504 <                    boolean added = false;
1505 <                    try {
1506 <                        if (tabAt(tab, i) == f) {
1507 <                            count = 1;
1508 <                            for (Node e = f;; ++count) {
1509 <                                Object ek, ev;
1510 <                                if ((e.hash & HASH_BITS) == h &&
1511 <                                    (ev = e.val) != null &&
1512 <                                    ((ek = e.key) == k || k.equals(ek))) {
1513 <                                    val = ev;
1514 <                                    break;
1515 <                                }
1516 <                                Node last = e;
1517 <                                if ((e = e.next) == null) {
1518 <                                    if ((val = mf.apply(k)) != null) {
1519 <                                        added = true;
1520 <                                        last.next = new Node(h, k, val, null);
1521 <                                        if (count >= TREE_THRESHOLD)
1522 <                                            replaceWithTreeBin(tab, i, k);
1523 <                                    }
1524 <                                    break;
1525 <                                }
1526 <                            }
1527 <                        }
1528 <                    } finally {
1529 <                        if (!f.casHash(fh | LOCKED, fh)) {
1530 <                            f.hash = fh;
1531 <                            synchronized (f) { f.notifyAll(); };
1532 <                        }
1533 <                    }
1534 <                    if (count != 0) {
1535 <                        if (!added)
1536 <                            return val;
1537 <                        if (tab.length <= 64)
1538 <                            count = 2;
1539 <                        break;
1540 <                    }
1541 <                }
1542 <            }
1543 <        }
1544 <        if (val != null) {
1545 <            counter.add(1L);
1546 <            if (count > 1)
1547 <                checkForResize();
1548 <        }
1549 <        return val;
1550 <    }
727 >    /*
728 >     * Volatile access methods are used for table elements as well as
729 >     * elements of in-progress next table while resizing.  All uses of
730 >     * the tab arguments must be null checked by callers.  All callers
731 >     * also paranoically precheck that tab's length is not zero (or an
732 >     * equivalent check), thus ensuring that any index argument taking
733 >     * the form of a hash value anded with (length - 1) is a valid
734 >     * index.  Note that, to be correct wrt arbitrary concurrency
735 >     * errors by users, these checks must operate on local variables,
736 >     * which accounts for some odd-looking inline assignments below.
737 >     * Note that calls to setTabAt always occur within locked regions,
738 >     * and so in principle require only release ordering, not need
739 >     * full volatile semantics, but are currently coded as volatile
740 >     * writes to be conservative.
741 >     */
742  
1552    /** Implementation for compute */
743      @SuppressWarnings("unchecked")
744 <    private final Object internalCompute(K k, boolean onlyIfPresent,
745 <                                             BiFun<? super K, ? super V, ? extends V> mf) {
1556 <        int h = spread(k.hashCode());
1557 <        Object val = null;
1558 <        int delta = 0;
1559 <        int count = 0;
1560 <        for (Node[] tab = table;;) {
1561 <            Node f; int i, fh; Object fk;
1562 <            if (tab == null)
1563 <                tab = initTable();
1564 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1565 <                if (onlyIfPresent)
1566 <                    break;
1567 <                Node node = new Node(fh = h | LOCKED, k, null, null);
1568 <                if (casTabAt(tab, i, null, node)) {
1569 <                    try {
1570 <                        count = 1;
1571 <                        if ((val = mf.apply(k, null)) != null) {
1572 <                            node.val = val;
1573 <                            delta = 1;
1574 <                        }
1575 <                    } finally {
1576 <                        if (delta == 0)
1577 <                            setTabAt(tab, i, null);
1578 <                        if (!node.casHash(fh, h)) {
1579 <                            node.hash = h;
1580 <                            synchronized (node) { node.notifyAll(); };
1581 <                        }
1582 <                    }
1583 <                }
1584 <                if (count != 0)
1585 <                    break;
1586 <            }
1587 <            else if ((fh = f.hash) == MOVED) {
1588 <                if ((fk = f.key) instanceof TreeBin) {
1589 <                    TreeBin t = (TreeBin)fk;
1590 <                    t.acquire(0);
1591 <                    try {
1592 <                        if (tabAt(tab, i) == f) {
1593 <                            count = 1;
1594 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1595 <                            Object pv = (p == null) ? null : p.val;
1596 <                            if ((val = mf.apply(k, (V)pv)) != null) {
1597 <                                if (p != null)
1598 <                                    p.val = val;
1599 <                                else {
1600 <                                    count = 2;
1601 <                                    delta = 1;
1602 <                                    t.putTreeNode(h, k, val);
1603 <                                }
1604 <                            }
1605 <                            else if (p != null) {
1606 <                                delta = -1;
1607 <                                t.deleteTreeNode(p);
1608 <                            }
1609 <                        }
1610 <                    } finally {
1611 <                        t.release(0);
1612 <                    }
1613 <                    if (count != 0)
1614 <                        break;
1615 <                }
1616 <                else
1617 <                    tab = (Node[])fk;
1618 <            }
1619 <            else if ((fh & LOCKED) != 0) {
1620 <                checkForResize();
1621 <                f.tryAwaitLock(tab, i);
1622 <            }
1623 <            else if (f.casHash(fh, fh | LOCKED)) {
1624 <                try {
1625 <                    if (tabAt(tab, i) == f) {
1626 <                        count = 1;
1627 <                        for (Node e = f, pred = null;; ++count) {
1628 <                            Object ek, ev;
1629 <                            if ((e.hash & HASH_BITS) == h &&
1630 <                                (ev = e.val) != null &&
1631 <                                ((ek = e.key) == k || k.equals(ek))) {
1632 <                                val = mf.apply(k, (V)ev);
1633 <                                if (val != null)
1634 <                                    e.val = val;
1635 <                                else {
1636 <                                    delta = -1;
1637 <                                    Node en = e.next;
1638 <                                    if (pred != null)
1639 <                                        pred.next = en;
1640 <                                    else
1641 <                                        setTabAt(tab, i, en);
1642 <                                }
1643 <                                break;
1644 <                            }
1645 <                            pred = e;
1646 <                            if ((e = e.next) == null) {
1647 <                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1648 <                                    pred.next = new Node(h, k, val, null);
1649 <                                    delta = 1;
1650 <                                    if (count >= TREE_THRESHOLD)
1651 <                                        replaceWithTreeBin(tab, i, k);
1652 <                                }
1653 <                                break;
1654 <                            }
1655 <                        }
1656 <                    }
1657 <                } finally {
1658 <                    if (!f.casHash(fh | LOCKED, fh)) {
1659 <                        f.hash = fh;
1660 <                        synchronized (f) { f.notifyAll(); };
1661 <                    }
1662 <                }
1663 <                if (count != 0) {
1664 <                    if (tab.length <= 64)
1665 <                        count = 2;
1666 <                    break;
1667 <                }
1668 <            }
1669 <        }
1670 <        if (delta != 0) {
1671 <            counter.add((long)delta);
1672 <            if (count > 1)
1673 <                checkForResize();
1674 <        }
1675 <        return val;
744 >    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
745 >        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
746      }
747  
748 <    /** Implementation for merge */
749 <    @SuppressWarnings("unchecked")
750 <    private final Object internalMerge(K k, V v,
1681 <                                       BiFun<? super V, ? super V, ? extends V> mf) {
1682 <        int h = spread(k.hashCode());
1683 <        Object val = null;
1684 <        int delta = 0;
1685 <        int count = 0;
1686 <        for (Node[] tab = table;;) {
1687 <            int i; Node f; int fh; Object fk, fv;
1688 <            if (tab == null)
1689 <                tab = initTable();
1690 <            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1691 <                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1692 <                    delta = 1;
1693 <                    val = v;
1694 <                    break;
1695 <                }
1696 <            }
1697 <            else if ((fh = f.hash) == MOVED) {
1698 <                if ((fk = f.key) instanceof TreeBin) {
1699 <                    TreeBin t = (TreeBin)fk;
1700 <                    t.acquire(0);
1701 <                    try {
1702 <                        if (tabAt(tab, i) == f) {
1703 <                            count = 1;
1704 <                            TreeNode p = t.getTreeNode(h, k, t.root);
1705 <                            val = (p == null) ? v : mf.apply((V)p.val, v);
1706 <                            if (val != null) {
1707 <                                if (p != null)
1708 <                                    p.val = val;
1709 <                                else {
1710 <                                    count = 2;
1711 <                                    delta = 1;
1712 <                                    t.putTreeNode(h, k, val);
1713 <                                }
1714 <                            }
1715 <                            else if (p != null) {
1716 <                                delta = -1;
1717 <                                t.deleteTreeNode(p);
1718 <                            }
1719 <                        }
1720 <                    } finally {
1721 <                        t.release(0);
1722 <                    }
1723 <                    if (count != 0)
1724 <                        break;
1725 <                }
1726 <                else
1727 <                    tab = (Node[])fk;
1728 <            }
1729 <            else if ((fh & LOCKED) != 0) {
1730 <                checkForResize();
1731 <                f.tryAwaitLock(tab, i);
1732 <            }
1733 <            else if (f.casHash(fh, fh | LOCKED)) {
1734 <                try {
1735 <                    if (tabAt(tab, i) == f) {
1736 <                        count = 1;
1737 <                        for (Node e = f, pred = null;; ++count) {
1738 <                            Object ek, ev;
1739 <                            if ((e.hash & HASH_BITS) == h &&
1740 <                                (ev = e.val) != null &&
1741 <                                ((ek = e.key) == k || k.equals(ek))) {
1742 <                                val = mf.apply(v, (V)ev);
1743 <                                if (val != null)
1744 <                                    e.val = val;
1745 <                                else {
1746 <                                    delta = -1;
1747 <                                    Node en = e.next;
1748 <                                    if (pred != null)
1749 <                                        pred.next = en;
1750 <                                    else
1751 <                                        setTabAt(tab, i, en);
1752 <                                }
1753 <                                break;
1754 <                            }
1755 <                            pred = e;
1756 <                            if ((e = e.next) == null) {
1757 <                                val = v;
1758 <                                pred.next = new Node(h, k, val, null);
1759 <                                delta = 1;
1760 <                                if (count >= TREE_THRESHOLD)
1761 <                                    replaceWithTreeBin(tab, i, k);
1762 <                                break;
1763 <                            }
1764 <                        }
1765 <                    }
1766 <                } finally {
1767 <                    if (!f.casHash(fh | LOCKED, fh)) {
1768 <                        f.hash = fh;
1769 <                        synchronized (f) { f.notifyAll(); };
1770 <                    }
1771 <                }
1772 <                if (count != 0) {
1773 <                    if (tab.length <= 64)
1774 <                        count = 2;
1775 <                    break;
1776 <                }
1777 <            }
1778 <        }
1779 <        if (delta != 0) {
1780 <            counter.add((long)delta);
1781 <            if (count > 1)
1782 <                checkForResize();
1783 <        }
1784 <        return val;
748 >    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
749 >                                        Node<K,V> c, Node<K,V> v) {
750 >        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
751      }
752  
753 <    /** Implementation for putAll */
754 <    private final void internalPutAll(Map<?, ?> m) {
1789 <        tryPresize(m.size());
1790 <        long delta = 0L;     // number of uncommitted additions
1791 <        boolean npe = false; // to throw exception on exit for nulls
1792 <        try {                // to clean up counts on other exceptions
1793 <            for (Map.Entry<?, ?> entry : m.entrySet()) {
1794 <                Object k, v;
1795 <                if (entry == null || (k = entry.getKey()) == null ||
1796 <                    (v = entry.getValue()) == null) {
1797 <                    npe = true;
1798 <                    break;
1799 <                }
1800 <                int h = spread(k.hashCode());
1801 <                for (Node[] tab = table;;) {
1802 <                    int i; Node f; int fh; Object fk;
1803 <                    if (tab == null)
1804 <                        tab = initTable();
1805 <                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1806 <                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1807 <                            ++delta;
1808 <                            break;
1809 <                        }
1810 <                    }
1811 <                    else if ((fh = f.hash) == MOVED) {
1812 <                        if ((fk = f.key) instanceof TreeBin) {
1813 <                            TreeBin t = (TreeBin)fk;
1814 <                            boolean validated = false;
1815 <                            t.acquire(0);
1816 <                            try {
1817 <                                if (tabAt(tab, i) == f) {
1818 <                                    validated = true;
1819 <                                    TreeNode p = t.getTreeNode(h, k, t.root);
1820 <                                    if (p != null)
1821 <                                        p.val = v;
1822 <                                    else {
1823 <                                        t.putTreeNode(h, k, v);
1824 <                                        ++delta;
1825 <                                    }
1826 <                                }
1827 <                            } finally {
1828 <                                t.release(0);
1829 <                            }
1830 <                            if (validated)
1831 <                                break;
1832 <                        }
1833 <                        else
1834 <                            tab = (Node[])fk;
1835 <                    }
1836 <                    else if ((fh & LOCKED) != 0) {
1837 <                        counter.add(delta);
1838 <                        delta = 0L;
1839 <                        checkForResize();
1840 <                        f.tryAwaitLock(tab, i);
1841 <                    }
1842 <                    else if (f.casHash(fh, fh | LOCKED)) {
1843 <                        int count = 0;
1844 <                        try {
1845 <                            if (tabAt(tab, i) == f) {
1846 <                                count = 1;
1847 <                                for (Node e = f;; ++count) {
1848 <                                    Object ek, ev;
1849 <                                    if ((e.hash & HASH_BITS) == h &&
1850 <                                        (ev = e.val) != null &&
1851 <                                        ((ek = e.key) == k || k.equals(ek))) {
1852 <                                        e.val = v;
1853 <                                        break;
1854 <                                    }
1855 <                                    Node last = e;
1856 <                                    if ((e = e.next) == null) {
1857 <                                        ++delta;
1858 <                                        last.next = new Node(h, k, v, null);
1859 <                                        if (count >= TREE_THRESHOLD)
1860 <                                            replaceWithTreeBin(tab, i, k);
1861 <                                        break;
1862 <                                    }
1863 <                                }
1864 <                            }
1865 <                        } finally {
1866 <                            if (!f.casHash(fh | LOCKED, fh)) {
1867 <                                f.hash = fh;
1868 <                                synchronized (f) { f.notifyAll(); };
1869 <                            }
1870 <                        }
1871 <                        if (count != 0) {
1872 <                            if (count > 1) {
1873 <                                counter.add(delta);
1874 <                                delta = 0L;
1875 <                                checkForResize();
1876 <                            }
1877 <                            break;
1878 <                        }
1879 <                    }
1880 <                }
1881 <            }
1882 <        } finally {
1883 <            if (delta != 0)
1884 <                counter.add(delta);
1885 <        }
1886 <        if (npe)
1887 <            throw new NullPointerException();
753 >    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
754 >        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
755      }
756  
757 <    /* ---------------- Table Initialization and Resizing -------------- */
757 >    /* ---------------- Fields -------------- */
758  
759      /**
760 <     * Returns a power of two table size for the given desired capacity.
761 <     * See Hackers Delight, sec 3.2
760 >     * The array of bins. Lazily initialized upon first insertion.
761 >     * Size is always a power of two. Accessed directly by iterators.
762       */
763 <    private static final int tableSizeFor(int c) {
1897 <        int n = c - 1;
1898 <        n |= n >>> 1;
1899 <        n |= n >>> 2;
1900 <        n |= n >>> 4;
1901 <        n |= n >>> 8;
1902 <        n |= n >>> 16;
1903 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1904 <    }
763 >    transient volatile Node<K,V>[] table;
764  
765      /**
766 <     * Initializes table, using the size recorded in sizeCtl.
766 >     * The next table to use; non-null only while resizing.
767       */
768 <    private final Node[] initTable() {
1910 <        Node[] tab; int sc;
1911 <        while ((tab = table) == null) {
1912 <            if ((sc = sizeCtl) < 0)
1913 <                Thread.yield(); // lost initialization race; just spin
1914 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1915 <                try {
1916 <                    if ((tab = table) == null) {
1917 <                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1918 <                        tab = table = new Node[n];
1919 <                        sc = n - (n >>> 2);
1920 <                    }
1921 <                } finally {
1922 <                    sizeCtl = sc;
1923 <                }
1924 <                break;
1925 <            }
1926 <        }
1927 <        return tab;
1928 <    }
1929 <
1930 <    /**
1931 <     * If table is too small and not already resizing, creates next
1932 <     * table and transfers bins.  Rechecks occupancy after a transfer
1933 <     * to see if another resize is already needed because resizings
1934 <     * are lagging additions.
1935 <     */
1936 <    private final void checkForResize() {
1937 <        Node[] tab; int n, sc;
1938 <        while ((tab = table) != null &&
1939 <               (n = tab.length) < MAXIMUM_CAPACITY &&
1940 <               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1941 <               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1942 <            try {
1943 <                if (tab == table) {
1944 <                    table = rebuild(tab);
1945 <                    sc = (n << 1) - (n >>> 1);
1946 <                }
1947 <            } finally {
1948 <                sizeCtl = sc;
1949 <            }
1950 <        }
1951 <    }
768 >    private transient volatile Node<K,V>[] nextTable;
769  
770      /**
771 <     * Tries to presize table to accommodate the given number of elements.
772 <     *
773 <     * @param size number of elements (doesn't need to be perfectly accurate)
771 >     * Base counter value, used mainly when there is no contention,
772 >     * but also as a fallback during table initialization
773 >     * races. Updated via CAS.
774       */
775 <    private final void tryPresize(int size) {
1959 <        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1960 <            tableSizeFor(size + (size >>> 1) + 1);
1961 <        int sc;
1962 <        while ((sc = sizeCtl) >= 0) {
1963 <            Node[] tab = table; int n;
1964 <            if (tab == null || (n = tab.length) == 0) {
1965 <                n = (sc > c) ? sc : c;
1966 <                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1967 <                    try {
1968 <                        if (table == tab) {
1969 <                            table = new Node[n];
1970 <                            sc = n - (n >>> 2);
1971 <                        }
1972 <                    } finally {
1973 <                        sizeCtl = sc;
1974 <                    }
1975 <                }
1976 <            }
1977 <            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1978 <                break;
1979 <            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1980 <                try {
1981 <                    if (table == tab) {
1982 <                        table = rebuild(tab);
1983 <                        sc = (n << 1) - (n >>> 1);
1984 <                    }
1985 <                } finally {
1986 <                    sizeCtl = sc;
1987 <                }
1988 <            }
1989 <        }
1990 <    }
1991 <
1992 <    /*
1993 <     * Moves and/or copies the nodes in each bin to new table. See
1994 <     * above for explanation.
1995 <     *
1996 <     * @return the new table
1997 <     */
1998 <    private static final Node[] rebuild(Node[] tab) {
1999 <        int n = tab.length;
2000 <        Node[] nextTab = new Node[n << 1];
2001 <        Node fwd = new Node(MOVED, nextTab, null, null);
2002 <        int[] buffer = null;       // holds bins to revisit; null until needed
2003 <        Node rev = null;           // reverse forwarder; null until needed
2004 <        int nbuffered = 0;         // the number of bins in buffer list
2005 <        int bufferIndex = 0;       // buffer index of current buffered bin
2006 <        int bin = n - 1;           // current non-buffered bin or -1 if none
2007 <
2008 <        for (int i = bin;;) {      // start upwards sweep
2009 <            int fh; Node f;
2010 <            if ((f = tabAt(tab, i)) == null) {
2011 <                if (bin >= 0) {    // no lock needed (or available)
2012 <                    if (!casTabAt(tab, i, f, fwd))
2013 <                        continue;
2014 <                }
2015 <                else {             // transiently use a locked forwarding node
2016 <                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2017 <                    if (!casTabAt(tab, i, f, g))
2018 <                        continue;
2019 <                    setTabAt(nextTab, i, null);
2020 <                    setTabAt(nextTab, i + n, null);
2021 <                    setTabAt(tab, i, fwd);
2022 <                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2023 <                        g.hash = MOVED;
2024 <                        synchronized (g) { g.notifyAll(); }
2025 <                    }
2026 <                }
2027 <            }
2028 <            else if ((fh = f.hash) == MOVED) {
2029 <                Object fk = f.key;
2030 <                if (fk instanceof TreeBin) {
2031 <                    TreeBin t = (TreeBin)fk;
2032 <                    boolean validated = false;
2033 <                    t.acquire(0);
2034 <                    try {
2035 <                        if (tabAt(tab, i) == f) {
2036 <                            validated = true;
2037 <                            splitTreeBin(nextTab, i, t);
2038 <                            setTabAt(tab, i, fwd);
2039 <                        }
2040 <                    } finally {
2041 <                        t.release(0);
2042 <                    }
2043 <                    if (!validated)
2044 <                        continue;
2045 <                }
2046 <            }
2047 <            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2048 <                boolean validated = false;
2049 <                try {              // split to lo and hi lists; copying as needed
2050 <                    if (tabAt(tab, i) == f) {
2051 <                        validated = true;
2052 <                        splitBin(nextTab, i, f);
2053 <                        setTabAt(tab, i, fwd);
2054 <                    }
2055 <                } finally {
2056 <                    if (!f.casHash(fh | LOCKED, fh)) {
2057 <                        f.hash = fh;
2058 <                        synchronized (f) { f.notifyAll(); };
2059 <                    }
2060 <                }
2061 <                if (!validated)
2062 <                    continue;
2063 <            }
2064 <            else {
2065 <                if (buffer == null) // initialize buffer for revisits
2066 <                    buffer = new int[TRANSFER_BUFFER_SIZE];
2067 <                if (bin < 0 && bufferIndex > 0) {
2068 <                    int j = buffer[--bufferIndex];
2069 <                    buffer[bufferIndex] = i;
2070 <                    i = j;         // swap with another bin
2071 <                    continue;
2072 <                }
2073 <                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2074 <                    f.tryAwaitLock(tab, i);
2075 <                    continue;      // no other options -- block
2076 <                }
2077 <                if (rev == null)   // initialize reverse-forwarder
2078 <                    rev = new Node(MOVED, tab, null, null);
2079 <                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2080 <                    continue;      // recheck before adding to list
2081 <                buffer[nbuffered++] = i;
2082 <                setTabAt(nextTab, i, rev);     // install place-holders
2083 <                setTabAt(nextTab, i + n, rev);
2084 <            }
2085 <
2086 <            if (bin > 0)
2087 <                i = --bin;
2088 <            else if (buffer != null && nbuffered > 0) {
2089 <                bin = -1;
2090 <                i = buffer[bufferIndex = --nbuffered];
2091 <            }
2092 <            else
2093 <                return nextTab;
2094 <        }
2095 <    }
775 >    private transient volatile long baseCount;
776  
777      /**
778 <     * Splits a normal bin with list headed by e into lo and hi parts;
779 <     * installs in given table.
778 >     * Table initialization and resizing control.  When negative, the
779 >     * table is being initialized or resized: -1 for initialization,
780 >     * else -(1 + the number of active resizing threads).  Otherwise,
781 >     * when table is null, holds the initial table size to use upon
782 >     * creation, or 0 for default. After initialization, holds the
783 >     * next element count value upon which to resize the table.
784       */
785 <    private static void splitBin(Node[] nextTab, int i, Node e) {
2102 <        int bit = nextTab.length >>> 1; // bit to split on
2103 <        int runBit = e.hash & bit;
2104 <        Node lastRun = e, lo = null, hi = null;
2105 <        for (Node p = e.next; p != null; p = p.next) {
2106 <            int b = p.hash & bit;
2107 <            if (b != runBit) {
2108 <                runBit = b;
2109 <                lastRun = p;
2110 <            }
2111 <        }
2112 <        if (runBit == 0)
2113 <            lo = lastRun;
2114 <        else
2115 <            hi = lastRun;
2116 <        for (Node p = e; p != lastRun; p = p.next) {
2117 <            int ph = p.hash & HASH_BITS;
2118 <            Object pk = p.key, pv = p.val;
2119 <            if ((ph & bit) == 0)
2120 <                lo = new Node(ph, pk, pv, lo);
2121 <            else
2122 <                hi = new Node(ph, pk, pv, hi);
2123 <        }
2124 <        setTabAt(nextTab, i, lo);
2125 <        setTabAt(nextTab, i + bit, hi);
2126 <    }
785 >    private transient volatile int sizeCtl;
786  
787      /**
788 <     * Splits a tree bin into lo and hi parts; installs in given table.
788 >     * The next table index (plus one) to split while resizing.
789       */
790 <    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2132 <        int bit = nextTab.length >>> 1;
2133 <        TreeBin lt = new TreeBin();
2134 <        TreeBin ht = new TreeBin();
2135 <        int lc = 0, hc = 0;
2136 <        for (Node e = t.first; e != null; e = e.next) {
2137 <            int h = e.hash & HASH_BITS;
2138 <            Object k = e.key, v = e.val;
2139 <            if ((h & bit) == 0) {
2140 <                ++lc;
2141 <                lt.putTreeNode(h, k, v);
2142 <            }
2143 <            else {
2144 <                ++hc;
2145 <                ht.putTreeNode(h, k, v);
2146 <            }
2147 <        }
2148 <        Node ln, hn; // throw away trees if too small
2149 <        if (lc <= (TREE_THRESHOLD >>> 1)) {
2150 <            ln = null;
2151 <            for (Node p = lt.first; p != null; p = p.next)
2152 <                ln = new Node(p.hash, p.key, p.val, ln);
2153 <        }
2154 <        else
2155 <            ln = new Node(MOVED, lt, null, null);
2156 <        setTabAt(nextTab, i, ln);
2157 <        if (hc <= (TREE_THRESHOLD >>> 1)) {
2158 <            hn = null;
2159 <            for (Node p = ht.first; p != null; p = p.next)
2160 <                hn = new Node(p.hash, p.key, p.val, hn);
2161 <        }
2162 <        else
2163 <            hn = new Node(MOVED, ht, null, null);
2164 <        setTabAt(nextTab, i + bit, hn);
2165 <    }
790 >    private transient volatile int transferIndex;
791  
792      /**
793 <     * Implementation for clear. Steps through each bin, removing all
2169 <     * nodes.
793 >     * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
794       */
795 <    private final void internalClear() {
2172 <        long delta = 0L; // negative number of deletions
2173 <        int i = 0;
2174 <        Node[] tab = table;
2175 <        while (tab != null && i < tab.length) {
2176 <            int fh; Object fk;
2177 <            Node f = tabAt(tab, i);
2178 <            if (f == null)
2179 <                ++i;
2180 <            else if ((fh = f.hash) == MOVED) {
2181 <                if ((fk = f.key) instanceof TreeBin) {
2182 <                    TreeBin t = (TreeBin)fk;
2183 <                    t.acquire(0);
2184 <                    try {
2185 <                        if (tabAt(tab, i) == f) {
2186 <                            for (Node p = t.first; p != null; p = p.next) {
2187 <                                p.val = null;
2188 <                                --delta;
2189 <                            }
2190 <                            t.first = null;
2191 <                            t.root = null;
2192 <                            ++i;
2193 <                        }
2194 <                    } finally {
2195 <                        t.release(0);
2196 <                    }
2197 <                }
2198 <                else
2199 <                    tab = (Node[])fk;
2200 <            }
2201 <            else if ((fh & LOCKED) != 0) {
2202 <                counter.add(delta); // opportunistically update count
2203 <                delta = 0L;
2204 <                f.tryAwaitLock(tab, i);
2205 <            }
2206 <            else if (f.casHash(fh, fh | LOCKED)) {
2207 <                try {
2208 <                    if (tabAt(tab, i) == f) {
2209 <                        for (Node e = f; e != null; e = e.next) {
2210 <                            e.val = null;
2211 <                            --delta;
2212 <                        }
2213 <                        setTabAt(tab, i, null);
2214 <                        ++i;
2215 <                    }
2216 <                } finally {
2217 <                    if (!f.casHash(fh | LOCKED, fh)) {
2218 <                        f.hash = fh;
2219 <                        synchronized (f) { f.notifyAll(); };
2220 <                    }
2221 <                }
2222 <            }
2223 <        }
2224 <        if (delta != 0)
2225 <            counter.add(delta);
2226 <    }
2227 <
2228 <    /* ----------------Table Traversal -------------- */
795 >    private transient volatile int cellsBusy;
796  
797      /**
798 <     * Encapsulates traversal for methods such as containsValue; also
2232 <     * serves as a base class for other iterators and bulk tasks.
2233 <     *
2234 <     * At each step, the iterator snapshots the key ("nextKey") and
2235 <     * value ("nextVal") of a valid node (i.e., one that, at point of
2236 <     * snapshot, has a non-null user value). Because val fields can
2237 <     * change (including to null, indicating deletion), field nextVal
2238 <     * might not be accurate at point of use, but still maintains the
2239 <     * weak consistency property of holding a value that was once
2240 <     * valid.
2241 <     *
2242 <     * Internal traversals directly access these fields, as in:
2243 <     * {@code while (it.advance() != null) { process(it.nextKey); }}
2244 <     *
2245 <     * Exported iterators must track whether the iterator has advanced
2246 <     * (in hasNext vs next) (by setting/checking/nulling field
2247 <     * nextVal), and then extract key, value, or key-value pairs as
2248 <     * return values of next().
2249 <     *
2250 <     * The iterator visits once each still-valid node that was
2251 <     * reachable upon iterator construction. It might miss some that
2252 <     * were added to a bin after the bin was visited, which is OK wrt
2253 <     * consistency guarantees. Maintaining this property in the face
2254 <     * of possible ongoing resizes requires a fair amount of
2255 <     * bookkeeping state that is difficult to optimize away amidst
2256 <     * volatile accesses.  Even so, traversal maintains reasonable
2257 <     * throughput.
2258 <     *
2259 <     * Normally, iteration proceeds bin-by-bin traversing lists.
2260 <     * However, if the table has been resized, then all future steps
2261 <     * must traverse both the bin at the current index as well as at
2262 <     * (index + baseSize); and so on for further resizings. To
2263 <     * paranoically cope with potential sharing by users of iterators
2264 <     * across threads, iteration terminates if a bounds checks fails
2265 <     * for a table read.
2266 <     *
2267 <     * This class extends ForkJoinTask to streamline parallel
2268 <     * iteration in bulk operations (see BulkTask). This adds only an
2269 <     * int of space overhead, which is close enough to negligible in
2270 <     * cases where it is not needed to not worry about it.  Because
2271 <     * ForkJoinTask is Serializable, but iterators need not be, we
2272 <     * need to add warning suppressions.
798 >     * Table of counter cells. When non-null, size is a power of 2.
799       */
800 <    @SuppressWarnings("serial")
2275 <    static class Traverser<K,V,R> extends ForkJoinTask<R> {
2276 <        final ConcurrentHashMapV8<K, V> map;
2277 <        Node next;           // the next entry to use
2278 <        Node last;           // the last entry used
2279 <        Object nextKey;      // cached key field of next
2280 <        Object nextVal;      // cached val field of next
2281 <        Node[] tab;          // current table; updated if resized
2282 <        int index;           // index of bin to use next
2283 <        int baseIndex;       // current index of initial table
2284 <        int baseLimit;       // index bound for initial table
2285 <        final int baseSize;  // initial table size
2286 <
2287 <        /** Creates iterator for all entries in the table. */
2288 <        Traverser(ConcurrentHashMapV8<K, V> map) {
2289 <            this.tab = (this.map = map).table;
2290 <            baseLimit = baseSize = (tab == null) ? 0 : tab.length;
2291 <        }
2292 <
2293 <        /** Creates iterator for split() methods */
2294 <        Traverser(Traverser<K,V,?> it, boolean split) {
2295 <            this.map = it.map;
2296 <            this.tab = it.tab;
2297 <            this.baseSize = it.baseSize;
2298 <            int lo = it.baseIndex;
2299 <            int hi = this.baseLimit = it.baseLimit;
2300 <            int i;
2301 <            if (split) // adjust parent
2302 <                i = it.baseLimit = (lo + hi + 1) >>> 1;
2303 <            else       // clone parent
2304 <                i = lo;
2305 <            this.index = this.baseIndex = i;
2306 <        }
2307 <
2308 <        /**
2309 <         * Advances next; returns nextVal or null if terminated.
2310 <         * See above for explanation.
2311 <         */
2312 <        final Object advance() {
2313 <            Node e = last = next;
2314 <            Object ev = null;
2315 <            outer: do {
2316 <                if (e != null)                  // advance past used/skipped node
2317 <                    e = e.next;
2318 <                while (e == null) {             // get to next non-null bin
2319 <                    Node[] t; int b, i, n; Object ek; // checks must use locals
2320 <                    if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
2321 <                        (t = tab) == null || i >= (n = t.length))
2322 <                        break outer;
2323 <                    else if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2324 <                        if ((ek = e.key) instanceof TreeBin)
2325 <                            e = ((TreeBin)ek).first;
2326 <                        else {
2327 <                            tab = (Node[])ek;
2328 <                            continue;           // restarts due to null val
2329 <                        }
2330 <                    }                           // visit upper slots if present
2331 <                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2332 <                }
2333 <                nextKey = e.key;
2334 <            } while ((ev = e.val) == null);    // skip deleted or special nodes
2335 <            next = e;
2336 <            return nextVal = ev;
2337 <        }
2338 <
2339 <        public final void remove() {
2340 <            if (nextVal == null && last == null)
2341 <                advance();
2342 <            Node e = last;
2343 <            if (e == null)
2344 <                throw new IllegalStateException();
2345 <            last = null;
2346 <            map.remove(e.key);
2347 <        }
800 >    private transient volatile CounterCell[] counterCells;
801  
802 <        public final boolean hasNext() {
803 <            return nextVal != null || advance() != null;
804 <        }
802 >    // views
803 >    private transient KeySetView<K,V> keySet;
804 >    private transient ValuesView<K,V> values;
805 >    private transient EntrySetView<K,V> entrySet;
806  
2353        public final boolean hasMoreElements() { return hasNext(); }
2354        public final void setRawResult(Object x) { }
2355        public R getRawResult() { return null; }
2356        public boolean exec() { return true; }
2357    }
807  
808      /* ---------------- Public operations -------------- */
809  
# Line 2362 | Line 811 | public class ConcurrentHashMapV8<K, V>
811       * Creates a new, empty map with the default initial table size (16).
812       */
813      public ConcurrentHashMapV8() {
2365        this.counter = new LongAdder();
814      }
815  
816      /**
# Line 2381 | Line 829 | public class ConcurrentHashMapV8<K, V>
829          int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
830                     MAXIMUM_CAPACITY :
831                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2384        this.counter = new LongAdder();
832          this.sizeCtl = cap;
833      }
834  
# Line 2391 | Line 838 | public class ConcurrentHashMapV8<K, V>
838       * @param m the map
839       */
840      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2394        this.counter = new LongAdder();
841          this.sizeCtl = DEFAULT_CAPACITY;
842 <        internalPutAll(m);
842 >        putAll(m);
843      }
844  
845      /**
# Line 2434 | Line 880 | public class ConcurrentHashMapV8<K, V>
880       * nonpositive
881       */
882      public ConcurrentHashMapV8(int initialCapacity,
883 <                               float loadFactor, int concurrencyLevel) {
883 >                             float loadFactor, int concurrencyLevel) {
884          if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
885              throw new IllegalArgumentException();
886          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
# Line 2442 | Line 888 | public class ConcurrentHashMapV8<K, V>
888          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
889          int cap = (size >= (long)MAXIMUM_CAPACITY) ?
890              MAXIMUM_CAPACITY : tableSizeFor((int)size);
2445        this.counter = new LongAdder();
891          this.sizeCtl = cap;
892      }
893  
894 <    /**
2450 <     * {@inheritDoc}
2451 <     */
2452 <    public boolean isEmpty() {
2453 <        return counter.sum() <= 0L; // ignore transient negative values
2454 <    }
894 >    // Original (since JDK1.2) Map methods
895  
896      /**
897       * {@inheritDoc}
898       */
899      public int size() {
900 <        long n = counter.sum();
900 >        long n = sumCount();
901          return ((n < 0L) ? 0 :
902                  (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
903                  (int)n);
904      }
905  
906      /**
907 <     * Returns the number of mappings. This method should be used
2468 <     * instead of {@link #size} because a ConcurrentHashMap may
2469 <     * contain more mappings than can be represented as an int. The
2470 <     * value returned is a snapshot; the actual count may differ if
2471 <     * there are ongoing concurrent insertions of removals.
2472 <     *
2473 <     * @return the number of mappings
907 >     * {@inheritDoc}
908       */
909 <    public long mappingCount() {
910 <        long n = counter.sum();
2477 <        return (n < 0L) ? 0L : n; // ignore transient negative values
909 >    public boolean isEmpty() {
910 >        return sumCount() <= 0L; // ignore transient negative values
911      }
912  
913      /**
# Line 2488 | Line 921 | public class ConcurrentHashMapV8<K, V>
921       *
922       * @throws NullPointerException if the specified key is null
923       */
2491    @SuppressWarnings("unchecked")
924      public V get(Object key) {
925 <        if (key == null)
926 <            throw new NullPointerException();
927 <        return (V)internalGet(key);
925 >        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
926 >        int h = spread(key.hashCode());
927 >        if ((tab = table) != null && (n = tab.length) > 0 &&
928 >            (e = tabAt(tab, (n - 1) & h)) != null) {
929 >            if ((eh = e.hash) == h) {
930 >                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
931 >                    return e.val;
932 >            }
933 >            else if (eh < 0)
934 >                return (p = e.find(h, key)) != null ? p.val : null;
935 >            while ((e = e.next) != null) {
936 >                if (e.hash == h &&
937 >                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
938 >                    return e.val;
939 >            }
940 >        }
941 >        return null;
942      }
943  
944      /**
945       * Tests if the specified object is a key in this table.
946       *
947 <     * @param  key   possible key
947 >     * @param  key possible key
948       * @return {@code true} if and only if the specified object
949       *         is a key in this table, as determined by the
950       *         {@code equals} method; {@code false} otherwise
951       * @throws NullPointerException if the specified key is null
952       */
953      public boolean containsKey(Object key) {
954 <        if (key == null)
2509 <            throw new NullPointerException();
2510 <        return internalGet(key) != null;
954 >        return get(key) != null;
955      }
956  
957      /**
# Line 2523 | Line 967 | public class ConcurrentHashMapV8<K, V>
967      public boolean containsValue(Object value) {
968          if (value == null)
969              throw new NullPointerException();
970 <        Object v;
971 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
972 <        while ((v = it.advance()) != null) {
973 <            if (v == value || value.equals(v))
974 <                return true;
970 >        Node<K,V>[] t;
971 >        if ((t = table) != null) {
972 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
973 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
974 >                V v;
975 >                if ((v = p.val) == value || (v != null && value.equals(v)))
976 >                    return true;
977 >            }
978          }
979          return false;
980      }
981  
982      /**
2536     * Legacy method testing if some key maps into the specified value
2537     * in this table.  This method is identical in functionality to
2538     * {@link #containsValue}, and exists solely to ensure
2539     * full compatibility with class {@link java.util.Hashtable},
2540     * which supported this method prior to introduction of the
2541     * Java Collections framework.
2542     *
2543     * @param  value a value to search for
2544     * @return {@code true} if and only if some key maps to the
2545     *         {@code value} argument in this table as
2546     *         determined by the {@code equals} method;
2547     *         {@code false} otherwise
2548     * @throws NullPointerException if the specified value is null
2549     */
2550    public boolean contains(Object value) {
2551        return containsValue(value);
2552    }
2553
2554    /**
983       * Maps the specified key to the specified value in this table.
984       * Neither the key nor the value can be null.
985       *
986 <     * <p> The value can be retrieved by calling the {@code get} method
986 >     * <p>The value can be retrieved by calling the {@code get} method
987       * with a key that is equal to the original key.
988       *
989       * @param key key with which the specified value is to be associated
# Line 2564 | Line 992 | public class ConcurrentHashMapV8<K, V>
992       *         {@code null} if there was no mapping for {@code key}
993       * @throws NullPointerException if the specified key or value is null
994       */
2567    @SuppressWarnings("unchecked")
995      public V put(K key, V value) {
996 <        if (key == null || value == null)
2570 <            throw new NullPointerException();
2571 <        return (V)internalPut(key, value);
996 >        return putVal(key, value, false);
997      }
998  
999 <    /**
1000 <     * {@inheritDoc}
1001 <     *
1002 <     * @return the previous value associated with the specified key,
1003 <     *         or {@code null} if there was no mapping for the key
1004 <     * @throws NullPointerException if the specified key or value is null
1005 <     */
1006 <    @SuppressWarnings("unchecked")
1007 <    public V putIfAbsent(K key, V value) {
1008 <        if (key == null || value == null)
1009 <            throw new NullPointerException();
1010 <        return (V)internalPutIfAbsent(key, value);
999 >    /** Implementation for put and putIfAbsent */
1000 >    final V putVal(K key, V value, boolean onlyIfAbsent) {
1001 >        if (key == null || value == null) throw new NullPointerException();
1002 >        int hash = spread(key.hashCode());
1003 >        int binCount = 0;
1004 >        for (Node<K,V>[] tab = table;;) {
1005 >            Node<K,V> f; int n, i, fh;
1006 >            if (tab == null || (n = tab.length) == 0)
1007 >                tab = initTable();
1008 >            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1009 >                if (casTabAt(tab, i, null,
1010 >                             new Node<K,V>(hash, key, value, null)))
1011 >                    break;                   // no lock when adding to empty bin
1012 >            }
1013 >            else if ((fh = f.hash) == MOVED)
1014 >                tab = helpTransfer(tab, f);
1015 >            else {
1016 >                V oldVal = null;
1017 >                synchronized (f) {
1018 >                    if (tabAt(tab, i) == f) {
1019 >                        if (fh >= 0) {
1020 >                            binCount = 1;
1021 >                            for (Node<K,V> e = f;; ++binCount) {
1022 >                                K ek;
1023 >                                if (e.hash == hash &&
1024 >                                    ((ek = e.key) == key ||
1025 >                                     (ek != null && key.equals(ek)))) {
1026 >                                    oldVal = e.val;
1027 >                                    if (!onlyIfAbsent)
1028 >                                        e.val = value;
1029 >                                    break;
1030 >                                }
1031 >                                Node<K,V> pred = e;
1032 >                                if ((e = e.next) == null) {
1033 >                                    pred.next = new Node<K,V>(hash, key,
1034 >                                                              value, null);
1035 >                                    break;
1036 >                                }
1037 >                            }
1038 >                        }
1039 >                        else if (f instanceof TreeBin) {
1040 >                            Node<K,V> p;
1041 >                            binCount = 2;
1042 >                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
1043 >                                                           value)) != null) {
1044 >                                oldVal = p.val;
1045 >                                if (!onlyIfAbsent)
1046 >                                    p.val = value;
1047 >                            }
1048 >                        }
1049 >                    }
1050 >                }
1051 >                if (binCount != 0) {
1052 >                    if (binCount >= TREEIFY_THRESHOLD)
1053 >                        treeifyBin(tab, i);
1054 >                    if (oldVal != null)
1055 >                        return oldVal;
1056 >                    break;
1057 >                }
1058 >            }
1059 >        }
1060 >        addCount(1L, binCount);
1061 >        return null;
1062      }
1063  
1064      /**
# Line 2593 | Line 1069 | public class ConcurrentHashMapV8<K, V>
1069       * @param m mappings to be stored in this map
1070       */
1071      public void putAll(Map<? extends K, ? extends V> m) {
1072 <        internalPutAll(m);
1073 <    }
1074 <
2599 <    /**
2600 <     * If the specified key is not already associated with a value,
2601 <     * computes its value using the given mappingFunction and enters
2602 <     * it into the map unless null.  This is equivalent to
2603 <     * <pre> {@code
2604 <     * if (map.containsKey(key))
2605 <     *   return map.get(key);
2606 <     * value = mappingFunction.apply(key);
2607 <     * if (value != null)
2608 <     *   map.put(key, value);
2609 <     * return value;}</pre>
2610 <     *
2611 <     * except that the action is performed atomically.  If the
2612 <     * function returns {@code null} no mapping is recorded. If the
2613 <     * function itself throws an (unchecked) exception, the exception
2614 <     * is rethrown to its caller, and no mapping is recorded.  Some
2615 <     * attempted update operations on this map by other threads may be
2616 <     * blocked while computation is in progress, so the computation
2617 <     * should be short and simple, and must not attempt to update any
2618 <     * other mappings of this Map. The most appropriate usage is to
2619 <     * construct a new object serving as an initial mapped value, or
2620 <     * memoized result, as in:
2621 <     *
2622 <     *  <pre> {@code
2623 <     * map.computeIfAbsent(key, new Fun<K, V>() {
2624 <     *   public V map(K k) { return new Value(f(k)); }});}</pre>
2625 <     *
2626 <     * @param key key with which the specified value is to be associated
2627 <     * @param mappingFunction the function to compute a value
2628 <     * @return the current (existing or computed) value associated with
2629 <     *         the specified key, or null if the computed value is null.
2630 <     * @throws NullPointerException if the specified key or mappingFunction
2631 <     *         is null
2632 <     * @throws IllegalStateException if the computation detectably
2633 <     *         attempts a recursive update to this map that would
2634 <     *         otherwise never complete
2635 <     * @throws RuntimeException or Error if the mappingFunction does so,
2636 <     *         in which case the mapping is left unestablished
2637 <     */
2638 <    @SuppressWarnings("unchecked")
2639 <    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
2640 <        if (key == null || mappingFunction == null)
2641 <            throw new NullPointerException();
2642 <        return (V)internalComputeIfAbsent(key, mappingFunction);
2643 <    }
2644 <
2645 <    /**
2646 <     * If the given key is present, computes a new mapping value given a key and
2647 <     * its current mapped value. This is equivalent to
2648 <     *  <pre> {@code
2649 <     *   if (map.containsKey(key)) {
2650 <     *     value = remappingFunction.apply(key, map.get(key));
2651 <     *     if (value != null)
2652 <     *       map.put(key, value);
2653 <     *     else
2654 <     *       map.remove(key);
2655 <     *   }
2656 <     * }</pre>
2657 <     *
2658 <     * except that the action is performed atomically.  If the
2659 <     * function returns {@code null}, the mapping is removed.  If the
2660 <     * function itself throws an (unchecked) exception, the exception
2661 <     * is rethrown to its caller, and the current mapping is left
2662 <     * unchanged.  Some attempted update operations on this map by
2663 <     * other threads may be blocked while computation is in progress,
2664 <     * so the computation should be short and simple, and must not
2665 <     * attempt to update any other mappings of this Map. For example,
2666 <     * to either create or append new messages to a value mapping:
2667 <     *
2668 <     * @param key key with which the specified value is to be associated
2669 <     * @param remappingFunction the function to compute a value
2670 <     * @return the new value associated with the specified key, or null if none
2671 <     * @throws NullPointerException if the specified key or remappingFunction
2672 <     *         is null
2673 <     * @throws IllegalStateException if the computation detectably
2674 <     *         attempts a recursive update to this map that would
2675 <     *         otherwise never complete
2676 <     * @throws RuntimeException or Error if the remappingFunction does so,
2677 <     *         in which case the mapping is unchanged
2678 <     */
2679 <    @SuppressWarnings("unchecked")
2680 <    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2681 <        if (key == null || remappingFunction == null)
2682 <            throw new NullPointerException();
2683 <        return (V)internalCompute(key, true, remappingFunction);
2684 <    }
2685 <
2686 <    /**
2687 <     * Computes a new mapping value given a key and
2688 <     * its current mapped value (or {@code null} if there is no current
2689 <     * mapping). This is equivalent to
2690 <     *  <pre> {@code
2691 <     *   value = remappingFunction.apply(key, map.get(key));
2692 <     *   if (value != null)
2693 <     *     map.put(key, value);
2694 <     *   else
2695 <     *     map.remove(key);
2696 <     * }</pre>
2697 <     *
2698 <     * except that the action is performed atomically.  If the
2699 <     * function returns {@code null}, the mapping is removed.  If the
2700 <     * function itself throws an (unchecked) exception, the exception
2701 <     * is rethrown to its caller, and the current mapping is left
2702 <     * unchanged.  Some attempted update operations on this map by
2703 <     * other threads may be blocked while computation is in progress,
2704 <     * so the computation should be short and simple, and must not
2705 <     * attempt to update any other mappings of this Map. For example,
2706 <     * to either create or append new messages to a value mapping:
2707 <     *
2708 <     * <pre> {@code
2709 <     * Map<Key, String> map = ...;
2710 <     * final String msg = ...;
2711 <     * map.compute(key, new BiFun<Key, String, String>() {
2712 <     *   public String apply(Key k, String v) {
2713 <     *    return (v == null) ? msg : v + msg;});}}</pre>
2714 <     *
2715 <     * @param key key with which the specified value is to be associated
2716 <     * @param remappingFunction the function to compute a value
2717 <     * @return the new value associated with the specified key, or null if none
2718 <     * @throws NullPointerException if the specified key or remappingFunction
2719 <     *         is null
2720 <     * @throws IllegalStateException if the computation detectably
2721 <     *         attempts a recursive update to this map that would
2722 <     *         otherwise never complete
2723 <     * @throws RuntimeException or Error if the remappingFunction does so,
2724 <     *         in which case the mapping is unchanged
2725 <     */
2726 <    @SuppressWarnings("unchecked")
2727 <    public V compute(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2728 <        if (key == null || remappingFunction == null)
2729 <            throw new NullPointerException();
2730 <        return (V)internalCompute(key, false, remappingFunction);
2731 <    }
2732 <
2733 <    /**
2734 <     * If the specified key is not already associated
2735 <     * with a value, associate it with the given value.
2736 <     * Otherwise, replace the value with the results of
2737 <     * the given remapping function. This is equivalent to:
2738 <     *  <pre> {@code
2739 <     *   if (!map.containsKey(key))
2740 <     *     map.put(value);
2741 <     *   else {
2742 <     *     newValue = remappingFunction.apply(map.get(key), value);
2743 <     *     if (value != null)
2744 <     *       map.put(key, value);
2745 <     *     else
2746 <     *       map.remove(key);
2747 <     *   }
2748 <     * }</pre>
2749 <     * except that the action is performed atomically.  If the
2750 <     * function returns {@code null}, the mapping is removed.  If the
2751 <     * function itself throws an (unchecked) exception, the exception
2752 <     * is rethrown to its caller, and the current mapping is left
2753 <     * unchanged.  Some attempted update operations on this map by
2754 <     * other threads may be blocked while computation is in progress,
2755 <     * so the computation should be short and simple, and must not
2756 <     * attempt to update any other mappings of this Map.
2757 <     */
2758 <    @SuppressWarnings("unchecked")
2759 <    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2760 <        if (key == null || value == null || remappingFunction == null)
2761 <            throw new NullPointerException();
2762 <        return (V)internalMerge(key, value, remappingFunction);
1072 >        tryPresize(m.size());
1073 >        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1074 >            putVal(e.getKey(), e.getValue(), false);
1075      }
1076  
1077      /**
# Line 2771 | Line 1083 | public class ConcurrentHashMapV8<K, V>
1083       *         {@code null} if there was no mapping for {@code key}
1084       * @throws NullPointerException if the specified key is null
1085       */
1086 <    @SuppressWarnings("unchecked")
1087 <        public V remove(Object key) {
2776 <        if (key == null)
2777 <            throw new NullPointerException();
2778 <        return (V)internalReplace(key, null, null);
1086 >    public V remove(Object key) {
1087 >        return replaceNode(key, null, null);
1088      }
1089  
1090      /**
1091 <     * {@inheritDoc}
1092 <     *
1093 <     * @throws NullPointerException if the specified key is null
2785 <     */
2786 <    public boolean remove(Object key, Object value) {
2787 <        if (key == null)
2788 <            throw new NullPointerException();
2789 <        if (value == null)
2790 <            return false;
2791 <        return internalReplace(key, null, value) != null;
2792 <    }
2793 <
2794 <    /**
2795 <     * {@inheritDoc}
2796 <     *
2797 <     * @throws NullPointerException if any of the arguments are null
2798 <     */
2799 <    public boolean replace(K key, V oldValue, V newValue) {
2800 <        if (key == null || oldValue == null || newValue == null)
2801 <            throw new NullPointerException();
2802 <        return internalReplace(key, newValue, oldValue) != null;
2803 <    }
2804 <
2805 <    /**
2806 <     * {@inheritDoc}
2807 <     *
2808 <     * @return the previous value associated with the specified key,
2809 <     *         or {@code null} if there was no mapping for the key
2810 <     * @throws NullPointerException if the specified key or value is null
1091 >     * Implementation for the four public remove/replace methods:
1092 >     * Replaces node value with v, conditional upon match of cv if
1093 >     * non-null.  If resulting value is null, delete.
1094       */
1095 <    @SuppressWarnings("unchecked")
1096 <        public V replace(K key, V value) {
1097 <        if (key == null || value == null)
1098 <            throw new NullPointerException();
1099 <        return (V)internalReplace(key, value, null);
1095 >    final V replaceNode(Object key, V value, Object cv) {
1096 >        int hash = spread(key.hashCode());
1097 >        for (Node<K,V>[] tab = table;;) {
1098 >            Node<K,V> f; int n, i, fh;
1099 >            if (tab == null || (n = tab.length) == 0 ||
1100 >                (f = tabAt(tab, i = (n - 1) & hash)) == null)
1101 >                break;
1102 >            else if ((fh = f.hash) == MOVED)
1103 >                tab = helpTransfer(tab, f);
1104 >            else {
1105 >                V oldVal = null;
1106 >                boolean validated = false;
1107 >                synchronized (f) {
1108 >                    if (tabAt(tab, i) == f) {
1109 >                        if (fh >= 0) {
1110 >                            validated = true;
1111 >                            for (Node<K,V> e = f, pred = null;;) {
1112 >                                K ek;
1113 >                                if (e.hash == hash &&
1114 >                                    ((ek = e.key) == key ||
1115 >                                     (ek != null && key.equals(ek)))) {
1116 >                                    V ev = e.val;
1117 >                                    if (cv == null || cv == ev ||
1118 >                                        (ev != null && cv.equals(ev))) {
1119 >                                        oldVal = ev;
1120 >                                        if (value != null)
1121 >                                            e.val = value;
1122 >                                        else if (pred != null)
1123 >                                            pred.next = e.next;
1124 >                                        else
1125 >                                            setTabAt(tab, i, e.next);
1126 >                                    }
1127 >                                    break;
1128 >                                }
1129 >                                pred = e;
1130 >                                if ((e = e.next) == null)
1131 >                                    break;
1132 >                            }
1133 >                        }
1134 >                        else if (f instanceof TreeBin) {
1135 >                            validated = true;
1136 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1137 >                            TreeNode<K,V> r, p;
1138 >                            if ((r = t.root) != null &&
1139 >                                (p = r.findTreeNode(hash, key, null)) != null) {
1140 >                                V pv = p.val;
1141 >                                if (cv == null || cv == pv ||
1142 >                                    (pv != null && cv.equals(pv))) {
1143 >                                    oldVal = pv;
1144 >                                    if (value != null)
1145 >                                        p.val = value;
1146 >                                    else if (t.removeTreeNode(p))
1147 >                                        setTabAt(tab, i, untreeify(t.first));
1148 >                                }
1149 >                            }
1150 >                        }
1151 >                    }
1152 >                }
1153 >                if (validated) {
1154 >                    if (oldVal != null) {
1155 >                        if (value == null)
1156 >                            addCount(-1L, -1);
1157 >                        return oldVal;
1158 >                    }
1159 >                    break;
1160 >                }
1161 >            }
1162 >        }
1163 >        return null;
1164      }
1165  
1166      /**
1167       * Removes all of the mappings from this map.
1168       */
1169      public void clear() {
1170 <        internalClear();
1170 >        long delta = 0L; // negative number of deletions
1171 >        int i = 0;
1172 >        Node<K,V>[] tab = table;
1173 >        while (tab != null && i < tab.length) {
1174 >            int fh;
1175 >            Node<K,V> f = tabAt(tab, i);
1176 >            if (f == null)
1177 >                ++i;
1178 >            else if ((fh = f.hash) == MOVED) {
1179 >                tab = helpTransfer(tab, f);
1180 >                i = 0; // restart
1181 >            }
1182 >            else {
1183 >                synchronized (f) {
1184 >                    if (tabAt(tab, i) == f) {
1185 >                        Node<K,V> p = (fh >= 0 ? f :
1186 >                                       (f instanceof TreeBin) ?
1187 >                                       ((TreeBin<K,V>)f).first : null);
1188 >                        while (p != null) {
1189 >                            --delta;
1190 >                            p = p.next;
1191 >                        }
1192 >                        setTabAt(tab, i++, null);
1193 >                    }
1194 >                }
1195 >            }
1196 >        }
1197 >        if (delta != 0L)
1198 >            addCount(delta, -1);
1199      }
1200  
1201      /**
1202       * Returns a {@link Set} view of the keys contained in this map.
1203       * The set is backed by the map, so changes to the map are
1204 <     * reflected in the set, and vice-versa.  The set supports element
1204 >     * reflected in the set, and vice-versa. The set supports element
1205       * removal, which removes the corresponding mapping from this map,
1206       * via the {@code Iterator.remove}, {@code Set.remove},
1207       * {@code removeAll}, {@code retainAll}, and {@code clear}
# Line 2838 | Line 1213 | public class ConcurrentHashMapV8<K, V>
1213       * and guarantees to traverse elements as they existed upon
1214       * construction of the iterator, and may (but is not guaranteed to)
1215       * reflect any modifications subsequent to construction.
1216 +     *
1217 +     * @return the set view
1218       */
1219 <    public Set<K> keySet() {
1220 <        KeySet<K,V> ks = keySet;
1221 <        return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
1219 >    public KeySetView<K,V> keySet() {
1220 >        KeySetView<K,V> ks;
1221 >        return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1222      }
1223  
1224      /**
# Line 2859 | Line 1236 | public class ConcurrentHashMapV8<K, V>
1236       * and guarantees to traverse elements as they existed upon
1237       * construction of the iterator, and may (but is not guaranteed to)
1238       * reflect any modifications subsequent to construction.
1239 +     *
1240 +     * @return the collection view
1241       */
1242      public Collection<V> values() {
1243 <        Values<K,V> vs = values;
1244 <        return (vs != null) ? vs : (values = new Values<K,V>(this));
1243 >        ValuesView<K,V> vs;
1244 >        return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1245      }
1246  
1247      /**
# Line 2872 | Line 1251 | public class ConcurrentHashMapV8<K, V>
1251       * removal, which removes the corresponding mapping from the map,
1252       * via the {@code Iterator.remove}, {@code Set.remove},
1253       * {@code removeAll}, {@code retainAll}, and {@code clear}
1254 <     * operations.  It does not support the {@code add} or
2876 <     * {@code addAll} operations.
1254 >     * operations.
1255       *
1256       * <p>The view's {@code iterator} is a "weakly consistent" iterator
1257       * that will never throw {@link ConcurrentModificationException},
1258       * and guarantees to traverse elements as they existed upon
1259       * construction of the iterator, and may (but is not guaranteed to)
1260       * reflect any modifications subsequent to construction.
2883     */
2884    public Set<Map.Entry<K,V>> entrySet() {
2885        EntrySet<K,V> es = entrySet;
2886        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2887    }
2888
2889    /**
2890     * Returns an enumeration of the keys in this table.
1261       *
1262 <     * @return an enumeration of the keys in this table
2893 <     * @see #keySet()
1262 >     * @return the set view
1263       */
1264 <    public Enumeration<K> keys() {
1265 <        return new KeyIterator<K,V>(this);
1266 <    }
2898 <
2899 <    /**
2900 <     * Returns an enumeration of the values in this table.
2901 <     *
2902 <     * @return an enumeration of the values in this table
2903 <     * @see #values()
2904 <     */
2905 <    public Enumeration<V> elements() {
2906 <        return new ValueIterator<K,V>(this);
2907 <    }
2908 <
2909 <    /**
2910 <     * Returns a partitionable iterator of the keys in this map.
2911 <     *
2912 <     * @return a partitionable iterator of the keys in this map
2913 <     */
2914 <    public Spliterator<K> keySpliterator() {
2915 <        return new KeyIterator<K,V>(this);
2916 <    }
2917 <
2918 <    /**
2919 <     * Returns a partitionable iterator of the values in this map.
2920 <     *
2921 <     * @return a partitionable iterator of the values in this map
2922 <     */
2923 <    public Spliterator<V> valueSpliterator() {
2924 <        return new ValueIterator<K,V>(this);
2925 <    }
2926 <
2927 <    /**
2928 <     * Returns a partitionable iterator of the entries in this map.
2929 <     *
2930 <     * @return a partitionable iterator of the entries in this map
2931 <     */
2932 <    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2933 <        return new EntryIterator<K,V>(this);
1264 >    public Set<Map.Entry<K,V>> entrySet() {
1265 >        EntrySetView<K,V> es;
1266 >        return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1267      }
1268  
1269      /**
# Line 2942 | Line 1275 | public class ConcurrentHashMapV8<K, V>
1275       */
1276      public int hashCode() {
1277          int h = 0;
1278 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1279 <        Object v;
1280 <        while ((v = it.advance()) != null) {
1281 <            h += it.nextKey.hashCode() ^ v.hashCode();
1278 >        Node<K,V>[] t;
1279 >        if ((t = table) != null) {
1280 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1281 >            for (Node<K,V> p; (p = it.advance()) != null; )
1282 >                h += p.key.hashCode() ^ p.val.hashCode();
1283          }
1284          return h;
1285      }
# Line 2962 | Line 1296 | public class ConcurrentHashMapV8<K, V>
1296       * @return a string representation of this map
1297       */
1298      public String toString() {
1299 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1299 >        Node<K,V>[] t;
1300 >        int f = (t = table) == null ? 0 : t.length;
1301 >        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1302          StringBuilder sb = new StringBuilder();
1303          sb.append('{');
1304 <        Object v;
1305 <        if ((v = it.advance()) != null) {
1304 >        Node<K,V> p;
1305 >        if ((p = it.advance()) != null) {
1306              for (;;) {
1307 <                Object k = it.nextKey;
1307 >                K k = p.key;
1308 >                V v = p.val;
1309                  sb.append(k == this ? "(this Map)" : k);
1310                  sb.append('=');
1311                  sb.append(v == this ? "(this Map)" : v);
1312 <                if ((v = it.advance()) == null)
1312 >                if ((p = it.advance()) == null)
1313                      break;
1314                  sb.append(',').append(' ');
1315              }
# Line 2995 | Line 1332 | public class ConcurrentHashMapV8<K, V>
1332              if (!(o instanceof Map))
1333                  return false;
1334              Map<?,?> m = (Map<?,?>) o;
1335 <            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
1336 <            Object val;
1337 <            while ((val = it.advance()) != null) {
1338 <                Object v = m.get(it.nextKey);
1335 >            Node<K,V>[] t;
1336 >            int f = (t = table) == null ? 0 : t.length;
1337 >            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1338 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1339 >                V val = p.val;
1340 >                Object v = m.get(p.key);
1341                  if (v == null || (v != val && !v.equals(val)))
1342                      return false;
1343              }
# Line 3006 | Line 1345 | public class ConcurrentHashMapV8<K, V>
1345                  Object mk, mv, v;
1346                  if ((mk = e.getKey()) == null ||
1347                      (mv = e.getValue()) == null ||
1348 <                    (v = internalGet(mk)) == null ||
1348 >                    (v = get(mk)) == null ||
1349                      (mv != v && !mv.equals(v)))
1350                      return false;
1351              }
# Line 3014 | Line 1353 | public class ConcurrentHashMapV8<K, V>
1353          return true;
1354      }
1355  
1356 <    /* ----------------Iterators -------------- */
1356 >    /**
1357 >     * Stripped-down version of helper class used in previous version,
1358 >     * declared for the sake of serialization compatibility
1359 >     */
1360 >    static class Segment<K,V> extends ReentrantLock implements Serializable {
1361 >        private static final long serialVersionUID = 2249069246763182397L;
1362 >        final float loadFactor;
1363 >        Segment(float lf) { this.loadFactor = lf; }
1364 >    }
1365  
1366 <    @SuppressWarnings("serial")
1367 <    static final class KeyIterator<K,V> extends Traverser<K,V,Object>
1368 <        implements Spliterator<K>, Enumeration<K> {
1369 <        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1370 <        KeyIterator(Traverser<K,V,Object> it, boolean split) {
1371 <            super(it, split);
1372 <        }
1373 <        public KeyIterator<K,V> split() {
1374 <            if (last != null || (next != null && nextVal == null))
1375 <                throw new IllegalStateException();
1376 <            return new KeyIterator<K,V>(this, true);
1377 <        }
1378 <        @SuppressWarnings("unchecked")
1379 <            public final K next() {
1380 <            if (nextVal == null && advance() == null)
1381 <                throw new NoSuchElementException();
1382 <            Object k = nextKey;
1383 <            nextVal = null;
1384 <            return (K) k;
1366 >    /**
1367 >     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
1368 >     * stream (i.e., serializes it).
1369 >     * @param s the stream
1370 >     * @throws java.io.IOException if an I/O error occurs
1371 >     * @serialData
1372 >     * the key (Object) and value (Object)
1373 >     * for each key-value mapping, followed by a null pair.
1374 >     * The key-value mappings are emitted in no particular order.
1375 >     */
1376 >    private void writeObject(java.io.ObjectOutputStream s)
1377 >        throws java.io.IOException {
1378 >        // For serialization compatibility
1379 >        // Emulate segment calculation from previous version of this class
1380 >        int sshift = 0;
1381 >        int ssize = 1;
1382 >        while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1383 >            ++sshift;
1384 >            ssize <<= 1;
1385 >        }
1386 >        int segmentShift = 32 - sshift;
1387 >        int segmentMask = ssize - 1;
1388 >        @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1389 >            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1390 >        for (int i = 0; i < segments.length; ++i)
1391 >            segments[i] = new Segment<K,V>(LOAD_FACTOR);
1392 >        s.putFields().put("segments", segments);
1393 >        s.putFields().put("segmentShift", segmentShift);
1394 >        s.putFields().put("segmentMask", segmentMask);
1395 >        s.writeFields();
1396 >
1397 >        Node<K,V>[] t;
1398 >        if ((t = table) != null) {
1399 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1400 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1401 >                s.writeObject(p.key);
1402 >                s.writeObject(p.val);
1403 >            }
1404          }
1405 <
1406 <        public final K nextElement() { return next(); }
1405 >        s.writeObject(null);
1406 >        s.writeObject(null);
1407 >        segments = null; // throw away
1408      }
1409  
1410 <    @SuppressWarnings("serial")
1411 <    static final class ValueIterator<K,V> extends Traverser<K,V,Object>
1412 <        implements Spliterator<V>, Enumeration<V> {
1413 <        ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1414 <        ValueIterator(Traverser<K,V,Object> it, boolean split) {
1415 <            super(it, split);
1416 <        }
1417 <        public ValueIterator<K,V> split() {
1418 <            if (last != null || (next != null && nextVal == null))
1419 <                throw new IllegalStateException();
1420 <            return new ValueIterator<K,V>(this, true);
1410 >    /**
1411 >     * Reconstitutes the instance from a stream (that is, deserializes it).
1412 >     * @param s the stream
1413 >     * @throws ClassNotFoundException if the class of a serialized object
1414 >     *         could not be found
1415 >     * @throws java.io.IOException if an I/O error occurs
1416 >     */
1417 >    private void readObject(java.io.ObjectInputStream s)
1418 >        throws java.io.IOException, ClassNotFoundException {
1419 >        /*
1420 >         * To improve performance in typical cases, we create nodes
1421 >         * while reading, then place in table once size is known.
1422 >         * However, we must also validate uniqueness and deal with
1423 >         * overpopulated bins while doing so, which requires
1424 >         * specialized versions of putVal mechanics.
1425 >         */
1426 >        sizeCtl = -1; // force exclusion for table construction
1427 >        s.defaultReadObject();
1428 >        long size = 0L;
1429 >        Node<K,V> p = null;
1430 >        for (;;) {
1431 >            @SuppressWarnings("unchecked") K k = (K) s.readObject();
1432 >            @SuppressWarnings("unchecked") V v = (V) s.readObject();
1433 >            if (k != null && v != null) {
1434 >                p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1435 >                ++size;
1436 >            }
1437 >            else
1438 >                break;
1439          }
1440 <
1441 <        @SuppressWarnings("unchecked")
1442 <            public final V next() {
1443 <            Object v;
1444 <            if ((v = nextVal) == null && (v = advance()) == null)
1445 <                throw new NoSuchElementException();
1446 <            nextVal = null;
1447 <            return (V) v;
1440 >        if (size == 0L)
1441 >            sizeCtl = 0;
1442 >        else {
1443 >            int n;
1444 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1445 >                n = MAXIMUM_CAPACITY;
1446 >            else {
1447 >                int sz = (int)size;
1448 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
1449 >            }
1450 >            @SuppressWarnings("unchecked")
1451 >                Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1452 >            int mask = n - 1;
1453 >            long added = 0L;
1454 >            while (p != null) {
1455 >                boolean insertAtFront;
1456 >                Node<K,V> next = p.next, first;
1457 >                int h = p.hash, j = h & mask;
1458 >                if ((first = tabAt(tab, j)) == null)
1459 >                    insertAtFront = true;
1460 >                else {
1461 >                    K k = p.key;
1462 >                    if (first.hash < 0) {
1463 >                        TreeBin<K,V> t = (TreeBin<K,V>)first;
1464 >                        if (t.putTreeVal(h, k, p.val) == null)
1465 >                            ++added;
1466 >                        insertAtFront = false;
1467 >                    }
1468 >                    else {
1469 >                        int binCount = 0;
1470 >                        insertAtFront = true;
1471 >                        Node<K,V> q; K qk;
1472 >                        for (q = first; q != null; q = q.next) {
1473 >                            if (q.hash == h &&
1474 >                                ((qk = q.key) == k ||
1475 >                                 (qk != null && k.equals(qk)))) {
1476 >                                insertAtFront = false;
1477 >                                break;
1478 >                            }
1479 >                            ++binCount;
1480 >                        }
1481 >                        if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1482 >                            insertAtFront = false;
1483 >                            ++added;
1484 >                            p.next = first;
1485 >                            TreeNode<K,V> hd = null, tl = null;
1486 >                            for (q = p; q != null; q = q.next) {
1487 >                                TreeNode<K,V> t = new TreeNode<K,V>
1488 >                                    (q.hash, q.key, q.val, null, null);
1489 >                                if ((t.prev = tl) == null)
1490 >                                    hd = t;
1491 >                                else
1492 >                                    tl.next = t;
1493 >                                tl = t;
1494 >                            }
1495 >                            setTabAt(tab, j, new TreeBin<K,V>(hd));
1496 >                        }
1497 >                    }
1498 >                }
1499 >                if (insertAtFront) {
1500 >                    ++added;
1501 >                    p.next = first;
1502 >                    setTabAt(tab, j, p);
1503 >                }
1504 >                p = next;
1505 >            }
1506 >            table = tab;
1507 >            sizeCtl = n - (n >>> 2);
1508 >            baseCount = added;
1509          }
3064
3065        public final V nextElement() { return next(); }
1510      }
1511  
1512 <    @SuppressWarnings("serial")
3069 <    static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3070 <        implements Spliterator<Map.Entry<K,V>> {
3071 <        EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3072 <        EntryIterator(Traverser<K,V,Object> it, boolean split) {
3073 <            super(it, split);
3074 <        }
3075 <        public EntryIterator<K,V> split() {
3076 <            if (last != null || (next != null && nextVal == null))
3077 <                throw new IllegalStateException();
3078 <            return new EntryIterator<K,V>(this, true);
3079 <        }
1512 >    // ConcurrentMap methods
1513  
1514 <        @SuppressWarnings("unchecked")
1515 <            public final Map.Entry<K,V> next() {
1516 <            Object v;
1517 <            if ((v = nextVal) == null && (v = advance()) == null)
1518 <                throw new NoSuchElementException();
1519 <            Object k = nextKey;
1520 <            nextVal = null;
1521 <            return new MapEntry<K,V>((K)k, (V)v, map);
1522 <        }
1514 >    /**
1515 >     * {@inheritDoc}
1516 >     *
1517 >     * @return the previous value associated with the specified key,
1518 >     *         or {@code null} if there was no mapping for the key
1519 >     * @throws NullPointerException if the specified key or value is null
1520 >     */
1521 >    public V putIfAbsent(K key, V value) {
1522 >        return putVal(key, value, true);
1523      }
1524  
1525      /**
1526 <     * Exported Entry for iterators
1526 >     * {@inheritDoc}
1527 >     *
1528 >     * @throws NullPointerException if the specified key is null
1529       */
1530 <    static final class MapEntry<K,V> implements Map.Entry<K, V> {
1531 <        final K key; // non-null
1532 <        V val;       // non-null
1533 <        final ConcurrentHashMapV8<K, V> map;
3099 <        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3100 <            this.key = key;
3101 <            this.val = val;
3102 <            this.map = map;
3103 <        }
3104 <        public final K getKey()       { return key; }
3105 <        public final V getValue()     { return val; }
3106 <        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3107 <        public final String toString(){ return key + "=" + val; }
3108 <
3109 <        public final boolean equals(Object o) {
3110 <            Object k, v; Map.Entry<?,?> e;
3111 <            return ((o instanceof Map.Entry) &&
3112 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3113 <                    (v = e.getValue()) != null &&
3114 <                    (k == key || k.equals(key)) &&
3115 <                    (v == val || v.equals(val)));
3116 <        }
3117 <
3118 <        /**
3119 <         * Sets our entry's value and writes through to the map. The
3120 <         * value to return is somewhat arbitrary here. Since we do not
3121 <         * necessarily track asynchronous changes, the most recent
3122 <         * "previous" value could be different from what we return (or
3123 <         * could even have been removed in which case the put will
3124 <         * re-establish). We do not and cannot guarantee more.
3125 <         */
3126 <        public final V setValue(V value) {
3127 <            if (value == null) throw new NullPointerException();
3128 <            V v = val;
3129 <            val = value;
3130 <            map.put(key, value);
3131 <            return v;
3132 <        }
1530 >    public boolean remove(Object key, Object value) {
1531 >        if (key == null)
1532 >            throw new NullPointerException();
1533 >        return value != null && replaceNode(key, null, value) != null;
1534      }
1535  
1536 <    /* ----------------Views -------------- */
1536 >    /**
1537 >     * {@inheritDoc}
1538 >     *
1539 >     * @throws NullPointerException if any of the arguments are null
1540 >     */
1541 >    public boolean replace(K key, V oldValue, V newValue) {
1542 >        if (key == null || oldValue == null || newValue == null)
1543 >            throw new NullPointerException();
1544 >        return replaceNode(key, newValue, oldValue) != null;
1545 >    }
1546  
1547      /**
1548 <     * Base class for views.
1548 >     * {@inheritDoc}
1549 >     *
1550 >     * @return the previous value associated with the specified key,
1551 >     *         or {@code null} if there was no mapping for the key
1552 >     * @throws NullPointerException if the specified key or value is null
1553       */
1554 <    static abstract class CHMView<K, V> {
1555 <        final ConcurrentHashMapV8<K, V> map;
1556 <        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
1557 <        public final int size()                 { return map.size(); }
1558 <        public final boolean isEmpty()          { return map.isEmpty(); }
3145 <        public final void clear()               { map.clear(); }
1554 >    public V replace(K key, V value) {
1555 >        if (key == null || value == null)
1556 >            throw new NullPointerException();
1557 >        return replaceNode(key, value, null);
1558 >    }
1559  
1560 <        // implementations below rely on concrete classes supplying these
3148 <        abstract public Iterator<?> iterator();
3149 <        abstract public boolean contains(Object o);
3150 <        abstract public boolean remove(Object o);
1560 >    // Overrides of JDK8+ Map extension method defaults
1561  
1562 <        private static final String oomeMsg = "Required array size too large";
1562 >    /**
1563 >     * Returns the value to which the specified key is mapped, or the
1564 >     * given default value if this map contains no mapping for the
1565 >     * key.
1566 >     *
1567 >     * @param key the key whose associated value is to be returned
1568 >     * @param defaultValue the value to return if this map contains
1569 >     * no mapping for the given key
1570 >     * @return the mapping for the key, if present; else the default value
1571 >     * @throws NullPointerException if the specified key is null
1572 >     */
1573 >    public V getOrDefault(Object key, V defaultValue) {
1574 >        V v;
1575 >        return (v = get(key)) == null ? defaultValue : v;
1576 >    }
1577 >
1578 >    public void forEach(BiAction<? super K, ? super V> action) {
1579 >        if (action == null) throw new NullPointerException();
1580 >        Node<K,V>[] t;
1581 >        if ((t = table) != null) {
1582 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1583 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1584 >                action.apply(p.key, p.val);
1585 >            }
1586 >        }
1587 >    }
1588  
1589 <        public final Object[] toArray() {
1590 <            long sz = map.mappingCount();
1591 <            if (sz > (long)(MAX_ARRAY_SIZE))
1592 <                throw new OutOfMemoryError(oomeMsg);
1593 <            int n = (int)sz;
1594 <            Object[] r = new Object[n];
1595 <            int i = 0;
1596 <            Iterator<?> it = iterator();
1597 <            while (it.hasNext()) {
1598 <                if (i == n) {
1599 <                    if (n >= MAX_ARRAY_SIZE)
1600 <                        throw new OutOfMemoryError(oomeMsg);
1601 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1602 <                        n = MAX_ARRAY_SIZE;
3168 <                    else
3169 <                        n += (n >>> 1) + 1;
3170 <                    r = Arrays.copyOf(r, n);
1589 >    public void replaceAll(BiFun<? super K, ? super V, ? extends V> function) {
1590 >        if (function == null) throw new NullPointerException();
1591 >        Node<K,V>[] t;
1592 >        if ((t = table) != null) {
1593 >            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1594 >            for (Node<K,V> p; (p = it.advance()) != null; ) {
1595 >                V oldValue = p.val;
1596 >                for (K key = p.key;;) {
1597 >                    V newValue = function.apply(key, oldValue);
1598 >                    if (newValue == null)
1599 >                        throw new NullPointerException();
1600 >                    if (replaceNode(key, newValue, oldValue) != null ||
1601 >                        (oldValue = get(key)) == null)
1602 >                        break;
1603                  }
3172                r[i++] = it.next();
1604              }
3174            return (i == n) ? r : Arrays.copyOf(r, i);
1605          }
1606 +    }
1607  
1608 <        @SuppressWarnings("unchecked")
1609 <            public final <T> T[] toArray(T[] a) {
1610 <            long sz = map.mappingCount();
1611 <            if (sz > (long)(MAX_ARRAY_SIZE))
1612 <                throw new OutOfMemoryError(oomeMsg);
1613 <            int m = (int)sz;
1614 <            T[] r = (a.length >= m) ? a :
1615 <                (T[])java.lang.reflect.Array
1616 <                .newInstance(a.getClass().getComponentType(), m);
1617 <            int n = r.length;
1618 <            int i = 0;
1619 <            Iterator<?> it = iterator();
1620 <            while (it.hasNext()) {
1621 <                if (i == n) {
1622 <                    if (n >= MAX_ARRAY_SIZE)
1623 <                        throw new OutOfMemoryError(oomeMsg);
1624 <                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
1625 <                        n = MAX_ARRAY_SIZE;
1626 <                    else
1627 <                        n += (n >>> 1) + 1;
1628 <                    r = Arrays.copyOf(r, n);
1608 >    /**
1609 >     * If the specified key is not already associated with a value,
1610 >     * attempts to compute its value using the given mapping function
1611 >     * and enters it into this map unless {@code null}.  The entire
1612 >     * method invocation is performed atomically, so the function is
1613 >     * applied at most once per key.  Some attempted update operations
1614 >     * on this map by other threads may be blocked while computation
1615 >     * is in progress, so the computation should be short and simple,
1616 >     * and must not attempt to update any other mappings of this map.
1617 >     *
1618 >     * @param key key with which the specified value is to be associated
1619 >     * @param mappingFunction the function to compute a value
1620 >     * @return the current (existing or computed) value associated with
1621 >     *         the specified key, or null if the computed value is null
1622 >     * @throws NullPointerException if the specified key or mappingFunction
1623 >     *         is null
1624 >     * @throws IllegalStateException if the computation detectably
1625 >     *         attempts a recursive update to this map that would
1626 >     *         otherwise never complete
1627 >     * @throws RuntimeException or Error if the mappingFunction does so,
1628 >     *         in which case the mapping is left unestablished
1629 >     */
1630 >    public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
1631 >        if (key == null || mappingFunction == null)
1632 >            throw new NullPointerException();
1633 >        int h = spread(key.hashCode());
1634 >        V val = null;
1635 >        int binCount = 0;
1636 >        for (Node<K,V>[] tab = table;;) {
1637 >            Node<K,V> f; int n, i, fh;
1638 >            if (tab == null || (n = tab.length) == 0)
1639 >                tab = initTable();
1640 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1641 >                Node<K,V> r = new ReservationNode<K,V>();
1642 >                synchronized (r) {
1643 >                    if (casTabAt(tab, i, null, r)) {
1644 >                        binCount = 1;
1645 >                        Node<K,V> node = null;
1646 >                        try {
1647 >                            if ((val = mappingFunction.apply(key)) != null)
1648 >                                node = new Node<K,V>(h, key, val, null);
1649 >                        } finally {
1650 >                            setTabAt(tab, i, node);
1651 >                        }
1652 >                    }
1653                  }
1654 <                r[i++] = (T)it.next();
1654 >                if (binCount != 0)
1655 >                    break;
1656              }
1657 <            if (a == r && i < n) {
1658 <                r[i] = null; // null-terminate
1659 <                return r;
1657 >            else if ((fh = f.hash) == MOVED)
1658 >                tab = helpTransfer(tab, f);
1659 >            else {
1660 >                boolean added = false;
1661 >                synchronized (f) {
1662 >                    if (tabAt(tab, i) == f) {
1663 >                        if (fh >= 0) {
1664 >                            binCount = 1;
1665 >                            for (Node<K,V> e = f;; ++binCount) {
1666 >                                K ek; V ev;
1667 >                                if (e.hash == h &&
1668 >                                    ((ek = e.key) == key ||
1669 >                                     (ek != null && key.equals(ek)))) {
1670 >                                    val = e.val;
1671 >                                    break;
1672 >                                }
1673 >                                Node<K,V> pred = e;
1674 >                                if ((e = e.next) == null) {
1675 >                                    if ((val = mappingFunction.apply(key)) != null) {
1676 >                                        added = true;
1677 >                                        pred.next = new Node<K,V>(h, key, val, null);
1678 >                                    }
1679 >                                    break;
1680 >                                }
1681 >                            }
1682 >                        }
1683 >                        else if (f instanceof TreeBin) {
1684 >                            binCount = 2;
1685 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1686 >                            TreeNode<K,V> r, p;
1687 >                            if ((r = t.root) != null &&
1688 >                                (p = r.findTreeNode(h, key, null)) != null)
1689 >                                val = p.val;
1690 >                            else if ((val = mappingFunction.apply(key)) != null) {
1691 >                                added = true;
1692 >                                t.putTreeVal(h, key, val);
1693 >                            }
1694 >                        }
1695 >                    }
1696 >                }
1697 >                if (binCount != 0) {
1698 >                    if (binCount >= TREEIFY_THRESHOLD)
1699 >                        treeifyBin(tab, i);
1700 >                    if (!added)
1701 >                        return val;
1702 >                    break;
1703 >                }
1704              }
3205            return (i == n) ? r : Arrays.copyOf(r, i);
3206        }
3207
3208        public final int hashCode() {
3209            int h = 0;
3210            for (Iterator<?> it = iterator(); it.hasNext();)
3211                h += it.next().hashCode();
3212            return h;
1705          }
1706 +        if (val != null)
1707 +            addCount(1L, binCount);
1708 +        return val;
1709 +    }
1710  
1711 <        public final String toString() {
1712 <            StringBuilder sb = new StringBuilder();
1713 <            sb.append('[');
1714 <            Iterator<?> it = iterator();
1715 <            if (it.hasNext()) {
1716 <                for (;;) {
1717 <                    Object e = it.next();
1718 <                    sb.append(e == this ? "(this Collection)" : e);
1719 <                    if (!it.hasNext())
1720 <                        break;
1721 <                    sb.append(',').append(' ');
1711 >    /**
1712 >     * If the value for the specified key is present, attempts to
1713 >     * compute a new mapping given the key and its current mapped
1714 >     * value.  The entire method invocation is performed atomically.
1715 >     * Some attempted update operations on this map by other threads
1716 >     * may be blocked while computation is in progress, so the
1717 >     * computation should be short and simple, and must not attempt to
1718 >     * update any other mappings of this map.
1719 >     *
1720 >     * @param key key with which a value may be associated
1721 >     * @param remappingFunction the function to compute a value
1722 >     * @return the new value associated with the specified key, or null if none
1723 >     * @throws NullPointerException if the specified key or remappingFunction
1724 >     *         is null
1725 >     * @throws IllegalStateException if the computation detectably
1726 >     *         attempts a recursive update to this map that would
1727 >     *         otherwise never complete
1728 >     * @throws RuntimeException or Error if the remappingFunction does so,
1729 >     *         in which case the mapping is unchanged
1730 >     */
1731 >    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1732 >        if (key == null || remappingFunction == null)
1733 >            throw new NullPointerException();
1734 >        int h = spread(key.hashCode());
1735 >        V val = null;
1736 >        int delta = 0;
1737 >        int binCount = 0;
1738 >        for (Node<K,V>[] tab = table;;) {
1739 >            Node<K,V> f; int n, i, fh;
1740 >            if (tab == null || (n = tab.length) == 0)
1741 >                tab = initTable();
1742 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1743 >                break;
1744 >            else if ((fh = f.hash) == MOVED)
1745 >                tab = helpTransfer(tab, f);
1746 >            else {
1747 >                synchronized (f) {
1748 >                    if (tabAt(tab, i) == f) {
1749 >                        if (fh >= 0) {
1750 >                            binCount = 1;
1751 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1752 >                                K ek;
1753 >                                if (e.hash == h &&
1754 >                                    ((ek = e.key) == key ||
1755 >                                     (ek != null && key.equals(ek)))) {
1756 >                                    val = remappingFunction.apply(key, e.val);
1757 >                                    if (val != null)
1758 >                                        e.val = val;
1759 >                                    else {
1760 >                                        delta = -1;
1761 >                                        Node<K,V> en = e.next;
1762 >                                        if (pred != null)
1763 >                                            pred.next = en;
1764 >                                        else
1765 >                                            setTabAt(tab, i, en);
1766 >                                    }
1767 >                                    break;
1768 >                                }
1769 >                                pred = e;
1770 >                                if ((e = e.next) == null)
1771 >                                    break;
1772 >                            }
1773 >                        }
1774 >                        else if (f instanceof TreeBin) {
1775 >                            binCount = 2;
1776 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1777 >                            TreeNode<K,V> r, p;
1778 >                            if ((r = t.root) != null &&
1779 >                                (p = r.findTreeNode(h, key, null)) != null) {
1780 >                                val = remappingFunction.apply(key, p.val);
1781 >                                if (val != null)
1782 >                                    p.val = val;
1783 >                                else {
1784 >                                    delta = -1;
1785 >                                    if (t.removeTreeNode(p))
1786 >                                        setTabAt(tab, i, untreeify(t.first));
1787 >                                }
1788 >                            }
1789 >                        }
1790 >                    }
1791                  }
1792 +                if (binCount != 0)
1793 +                    break;
1794              }
3228            return sb.append(']').toString();
1795          }
1796 +        if (delta != 0)
1797 +            addCount((long)delta, binCount);
1798 +        return val;
1799 +    }
1800  
1801 <        public final boolean containsAll(Collection<?> c) {
1802 <            if (c != this) {
1803 <                for (Iterator<?> it = c.iterator(); it.hasNext();) {
1804 <                    Object e = it.next();
1805 <                    if (e == null || !contains(e))
1806 <                        return false;
1801 >    /**
1802 >     * Attempts to compute a mapping for the specified key and its
1803 >     * current mapped value (or {@code null} if there is no current
1804 >     * mapping). The entire method invocation is performed atomically.
1805 >     * Some attempted update operations on this map by other threads
1806 >     * may be blocked while computation is in progress, so the
1807 >     * computation should be short and simple, and must not attempt to
1808 >     * update any other mappings of this Map.
1809 >     *
1810 >     * @param key key with which the specified value is to be associated
1811 >     * @param remappingFunction the function to compute a value
1812 >     * @return the new value associated with the specified key, or null if none
1813 >     * @throws NullPointerException if the specified key or remappingFunction
1814 >     *         is null
1815 >     * @throws IllegalStateException if the computation detectably
1816 >     *         attempts a recursive update to this map that would
1817 >     *         otherwise never complete
1818 >     * @throws RuntimeException or Error if the remappingFunction does so,
1819 >     *         in which case the mapping is unchanged
1820 >     */
1821 >    public V compute(K key,
1822 >                     BiFun<? super K, ? super V, ? extends V> remappingFunction) {
1823 >        if (key == null || remappingFunction == null)
1824 >            throw new NullPointerException();
1825 >        int h = spread(key.hashCode());
1826 >        V val = null;
1827 >        int delta = 0;
1828 >        int binCount = 0;
1829 >        for (Node<K,V>[] tab = table;;) {
1830 >            Node<K,V> f; int n, i, fh;
1831 >            if (tab == null || (n = tab.length) == 0)
1832 >                tab = initTable();
1833 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1834 >                Node<K,V> r = new ReservationNode<K,V>();
1835 >                synchronized (r) {
1836 >                    if (casTabAt(tab, i, null, r)) {
1837 >                        binCount = 1;
1838 >                        Node<K,V> node = null;
1839 >                        try {
1840 >                            if ((val = remappingFunction.apply(key, null)) != null) {
1841 >                                delta = 1;
1842 >                                node = new Node<K,V>(h, key, val, null);
1843 >                            }
1844 >                        } finally {
1845 >                            setTabAt(tab, i, node);
1846 >                        }
1847 >                    }
1848                  }
1849 +                if (binCount != 0)
1850 +                    break;
1851              }
1852 <            return true;
1853 <        }
1854 <
1855 <        public final boolean removeAll(Collection<?> c) {
1856 <            boolean modified = false;
1857 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1858 <                if (c.contains(it.next())) {
1859 <                    it.remove();
1860 <                    modified = true;
1852 >            else if ((fh = f.hash) == MOVED)
1853 >                tab = helpTransfer(tab, f);
1854 >            else {
1855 >                synchronized (f) {
1856 >                    if (tabAt(tab, i) == f) {
1857 >                        if (fh >= 0) {
1858 >                            binCount = 1;
1859 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1860 >                                K ek;
1861 >                                if (e.hash == h &&
1862 >                                    ((ek = e.key) == key ||
1863 >                                     (ek != null && key.equals(ek)))) {
1864 >                                    val = remappingFunction.apply(key, e.val);
1865 >                                    if (val != null)
1866 >                                        e.val = val;
1867 >                                    else {
1868 >                                        delta = -1;
1869 >                                        Node<K,V> en = e.next;
1870 >                                        if (pred != null)
1871 >                                            pred.next = en;
1872 >                                        else
1873 >                                            setTabAt(tab, i, en);
1874 >                                    }
1875 >                                    break;
1876 >                                }
1877 >                                pred = e;
1878 >                                if ((e = e.next) == null) {
1879 >                                    val = remappingFunction.apply(key, null);
1880 >                                    if (val != null) {
1881 >                                        delta = 1;
1882 >                                        pred.next =
1883 >                                            new Node<K,V>(h, key, val, null);
1884 >                                    }
1885 >                                    break;
1886 >                                }
1887 >                            }
1888 >                        }
1889 >                        else if (f instanceof TreeBin) {
1890 >                            binCount = 1;
1891 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
1892 >                            TreeNode<K,V> r, p;
1893 >                            if ((r = t.root) != null)
1894 >                                p = r.findTreeNode(h, key, null);
1895 >                            else
1896 >                                p = null;
1897 >                            V pv = (p == null) ? null : p.val;
1898 >                            val = remappingFunction.apply(key, pv);
1899 >                            if (val != null) {
1900 >                                if (p != null)
1901 >                                    p.val = val;
1902 >                                else {
1903 >                                    delta = 1;
1904 >                                    t.putTreeVal(h, key, val);
1905 >                                }
1906 >                            }
1907 >                            else if (p != null) {
1908 >                                delta = -1;
1909 >                                if (t.removeTreeNode(p))
1910 >                                    setTabAt(tab, i, untreeify(t.first));
1911 >                            }
1912 >                        }
1913 >                    }
1914 >                }
1915 >                if (binCount != 0) {
1916 >                    if (binCount >= TREEIFY_THRESHOLD)
1917 >                        treeifyBin(tab, i);
1918 >                    break;
1919                  }
1920              }
3250            return modified;
1921          }
1922 +        if (delta != 0)
1923 +            addCount((long)delta, binCount);
1924 +        return val;
1925 +    }
1926  
1927 <        public final boolean retainAll(Collection<?> c) {
1928 <            boolean modified = false;
1929 <            for (Iterator<?> it = iterator(); it.hasNext();) {
1930 <                if (!c.contains(it.next())) {
1931 <                    it.remove();
1932 <                    modified = true;
1927 >    /**
1928 >     * If the specified key is not already associated with a
1929 >     * (non-null) value, associates it with the given value.
1930 >     * Otherwise, replaces the value with the results of the given
1931 >     * remapping function, or removes if {@code null}. The entire
1932 >     * method invocation is performed atomically.  Some attempted
1933 >     * update operations on this map by other threads may be blocked
1934 >     * while computation is in progress, so the computation should be
1935 >     * short and simple, and must not attempt to update any other
1936 >     * mappings of this Map.
1937 >     *
1938 >     * @param key key with which the specified value is to be associated
1939 >     * @param value the value to use if absent
1940 >     * @param remappingFunction the function to recompute a value if present
1941 >     * @return the new value associated with the specified key, or null if none
1942 >     * @throws NullPointerException if the specified key or the
1943 >     *         remappingFunction is null
1944 >     * @throws RuntimeException or Error if the remappingFunction does so,
1945 >     *         in which case the mapping is unchanged
1946 >     */
1947 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
1948 >        if (key == null || value == null || remappingFunction == null)
1949 >            throw new NullPointerException();
1950 >        int h = spread(key.hashCode());
1951 >        V val = null;
1952 >        int delta = 0;
1953 >        int binCount = 0;
1954 >        for (Node<K,V>[] tab = table;;) {
1955 >            Node<K,V> f; int n, i, fh;
1956 >            if (tab == null || (n = tab.length) == 0)
1957 >                tab = initTable();
1958 >            else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1959 >                if (casTabAt(tab, i, null, new Node<K,V>(h, key, value, null))) {
1960 >                    delta = 1;
1961 >                    val = value;
1962 >                    break;
1963 >                }
1964 >            }
1965 >            else if ((fh = f.hash) == MOVED)
1966 >                tab = helpTransfer(tab, f);
1967 >            else {
1968 >                synchronized (f) {
1969 >                    if (tabAt(tab, i) == f) {
1970 >                        if (fh >= 0) {
1971 >                            binCount = 1;
1972 >                            for (Node<K,V> e = f, pred = null;; ++binCount) {
1973 >                                K ek;
1974 >                                if (e.hash == h &&
1975 >                                    ((ek = e.key) == key ||
1976 >                                     (ek != null && key.equals(ek)))) {
1977 >                                    val = remappingFunction.apply(e.val, value);
1978 >                                    if (val != null)
1979 >                                        e.val = val;
1980 >                                    else {
1981 >                                        delta = -1;
1982 >                                        Node<K,V> en = e.next;
1983 >                                        if (pred != null)
1984 >                                            pred.next = en;
1985 >                                        else
1986 >                                            setTabAt(tab, i, en);
1987 >                                    }
1988 >                                    break;
1989 >                                }
1990 >                                pred = e;
1991 >                                if ((e = e.next) == null) {
1992 >                                    delta = 1;
1993 >                                    val = value;
1994 >                                    pred.next =
1995 >                                        new Node<K,V>(h, key, val, null);
1996 >                                    break;
1997 >                                }
1998 >                            }
1999 >                        }
2000 >                        else if (f instanceof TreeBin) {
2001 >                            binCount = 2;
2002 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2003 >                            TreeNode<K,V> r = t.root;
2004 >                            TreeNode<K,V> p = (r == null) ? null :
2005 >                                r.findTreeNode(h, key, null);
2006 >                            val = (p == null) ? value :
2007 >                                remappingFunction.apply(p.val, value);
2008 >                            if (val != null) {
2009 >                                if (p != null)
2010 >                                    p.val = val;
2011 >                                else {
2012 >                                    delta = 1;
2013 >                                    t.putTreeVal(h, key, val);
2014 >                                }
2015 >                            }
2016 >                            else if (p != null) {
2017 >                                delta = -1;
2018 >                                if (t.removeTreeNode(p))
2019 >                                    setTabAt(tab, i, untreeify(t.first));
2020 >                            }
2021 >                        }
2022 >                    }
2023 >                }
2024 >                if (binCount != 0) {
2025 >                    if (binCount >= TREEIFY_THRESHOLD)
2026 >                        treeifyBin(tab, i);
2027 >                    break;
2028                  }
2029              }
3261            return modified;
2030          }
2031 +        if (delta != 0)
2032 +            addCount((long)delta, binCount);
2033 +        return val;
2034 +    }
2035 +
2036 +    // Hashtable legacy methods
2037 +
2038 +    /**
2039 +     * Legacy method testing if some key maps into the specified value
2040 +     * in this table.  This method is identical in functionality to
2041 +     * {@link #containsValue(Object)}, and exists solely to ensure
2042 +     * full compatibility with class {@link java.util.Hashtable},
2043 +     * which supported this method prior to introduction of the
2044 +     * Java Collections framework.
2045 +     *
2046 +     * @param  value a value to search for
2047 +     * @return {@code true} if and only if some key maps to the
2048 +     *         {@code value} argument in this table as
2049 +     *         determined by the {@code equals} method;
2050 +     *         {@code false} otherwise
2051 +     * @throws NullPointerException if the specified value is null
2052 +     */
2053 +    @Deprecated public boolean contains(Object value) {
2054 +        return containsValue(value);
2055 +    }
2056  
2057 +    /**
2058 +     * Returns an enumeration of the keys in this table.
2059 +     *
2060 +     * @return an enumeration of the keys in this table
2061 +     * @see #keySet()
2062 +     */
2063 +    public Enumeration<K> keys() {
2064 +        Node<K,V>[] t;
2065 +        int f = (t = table) == null ? 0 : t.length;
2066 +        return new KeyIterator<K,V>(t, f, 0, f, this);
2067      }
2068  
2069 <    static final class KeySet<K,V> extends CHMView<K,V> implements Set<K> {
2070 <        KeySet(ConcurrentHashMapV8<K, V> map)  {
2071 <            super(map);
2072 <        }
2073 <        public final boolean contains(Object o) { return map.containsKey(o); }
2074 <        public final boolean remove(Object o)   { return map.remove(o) != null; }
2075 <        public final Iterator<K> iterator() {
2076 <            return new KeyIterator<K,V>(map);
2077 <        }
2078 <        public final boolean add(K e) {
3276 <            throw new UnsupportedOperationException();
3277 <        }
3278 <        public final boolean addAll(Collection<? extends K> c) {
3279 <            throw new UnsupportedOperationException();
3280 <        }
3281 <        public boolean equals(Object o) {
3282 <            Set<?> c;
3283 <            return ((o instanceof Set) &&
3284 <                    ((c = (Set<?>)o) == this ||
3285 <                     (containsAll(c) && c.containsAll(this))));
3286 <        }
2069 >    /**
2070 >     * Returns an enumeration of the values in this table.
2071 >     *
2072 >     * @return an enumeration of the values in this table
2073 >     * @see #values()
2074 >     */
2075 >    public Enumeration<V> elements() {
2076 >        Node<K,V>[] t;
2077 >        int f = (t = table) == null ? 0 : t.length;
2078 >        return new ValueIterator<K,V>(t, f, 0, f, this);
2079      }
2080  
2081 +    // ConcurrentHashMapV8-only methods
2082  
2083 <    static final class Values<K,V> extends CHMView<K,V>
2084 <        implements Collection<V> {
2085 <        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
2086 <        public final boolean contains(Object o) { return map.containsValue(o); }
2087 <        public final boolean remove(Object o) {
2088 <            if (o != null) {
2089 <                Iterator<V> it = new ValueIterator<K,V>(map);
2090 <                while (it.hasNext()) {
2091 <                    if (o.equals(it.next())) {
2092 <                        it.remove();
2093 <                        return true;
2083 >    /**
2084 >     * Returns the number of mappings. This method should be used
2085 >     * instead of {@link #size} because a ConcurrentHashMapV8 may
2086 >     * contain more mappings than can be represented as an int. The
2087 >     * value returned is an estimate; the actual count may differ if
2088 >     * there are concurrent insertions or removals.
2089 >     *
2090 >     * @return the number of mappings
2091 >     * @since 1.8
2092 >     */
2093 >    public long mappingCount() {
2094 >        long n = sumCount();
2095 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2096 >    }
2097 >
2098 >    /**
2099 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2100 >     * from the given type to {@code Boolean.TRUE}.
2101 >     *
2102 >     * @return the new set
2103 >     * @since 1.8
2104 >     */
2105 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2106 >        return new KeySetView<K,Boolean>
2107 >            (new ConcurrentHashMapV8<K,Boolean>(), Boolean.TRUE);
2108 >    }
2109 >
2110 >    /**
2111 >     * Creates a new {@link Set} backed by a ConcurrentHashMapV8
2112 >     * from the given type to {@code Boolean.TRUE}.
2113 >     *
2114 >     * @param initialCapacity The implementation performs internal
2115 >     * sizing to accommodate this many elements.
2116 >     * @return the new set
2117 >     * @throws IllegalArgumentException if the initial capacity of
2118 >     * elements is negative
2119 >     * @since 1.8
2120 >     */
2121 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2122 >        return new KeySetView<K,Boolean>
2123 >            (new ConcurrentHashMapV8<K,Boolean>(initialCapacity), Boolean.TRUE);
2124 >    }
2125 >
2126 >    /**
2127 >     * Returns a {@link Set} view of the keys in this map, using the
2128 >     * given common mapped value for any additions (i.e., {@link
2129 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2130 >     * This is of course only appropriate if it is acceptable to use
2131 >     * the same value for all additions from this view.
2132 >     *
2133 >     * @param mappedValue the mapped value to use for any additions
2134 >     * @return the set view
2135 >     * @throws NullPointerException if the mappedValue is null
2136 >     */
2137 >    public KeySetView<K,V> keySet(V mappedValue) {
2138 >        if (mappedValue == null)
2139 >            throw new NullPointerException();
2140 >        return new KeySetView<K,V>(this, mappedValue);
2141 >    }
2142 >
2143 >    /* ---------------- Special Nodes -------------- */
2144 >
2145 >    /**
2146 >     * A node inserted at head of bins during transfer operations.
2147 >     */
2148 >    static final class ForwardingNode<K,V> extends Node<K,V> {
2149 >        final Node<K,V>[] nextTable;
2150 >        ForwardingNode(Node<K,V>[] tab) {
2151 >            super(MOVED, null, null, null);
2152 >            this.nextTable = tab;
2153 >        }
2154 >
2155 >        Node<K,V> find(int h, Object k) {
2156 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2157 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2158 >                Node<K,V> e; int n;
2159 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2160 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2161 >                    return null;
2162 >                for (;;) {
2163 >                    int eh; K ek;
2164 >                    if ((eh = e.hash) == h &&
2165 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2166 >                        return e;
2167 >                    if (eh < 0) {
2168 >                        if (e instanceof ForwardingNode) {
2169 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2170 >                            continue outer;
2171 >                        }
2172 >                        else
2173 >                            return e.find(h, k);
2174                      }
2175 +                    if ((e = e.next) == null)
2176 +                        return null;
2177                  }
2178              }
3304            return false;
3305        }
3306        public final Iterator<V> iterator() {
3307            return new ValueIterator<K,V>(map);
3308        }
3309        public final boolean add(V e) {
3310            throw new UnsupportedOperationException();
3311        }
3312        public final boolean addAll(Collection<? extends V> c) {
3313            throw new UnsupportedOperationException();
2179          }
3315
2180      }
2181  
2182 <    static final class EntrySet<K,V> extends CHMView<K,V>
2183 <        implements Set<Map.Entry<K,V>> {
2184 <        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2185 <        public final boolean contains(Object o) {
2186 <            Object k, v, r; Map.Entry<?,?> e;
2187 <            return ((o instanceof Map.Entry) &&
3324 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3325 <                    (r = map.get(k)) != null &&
3326 <                    (v = e.getValue()) != null &&
3327 <                    (v == r || v.equals(r)));
3328 <        }
3329 <        public final boolean remove(Object o) {
3330 <            Object k, v; Map.Entry<?,?> e;
3331 <            return ((o instanceof Map.Entry) &&
3332 <                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3333 <                    (v = e.getValue()) != null &&
3334 <                    map.remove(k, v));
3335 <        }
3336 <        public final Iterator<Map.Entry<K,V>> iterator() {
3337 <            return new EntryIterator<K,V>(map);
3338 <        }
3339 <        public final boolean add(Entry<K,V> e) {
3340 <            throw new UnsupportedOperationException();
3341 <        }
3342 <        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3343 <            throw new UnsupportedOperationException();
2182 >    /**
2183 >     * A place-holder node used in computeIfAbsent and compute
2184 >     */
2185 >    static final class ReservationNode<K,V> extends Node<K,V> {
2186 >        ReservationNode() {
2187 >            super(RESERVED, null, null, null);
2188          }
2189 <        public boolean equals(Object o) {
2190 <            Set<?> c;
2191 <            return ((o instanceof Set) &&
3348 <                    ((c = (Set<?>)o) == this ||
3349 <                     (containsAll(c) && c.containsAll(this))));
2189 >
2190 >        Node<K,V> find(int h, Object k) {
2191 >            return null;
2192          }
2193      }
2194  
2195 <    /* ---------------- Serialization Support -------------- */
2195 >    /* ---------------- Table Initialization and Resizing -------------- */
2196  
2197      /**
2198 <     * Stripped-down version of helper class used in previous version,
3357 <     * declared for the sake of serialization compatibility
2198 >     * Initializes table, using the size recorded in sizeCtl.
2199       */
2200 <    static class Segment<K,V> implements Serializable {
2201 <        private static final long serialVersionUID = 2249069246763182397L;
2202 <        final float loadFactor;
2203 <        Segment(float lf) { this.loadFactor = lf; }
2200 >    private final Node<K,V>[] initTable() {
2201 >        Node<K,V>[] tab; int sc;
2202 >        while ((tab = table) == null || tab.length == 0) {
2203 >            if ((sc = sizeCtl) < 0)
2204 >                Thread.yield(); // lost initialization race; just spin
2205 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2206 >                try {
2207 >                    if ((tab = table) == null || tab.length == 0) {
2208 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2209 >                        @SuppressWarnings("unchecked")
2210 >                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2211 >                        table = tab = nt;
2212 >                        sc = n - (n >>> 2);
2213 >                    }
2214 >                } finally {
2215 >                    sizeCtl = sc;
2216 >                }
2217 >                break;
2218 >            }
2219 >        }
2220 >        return tab;
2221      }
2222  
2223      /**
2224 <     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
2225 <     * stream (i.e., serializes it).
2226 <     * @param s the stream
2227 <     * @serialData
2228 <     * the key (Object) and value (Object)
2229 <     * for each key-value mapping, followed by a null pair.
2230 <     * The key-value mappings are emitted in no particular order.
2231 <     */
2232 <    @SuppressWarnings("unchecked")
2233 <        private void writeObject(java.io.ObjectOutputStream s)
2234 <        throws java.io.IOException {
2235 <        if (segments == null) { // for serialization compatibility
2236 <            segments = (Segment<K,V>[])
2237 <                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
2238 <            for (int i = 0; i < segments.length; ++i)
2239 <                segments[i] = new Segment<K,V>(LOAD_FACTOR);
2240 <        }
2241 <        s.defaultWriteObject();
2242 <        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2243 <        Object v;
2244 <        while ((v = it.advance()) != null) {
2245 <            s.writeObject(it.nextKey);
2246 <            s.writeObject(v);
2224 >     * Adds to count, and if table is too small and not already
2225 >     * resizing, initiates transfer. If already resizing, helps
2226 >     * perform transfer if work is available.  Rechecks occupancy
2227 >     * after a transfer to see if another resize is already needed
2228 >     * because resizings are lagging additions.
2229 >     *
2230 >     * @param x the count to add
2231 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2232 >     */
2233 >    private final void addCount(long x, int check) {
2234 >        CounterCell[] as; long b, s;
2235 >        if ((as = counterCells) != null ||
2236 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2237 >            CounterHashCode hc; CounterCell a; long v; int m;
2238 >            boolean uncontended = true;
2239 >            if ((hc = threadCounterHashCode.get()) == null ||
2240 >                as == null || (m = as.length - 1) < 0 ||
2241 >                (a = as[m & hc.code]) == null ||
2242 >                !(uncontended =
2243 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2244 >                fullAddCount(x, hc, uncontended);
2245 >                return;
2246 >            }
2247 >            if (check <= 1)
2248 >                return;
2249 >            s = sumCount();
2250 >        }
2251 >        if (check >= 0) {
2252 >            Node<K,V>[] tab, nt; int sc;
2253 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2254 >                   tab.length < MAXIMUM_CAPACITY) {
2255 >                if (sc < 0) {
2256 >                    if (sc == -1 || transferIndex <= 0 ||
2257 >                        (nt = nextTable) == null)
2258 >                        break;
2259 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2260 >                        transfer(tab, nt);
2261 >                }
2262 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2263 >                    transfer(tab, null);
2264 >                s = sumCount();
2265 >            }
2266          }
3390        s.writeObject(null);
3391        s.writeObject(null);
3392        segments = null; // throw away
2267      }
2268  
2269      /**
2270 <     * Reconstitutes the instance from a stream (that is, deserializes it).
3397 <     * @param s the stream
2270 >     * Helps transfer if a resize is in progress.
2271       */
2272 <    @SuppressWarnings("unchecked")
2273 <        private void readObject(java.io.ObjectInputStream s)
2274 <        throws java.io.IOException, ClassNotFoundException {
2275 <        s.defaultReadObject();
2276 <        this.segments = null; // unneeded
2277 <        // initialize transient final field
2278 <        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
2272 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2273 >        Node<K,V>[] nextTab; int sc;
2274 >        if ((f instanceof ForwardingNode) &&
2275 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2276 >            while (transferIndex > 0 && nextTab == nextTable &&
2277 >                   (sc = sizeCtl) < -1) {
2278 >                if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1)) {
2279 >                    transfer(tab, nextTab);
2280 >                    break;
2281 >                }
2282 >            }
2283 >            return nextTab;
2284 >        }
2285 >        return table;
2286 >    }
2287  
2288 <        // Create all nodes, then place in table once size is known
2289 <        long size = 0L;
2290 <        Node p = null;
2291 <        for (;;) {
2292 <            K k = (K) s.readObject();
2293 <            V v = (V) s.readObject();
2294 <            if (k != null && v != null) {
2295 <                int h = spread(k.hashCode());
2296 <                p = new Node(h, k, v, p);
2297 <                ++size;
2288 >    /**
2289 >     * Tries to presize table to accommodate the given number of elements.
2290 >     *
2291 >     * @param size number of elements (doesn't need to be perfectly accurate)
2292 >     */
2293 >    private final void tryPresize(int size) {
2294 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2295 >            tableSizeFor(size + (size >>> 1) + 1);
2296 >        int sc;
2297 >        while ((sc = sizeCtl) >= 0) {
2298 >            Node<K,V>[] tab = table; int n;
2299 >            if (tab == null || (n = tab.length) == 0) {
2300 >                n = (sc > c) ? sc : c;
2301 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2302 >                    try {
2303 >                        if (table == tab) {
2304 >                            @SuppressWarnings("unchecked")
2305 >                                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2306 >                            table = nt;
2307 >                            sc = n - (n >>> 2);
2308 >                        }
2309 >                    } finally {
2310 >                        sizeCtl = sc;
2311 >                    }
2312 >                }
2313              }
2314 <            else
2314 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2315                  break;
2316 +            else if (tab == table &&
2317 +                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2318 +                transfer(tab, null);
2319          }
2320 <        if (p != null) {
2321 <            boolean init = false;
2322 <            int n;
2323 <            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
2324 <                n = MAXIMUM_CAPACITY;
2325 <            else {
2326 <                int sz = (int)size;
2327 <                n = tableSizeFor(sz + (sz >>> 1) + 1);
2320 >    }
2321 >
2322 >    /**
2323 >     * Moves and/or copies the nodes in each bin to new table. See
2324 >     * above for explanation.
2325 >     */
2326 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2327 >        int n = tab.length, stride;
2328 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2329 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2330 >        if (nextTab == null) {            // initiating
2331 >            try {
2332 >                @SuppressWarnings("unchecked")
2333 >                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2334 >                nextTab = nt;
2335 >            } catch (Throwable ex) {      // try to cope with OOME
2336 >                sizeCtl = Integer.MAX_VALUE;
2337 >                return;
2338 >            }
2339 >            nextTable = nextTab;
2340 >            transferIndex = n;
2341 >        }
2342 >        int nextn = nextTab.length;
2343 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2344 >        boolean advance = true;
2345 >        boolean finishing = false; // to ensure sweep before committing nextTab
2346 >        for (int i = 0, bound = 0;;) {
2347 >            Node<K,V> f; int fh;
2348 >            while (advance) {
2349 >                int nextIndex, nextBound;
2350 >                if (--i >= bound || finishing)
2351 >                    advance = false;
2352 >                else if ((nextIndex = transferIndex) <= 0) {
2353 >                    i = -1;
2354 >                    advance = false;
2355 >                }
2356 >                else if (U.compareAndSwapInt
2357 >                         (this, TRANSFERINDEX, nextIndex,
2358 >                          nextBound = (nextIndex > stride ?
2359 >                                       nextIndex - stride : 0))) {
2360 >                    bound = nextBound;
2361 >                    i = nextIndex - 1;
2362 >                    advance = false;
2363 >                }
2364 >            }
2365 >            if (i < 0 || i >= n || i + n >= nextn) {
2366 >                int sc;
2367 >                if (finishing) {
2368 >                    nextTable = null;
2369 >                    table = nextTab;
2370 >                    sizeCtl = (n << 1) - (n >>> 1);
2371 >                    return;
2372 >                }
2373 >                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2374 >                    if (sc != -1)
2375 >                        return;
2376 >                    finishing = advance = true;
2377 >                    i = n; // recheck before commit
2378 >                }
2379              }
2380 <            int sc = sizeCtl;
2381 <            boolean collide = false;
2382 <            if (n > sc &&
2383 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2384 <                try {
2385 <                    if (table == null) {
2386 <                        init = true;
2387 <                        Node[] tab = new Node[n];
2388 <                        int mask = n - 1;
2389 <                        while (p != null) {
2390 <                            int j = p.hash & mask;
2391 <                            Node next = p.next;
2392 <                            Node q = p.next = tabAt(tab, j);
2393 <                            setTabAt(tab, j, p);
2394 <                            if (!collide && q != null && q.hash == p.hash)
2395 <                                collide = true;
2396 <                            p = next;
2380 >            else if ((f = tabAt(tab, i)) == null)
2381 >                advance = casTabAt(tab, i, null, fwd);
2382 >            else if ((fh = f.hash) == MOVED)
2383 >                advance = true; // already processed
2384 >            else {
2385 >                synchronized (f) {
2386 >                    if (tabAt(tab, i) == f) {
2387 >                        Node<K,V> ln, hn;
2388 >                        if (fh >= 0) {
2389 >                            int runBit = fh & n;
2390 >                            Node<K,V> lastRun = f;
2391 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2392 >                                int b = p.hash & n;
2393 >                                if (b != runBit) {
2394 >                                    runBit = b;
2395 >                                    lastRun = p;
2396 >                                }
2397 >                            }
2398 >                            if (runBit == 0) {
2399 >                                ln = lastRun;
2400 >                                hn = null;
2401 >                            }
2402 >                            else {
2403 >                                hn = lastRun;
2404 >                                ln = null;
2405 >                            }
2406 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2407 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2408 >                                if ((ph & n) == 0)
2409 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2410 >                                else
2411 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2412 >                            }
2413 >                            setTabAt(nextTab, i, ln);
2414 >                            setTabAt(nextTab, i + n, hn);
2415 >                            setTabAt(tab, i, fwd);
2416 >                            advance = true;
2417                          }
2418 <                        table = tab;
2419 <                        counter.add(size);
2420 <                        sc = n - (n >>> 2);
2421 <                    }
2422 <                } finally {
2423 <                    sizeCtl = sc;
2424 <                }
2425 <                if (collide) { // rescan and convert to TreeBins
2426 <                    Node[] tab = table;
2427 <                    for (int i = 0; i < tab.length; ++i) {
2428 <                        int c = 0;
2429 <                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
2430 <                            if (++c > TREE_THRESHOLD &&
2431 <                                (e.key instanceof Comparable)) {
2432 <                                replaceWithTreeBin(tab, i, e.key);
2433 <                                break;
2418 >                        else if (f instanceof TreeBin) {
2419 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2420 >                            TreeNode<K,V> lo = null, loTail = null;
2421 >                            TreeNode<K,V> hi = null, hiTail = null;
2422 >                            int lc = 0, hc = 0;
2423 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2424 >                                int h = e.hash;
2425 >                                TreeNode<K,V> p = new TreeNode<K,V>
2426 >                                    (h, e.key, e.val, null, null);
2427 >                                if ((h & n) == 0) {
2428 >                                    if ((p.prev = loTail) == null)
2429 >                                        lo = p;
2430 >                                    else
2431 >                                        loTail.next = p;
2432 >                                    loTail = p;
2433 >                                    ++lc;
2434 >                                }
2435 >                                else {
2436 >                                    if ((p.prev = hiTail) == null)
2437 >                                        hi = p;
2438 >                                    else
2439 >                                        hiTail.next = p;
2440 >                                    hiTail = p;
2441 >                                    ++hc;
2442 >                                }
2443                              }
2444 +                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2445 +                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2446 +                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2447 +                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2448 +                            setTabAt(nextTab, i, ln);
2449 +                            setTabAt(nextTab, i + n, hn);
2450 +                            setTabAt(tab, i, fwd);
2451 +                            advance = true;
2452                          }
2453                      }
2454                  }
2455              }
3469            if (!init) { // Can only happen if unsafely published.
3470                while (p != null) {
3471                    internalPut(p.key, p.val);
3472                    p = p.next;
3473                }
3474            }
2456          }
2457      }
2458  
2459 +    /* ---------------- Conversion from/to TreeBins -------------- */
2460  
2461 <    // -------------------------------------------------------
2462 <
2463 <    // Sams
2464 <    /** Interface describing a void action of one argument */
2465 <    public interface Action<A> { void apply(A a); }
2466 <    /** Interface describing a void action of two arguments */
2467 <    public interface BiAction<A,B> { void apply(A a, B b); }
2468 <    /** Interface describing a function of one argument */
2469 <    public interface Fun<A,T> { T apply(A a); }
2470 <    /** Interface describing a function of two arguments */
2471 <    public interface BiFun<A,B,T> { T apply(A a, B b); }
2472 <    /** Interface describing a function of no arguments */
2473 <    public interface Generator<T> { T apply(); }
2474 <    /** Interface describing a function mapping its argument to a double */
2475 <    public interface ObjectToDouble<A> { double apply(A a); }
2476 <    /** Interface describing a function mapping its argument to a long */
2477 <    public interface ObjectToLong<A> { long apply(A a); }
2478 <    /** Interface describing a function mapping its argument to an int */
2479 <    public interface ObjectToInt<A> {int apply(A a); }
2480 <    /** Interface describing a function mapping two arguments to a double */
2481 <    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
2482 <    /** Interface describing a function mapping two arguments to a long */
2483 <    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
2484 <    /** Interface describing a function mapping two arguments to an int */
2485 <    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
2486 <    /** Interface describing a function mapping a double to a double */
2487 <    public interface DoubleToDouble { double apply(double a); }
2488 <    /** Interface describing a function mapping a long to a long */
2489 <    public interface LongToLong { long apply(long a); }
2490 <    /** Interface describing a function mapping an int to an int */
2491 <    public interface IntToInt { int apply(int a); }
2492 <    /** Interface describing a function mapping two doubles to a double */
3511 <    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3512 <    /** Interface describing a function mapping two longs to a long */
3513 <    public interface LongByLongToLong { long apply(long a, long b); }
3514 <    /** Interface describing a function mapping two ints to an int */
3515 <    public interface IntByIntToInt { int apply(int a, int b); }
3516 <
3517 <
3518 <    // -------------------------------------------------------
2461 >    /**
2462 >     * Replaces all linked nodes in bin at given index unless table is
2463 >     * too small, in which case resizes instead.
2464 >     */
2465 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2466 >        Node<K,V> b; int n, sc;
2467 >        if (tab != null) {
2468 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2469 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2470 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2471 >                    transfer(tab, null);
2472 >            }
2473 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2474 >                synchronized (b) {
2475 >                    if (tabAt(tab, index) == b) {
2476 >                        TreeNode<K,V> hd = null, tl = null;
2477 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2478 >                            TreeNode<K,V> p =
2479 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2480 >                                                  null, null);
2481 >                            if ((p.prev = tl) == null)
2482 >                                hd = p;
2483 >                            else
2484 >                                tl.next = p;
2485 >                            tl = p;
2486 >                        }
2487 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2488 >                    }
2489 >                }
2490 >            }
2491 >        }
2492 >    }
2493  
2494      /**
2495 <     * Returns an extended {@link Parallel} view of this map using the
3522 <     * given executor for bulk parallel operations.
3523 <     *
3524 <     * @param executor the executor
3525 <     * @return a parallel view
2495 >     * Returns a list on non-TreeNodes replacing those in given list.
2496       */
2497 <    public Parallel parallel(ForkJoinPool executor)  {
2498 <        return new Parallel(executor);
2497 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2498 >        Node<K,V> hd = null, tl = null;
2499 >        for (Node<K,V> q = b; q != null; q = q.next) {
2500 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2501 >            if (tl == null)
2502 >                hd = p;
2503 >            else
2504 >                tl.next = p;
2505 >            tl = p;
2506 >        }
2507 >        return hd;
2508      }
2509  
2510 +    /* ---------------- TreeNodes -------------- */
2511 +
2512      /**
2513 <     * An extended view of a ConcurrentHashMap supporting bulk
3533 <     * parallel operations. These operations are designed to be
3534 <     * safely, and often sensibly, applied even with maps that are
3535 <     * being concurrently updated by other threads; for example, when
3536 <     * computing a snapshot summary of the values in a shared
3537 <     * registry.  There are three kinds of operation, each with four
3538 <     * forms, accepting functions with Keys, Values, Entries, and
3539 <     * (Key, Value) arguments and/or return values. Because the
3540 <     * elements of a ConcurrentHashMap are not ordered in any
3541 <     * particular way, and may be processed in different orders in
3542 <     * different parallel executions, the correctness of supplied
3543 <     * functions should not depend on any ordering, or on any other
3544 <     * objects or values that may transiently change while computation
3545 <     * is in progress; and except for forEach actions, should ideally
3546 <     * be side-effect-free.
3547 <     *
3548 <     * <ul>
3549 <     * <li> forEach: Perform a given action on each element.
3550 <     * A variant form applies a given transformation on each element
3551 <     * before performing the action.</li>
3552 <     *
3553 <     * <li> search: Return the first available non-null result of
3554 <     * applying a given function on each element; skipping further
3555 <     * search when a result is found.</li>
3556 <     *
3557 <     * <li> reduce: Accumulate each element.  The supplied reduction
3558 <     * function cannot rely on ordering (more formally, it should be
3559 <     * both associative and commutative).  There are five variants:
3560 <     *
3561 <     * <ul>
3562 <     *
3563 <     * <li> Plain reductions. (There is not a form of this method for
3564 <     * (key, value) function arguments since there is no corresponding
3565 <     * return type.)</li>
3566 <     *
3567 <     * <li> Mapped reductions that accumulate the results of a given
3568 <     * function applied to each element.</li>
3569 <     *
3570 <     * <li> Reductions to scalar doubles, longs, and ints, using a
3571 <     * given basis value.</li>
3572 <     *
3573 <     * </li>
3574 <     * </ul>
3575 <     * </ul>
3576 <     *
3577 <     * <p>The concurrency properties of the bulk operations follow
3578 <     * from those of ConcurrentHashMap: Any non-null result returned
3579 <     * from {@code get(key)} and related access methods bears a
3580 <     * happens-before relation with the associated insertion or
3581 <     * update.  The result of any bulk operation reflects the
3582 <     * composition of these per-element relations (but is not
3583 <     * necessarily atomic with respect to the map as a whole unless it
3584 <     * is somehow known to be quiescent).  Conversely, because keys
3585 <     * and values in the map are never null, null serves as a reliable
3586 <     * atomic indicator of the current lack of any result.  To
3587 <     * maintain this property, null serves as an implicit basis for
3588 <     * all non-scalar reduction operations. For the double, long, and
3589 <     * int versions, the basis should be one that, when combined with
3590 <     * any other value, returns that other value (more formally, it
3591 <     * should be the identity element for the reduction). Most common
3592 <     * reductions have these properties; for example, computing a sum
3593 <     * with basis 0 or a minimum with basis MAX_VALUE.
3594 <     *
3595 <     * <p>Search and transformation functions provided as arguments
3596 <     * should similarly return null to indicate the lack of any result
3597 <     * (in which case it is not used). In the case of mapped
3598 <     * reductions, this also enables transformations to serve as
3599 <     * filters, returning null (or, in the case of primitive
3600 <     * specializations, the identity basis) if the element should not
3601 <     * be combined. You can create compound transformations and
3602 <     * filterings by composing them yourself under this "null means
3603 <     * there is nothing there now" rule before using them in search or
3604 <     * reduce operations.
3605 <     *
3606 <     * <p>Methods accepting and/or returning Entry arguments maintain
3607 <     * key-value associations. They may be useful for example when
3608 <     * finding the key for the greatest value. Note that "plain" Entry
3609 <     * arguments can be supplied using {@code new
3610 <     * AbstractMap.SimpleEntry(k,v)}.
3611 <     *
3612 <     * <p> Bulk operations may complete abruptly, throwing an
3613 <     * exception encountered in the application of a supplied
3614 <     * function. Bear in mind when handling such exceptions that other
3615 <     * concurrently executing functions could also have thrown
3616 <     * exceptions, or would have done so if the first exception had
3617 <     * not occurred.
3618 <     *
3619 <     * <p>Parallel speedups compared to sequential processing are
3620 <     * common but not guaranteed.  Operations involving brief
3621 <     * functions on small maps may execute more slowly than sequential
3622 <     * loops if the underlying work to parallelize the computation is
3623 <     * more expensive than the computation itself. Similarly,
3624 <     * parallelization may not lead to much actual parallelism if all
3625 <     * processors are busy performing unrelated tasks.
3626 <     *
3627 <     * <p> All arguments to all task methods must be non-null.
3628 <     *
3629 <     * <p><em>jsr166e note: During transition, this class
3630 <     * uses nested functional interfaces with different names but the
3631 <     * same forms as those expected for JDK8.<em>
2513 >     * Nodes for use in TreeBins
2514       */
2515 <    public class Parallel {
2516 <        final ForkJoinPool fjp;
2515 >    static final class TreeNode<K,V> extends Node<K,V> {
2516 >        TreeNode<K,V> parent;  // red-black tree links
2517 >        TreeNode<K,V> left;
2518 >        TreeNode<K,V> right;
2519 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2520 >        boolean red;
2521  
2522 <        /**
2523 <         * Returns an extended view of this map using the given
2524 <         * executor for bulk parallel operations.
2525 <         *
3640 <         * @param executor the executor
3641 <         */
3642 <        public Parallel(ForkJoinPool executor)  {
3643 <            this.fjp = executor;
2522 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2523 >                 TreeNode<K,V> parent) {
2524 >            super(hash, key, val, next);
2525 >            this.parent = parent;
2526          }
2527  
2528 <        /**
2529 <         * Performs the given action for each (key, value).
3648 <         *
3649 <         * @param action the action
3650 <         */
3651 <        public void forEach(BiAction<K,V> action) {
3652 <            fjp.invoke(ForkJoinTasks.forEach
3653 <                       (ConcurrentHashMapV8.this, action));
2528 >        Node<K,V> find(int h, Object k) {
2529 >            return findTreeNode(h, k, null);
2530          }
2531  
2532          /**
2533 <         * Performs the given action for each non-null transformation
2534 <         * of each (key, value).
3659 <         *
3660 <         * @param transformer a function returning the transformation
3661 <         * for an element, or null of there is no transformation (in
3662 <         * which case the action is not applied).
3663 <         * @param action the action
2533 >         * Returns the TreeNode (or null if not found) for the given key
2534 >         * starting at given root.
2535           */
2536 <        public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
2537 <                                Action<U> action) {
2538 <            fjp.invoke(ForkJoinTasks.forEach
2539 <                       (ConcurrentHashMapV8.this, transformer, action));
2536 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2537 >            if (k != null) {
2538 >                TreeNode<K,V> p = this;
2539 >                do  {
2540 >                    int ph, dir; K pk; TreeNode<K,V> q;
2541 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2542 >                    if ((ph = p.hash) > h)
2543 >                        p = pl;
2544 >                    else if (ph < h)
2545 >                        p = pr;
2546 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2547 >                        return p;
2548 >                    else if (pl == null)
2549 >                        p = pr;
2550 >                    else if (pr == null)
2551 >                        p = pl;
2552 >                    else if ((kc != null ||
2553 >                              (kc = comparableClassFor(k)) != null) &&
2554 >                             (dir = compareComparables(kc, k, pk)) != 0)
2555 >                        p = (dir < 0) ? pl : pr;
2556 >                    else if ((q = pr.findTreeNode(h, k, kc)) != null)
2557 >                        return q;
2558 >                    else
2559 >                        p = pl;
2560 >                } while (p != null);
2561 >            }
2562 >            return null;
2563          }
2564 +    }
2565  
2566 <        /**
2567 <         * Returns a non-null result from applying the given search
2568 <         * function on each (key, value), or null if none.  Upon
2569 <         * success, further element processing is suppressed and the
2570 <         * results of any other parallel invocations of the search
2571 <         * function are ignored.
2572 <         *
2573 <         * @param searchFunction a function returning a non-null
2574 <         * result on success, else null
2575 <         * @return a non-null result from applying the given search
2576 <         * function on each (key, value), or null if none
2577 <         */
2578 <        public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
2579 <            return fjp.invoke(ForkJoinTasks.search
2580 <                              (ConcurrentHashMapV8.this, searchFunction));
2566 >    /* ---------------- TreeBins -------------- */
2567 >
2568 >    /**
2569 >     * TreeNodes used at the heads of bins. TreeBins do not hold user
2570 >     * keys or values, but instead point to list of TreeNodes and
2571 >     * their root. They also maintain a parasitic read-write lock
2572 >     * forcing writers (who hold bin lock) to wait for readers (who do
2573 >     * not) to complete before tree restructuring operations.
2574 >     */
2575 >    static final class TreeBin<K,V> extends Node<K,V> {
2576 >        TreeNode<K,V> root;
2577 >        volatile TreeNode<K,V> first;
2578 >        volatile Thread waiter;
2579 >        volatile int lockState;
2580 >        // values for lockState
2581 >        static final int WRITER = 1; // set while holding write lock
2582 >        static final int WAITER = 2; // set when waiting for write lock
2583 >        static final int READER = 4; // increment value for setting read lock
2584 >
2585 >        /**
2586 >         * Tie-breaking utility for ordering insertions when equal
2587 >         * hashCodes and non-comparable. We don't require a total
2588 >         * order, just a consistent insertion rule to maintain
2589 >         * equivalence across rebalancings. Tie-breaking further than
2590 >         * necessary simplifies testing a bit.
2591 >         */
2592 >        static int tieBreakOrder(Object a, Object b) {
2593 >            int d;
2594 >            if (a == null || b == null ||
2595 >                (d = a.getClass().getName().
2596 >                 compareTo(b.getClass().getName())) == 0)
2597 >                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2598 >                     -1 : 1);
2599 >            return d;
2600          }
2601  
2602          /**
2603 <         * Returns the result of accumulating the given transformation
2604 <         * of all (key, value) pairs using the given reducer to
2605 <         * combine values, or null if none.
2606 <         *
2607 <         * @param transformer a function returning the transformation
2608 <         * for an element, or null of there is no transformation (in
2609 <         * which case it is not combined).
2610 <         * @param reducer a commutative associative combining function
2611 <         * @return the result of accumulating the given transformation
2612 <         * of all (key, value) pairs
2613 <         */
2614 <        public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
2615 <                            BiFun<? super U, ? super U, ? extends U> reducer) {
2616 <            return fjp.invoke(ForkJoinTasks.reduce
2617 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2603 >         * Creates bin with initial set of nodes headed by b.
2604 >         */
2605 >        TreeBin(TreeNode<K,V> b) {
2606 >            super(TREEBIN, null, null, null);
2607 >            this.first = b;
2608 >            TreeNode<K,V> r = null;
2609 >            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2610 >                next = (TreeNode<K,V>)x.next;
2611 >                x.left = x.right = null;
2612 >                if (r == null) {
2613 >                    x.parent = null;
2614 >                    x.red = false;
2615 >                    r = x;
2616 >                }
2617 >                else {
2618 >                    K k = x.key;
2619 >                    int h = x.hash;
2620 >                    Class<?> kc = null;
2621 >                    for (TreeNode<K,V> p = r;;) {
2622 >                        int dir, ph;
2623 >                        K pk = p.key;
2624 >                        if ((ph = p.hash) > h)
2625 >                            dir = -1;
2626 >                        else if (ph < h)
2627 >                            dir = 1;
2628 >                        else if ((kc == null &&
2629 >                                  (kc = comparableClassFor(k)) == null) ||
2630 >                                 (dir = compareComparables(kc, k, pk)) == 0)
2631 >                            dir = tieBreakOrder(k, pk);
2632 >                            TreeNode<K,V> xp = p;
2633 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2634 >                            x.parent = xp;
2635 >                            if (dir <= 0)
2636 >                                xp.left = x;
2637 >                            else
2638 >                                xp.right = x;
2639 >                            r = balanceInsertion(r, x);
2640 >                            break;
2641 >                        }
2642 >                    }
2643 >                }
2644 >            }
2645 >            this.root = r;
2646 >            assert checkInvariants(root);
2647          }
2648  
2649          /**
2650 <         * Returns the result of accumulating the given transformation
3708 <         * of all (key, value) pairs using the given reducer to
3709 <         * combine values, and the given basis as an identity value.
3710 <         *
3711 <         * @param transformer a function returning the transformation
3712 <         * for an element
3713 <         * @param basis the identity (initial default value) for the reduction
3714 <         * @param reducer a commutative associative combining function
3715 <         * @return the result of accumulating the given transformation
3716 <         * of all (key, value) pairs
2650 >         * Acquires write lock for tree restructuring.
2651           */
2652 <        public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
2653 <                                     double basis,
2654 <                                     DoubleByDoubleToDouble reducer) {
3721 <            return fjp.invoke(ForkJoinTasks.reduceToDouble
3722 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2652 >        private final void lockRoot() {
2653 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2654 >                contendedLock(); // offload to separate method
2655          }
2656  
2657          /**
2658 <         * Returns the result of accumulating the given transformation
3727 <         * of all (key, value) pairs using the given reducer to
3728 <         * combine values, and the given basis as an identity value.
3729 <         *
3730 <         * @param transformer a function returning the transformation
3731 <         * for an element
3732 <         * @param basis the identity (initial default value) for the reduction
3733 <         * @param reducer a commutative associative combining function
3734 <         * @return the result of accumulating the given transformation
3735 <         * of all (key, value) pairs
2658 >         * Releases write lock for tree restructuring.
2659           */
2660 <        public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
2661 <                                 long basis,
3739 <                                 LongByLongToLong reducer) {
3740 <            return fjp.invoke(ForkJoinTasks.reduceToLong
3741 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2660 >        private final void unlockRoot() {
2661 >            lockState = 0;
2662          }
2663  
2664          /**
2665 <         * Returns the result of accumulating the given transformation
3746 <         * of all (key, value) pairs using the given reducer to
3747 <         * combine values, and the given basis as an identity value.
3748 <         *
3749 <         * @param transformer a function returning the transformation
3750 <         * for an element
3751 <         * @param basis the identity (initial default value) for the reduction
3752 <         * @param reducer a commutative associative combining function
3753 <         * @return the result of accumulating the given transformation
3754 <         * of all (key, value) pairs
2665 >         * Possibly blocks awaiting root lock.
2666           */
2667 <        public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
2668 <                               int basis,
2669 <                               IntByIntToInt reducer) {
2670 <            return fjp.invoke(ForkJoinTasks.reduceToInt
2671 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2667 >        private final void contendedLock() {
2668 >            boolean waiting = false;
2669 >            for (int s;;) {
2670 >                if (((s = lockState) & WRITER) == 0) {
2671 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2672 >                        if (waiting)
2673 >                            waiter = null;
2674 >                        return;
2675 >                    }
2676 >                }
2677 >                else if ((s & WAITER) == 0) {
2678 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2679 >                        waiting = true;
2680 >                        waiter = Thread.currentThread();
2681 >                    }
2682 >                }
2683 >                else if (waiting)
2684 >                    LockSupport.park(this);
2685 >            }
2686          }
2687  
2688          /**
2689 <         * Performs the given action for each key.
2690 <         *
2691 <         * @param action the action
2689 >         * Returns matching node or null if none. Tries to search
2690 >         * using tree comparisons from root, but continues linear
2691 >         * search when lock not available.
2692           */
2693 <        public void forEachKey(Action<K> action) {
2694 <            fjp.invoke(ForkJoinTasks.forEachKey
2695 <                       (ConcurrentHashMapV8.this, action));
2693 > final Node<K,V> find(int h, Object k) {
2694 >            if (k != null) {
2695 >                for (Node<K,V> e = first; e != null; e = e.next) {
2696 >                    int s; K ek;
2697 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2698 >                        if (e.hash == h &&
2699 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2700 >                            return e;
2701 >                    }
2702 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2703 >                                                 s + READER)) {
2704 >                        TreeNode<K,V> r, p;
2705 >                        try {
2706 >                            p = ((r = root) == null ? null :
2707 >                                 r.findTreeNode(h, k, null));
2708 >                        } finally {
2709 >                            Thread w;
2710 >                            int ls;
2711 >                            do {} while (!U.compareAndSwapInt
2712 >                                         (this, LOCKSTATE,
2713 >                                          ls = lockState, ls - READER));
2714 >                            if (ls == (READER|WAITER) && (w = waiter) != null)
2715 >                                LockSupport.unpark(w);
2716 >                        }
2717 >                        return p;
2718 >                    }
2719 >                }
2720 >            }
2721 >            return null;
2722          }
2723  
2724          /**
2725 <         * Performs the given action for each non-null transformation
2726 <         * of each key.
3776 <         *
3777 <         * @param transformer a function returning the transformation
3778 <         * for an element, or null of there is no transformation (in
3779 <         * which case the action is not applied).
3780 <         * @param action the action
2725 >         * Finds or adds a node.
2726 >         * @return null if added
2727           */
2728 <        public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
2729 <                                   Action<U> action) {
2730 <            fjp.invoke(ForkJoinTasks.forEachKey
2731 <                       (ConcurrentHashMapV8.this, transformer, action));
2728 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2729 >            Class<?> kc = null;
2730 >            boolean searched = false;
2731 >            for (TreeNode<K,V> p = root;;) {
2732 >                int dir, ph; K pk;
2733 >                if (p == null) {
2734 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2735 >                    break;
2736 >                }
2737 >                else if ((ph = p.hash) > h)
2738 >                    dir = -1;
2739 >                else if (ph < h)
2740 >                    dir = 1;
2741 >                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2742 >                    return p;
2743 >                else if ((kc == null &&
2744 >                          (kc = comparableClassFor(k)) == null) ||
2745 >                         (dir = compareComparables(kc, k, pk)) == 0) {
2746 >                    if (!searched) {
2747 >                        TreeNode<K,V> q, ch;
2748 >                        searched = true;
2749 >                        if (((ch = p.left) != null &&
2750 >                             (q = ch.findTreeNode(h, k, kc)) != null) ||
2751 >                            ((ch = p.right) != null &&
2752 >                             (q = ch.findTreeNode(h, k, kc)) != null))
2753 >                            return q;
2754 >                    }
2755 >                    dir = tieBreakOrder(k, pk);
2756 >                }
2757 >
2758 >                TreeNode<K,V> xp = p;
2759 >                if ((p = (dir <= 0) ? p.left : p.right) == null) {
2760 >                    TreeNode<K,V> x, f = first;
2761 >                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2762 >                    if (f != null)
2763 >                        f.prev = x;
2764 >                    if (dir <= 0)
2765 >                        xp.left = x;
2766 >                    else
2767 >                        xp.right = x;
2768 >                    if (!xp.red)
2769 >                        x.red = true;
2770 >                    else {
2771 >                        lockRoot();
2772 >                        try {
2773 >                            root = balanceInsertion(root, x);
2774 >                        } finally {
2775 >                            unlockRoot();
2776 >                        }
2777 >                    }
2778 >                    break;
2779 >                }
2780 >            }
2781 >            assert checkInvariants(root);
2782 >            return null;
2783          }
2784  
2785          /**
2786 <         * Returns a non-null result from applying the given search
2787 <         * function on each key, or null if none. Upon success,
2788 <         * further element processing is suppressed and the results of
2789 <         * any other parallel invocations of the search function are
2790 <         * ignored.
2786 >         * Removes the given node, that must be present before this
2787 >         * call.  This is messier than typical red-black deletion code
2788 >         * because we cannot swap the contents of an interior node
2789 >         * with a leaf successor that is pinned by "next" pointers
2790 >         * that are accessible independently of lock. So instead we
2791 >         * swap the tree linkages.
2792           *
2793 <         * @param searchFunction a function returning a non-null
3796 <         * result on success, else null
3797 <         * @return a non-null result from applying the given search
3798 <         * function on each key, or null if none
2793 >         * @return true if now too small, so should be untreeified
2794           */
2795 <        public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
2796 <            return fjp.invoke(ForkJoinTasks.searchKeys
2797 <                              (ConcurrentHashMapV8.this, searchFunction));
2795 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2796 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2797 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2798 >            TreeNode<K,V> r, rl;
2799 >            if (pred == null)
2800 >                first = next;
2801 >            else
2802 >                pred.next = next;
2803 >            if (next != null)
2804 >                next.prev = pred;
2805 >            if (first == null) {
2806 >                root = null;
2807 >                return true;
2808 >            }
2809 >            if ((r = root) == null || r.right == null || // too small
2810 >                (rl = r.left) == null || rl.left == null)
2811 >                return true;
2812 >            lockRoot();
2813 >            try {
2814 >                TreeNode<K,V> replacement;
2815 >                TreeNode<K,V> pl = p.left;
2816 >                TreeNode<K,V> pr = p.right;
2817 >                if (pl != null && pr != null) {
2818 >                    TreeNode<K,V> s = pr, sl;
2819 >                    while ((sl = s.left) != null) // find successor
2820 >                        s = sl;
2821 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2822 >                    TreeNode<K,V> sr = s.right;
2823 >                    TreeNode<K,V> pp = p.parent;
2824 >                    if (s == pr) { // p was s's direct parent
2825 >                        p.parent = s;
2826 >                        s.right = p;
2827 >                    }
2828 >                    else {
2829 >                        TreeNode<K,V> sp = s.parent;
2830 >                        if ((p.parent = sp) != null) {
2831 >                            if (s == sp.left)
2832 >                                sp.left = p;
2833 >                            else
2834 >                                sp.right = p;
2835 >                        }
2836 >                        if ((s.right = pr) != null)
2837 >                            pr.parent = s;
2838 >                    }
2839 >                    p.left = null;
2840 >                    if ((p.right = sr) != null)
2841 >                        sr.parent = p;
2842 >                    if ((s.left = pl) != null)
2843 >                        pl.parent = s;
2844 >                    if ((s.parent = pp) == null)
2845 >                        r = s;
2846 >                    else if (p == pp.left)
2847 >                        pp.left = s;
2848 >                    else
2849 >                        pp.right = s;
2850 >                    if (sr != null)
2851 >                        replacement = sr;
2852 >                    else
2853 >                        replacement = p;
2854 >                }
2855 >                else if (pl != null)
2856 >                    replacement = pl;
2857 >                else if (pr != null)
2858 >                    replacement = pr;
2859 >                else
2860 >                    replacement = p;
2861 >                if (replacement != p) {
2862 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2863 >                    if (pp == null)
2864 >                        r = replacement;
2865 >                    else if (p == pp.left)
2866 >                        pp.left = replacement;
2867 >                    else
2868 >                        pp.right = replacement;
2869 >                    p.left = p.right = p.parent = null;
2870 >                }
2871 >
2872 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2873 >
2874 >                if (p == replacement) {  // detach pointers
2875 >                    TreeNode<K,V> pp;
2876 >                    if ((pp = p.parent) != null) {
2877 >                        if (p == pp.left)
2878 >                            pp.left = null;
2879 >                        else if (p == pp.right)
2880 >                            pp.right = null;
2881 >                        p.parent = null;
2882 >                    }
2883 >                }
2884 >            } finally {
2885 >                unlockRoot();
2886 >            }
2887 >            assert checkInvariants(root);
2888 >            return false;
2889          }
2890  
2891 <        /**
2892 <         * Returns the result of accumulating all keys using the given
2893 <         * reducer to combine values, or null if none.
2894 <         *
2895 <         * @param reducer a commutative associative combining function
2896 <         * @return the result of accumulating all keys using the given
2897 <         * reducer to combine values, or null if none
2898 <         */
2899 <        public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
2900 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2901 <                              (ConcurrentHashMapV8.this, reducer));
2891 >        /* ------------------------------------------------------------ */
2892 >        // Red-black tree methods, all adapted from CLR
2893 >
2894 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2895 >                                              TreeNode<K,V> p) {
2896 >            TreeNode<K,V> r, pp, rl;
2897 >            if (p != null && (r = p.right) != null) {
2898 >                if ((rl = p.right = r.left) != null)
2899 >                    rl.parent = p;
2900 >                if ((pp = r.parent = p.parent) == null)
2901 >                    (root = r).red = false;
2902 >                else if (pp.left == p)
2903 >                    pp.left = r;
2904 >                else
2905 >                    pp.right = r;
2906 >                r.left = p;
2907 >                p.parent = r;
2908 >            }
2909 >            return root;
2910          }
2911  
2912 <        /**
2913 <         * Returns the result of accumulating the given transformation
2914 <         * of all keys using the given reducer to combine values, or
2915 <         * null if none.
2916 <         *
2917 <         * @param transformer a function returning the transformation
2918 <         * for an element, or null of there is no transformation (in
2919 <         * which case it is not combined).
2920 <         * @param reducer a commutative associative combining function
2921 <         * @return the result of accumulating the given transformation
2922 <         * of all keys
2923 <         */
2924 <        public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
2925 <                                BiFun<? super U, ? super U, ? extends U> reducer) {
2926 <            return fjp.invoke(ForkJoinTasks.reduceKeys
2927 <                              (ConcurrentHashMapV8.this, transformer, reducer));
2912 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2913 >                                               TreeNode<K,V> p) {
2914 >            TreeNode<K,V> l, pp, lr;
2915 >            if (p != null && (l = p.left) != null) {
2916 >                if ((lr = p.left = l.right) != null)
2917 >                    lr.parent = p;
2918 >                if ((pp = l.parent = p.parent) == null)
2919 >                    (root = l).red = false;
2920 >                else if (pp.right == p)
2921 >                    pp.right = l;
2922 >                else
2923 >                    pp.left = l;
2924 >                l.right = p;
2925 >                p.parent = l;
2926 >            }
2927 >            return root;
2928          }
2929  
2930 <        /**
2931 <         * Returns the result of accumulating the given transformation
2932 <         * of all keys using the given reducer to combine values, and
2933 <         * the given basis as an identity value.
2934 <         *
2935 <         * @param transformer a function returning the transformation
2936 <         * for an element
2937 <         * @param basis the identity (initial default value) for the reduction
2938 <         * @param reducer a commutative associative combining function
2939 <         * @return  the result of accumulating the given transformation
2940 <         * of all keys
2941 <         */
2942 <        public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
2943 <                                         double basis,
2944 <                                         DoubleByDoubleToDouble reducer) {
2945 <            return fjp.invoke(ForkJoinTasks.reduceKeysToDouble
2946 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2930 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2931 >                                                    TreeNode<K,V> x) {
2932 >            x.red = true;
2933 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2934 >                if ((xp = x.parent) == null) {
2935 >                    x.red = false;
2936 >                    return x;
2937 >                }
2938 >                else if (!xp.red || (xpp = xp.parent) == null)
2939 >                    return root;
2940 >                if (xp == (xppl = xpp.left)) {
2941 >                    if ((xppr = xpp.right) != null && xppr.red) {
2942 >                        xppr.red = false;
2943 >                        xp.red = false;
2944 >                        xpp.red = true;
2945 >                        x = xpp;
2946 >                    }
2947 >                    else {
2948 >                        if (x == xp.right) {
2949 >                            root = rotateLeft(root, x = xp);
2950 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2951 >                        }
2952 >                        if (xp != null) {
2953 >                            xp.red = false;
2954 >                            if (xpp != null) {
2955 >                                xpp.red = true;
2956 >                                root = rotateRight(root, xpp);
2957 >                            }
2958 >                        }
2959 >                    }
2960 >                }
2961 >                else {
2962 >                    if (xppl != null && xppl.red) {
2963 >                        xppl.red = false;
2964 >                        xp.red = false;
2965 >                        xpp.red = true;
2966 >                        x = xpp;
2967 >                    }
2968 >                    else {
2969 >                        if (x == xp.left) {
2970 >                            root = rotateRight(root, x = xp);
2971 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2972 >                        }
2973 >                        if (xp != null) {
2974 >                            xp.red = false;
2975 >                            if (xpp != null) {
2976 >                                xpp.red = true;
2977 >                                root = rotateLeft(root, xpp);
2978 >                            }
2979 >                        }
2980 >                    }
2981 >                }
2982 >            }
2983          }
2984  
2985 <        /**
2986 <         * Returns the result of accumulating the given transformation
2987 <         * of all keys using the given reducer to combine values, and
2988 <         * the given basis as an identity value.
2989 <         *
2990 <         * @param transformer a function returning the transformation
2991 <         * for an element
2992 <         * @param basis the identity (initial default value) for the reduction
2993 <         * @param reducer a commutative associative combining function
2994 <         * @return the result of accumulating the given transformation
2995 <         * of all keys
2996 <         */
2997 <        public long reduceKeysToLong(ObjectToLong<? super K> transformer,
2998 <                                     long basis,
2999 <                                     LongByLongToLong reducer) {
3000 <            return fjp.invoke(ForkJoinTasks.reduceKeysToLong
3001 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
2985 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2986 >                                                   TreeNode<K,V> x) {
2987 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
2988 >                if (x == null || x == root)
2989 >                    return root;
2990 >                else if ((xp = x.parent) == null) {
2991 >                    x.red = false;
2992 >                    return x;
2993 >                }
2994 >                else if (x.red) {
2995 >                    x.red = false;
2996 >                    return root;
2997 >                }
2998 >                else if ((xpl = xp.left) == x) {
2999 >                    if ((xpr = xp.right) != null && xpr.red) {
3000 >                        xpr.red = false;
3001 >                        xp.red = true;
3002 >                        root = rotateLeft(root, xp);
3003 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3004 >                    }
3005 >                    if (xpr == null)
3006 >                        x = xp;
3007 >                    else {
3008 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3009 >                        if ((sr == null || !sr.red) &&
3010 >                            (sl == null || !sl.red)) {
3011 >                            xpr.red = true;
3012 >                            x = xp;
3013 >                        }
3014 >                        else {
3015 >                            if (sr == null || !sr.red) {
3016 >                                if (sl != null)
3017 >                                    sl.red = false;
3018 >                                xpr.red = true;
3019 >                                root = rotateRight(root, xpr);
3020 >                                xpr = (xp = x.parent) == null ?
3021 >                                    null : xp.right;
3022 >                            }
3023 >                            if (xpr != null) {
3024 >                                xpr.red = (xp == null) ? false : xp.red;
3025 >                                if ((sr = xpr.right) != null)
3026 >                                    sr.red = false;
3027 >                            }
3028 >                            if (xp != null) {
3029 >                                xp.red = false;
3030 >                                root = rotateLeft(root, xp);
3031 >                            }
3032 >                            x = root;
3033 >                        }
3034 >                    }
3035 >                }
3036 >                else { // symmetric
3037 >                    if (xpl != null && xpl.red) {
3038 >                        xpl.red = false;
3039 >                        xp.red = true;
3040 >                        root = rotateRight(root, xp);
3041 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3042 >                    }
3043 >                    if (xpl == null)
3044 >                        x = xp;
3045 >                    else {
3046 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3047 >                        if ((sl == null || !sl.red) &&
3048 >                            (sr == null || !sr.red)) {
3049 >                            xpl.red = true;
3050 >                            x = xp;
3051 >                        }
3052 >                        else {
3053 >                            if (sl == null || !sl.red) {
3054 >                                if (sr != null)
3055 >                                    sr.red = false;
3056 >                                xpl.red = true;
3057 >                                root = rotateLeft(root, xpl);
3058 >                                xpl = (xp = x.parent) == null ?
3059 >                                    null : xp.left;
3060 >                            }
3061 >                            if (xpl != null) {
3062 >                                xpl.red = (xp == null) ? false : xp.red;
3063 >                                if ((sl = xpl.left) != null)
3064 >                                    sl.red = false;
3065 >                            }
3066 >                            if (xp != null) {
3067 >                                xp.red = false;
3068 >                                root = rotateRight(root, xp);
3069 >                            }
3070 >                            x = root;
3071 >                        }
3072 >                    }
3073 >                }
3074 >            }
3075          }
3076  
3077          /**
3078 <         * Returns the result of accumulating the given transformation
3876 <         * of all keys using the given reducer to combine values, and
3877 <         * the given basis as an identity value.
3878 <         *
3879 <         * @param transformer a function returning the transformation
3880 <         * for an element
3881 <         * @param basis the identity (initial default value) for the reduction
3882 <         * @param reducer a commutative associative combining function
3883 <         * @return the result of accumulating the given transformation
3884 <         * of all keys
3078 >         * Recursive invariant check
3079           */
3080 <        public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3081 <                                   int basis,
3082 <                                   IntByIntToInt reducer) {
3083 <            return fjp.invoke(ForkJoinTasks.reduceKeysToInt
3084 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3080 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3081 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3082 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3083 >            if (tb != null && tb.next != t)
3084 >                return false;
3085 >            if (tn != null && tn.prev != t)
3086 >                return false;
3087 >            if (tp != null && t != tp.left && t != tp.right)
3088 >                return false;
3089 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3090 >                return false;
3091 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3092 >                return false;
3093 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3094 >                return false;
3095 >            if (tl != null && !checkInvariants(tl))
3096 >                return false;
3097 >            if (tr != null && !checkInvariants(tr))
3098 >                return false;
3099 >            return true;
3100          }
3101  
3102 <        /**
3103 <         * Performs the given action for each value.
3104 <         *
3105 <         * @param action the action
3106 <         */
3107 <        public void forEachValue(Action<V> action) {
3108 <            fjp.invoke(ForkJoinTasks.forEachValue
3109 <                       (ConcurrentHashMapV8.this, action));
3102 >        private static final sun.misc.Unsafe U;
3103 >        private static final long LOCKSTATE;
3104 >        static {
3105 >            try {
3106 >                U = getUnsafe();
3107 >                Class<?> k = TreeBin.class;
3108 >                LOCKSTATE = U.objectFieldOffset
3109 >                    (k.getDeclaredField("lockState"));
3110 >            } catch (Exception e) {
3111 >                throw new Error(e);
3112 >            }
3113          }
3114 +    }
3115  
3116 <        /**
3117 <         * Performs the given action for each non-null transformation
3118 <         * of each value.
3119 <         *
3120 <         * @param transformer a function returning the transformation
3121 <         * for an element, or null of there is no transformation (in
3122 <         * which case the action is not applied).
3123 <         */
3124 <        public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3125 <                                     Action<U> action) {
3126 <            fjp.invoke(ForkJoinTasks.forEachValue
3127 <                       (ConcurrentHashMapV8.this, transformer, action));
3116 >    /* ----------------Table Traversal -------------- */
3117 >
3118 >    /**
3119 >     * Records the table, its length, and current traversal index for a
3120 >     * traverser that must process a region of a forwarded table before
3121 >     * proceeding with current table.
3122 >     */
3123 >    static final class TableStack<K,V> {
3124 >        int length;
3125 >        int index;
3126 >        Node<K,V>[] tab;
3127 >        TableStack<K,V> next;
3128 >    }
3129 >
3130 >    /**
3131 >     * Encapsulates traversal for methods such as containsValue; also
3132 >     * serves as a base class for other iterators and spliterators.
3133 >     *
3134 >     * Method advance visits once each still-valid node that was
3135 >     * reachable upon iterator construction. It might miss some that
3136 >     * were added to a bin after the bin was visited, which is OK wrt
3137 >     * consistency guarantees. Maintaining this property in the face
3138 >     * of possible ongoing resizes requires a fair amount of
3139 >     * bookkeeping state that is difficult to optimize away amidst
3140 >     * volatile accesses.  Even so, traversal maintains reasonable
3141 >     * throughput.
3142 >     *
3143 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3144 >     * However, if the table has been resized, then all future steps
3145 >     * must traverse both the bin at the current index as well as at
3146 >     * (index + baseSize); and so on for further resizings. To
3147 >     * paranoically cope with potential sharing by users of iterators
3148 >     * across threads, iteration terminates if a bounds checks fails
3149 >     * for a table read.
3150 >     */
3151 >    static class Traverser<K,V> {
3152 >        Node<K,V>[] tab;        // current table; updated if resized
3153 >        Node<K,V> next;         // the next entry to use
3154 >        TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3155 >        int index;              // index of bin to use next
3156 >        int baseIndex;          // current index of initial table
3157 >        int baseLimit;          // index bound for initial table
3158 >        final int baseSize;     // initial table size
3159 >
3160 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3161 >            this.tab = tab;
3162 >            this.baseSize = size;
3163 >            this.baseIndex = this.index = index;
3164 >            this.baseLimit = limit;
3165 >            this.next = null;
3166          }
3167  
3168          /**
3169 <         * Returns a non-null result from applying the given search
3170 <         * function on each value, or null if none.  Upon success,
3171 <         * further element processing is suppressed and the results of
3172 <         * any other parallel invocations of the search function are
3173 <         * ignored.
3174 <         *
3175 <         * @param searchFunction a function returning a non-null
3176 <         * result on success, else null
3177 <         * @return a non-null result from applying the given search
3178 <         * function on each value, or null if none
3179 <         *
3180 <         */
3181 <        public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3182 <            return fjp.invoke(ForkJoinTasks.searchValues
3183 <                              (ConcurrentHashMapV8.this, searchFunction));
3169 >         * Advances if possible, returning next valid node, or null if none.
3170 >         */
3171 >        final Node<K,V> advance() {
3172 >            Node<K,V> e;
3173 >            if ((e = next) != null)
3174 >                e = e.next;
3175 >            for (;;) {
3176 >                Node<K,V>[] t; int i, n;  // must use locals in checks
3177 >                if (e != null)
3178 >                    return next = e;
3179 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3180 >                    (n = t.length) <= (i = index) || i < 0)
3181 >                    return next = null;
3182 >                if ((e = tabAt(t, i)) != null && e.hash < 0) {
3183 >                    if (e instanceof ForwardingNode) {
3184 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3185 >                        e = null;
3186 >                        pushState(t, i, n);
3187 >                        continue;
3188 >                    }
3189 >                    else if (e instanceof TreeBin)
3190 >                        e = ((TreeBin<K,V>)e).first;
3191 >                    else
3192 >                        e = null;
3193 >                }
3194 >                if (stack != null)
3195 >                    recoverState(n);
3196 >                else if ((index = i + baseSize) >= n)
3197 >                    index = ++baseIndex; // visit upper slots if present
3198 >            }
3199          }
3200  
3201          /**
3202 <         * Returns the result of accumulating all values using the
3937 <         * given reducer to combine values, or null if none.
3938 <         *
3939 <         * @param reducer a commutative associative combining function
3940 <         * @return  the result of accumulating all values
3202 >         * Saves traversal state upon encountering a forwarding node.
3203           */
3204 <        public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3205 <            return fjp.invoke(ForkJoinTasks.reduceValues
3206 <                              (ConcurrentHashMapV8.this, reducer));
3204 >        private void pushState(Node<K,V>[] t, int i, int n) {
3205 >            TableStack<K,V> s = spare;  // reuse if possible
3206 >            if (s != null)
3207 >                spare = s.next;
3208 >            else
3209 >                s = new TableStack<K,V>();
3210 >            s.tab = t;
3211 >            s.length = n;
3212 >            s.index = i;
3213 >            s.next = stack;
3214 >            stack = s;
3215          }
3216  
3217          /**
3218 <         * Returns the result of accumulating the given transformation
3949 <         * of all values using the given reducer to combine values, or
3950 <         * null if none.
3218 >         * Possibly pops traversal state.
3219           *
3220 <         * @param transformer a function returning the transformation
3953 <         * for an element, or null of there is no transformation (in
3954 <         * which case it is not combined).
3955 <         * @param reducer a commutative associative combining function
3956 <         * @return the result of accumulating the given transformation
3957 <         * of all values
3220 >         * @param n length of current table
3221           */
3222 <        public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3223 <                                  BiFun<? super U, ? super U, ? extends U> reducer) {
3224 <            return fjp.invoke(ForkJoinTasks.reduceValues
3225 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3222 >        private void recoverState(int n) {
3223 >            TableStack<K,V> s; int len;
3224 >            while ((s = stack) != null && (index += (len = s.length)) >= n) {
3225 >                n = len;
3226 >                index = s.index;
3227 >                tab = s.tab;
3228 >                s.tab = null;
3229 >                TableStack<K,V> next = s.next;
3230 >                s.next = spare; // save for reuse
3231 >                stack = next;
3232 >                spare = s;
3233 >            }
3234 >            if (s == null && (index += baseSize) >= n)
3235 >                index = ++baseIndex;
3236          }
3237 +    }
3238  
3239 <        /**
3240 <         * Returns the result of accumulating the given transformation
3241 <         * of all values using the given reducer to combine values,
3242 <         * and the given basis as an identity value.
3243 <         *
3244 <         * @param transformer a function returning the transformation
3245 <         * for an element
3246 <         * @param basis the identity (initial default value) for the reduction
3247 <         * @param reducer a commutative associative combining function
3248 <         * @return the result of accumulating the given transformation
3249 <         * of all values
3250 <         */
3977 <        public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3978 <                                           double basis,
3979 <                                           DoubleByDoubleToDouble reducer) {
3980 <            return fjp.invoke(ForkJoinTasks.reduceValuesToDouble
3981 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3239 >    /**
3240 >     * Base of key, value, and entry Iterators. Adds fields to
3241 >     * Traverser to support iterator.remove.
3242 >     */
3243 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3244 >        final ConcurrentHashMapV8<K,V> map;
3245 >        Node<K,V> lastReturned;
3246 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3247 >                    ConcurrentHashMapV8<K,V> map) {
3248 >            super(tab, size, index, limit);
3249 >            this.map = map;
3250 >            advance();
3251          }
3252  
3253 <        /**
3254 <         * Returns the result of accumulating the given transformation
3255 <         * of all values using the given reducer to combine values,
3256 <         * and the given basis as an identity value.
3257 <         *
3258 <         * @param transformer a function returning the transformation
3259 <         * for an element
3260 <         * @param basis the identity (initial default value) for the reduction
3261 <         * @param reducer a commutative associative combining function
3993 <         * @return the result of accumulating the given transformation
3994 <         * of all values
3995 <         */
3996 <        public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3997 <                                       long basis,
3998 <                                       LongByLongToLong reducer) {
3999 <            return fjp.invoke(ForkJoinTasks.reduceValuesToLong
4000 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3253 >        public final boolean hasNext() { return next != null; }
3254 >        public final boolean hasMoreElements() { return next != null; }
3255 >
3256 >        public final void remove() {
3257 >            Node<K,V> p;
3258 >            if ((p = lastReturned) == null)
3259 >                throw new IllegalStateException();
3260 >            lastReturned = null;
3261 >            map.replaceNode(p.key, null, null);
3262          }
3263 +    }
3264  
3265 <        /**
3266 <         * Returns the result of accumulating the given transformation
3267 <         * of all values using the given reducer to combine values,
3268 <         * and the given basis as an identity value.
3269 <         *
4008 <         * @param transformer a function returning the transformation
4009 <         * for an element
4010 <         * @param basis the identity (initial default value) for the reduction
4011 <         * @param reducer a commutative associative combining function
4012 <         * @return the result of accumulating the given transformation
4013 <         * of all values
4014 <         */
4015 <        public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4016 <                                     int basis,
4017 <                                     IntByIntToInt reducer) {
4018 <            return fjp.invoke(ForkJoinTasks.reduceValuesToInt
4019 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3265 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3266 >        implements Iterator<K>, Enumeration<K> {
3267 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3268 >                    ConcurrentHashMapV8<K,V> map) {
3269 >            super(tab, index, size, limit, map);
3270          }
3271  
3272 <        /**
3273 <         * Performs the given action for each entry.
3274 <         *
3275 <         * @param action the action
3276 <         */
3277 <        public void forEachEntry(Action<Map.Entry<K,V>> action) {
3278 <            fjp.invoke(ForkJoinTasks.forEachEntry
3279 <                       (ConcurrentHashMapV8.this, action));
3272 >        public final K next() {
3273 >            Node<K,V> p;
3274 >            if ((p = next) == null)
3275 >                throw new NoSuchElementException();
3276 >            K k = p.key;
3277 >            lastReturned = p;
3278 >            advance();
3279 >            return k;
3280          }
3281  
3282 <        /**
3283 <         * Performs the given action for each non-null transformation
3284 <         * of each entry.
3285 <         *
3286 <         * @param transformer a function returning the transformation
3287 <         * for an element, or null of there is no transformation (in
3288 <         * which case the action is not applied).
3289 <         * @param action the action
4040 <         */
4041 <        public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4042 <                                     Action<U> action) {
4043 <            fjp.invoke(ForkJoinTasks.forEachEntry
4044 <                       (ConcurrentHashMapV8.this, transformer, action));
3282 >        public final K nextElement() { return next(); }
3283 >    }
3284 >
3285 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3286 >        implements Iterator<V>, Enumeration<V> {
3287 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3288 >                      ConcurrentHashMapV8<K,V> map) {
3289 >            super(tab, index, size, limit, map);
3290          }
3291  
3292 <        /**
3293 <         * Returns a non-null result from applying the given search
3294 <         * function on each entry, or null if none.  Upon success,
3295 <         * further element processing is suppressed and the results of
3296 <         * any other parallel invocations of the search function are
3297 <         * ignored.
3298 <         *
3299 <         * @param searchFunction a function returning a non-null
4055 <         * result on success, else null
4056 <         * @return a non-null result from applying the given search
4057 <         * function on each entry, or null if none
4058 <         */
4059 <        public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4060 <            return fjp.invoke(ForkJoinTasks.searchEntries
4061 <                              (ConcurrentHashMapV8.this, searchFunction));
3292 >        public final V next() {
3293 >            Node<K,V> p;
3294 >            if ((p = next) == null)
3295 >                throw new NoSuchElementException();
3296 >            V v = p.val;
3297 >            lastReturned = p;
3298 >            advance();
3299 >            return v;
3300          }
3301  
3302 <        /**
3303 <         * Returns the result of accumulating all entries using the
3304 <         * given reducer to combine values, or null if none.
3305 <         *
3306 <         * @param reducer a commutative associative combining function
3307 <         * @return the result of accumulating all entries
3308 <         */
3309 <        public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4072 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4073 <                              (ConcurrentHashMapV8.this, reducer));
3302 >        public final V nextElement() { return next(); }
3303 >    }
3304 >
3305 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3306 >        implements Iterator<Map.Entry<K,V>> {
3307 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3308 >                      ConcurrentHashMapV8<K,V> map) {
3309 >            super(tab, index, size, limit, map);
3310          }
3311  
3312 <        /**
3313 <         * Returns the result of accumulating the given transformation
3314 <         * of all entries using the given reducer to combine values,
3315 <         * or null if none.
3316 <         *
3317 <         * @param transformer a function returning the transformation
3318 <         * for an element, or null of there is no transformation (in
3319 <         * which case it is not combined).
3320 <         * @param reducer a commutative associative combining function
4085 <         * @return the result of accumulating the given transformation
4086 <         * of all entries
4087 <         */
4088 <        public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4089 <                                   BiFun<? super U, ? super U, ? extends U> reducer) {
4090 <            return fjp.invoke(ForkJoinTasks.reduceEntries
4091 <                              (ConcurrentHashMapV8.this, transformer, reducer));
3312 >        public final Map.Entry<K,V> next() {
3313 >            Node<K,V> p;
3314 >            if ((p = next) == null)
3315 >                throw new NoSuchElementException();
3316 >            K k = p.key;
3317 >            V v = p.val;
3318 >            lastReturned = p;
3319 >            advance();
3320 >            return new MapEntry<K,V>(k, v, map);
3321          }
3322 +    }
3323  
3324 <        /**
3325 <         * Returns the result of accumulating the given transformation
3326 <         * of all entries using the given reducer to combine values,
3327 <         * and the given basis as an identity value.
3328 <         *
3329 <         * @param transformer a function returning the transformation
3330 <         * for an element
3331 <         * @param basis the identity (initial default value) for the reduction
3332 <         * @param reducer a commutative associative combining function
3333 <         * @return the result of accumulating the given transformation
3334 <         * of all entries
4105 <         */
4106 <        public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4107 <                                            double basis,
4108 <                                            DoubleByDoubleToDouble reducer) {
4109 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToDouble
4110 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3324 >    /**
3325 >     * Exported Entry for EntryIterator
3326 >     */
3327 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3328 >        final K key; // non-null
3329 >        V val;       // non-null
3330 >        final ConcurrentHashMapV8<K,V> map;
3331 >        MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
3332 >            this.key = key;
3333 >            this.val = val;
3334 >            this.map = map;
3335          }
3336 +        public K getKey()        { return key; }
3337 +        public V getValue()      { return val; }
3338 +        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3339 +        public String toString() { return key + "=" + val; }
3340  
3341 <        /**
3342 <         * Returns the result of accumulating the given transformation
3343 <         * of all entries using the given reducer to combine values,
3344 <         * and the given basis as an identity value.
3345 <         *
3346 <         * @param transformer a function returning the transformation
3347 <         * for an element
4120 <         * @param basis the identity (initial default value) for the reduction
4121 <         * @param reducer a commutative associative combining function
4122 <         * @return  the result of accumulating the given transformation
4123 <         * of all entries
4124 <         */
4125 <        public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4126 <                                        long basis,
4127 <                                        LongByLongToLong reducer) {
4128 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToLong
4129 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3341 >        public boolean equals(Object o) {
3342 >            Object k, v; Map.Entry<?,?> e;
3343 >            return ((o instanceof Map.Entry) &&
3344 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3345 >                    (v = e.getValue()) != null &&
3346 >                    (k == key || k.equals(key)) &&
3347 >                    (v == val || v.equals(val)));
3348          }
3349  
3350          /**
3351 <         * Returns the result of accumulating the given transformation
3352 <         * of all entries using the given reducer to combine values,
3353 <         * and the given basis as an identity value.
3354 <         *
3355 <         * @param transformer a function returning the transformation
3356 <         * for an element
4139 <         * @param basis the identity (initial default value) for the reduction
4140 <         * @param reducer a commutative associative combining function
4141 <         * @return the result of accumulating the given transformation
4142 <         * of all entries
3351 >         * Sets our entry's value and writes through to the map. The
3352 >         * value to return is somewhat arbitrary here. Since we do not
3353 >         * necessarily track asynchronous changes, the most recent
3354 >         * "previous" value could be different from what we return (or
3355 >         * could even have been removed, in which case the put will
3356 >         * re-establish). We do not and cannot guarantee more.
3357           */
3358 <        public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
3359 <                                      int basis,
3360 <                                      IntByIntToInt reducer) {
3361 <            return fjp.invoke(ForkJoinTasks.reduceEntriesToInt
3362 <                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3358 >        public V setValue(V value) {
3359 >            if (value == null) throw new NullPointerException();
3360 >            V v = val;
3361 >            val = value;
3362 >            map.put(key, value);
3363 >            return v;
3364          }
3365      }
3366  
3367 <    // ---------------------------------------------------------------------
3367 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3368 >        implements ConcurrentHashMapSpliterator<K> {
3369 >        long est;               // size estimate
3370 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3371 >                       long est) {
3372 >            super(tab, size, index, limit);
3373 >            this.est = est;
3374 >        }
3375 >
3376 >        public ConcurrentHashMapSpliterator<K> trySplit() {
3377 >            int i, f, h;
3378 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3379 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3380 >                                        f, est >>>= 1);
3381 >        }
3382  
3383 <    /**
3384 <     * Predefined tasks for performing bulk parallel operations on
3385 <     * ConcurrentHashMaps. These tasks follow the forms and rules used
3386 <     * in class {@link Parallel}. Each method has the same name, but
3387 <     * returns a task rather than invoking it. These methods may be
4159 <     * useful in custom applications such as submitting a task without
4160 <     * waiting for completion, or combining with other tasks.
4161 <     */
4162 <    public static class ForkJoinTasks {
4163 <        private ForkJoinTasks() {}
3383 >        public void forEachRemaining(Action<? super K> action) {
3384 >            if (action == null) throw new NullPointerException();
3385 >            for (Node<K,V> p; (p = advance()) != null;)
3386 >                action.apply(p.key);
3387 >        }
3388  
3389 <        /**
4166 <         * Returns a task that when invoked, performs the given
4167 <         * action for each (key, value)
4168 <         *
4169 <         * @param map the map
4170 <         * @param action the action
4171 <         * @return the task
4172 <         */
4173 <        public static <K,V> ForkJoinTask<Void> forEach
4174 <            (ConcurrentHashMapV8<K,V> map,
4175 <             BiAction<K,V> action) {
3389 >        public boolean tryAdvance(Action<? super K> action) {
3390              if (action == null) throw new NullPointerException();
3391 <            return new ForEachMappingTask<K,V>(map, action);
3391 >            Node<K,V> p;
3392 >            if ((p = advance()) == null)
3393 >                return false;
3394 >            action.apply(p.key);
3395 >            return true;
3396          }
3397  
3398 <        /**
3399 <         * Returns a task that when invoked, performs the given
3400 <         * action for each non-null transformation of each (key, value)
3401 <         *
3402 <         * @param map the map
3403 <         * @param transformer a function returning the transformation
3404 <         * for an element, or null of there is no transformation (in
3405 <         * which case the action is not applied).
3406 <         * @param action the action
3407 <         * @return the task
3408 <         */
4191 <        public static <K,V,U> ForkJoinTask<Void> forEach
4192 <            (ConcurrentHashMapV8<K,V> map,
4193 <             BiFun<? super K, ? super V, ? extends U> transformer,
4194 <             Action<U> action) {
4195 <            if (transformer == null || action == null)
4196 <                throw new NullPointerException();
4197 <            return new ForEachTransformedMappingTask<K,V,U>
4198 <                (map, transformer, action);
3398 >        public long estimateSize() { return est; }
3399 >
3400 >    }
3401 >
3402 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3403 >        implements ConcurrentHashMapSpliterator<V> {
3404 >        long est;               // size estimate
3405 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3406 >                         long est) {
3407 >            super(tab, size, index, limit);
3408 >            this.est = est;
3409          }
3410  
3411 <        /**
3412 <         * Returns a task that when invoked, returns a non-null result
3413 <         * from applying the given search function on each (key,
3414 <         * value), or null if none. Upon success, further element
3415 <         * processing is suppressed and the results of any other
4206 <         * parallel invocations of the search function are ignored.
4207 <         *
4208 <         * @param map the map
4209 <         * @param searchFunction a function returning a non-null
4210 <         * result on success, else null
4211 <         * @return the task
4212 <         */
4213 <        public static <K,V,U> ForkJoinTask<U> search
4214 <            (ConcurrentHashMapV8<K,V> map,
4215 <             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4216 <            if (searchFunction == null) throw new NullPointerException();
4217 <            return new SearchMappingsTask<K,V,U>
4218 <                (map, searchFunction,
4219 <                 new AtomicReference<U>());
3411 >        public ConcurrentHashMapSpliterator<V> trySplit() {
3412 >            int i, f, h;
3413 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3414 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3415 >                                          f, est >>>= 1);
3416          }
3417  
3418 <        /**
3419 <         * Returns a task that when invoked, returns the result of
3420 <         * accumulating the given transformation of all (key, value) pairs
3421 <         * using the given reducer to combine values, or null if none.
4226 <         *
4227 <         * @param map the map
4228 <         * @param transformer a function returning the transformation
4229 <         * for an element, or null of there is no transformation (in
4230 <         * which case it is not combined).
4231 <         * @param reducer a commutative associative combining function
4232 <         * @return the task
4233 <         */
4234 <        public static <K,V,U> ForkJoinTask<U> reduce
4235 <            (ConcurrentHashMapV8<K,V> map,
4236 <             BiFun<? super K, ? super V, ? extends U> transformer,
4237 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4238 <            if (transformer == null || reducer == null)
4239 <                throw new NullPointerException();
4240 <            return new MapReduceMappingsTask<K,V,U>
4241 <                (map, transformer, reducer);
3418 >        public void forEachRemaining(Action<? super V> action) {
3419 >            if (action == null) throw new NullPointerException();
3420 >            for (Node<K,V> p; (p = advance()) != null;)
3421 >                action.apply(p.val);
3422          }
3423  
3424 <        /**
3425 <         * Returns a task that when invoked, returns the result of
3426 <         * accumulating the given transformation of all (key, value) pairs
3427 <         * using the given reducer to combine values, and the given
3428 <         * basis as an identity value.
3429 <         *
3430 <         * @param map the map
4251 <         * @param transformer a function returning the transformation
4252 <         * for an element
4253 <         * @param basis the identity (initial default value) for the reduction
4254 <         * @param reducer a commutative associative combining function
4255 <         * @return the task
4256 <         */
4257 <        public static <K,V> ForkJoinTask<Double> reduceToDouble
4258 <            (ConcurrentHashMapV8<K,V> map,
4259 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
4260 <             double basis,
4261 <             DoubleByDoubleToDouble reducer) {
4262 <            if (transformer == null || reducer == null)
4263 <                throw new NullPointerException();
4264 <            return new MapReduceMappingsToDoubleTask<K,V>
4265 <                (map, transformer, basis, reducer);
3424 >        public boolean tryAdvance(Action<? super V> action) {
3425 >            if (action == null) throw new NullPointerException();
3426 >            Node<K,V> p;
3427 >            if ((p = advance()) == null)
3428 >                return false;
3429 >            action.apply(p.val);
3430 >            return true;
3431          }
3432  
3433 <        /**
3434 <         * Returns a task that when invoked, returns the result of
3435 <         * accumulating the given transformation of all (key, value) pairs
3436 <         * using the given reducer to combine values, and the given
3437 <         * basis as an identity value.
3438 <         *
3439 <         * @param map the map
3440 <         * @param transformer a function returning the transformation
3441 <         * for an element
3442 <         * @param basis the identity (initial default value) for the reduction
3443 <         * @param reducer a commutative associative combining function
3444 <         * @return the task
3445 <         */
4281 <        public static <K,V> ForkJoinTask<Long> reduceToLong
4282 <            (ConcurrentHashMapV8<K,V> map,
4283 <             ObjectByObjectToLong<? super K, ? super V> transformer,
4284 <             long basis,
4285 <             LongByLongToLong reducer) {
4286 <            if (transformer == null || reducer == null)
4287 <                throw new NullPointerException();
4288 <            return new MapReduceMappingsToLongTask<K,V>
4289 <                (map, transformer, basis, reducer);
3433 >        public long estimateSize() { return est; }
3434 >
3435 >    }
3436 >
3437 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3438 >        implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
3439 >        final ConcurrentHashMapV8<K,V> map; // To export MapEntry
3440 >        long est;               // size estimate
3441 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3442 >                         long est, ConcurrentHashMapV8<K,V> map) {
3443 >            super(tab, size, index, limit);
3444 >            this.map = map;
3445 >            this.est = est;
3446          }
3447  
3448 <        /**
3449 <         * Returns a task that when invoked, returns the result of
3450 <         * accumulating the given transformation of all (key, value) pairs
3451 <         * using the given reducer to combine values, and the given
3452 <         * basis as an identity value.
4297 <         *
4298 <         * @param transformer a function returning the transformation
4299 <         * for an element
4300 <         * @param basis the identity (initial default value) for the reduction
4301 <         * @param reducer a commutative associative combining function
4302 <         * @return the task
4303 <         */
4304 <        public static <K,V> ForkJoinTask<Integer> reduceToInt
4305 <            (ConcurrentHashMapV8<K,V> map,
4306 <             ObjectByObjectToInt<? super K, ? super V> transformer,
4307 <             int basis,
4308 <             IntByIntToInt reducer) {
4309 <            if (transformer == null || reducer == null)
4310 <                throw new NullPointerException();
4311 <            return new MapReduceMappingsToIntTask<K,V>
4312 <                (map, transformer, basis, reducer);
3448 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
3449 >            int i, f, h;
3450 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3451 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3452 >                                          f, est >>>= 1, map);
3453          }
3454  
3455 <        /**
4316 <         * Returns a task that when invoked, performs the given action
4317 <         * for each key.
4318 <         *
4319 <         * @param map the map
4320 <         * @param action the action
4321 <         * @return the task
4322 <         */
4323 <        public static <K,V> ForkJoinTask<Void> forEachKey
4324 <            (ConcurrentHashMapV8<K,V> map,
4325 <             Action<K> action) {
3455 >        public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
3456              if (action == null) throw new NullPointerException();
3457 <            return new ForEachKeyTask<K,V>(map, action);
3457 >            for (Node<K,V> p; (p = advance()) != null; )
3458 >                action.apply(new MapEntry<K,V>(p.key, p.val, map));
3459          }
3460  
3461 <        /**
3462 <         * Returns a task that when invoked, performs the given action
3463 <         * for each non-null transformation of each key.
3464 <         *
3465 <         * @param map the map
3466 <         * @param transformer a function returning the transformation
3467 <         * for an element, or null of there is no transformation (in
4337 <         * which case the action is not applied).
4338 <         * @param action the action
4339 <         * @return the task
4340 <         */
4341 <        public static <K,V,U> ForkJoinTask<Void> forEachKey
4342 <            (ConcurrentHashMapV8<K,V> map,
4343 <             Fun<? super K, ? extends U> transformer,
4344 <             Action<U> action) {
4345 <            if (transformer == null || action == null)
4346 <                throw new NullPointerException();
4347 <            return new ForEachTransformedKeyTask<K,V,U>
4348 <                (map, transformer, action);
3461 >        public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
3462 >            if (action == null) throw new NullPointerException();
3463 >            Node<K,V> p;
3464 >            if ((p = advance()) == null)
3465 >                return false;
3466 >            action.apply(new MapEntry<K,V>(p.key, p.val, map));
3467 >            return true;
3468          }
3469  
3470 +        public long estimateSize() { return est; }
3471 +
3472 +    }
3473 +
3474 +    // Parallel bulk operations
3475 +
3476 +    /**
3477 +     * Computes initial batch value for bulk tasks. The returned value
3478 +     * is approximately exp2 of the number of times (minus one) to
3479 +     * split task by two before executing leaf action. This value is
3480 +     * faster to compute and more convenient to use as a guide to
3481 +     * splitting than is the depth, since it is used while dividing by
3482 +     * two anyway.
3483 +     */
3484 +    final int batchFor(long b) {
3485 +        long n;
3486 +        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3487 +            return 0;
3488 +        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3489 +        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3490 +    }
3491 +
3492 +    /**
3493 +     * Performs the given action for each (key, value).
3494 +     *
3495 +     * @param parallelismThreshold the (estimated) number of elements
3496 +     * needed for this operation to be executed in parallel
3497 +     * @param action the action
3498 +     * @since 1.8
3499 +     */
3500 +    public void forEach(long parallelismThreshold,
3501 +                        BiAction<? super K,? super V> action) {
3502 +        if (action == null) throw new NullPointerException();
3503 +        new ForEachMappingTask<K,V>
3504 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3505 +             action).invoke();
3506 +    }
3507 +
3508 +    /**
3509 +     * Performs the given action for each non-null transformation
3510 +     * of each (key, value).
3511 +     *
3512 +     * @param parallelismThreshold the (estimated) number of elements
3513 +     * needed for this operation to be executed in parallel
3514 +     * @param transformer a function returning the transformation
3515 +     * for an element, or null if there is no transformation (in
3516 +     * which case the action is not applied)
3517 +     * @param action the action
3518 +     * @since 1.8
3519 +     */
3520 +    public <U> void forEach(long parallelismThreshold,
3521 +                            BiFun<? super K, ? super V, ? extends U> transformer,
3522 +                            Action<? super U> action) {
3523 +        if (transformer == null || action == null)
3524 +            throw new NullPointerException();
3525 +        new ForEachTransformedMappingTask<K,V,U>
3526 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3527 +             transformer, action).invoke();
3528 +    }
3529 +
3530 +    /**
3531 +     * Returns a non-null result from applying the given search
3532 +     * function on each (key, value), or null if none.  Upon
3533 +     * success, further element processing is suppressed and the
3534 +     * results of any other parallel invocations of the search
3535 +     * function are ignored.
3536 +     *
3537 +     * @param parallelismThreshold the (estimated) number of elements
3538 +     * needed for this operation to be executed in parallel
3539 +     * @param searchFunction a function returning a non-null
3540 +     * result on success, else null
3541 +     * @return a non-null result from applying the given search
3542 +     * function on each (key, value), or null if none
3543 +     * @since 1.8
3544 +     */
3545 +    public <U> U search(long parallelismThreshold,
3546 +                        BiFun<? super K, ? super V, ? extends U> searchFunction) {
3547 +        if (searchFunction == null) throw new NullPointerException();
3548 +        return new SearchMappingsTask<K,V,U>
3549 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3550 +             searchFunction, new AtomicReference<U>()).invoke();
3551 +    }
3552 +
3553 +    /**
3554 +     * Returns the result of accumulating the given transformation
3555 +     * of all (key, value) pairs using the given reducer to
3556 +     * combine values, or null if none.
3557 +     *
3558 +     * @param parallelismThreshold the (estimated) number of elements
3559 +     * needed for this operation to be executed in parallel
3560 +     * @param transformer a function returning the transformation
3561 +     * for an element, or null if there is no transformation (in
3562 +     * which case it is not combined)
3563 +     * @param reducer a commutative associative combining function
3564 +     * @return the result of accumulating the given transformation
3565 +     * of all (key, value) pairs
3566 +     * @since 1.8
3567 +     */
3568 +    public <U> U reduce(long parallelismThreshold,
3569 +                        BiFun<? super K, ? super V, ? extends U> transformer,
3570 +                        BiFun<? super U, ? super U, ? extends U> reducer) {
3571 +        if (transformer == null || reducer == null)
3572 +            throw new NullPointerException();
3573 +        return new MapReduceMappingsTask<K,V,U>
3574 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3575 +             null, transformer, reducer).invoke();
3576 +    }
3577 +
3578 +    /**
3579 +     * Returns the result of accumulating the given transformation
3580 +     * of all (key, value) pairs using the given reducer to
3581 +     * combine values, and the given basis as an identity value.
3582 +     *
3583 +     * @param parallelismThreshold the (estimated) number of elements
3584 +     * needed for this operation to be executed in parallel
3585 +     * @param transformer a function returning the transformation
3586 +     * for an element
3587 +     * @param basis the identity (initial default value) for the reduction
3588 +     * @param reducer a commutative associative combining function
3589 +     * @return the result of accumulating the given transformation
3590 +     * of all (key, value) pairs
3591 +     * @since 1.8
3592 +     */
3593 +    public double reduceToDouble(long parallelismThreshold,
3594 +                                 ObjectByObjectToDouble<? super K, ? super V> transformer,
3595 +                                 double basis,
3596 +                                 DoubleByDoubleToDouble reducer) {
3597 +        if (transformer == null || reducer == null)
3598 +            throw new NullPointerException();
3599 +        return new MapReduceMappingsToDoubleTask<K,V>
3600 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3601 +             null, transformer, basis, reducer).invoke();
3602 +    }
3603 +
3604 +    /**
3605 +     * Returns the result of accumulating the given transformation
3606 +     * of all (key, value) pairs using the given reducer to
3607 +     * combine values, and the given basis as an identity value.
3608 +     *
3609 +     * @param parallelismThreshold the (estimated) number of elements
3610 +     * needed for this operation to be executed in parallel
3611 +     * @param transformer a function returning the transformation
3612 +     * for an element
3613 +     * @param basis the identity (initial default value) for the reduction
3614 +     * @param reducer a commutative associative combining function
3615 +     * @return the result of accumulating the given transformation
3616 +     * of all (key, value) pairs
3617 +     * @since 1.8
3618 +     */
3619 +    public long reduceToLong(long parallelismThreshold,
3620 +                             ObjectByObjectToLong<? super K, ? super V> transformer,
3621 +                             long basis,
3622 +                             LongByLongToLong reducer) {
3623 +        if (transformer == null || reducer == null)
3624 +            throw new NullPointerException();
3625 +        return new MapReduceMappingsToLongTask<K,V>
3626 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3627 +             null, transformer, basis, reducer).invoke();
3628 +    }
3629 +
3630 +    /**
3631 +     * Returns the result of accumulating the given transformation
3632 +     * of all (key, value) pairs using the given reducer to
3633 +     * combine values, and the given basis as an identity value.
3634 +     *
3635 +     * @param parallelismThreshold the (estimated) number of elements
3636 +     * needed for this operation to be executed in parallel
3637 +     * @param transformer a function returning the transformation
3638 +     * for an element
3639 +     * @param basis the identity (initial default value) for the reduction
3640 +     * @param reducer a commutative associative combining function
3641 +     * @return the result of accumulating the given transformation
3642 +     * of all (key, value) pairs
3643 +     * @since 1.8
3644 +     */
3645 +    public int reduceToInt(long parallelismThreshold,
3646 +                           ObjectByObjectToInt<? super K, ? super V> transformer,
3647 +                           int basis,
3648 +                           IntByIntToInt reducer) {
3649 +        if (transformer == null || reducer == null)
3650 +            throw new NullPointerException();
3651 +        return new MapReduceMappingsToIntTask<K,V>
3652 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3653 +             null, transformer, basis, reducer).invoke();
3654 +    }
3655 +
3656 +    /**
3657 +     * Performs the given action for each key.
3658 +     *
3659 +     * @param parallelismThreshold the (estimated) number of elements
3660 +     * needed for this operation to be executed in parallel
3661 +     * @param action the action
3662 +     * @since 1.8
3663 +     */
3664 +    public void forEachKey(long parallelismThreshold,
3665 +                           Action<? super K> action) {
3666 +        if (action == null) throw new NullPointerException();
3667 +        new ForEachKeyTask<K,V>
3668 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3669 +             action).invoke();
3670 +    }
3671 +
3672 +    /**
3673 +     * Performs the given action for each non-null transformation
3674 +     * of each key.
3675 +     *
3676 +     * @param parallelismThreshold the (estimated) number of elements
3677 +     * needed for this operation to be executed in parallel
3678 +     * @param transformer a function returning the transformation
3679 +     * for an element, or null if there is no transformation (in
3680 +     * which case the action is not applied)
3681 +     * @param action the action
3682 +     * @since 1.8
3683 +     */
3684 +    public <U> void forEachKey(long parallelismThreshold,
3685 +                               Fun<? super K, ? extends U> transformer,
3686 +                               Action<? super U> action) {
3687 +        if (transformer == null || action == null)
3688 +            throw new NullPointerException();
3689 +        new ForEachTransformedKeyTask<K,V,U>
3690 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3691 +             transformer, action).invoke();
3692 +    }
3693 +
3694 +    /**
3695 +     * Returns a non-null result from applying the given search
3696 +     * function on each key, or null if none. Upon success,
3697 +     * further element processing is suppressed and the results of
3698 +     * any other parallel invocations of the search function are
3699 +     * ignored.
3700 +     *
3701 +     * @param parallelismThreshold the (estimated) number of elements
3702 +     * needed for this operation to be executed in parallel
3703 +     * @param searchFunction a function returning a non-null
3704 +     * result on success, else null
3705 +     * @return a non-null result from applying the given search
3706 +     * function on each key, or null if none
3707 +     * @since 1.8
3708 +     */
3709 +    public <U> U searchKeys(long parallelismThreshold,
3710 +                            Fun<? super K, ? extends U> searchFunction) {
3711 +        if (searchFunction == null) throw new NullPointerException();
3712 +        return new SearchKeysTask<K,V,U>
3713 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3714 +             searchFunction, new AtomicReference<U>()).invoke();
3715 +    }
3716 +
3717 +    /**
3718 +     * Returns the result of accumulating all keys using the given
3719 +     * reducer to combine values, or null if none.
3720 +     *
3721 +     * @param parallelismThreshold the (estimated) number of elements
3722 +     * needed for this operation to be executed in parallel
3723 +     * @param reducer a commutative associative combining function
3724 +     * @return the result of accumulating all keys using the given
3725 +     * reducer to combine values, or null if none
3726 +     * @since 1.8
3727 +     */
3728 +    public K reduceKeys(long parallelismThreshold,
3729 +                        BiFun<? super K, ? super K, ? extends K> reducer) {
3730 +        if (reducer == null) throw new NullPointerException();
3731 +        return new ReduceKeysTask<K,V>
3732 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3733 +             null, reducer).invoke();
3734 +    }
3735 +
3736 +    /**
3737 +     * Returns the result of accumulating the given transformation
3738 +     * of all keys using the given reducer to combine values, or
3739 +     * null if none.
3740 +     *
3741 +     * @param parallelismThreshold the (estimated) number of elements
3742 +     * needed for this operation to be executed in parallel
3743 +     * @param transformer a function returning the transformation
3744 +     * for an element, or null if there is no transformation (in
3745 +     * which case it is not combined)
3746 +     * @param reducer a commutative associative combining function
3747 +     * @return the result of accumulating the given transformation
3748 +     * of all keys
3749 +     * @since 1.8
3750 +     */
3751 +    public <U> U reduceKeys(long parallelismThreshold,
3752 +                            Fun<? super K, ? extends U> transformer,
3753 +         BiFun<? super U, ? super U, ? extends U> reducer) {
3754 +        if (transformer == null || reducer == null)
3755 +            throw new NullPointerException();
3756 +        return new MapReduceKeysTask<K,V,U>
3757 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3758 +             null, transformer, reducer).invoke();
3759 +    }
3760 +
3761 +    /**
3762 +     * Returns the result of accumulating the given transformation
3763 +     * of all keys using the given reducer to combine values, and
3764 +     * the given basis as an identity value.
3765 +     *
3766 +     * @param parallelismThreshold the (estimated) number of elements
3767 +     * needed for this operation to be executed in parallel
3768 +     * @param transformer a function returning the transformation
3769 +     * for an element
3770 +     * @param basis the identity (initial default value) for the reduction
3771 +     * @param reducer a commutative associative combining function
3772 +     * @return the result of accumulating the given transformation
3773 +     * of all keys
3774 +     * @since 1.8
3775 +     */
3776 +    public double reduceKeysToDouble(long parallelismThreshold,
3777 +                                     ObjectToDouble<? super K> transformer,
3778 +                                     double basis,
3779 +                                     DoubleByDoubleToDouble reducer) {
3780 +        if (transformer == null || reducer == null)
3781 +            throw new NullPointerException();
3782 +        return new MapReduceKeysToDoubleTask<K,V>
3783 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3784 +             null, transformer, basis, reducer).invoke();
3785 +    }
3786 +
3787 +    /**
3788 +     * Returns the result of accumulating the given transformation
3789 +     * of all keys using the given reducer to combine values, and
3790 +     * the given basis as an identity value.
3791 +     *
3792 +     * @param parallelismThreshold the (estimated) number of elements
3793 +     * needed for this operation to be executed in parallel
3794 +     * @param transformer a function returning the transformation
3795 +     * for an element
3796 +     * @param basis the identity (initial default value) for the reduction
3797 +     * @param reducer a commutative associative combining function
3798 +     * @return the result of accumulating the given transformation
3799 +     * of all keys
3800 +     * @since 1.8
3801 +     */
3802 +    public long reduceKeysToLong(long parallelismThreshold,
3803 +                                 ObjectToLong<? super K> transformer,
3804 +                                 long basis,
3805 +                                 LongByLongToLong reducer) {
3806 +        if (transformer == null || reducer == null)
3807 +            throw new NullPointerException();
3808 +        return new MapReduceKeysToLongTask<K,V>
3809 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3810 +             null, transformer, basis, reducer).invoke();
3811 +    }
3812 +
3813 +    /**
3814 +     * Returns the result of accumulating the given transformation
3815 +     * of all keys using the given reducer to combine values, and
3816 +     * the given basis as an identity value.
3817 +     *
3818 +     * @param parallelismThreshold the (estimated) number of elements
3819 +     * needed for this operation to be executed in parallel
3820 +     * @param transformer a function returning the transformation
3821 +     * for an element
3822 +     * @param basis the identity (initial default value) for the reduction
3823 +     * @param reducer a commutative associative combining function
3824 +     * @return the result of accumulating the given transformation
3825 +     * of all keys
3826 +     * @since 1.8
3827 +     */
3828 +    public int reduceKeysToInt(long parallelismThreshold,
3829 +                               ObjectToInt<? super K> transformer,
3830 +                               int basis,
3831 +                               IntByIntToInt reducer) {
3832 +        if (transformer == null || reducer == null)
3833 +            throw new NullPointerException();
3834 +        return new MapReduceKeysToIntTask<K,V>
3835 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3836 +             null, transformer, basis, reducer).invoke();
3837 +    }
3838 +
3839 +    /**
3840 +     * Performs the given action for each value.
3841 +     *
3842 +     * @param parallelismThreshold the (estimated) number of elements
3843 +     * needed for this operation to be executed in parallel
3844 +     * @param action the action
3845 +     * @since 1.8
3846 +     */
3847 +    public void forEachValue(long parallelismThreshold,
3848 +                             Action<? super V> action) {
3849 +        if (action == null)
3850 +            throw new NullPointerException();
3851 +        new ForEachValueTask<K,V>
3852 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3853 +             action).invoke();
3854 +    }
3855 +
3856 +    /**
3857 +     * Performs the given action for each non-null transformation
3858 +     * of each value.
3859 +     *
3860 +     * @param parallelismThreshold the (estimated) number of elements
3861 +     * needed for this operation to be executed in parallel
3862 +     * @param transformer a function returning the transformation
3863 +     * for an element, or null if there is no transformation (in
3864 +     * which case the action is not applied)
3865 +     * @param action the action
3866 +     * @since 1.8
3867 +     */
3868 +    public <U> void forEachValue(long parallelismThreshold,
3869 +                                 Fun<? super V, ? extends U> transformer,
3870 +                                 Action<? super U> action) {
3871 +        if (transformer == null || action == null)
3872 +            throw new NullPointerException();
3873 +        new ForEachTransformedValueTask<K,V,U>
3874 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3875 +             transformer, action).invoke();
3876 +    }
3877 +
3878 +    /**
3879 +     * Returns a non-null result from applying the given search
3880 +     * function on each value, or null if none.  Upon success,
3881 +     * further element processing is suppressed and the results of
3882 +     * any other parallel invocations of the search function are
3883 +     * ignored.
3884 +     *
3885 +     * @param parallelismThreshold the (estimated) number of elements
3886 +     * needed for this operation to be executed in parallel
3887 +     * @param searchFunction a function returning a non-null
3888 +     * result on success, else null
3889 +     * @return a non-null result from applying the given search
3890 +     * function on each value, or null if none
3891 +     * @since 1.8
3892 +     */
3893 +    public <U> U searchValues(long parallelismThreshold,
3894 +                              Fun<? super V, ? extends U> searchFunction) {
3895 +        if (searchFunction == null) throw new NullPointerException();
3896 +        return new SearchValuesTask<K,V,U>
3897 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3898 +             searchFunction, new AtomicReference<U>()).invoke();
3899 +    }
3900 +
3901 +    /**
3902 +     * Returns the result of accumulating all values using the
3903 +     * given reducer to combine values, or null if none.
3904 +     *
3905 +     * @param parallelismThreshold the (estimated) number of elements
3906 +     * needed for this operation to be executed in parallel
3907 +     * @param reducer a commutative associative combining function
3908 +     * @return the result of accumulating all values
3909 +     * @since 1.8
3910 +     */
3911 +    public V reduceValues(long parallelismThreshold,
3912 +                          BiFun<? super V, ? super V, ? extends V> reducer) {
3913 +        if (reducer == null) throw new NullPointerException();
3914 +        return new ReduceValuesTask<K,V>
3915 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3916 +             null, reducer).invoke();
3917 +    }
3918 +
3919 +    /**
3920 +     * Returns the result of accumulating the given transformation
3921 +     * of all values using the given reducer to combine values, or
3922 +     * null if none.
3923 +     *
3924 +     * @param parallelismThreshold the (estimated) number of elements
3925 +     * needed for this operation to be executed in parallel
3926 +     * @param transformer a function returning the transformation
3927 +     * for an element, or null if there is no transformation (in
3928 +     * which case it is not combined)
3929 +     * @param reducer a commutative associative combining function
3930 +     * @return the result of accumulating the given transformation
3931 +     * of all values
3932 +     * @since 1.8
3933 +     */
3934 +    public <U> U reduceValues(long parallelismThreshold,
3935 +                              Fun<? super V, ? extends U> transformer,
3936 +                              BiFun<? super U, ? super U, ? extends U> reducer) {
3937 +        if (transformer == null || reducer == null)
3938 +            throw new NullPointerException();
3939 +        return new MapReduceValuesTask<K,V,U>
3940 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3941 +             null, transformer, reducer).invoke();
3942 +    }
3943 +
3944 +    /**
3945 +     * Returns the result of accumulating the given transformation
3946 +     * of all values using the given reducer to combine values,
3947 +     * and the given basis as an identity value.
3948 +     *
3949 +     * @param parallelismThreshold the (estimated) number of elements
3950 +     * needed for this operation to be executed in parallel
3951 +     * @param transformer a function returning the transformation
3952 +     * for an element
3953 +     * @param basis the identity (initial default value) for the reduction
3954 +     * @param reducer a commutative associative combining function
3955 +     * @return the result of accumulating the given transformation
3956 +     * of all values
3957 +     * @since 1.8
3958 +     */
3959 +    public double reduceValuesToDouble(long parallelismThreshold,
3960 +                                       ObjectToDouble<? super V> transformer,
3961 +                                       double basis,
3962 +                                       DoubleByDoubleToDouble reducer) {
3963 +        if (transformer == null || reducer == null)
3964 +            throw new NullPointerException();
3965 +        return new MapReduceValuesToDoubleTask<K,V>
3966 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3967 +             null, transformer, basis, reducer).invoke();
3968 +    }
3969 +
3970 +    /**
3971 +     * Returns the result of accumulating the given transformation
3972 +     * of all values using the given reducer to combine values,
3973 +     * and the given basis as an identity value.
3974 +     *
3975 +     * @param parallelismThreshold the (estimated) number of elements
3976 +     * needed for this operation to be executed in parallel
3977 +     * @param transformer a function returning the transformation
3978 +     * for an element
3979 +     * @param basis the identity (initial default value) for the reduction
3980 +     * @param reducer a commutative associative combining function
3981 +     * @return the result of accumulating the given transformation
3982 +     * of all values
3983 +     * @since 1.8
3984 +     */
3985 +    public long reduceValuesToLong(long parallelismThreshold,
3986 +                                   ObjectToLong<? super V> transformer,
3987 +                                   long basis,
3988 +                                   LongByLongToLong reducer) {
3989 +        if (transformer == null || reducer == null)
3990 +            throw new NullPointerException();
3991 +        return new MapReduceValuesToLongTask<K,V>
3992 +            (null, batchFor(parallelismThreshold), 0, 0, table,
3993 +             null, transformer, basis, reducer).invoke();
3994 +    }
3995 +
3996 +    /**
3997 +     * Returns the result of accumulating the given transformation
3998 +     * of all values using the given reducer to combine values,
3999 +     * and the given basis as an identity value.
4000 +     *
4001 +     * @param parallelismThreshold the (estimated) number of elements
4002 +     * needed for this operation to be executed in parallel
4003 +     * @param transformer a function returning the transformation
4004 +     * for an element
4005 +     * @param basis the identity (initial default value) for the reduction
4006 +     * @param reducer a commutative associative combining function
4007 +     * @return the result of accumulating the given transformation
4008 +     * of all values
4009 +     * @since 1.8
4010 +     */
4011 +    public int reduceValuesToInt(long parallelismThreshold,
4012 +                                 ObjectToInt<? super V> transformer,
4013 +                                 int basis,
4014 +                                 IntByIntToInt reducer) {
4015 +        if (transformer == null || reducer == null)
4016 +            throw new NullPointerException();
4017 +        return new MapReduceValuesToIntTask<K,V>
4018 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4019 +             null, transformer, basis, reducer).invoke();
4020 +    }
4021 +
4022 +    /**
4023 +     * Performs the given action for each entry.
4024 +     *
4025 +     * @param parallelismThreshold the (estimated) number of elements
4026 +     * needed for this operation to be executed in parallel
4027 +     * @param action the action
4028 +     * @since 1.8
4029 +     */
4030 +    public void forEachEntry(long parallelismThreshold,
4031 +                             Action<? super Map.Entry<K,V>> action) {
4032 +        if (action == null) throw new NullPointerException();
4033 +        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4034 +                                  action).invoke();
4035 +    }
4036 +
4037 +    /**
4038 +     * Performs the given action for each non-null transformation
4039 +     * of each entry.
4040 +     *
4041 +     * @param parallelismThreshold the (estimated) number of elements
4042 +     * needed for this operation to be executed in parallel
4043 +     * @param transformer a function returning the transformation
4044 +     * for an element, or null if there is no transformation (in
4045 +     * which case the action is not applied)
4046 +     * @param action the action
4047 +     * @since 1.8
4048 +     */
4049 +    public <U> void forEachEntry(long parallelismThreshold,
4050 +                                 Fun<Map.Entry<K,V>, ? extends U> transformer,
4051 +                                 Action<? super U> action) {
4052 +        if (transformer == null || action == null)
4053 +            throw new NullPointerException();
4054 +        new ForEachTransformedEntryTask<K,V,U>
4055 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4056 +             transformer, action).invoke();
4057 +    }
4058 +
4059 +    /**
4060 +     * Returns a non-null result from applying the given search
4061 +     * function on each entry, or null if none.  Upon success,
4062 +     * further element processing is suppressed and the results of
4063 +     * any other parallel invocations of the search function are
4064 +     * ignored.
4065 +     *
4066 +     * @param parallelismThreshold the (estimated) number of elements
4067 +     * needed for this operation to be executed in parallel
4068 +     * @param searchFunction a function returning a non-null
4069 +     * result on success, else null
4070 +     * @return a non-null result from applying the given search
4071 +     * function on each entry, or null if none
4072 +     * @since 1.8
4073 +     */
4074 +    public <U> U searchEntries(long parallelismThreshold,
4075 +                               Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4076 +        if (searchFunction == null) throw new NullPointerException();
4077 +        return new SearchEntriesTask<K,V,U>
4078 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4079 +             searchFunction, new AtomicReference<U>()).invoke();
4080 +    }
4081 +
4082 +    /**
4083 +     * Returns the result of accumulating all entries using the
4084 +     * given reducer to combine values, or null if none.
4085 +     *
4086 +     * @param parallelismThreshold the (estimated) number of elements
4087 +     * needed for this operation to be executed in parallel
4088 +     * @param reducer a commutative associative combining function
4089 +     * @return the result of accumulating all entries
4090 +     * @since 1.8
4091 +     */
4092 +    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4093 +                                        BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4094 +        if (reducer == null) throw new NullPointerException();
4095 +        return new ReduceEntriesTask<K,V>
4096 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4097 +             null, reducer).invoke();
4098 +    }
4099 +
4100 +    /**
4101 +     * Returns the result of accumulating the given transformation
4102 +     * of all entries using the given reducer to combine values,
4103 +     * or null if none.
4104 +     *
4105 +     * @param parallelismThreshold the (estimated) number of elements
4106 +     * needed for this operation to be executed in parallel
4107 +     * @param transformer a function returning the transformation
4108 +     * for an element, or null if there is no transformation (in
4109 +     * which case it is not combined)
4110 +     * @param reducer a commutative associative combining function
4111 +     * @return the result of accumulating the given transformation
4112 +     * of all entries
4113 +     * @since 1.8
4114 +     */
4115 +    public <U> U reduceEntries(long parallelismThreshold,
4116 +                               Fun<Map.Entry<K,V>, ? extends U> transformer,
4117 +                               BiFun<? super U, ? super U, ? extends U> reducer) {
4118 +        if (transformer == null || reducer == null)
4119 +            throw new NullPointerException();
4120 +        return new MapReduceEntriesTask<K,V,U>
4121 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4122 +             null, transformer, reducer).invoke();
4123 +    }
4124 +
4125 +    /**
4126 +     * Returns the result of accumulating the given transformation
4127 +     * of all entries using the given reducer to combine values,
4128 +     * and the given basis as an identity value.
4129 +     *
4130 +     * @param parallelismThreshold the (estimated) number of elements
4131 +     * needed for this operation to be executed in parallel
4132 +     * @param transformer a function returning the transformation
4133 +     * for an element
4134 +     * @param basis the identity (initial default value) for the reduction
4135 +     * @param reducer a commutative associative combining function
4136 +     * @return the result of accumulating the given transformation
4137 +     * of all entries
4138 +     * @since 1.8
4139 +     */
4140 +    public double reduceEntriesToDouble(long parallelismThreshold,
4141 +                                        ObjectToDouble<Map.Entry<K,V>> transformer,
4142 +                                        double basis,
4143 +                                        DoubleByDoubleToDouble reducer) {
4144 +        if (transformer == null || reducer == null)
4145 +            throw new NullPointerException();
4146 +        return new MapReduceEntriesToDoubleTask<K,V>
4147 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4148 +             null, transformer, basis, reducer).invoke();
4149 +    }
4150 +
4151 +    /**
4152 +     * Returns the result of accumulating the given transformation
4153 +     * of all entries using the given reducer to combine values,
4154 +     * and the given basis as an identity value.
4155 +     *
4156 +     * @param parallelismThreshold the (estimated) number of elements
4157 +     * needed for this operation to be executed in parallel
4158 +     * @param transformer a function returning the transformation
4159 +     * for an element
4160 +     * @param basis the identity (initial default value) for the reduction
4161 +     * @param reducer a commutative associative combining function
4162 +     * @return the result of accumulating the given transformation
4163 +     * of all entries
4164 +     * @since 1.8
4165 +     */
4166 +    public long reduceEntriesToLong(long parallelismThreshold,
4167 +                                    ObjectToLong<Map.Entry<K,V>> transformer,
4168 +                                    long basis,
4169 +                                    LongByLongToLong reducer) {
4170 +        if (transformer == null || reducer == null)
4171 +            throw new NullPointerException();
4172 +        return new MapReduceEntriesToLongTask<K,V>
4173 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4174 +             null, transformer, basis, reducer).invoke();
4175 +    }
4176 +
4177 +    /**
4178 +     * Returns the result of accumulating the given transformation
4179 +     * of all entries using the given reducer to combine values,
4180 +     * and the given basis as an identity value.
4181 +     *
4182 +     * @param parallelismThreshold the (estimated) number of elements
4183 +     * needed for this operation to be executed in parallel
4184 +     * @param transformer a function returning the transformation
4185 +     * for an element
4186 +     * @param basis the identity (initial default value) for the reduction
4187 +     * @param reducer a commutative associative combining function
4188 +     * @return the result of accumulating the given transformation
4189 +     * of all entries
4190 +     * @since 1.8
4191 +     */
4192 +    public int reduceEntriesToInt(long parallelismThreshold,
4193 +                                  ObjectToInt<Map.Entry<K,V>> transformer,
4194 +                                  int basis,
4195 +                                  IntByIntToInt reducer) {
4196 +        if (transformer == null || reducer == null)
4197 +            throw new NullPointerException();
4198 +        return new MapReduceEntriesToIntTask<K,V>
4199 +            (null, batchFor(parallelismThreshold), 0, 0, table,
4200 +             null, transformer, basis, reducer).invoke();
4201 +    }
4202 +
4203 +
4204 +    /* ----------------Views -------------- */
4205 +
4206 +    /**
4207 +     * Base class for views.
4208 +     */
4209 +    abstract static class CollectionView<K,V,E>
4210 +        implements Collection<E>, java.io.Serializable {
4211 +        private static final long serialVersionUID = 7249069246763182397L;
4212 +        final ConcurrentHashMapV8<K,V> map;
4213 +        CollectionView(ConcurrentHashMapV8<K,V> map)  { this.map = map; }
4214 +
4215          /**
4216 <         * Returns a task that when invoked, returns a non-null result
4353 <         * from applying the given search function on each key, or
4354 <         * null if none.  Upon success, further element processing is
4355 <         * suppressed and the results of any other parallel
4356 <         * invocations of the search function are ignored.
4216 >         * Returns the map backing this view.
4217           *
4218 <         * @param map the map
4359 <         * @param searchFunction a function returning a non-null
4360 <         * result on success, else null
4361 <         * @return the task
4218 >         * @return the map backing this view
4219           */
4220 <        public static <K,V,U> ForkJoinTask<U> searchKeys
4364 <            (ConcurrentHashMapV8<K,V> map,
4365 <             Fun<? super K, ? extends U> searchFunction) {
4366 <            if (searchFunction == null) throw new NullPointerException();
4367 <            return new SearchKeysTask<K,V,U>
4368 <                (map, searchFunction,
4369 <                 new AtomicReference<U>());
4370 <        }
4220 >        public ConcurrentHashMapV8<K,V> getMap() { return map; }
4221  
4222          /**
4223 <         * Returns a task that when invoked, returns the result of
4224 <         * accumulating all keys using the given reducer to combine
4375 <         * values, or null if none.
4376 <         *
4377 <         * @param map the map
4378 <         * @param reducer a commutative associative combining function
4379 <         * @return the task
4223 >         * Removes all of the elements from this view, by removing all
4224 >         * the mappings from the map backing this view.
4225           */
4226 <        public static <K,V> ForkJoinTask<K> reduceKeys
4227 <            (ConcurrentHashMapV8<K,V> map,
4228 <             BiFun<? super K, ? super K, ? extends K> reducer) {
4384 <            if (reducer == null) throw new NullPointerException();
4385 <            return new ReduceKeysTask<K,V>
4386 <                (map, reducer);
4387 <        }
4226 >        public final void clear()      { map.clear(); }
4227 >        public final int size()        { return map.size(); }
4228 >        public final boolean isEmpty() { return map.isEmpty(); }
4229  
4230 +        // implementations below rely on concrete classes supplying these
4231 +        // abstract methods
4232          /**
4233 <         * Returns a task that when invoked, returns the result of
4234 <         * accumulating the given transformation of all keys using the given
4235 <         * reducer to combine values, or null if none.
4236 <         *
4237 <         * @param map the map
4238 <         * @param transformer a function returning the transformation
4239 <         * for an element, or null of there is no transformation (in
4240 <         * which case it is not combined).
4241 <         * @param reducer a commutative associative combining function
4242 <         * @return the task
4243 <         */
4244 <        public static <K,V,U> ForkJoinTask<U> reduceKeys
4245 <            (ConcurrentHashMapV8<K,V> map,
4246 <             Fun<? super K, ? extends U> transformer,
4247 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4248 <            if (transformer == null || reducer == null)
4249 <                throw new NullPointerException();
4250 <            return new MapReduceKeysTask<K,V,U>
4251 <                (map, transformer, reducer);
4233 >         * Returns a "weakly consistent" iterator that will never
4234 >         * throw {@link ConcurrentModificationException}, and
4235 >         * guarantees to traverse elements as they existed upon
4236 >         * construction of the iterator, and may (but is not
4237 >         * guaranteed to) reflect any modifications subsequent to
4238 >         * construction.
4239 >         */
4240 >        public abstract Iterator<E> iterator();
4241 >        public abstract boolean contains(Object o);
4242 >        public abstract boolean remove(Object o);
4243 >
4244 >        private static final String oomeMsg = "Required array size too large";
4245 >
4246 >        public final Object[] toArray() {
4247 >            long sz = map.mappingCount();
4248 >            if (sz > MAX_ARRAY_SIZE)
4249 >                throw new OutOfMemoryError(oomeMsg);
4250 >            int n = (int)sz;
4251 >            Object[] r = new Object[n];
4252 >            int i = 0;
4253 >            for (E e : this) {
4254 >                if (i == n) {
4255 >                    if (n >= MAX_ARRAY_SIZE)
4256 >                        throw new OutOfMemoryError(oomeMsg);
4257 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4258 >                        n = MAX_ARRAY_SIZE;
4259 >                    else
4260 >                        n += (n >>> 1) + 1;
4261 >                    r = Arrays.copyOf(r, n);
4262 >                }
4263 >                r[i++] = e;
4264 >            }
4265 >            return (i == n) ? r : Arrays.copyOf(r, i);
4266          }
4267  
4268 <        /**
4269 <         * Returns a task that when invoked, returns the result of
4270 <         * accumulating the given transformation of all keys using the given
4271 <         * reducer to combine values, and the given basis as an
4272 <         * identity value.
4273 <         *
4274 <         * @param map the map
4275 <         * @param transformer a function returning the transformation
4276 <         * for an element
4277 <         * @param basis the identity (initial default value) for the reduction
4278 <         * @param reducer a commutative associative combining function
4279 <         * @return the task
4280 <         */
4281 <        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4282 <            (ConcurrentHashMapV8<K,V> map,
4283 <             ObjectToDouble<? super K> transformer,
4284 <             double basis,
4285 <             DoubleByDoubleToDouble reducer) {
4286 <            if (transformer == null || reducer == null)
4287 <                throw new NullPointerException();
4288 <            return new MapReduceKeysToDoubleTask<K,V>
4289 <                (map, transformer, basis, reducer);
4268 >        @SuppressWarnings("unchecked")
4269 >        public final <T> T[] toArray(T[] a) {
4270 >            long sz = map.mappingCount();
4271 >            if (sz > MAX_ARRAY_SIZE)
4272 >                throw new OutOfMemoryError(oomeMsg);
4273 >            int m = (int)sz;
4274 >            T[] r = (a.length >= m) ? a :
4275 >                (T[])java.lang.reflect.Array
4276 >                .newInstance(a.getClass().getComponentType(), m);
4277 >            int n = r.length;
4278 >            int i = 0;
4279 >            for (E e : this) {
4280 >                if (i == n) {
4281 >                    if (n >= MAX_ARRAY_SIZE)
4282 >                        throw new OutOfMemoryError(oomeMsg);
4283 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4284 >                        n = MAX_ARRAY_SIZE;
4285 >                    else
4286 >                        n += (n >>> 1) + 1;
4287 >                    r = Arrays.copyOf(r, n);
4288 >                }
4289 >                r[i++] = (T)e;
4290 >            }
4291 >            if (a == r && i < n) {
4292 >                r[i] = null; // null-terminate
4293 >                return r;
4294 >            }
4295 >            return (i == n) ? r : Arrays.copyOf(r, i);
4296          }
4297  
4298          /**
4299 <         * Returns a task that when invoked, returns the result of
4300 <         * accumulating the given transformation of all keys using the given
4301 <         * reducer to combine values, and the given basis as an
4302 <         * identity value.
4299 >         * Returns a string representation of this collection.
4300 >         * The string representation consists of the string representations
4301 >         * of the collection's elements in the order they are returned by
4302 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4303 >         * Adjacent elements are separated by the characters {@code ", "}
4304 >         * (comma and space).  Elements are converted to strings as by
4305 >         * {@link String#valueOf(Object)}.
4306           *
4307 <         * @param map the map
4442 <         * @param transformer a function returning the transformation
4443 <         * for an element
4444 <         * @param basis the identity (initial default value) for the reduction
4445 <         * @param reducer a commutative associative combining function
4446 <         * @return the task
4307 >         * @return a string representation of this collection
4308           */
4309 <        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4310 <            (ConcurrentHashMapV8<K,V> map,
4311 <             ObjectToLong<? super K> transformer,
4312 <             long basis,
4313 <             LongByLongToLong reducer) {
4314 <            if (transformer == null || reducer == null)
4315 <                throw new NullPointerException();
4316 <            return new MapReduceKeysToLongTask<K,V>
4317 <                (map, transformer, basis, reducer);
4309 >        public final String toString() {
4310 >            StringBuilder sb = new StringBuilder();
4311 >            sb.append('[');
4312 >            Iterator<E> it = iterator();
4313 >            if (it.hasNext()) {
4314 >                for (;;) {
4315 >                    Object e = it.next();
4316 >                    sb.append(e == this ? "(this Collection)" : e);
4317 >                    if (!it.hasNext())
4318 >                        break;
4319 >                    sb.append(',').append(' ');
4320 >                }
4321 >            }
4322 >            return sb.append(']').toString();
4323          }
4324  
4325 <        /**
4326 <         * Returns a task that when invoked, returns the result of
4327 <         * accumulating the given transformation of all keys using the given
4328 <         * reducer to combine values, and the given basis as an
4329 <         * identity value.
4330 <         *
4331 <         * @param map the map
4332 <         * @param transformer a function returning the transformation
4467 <         * for an element
4468 <         * @param basis the identity (initial default value) for the reduction
4469 <         * @param reducer a commutative associative combining function
4470 <         * @return the task
4471 <         */
4472 <        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4473 <            (ConcurrentHashMapV8<K,V> map,
4474 <             ObjectToInt<? super K> transformer,
4475 <             int basis,
4476 <             IntByIntToInt reducer) {
4477 <            if (transformer == null || reducer == null)
4478 <                throw new NullPointerException();
4479 <            return new MapReduceKeysToIntTask<K,V>
4480 <                (map, transformer, basis, reducer);
4325 >        public final boolean containsAll(Collection<?> c) {
4326 >            if (c != this) {
4327 >                for (Object e : c) {
4328 >                    if (e == null || !contains(e))
4329 >                        return false;
4330 >                }
4331 >            }
4332 >            return true;
4333          }
4334  
4335 <        /**
4336 <         * Returns a task that when invoked, performs the given action
4337 <         * for each value.
4338 <         *
4339 <         * @param map the map
4340 <         * @param action the action
4341 <         */
4342 <        public static <K,V> ForkJoinTask<Void> forEachValue
4343 <            (ConcurrentHashMapV8<K,V> map,
4492 <             Action<V> action) {
4493 <            if (action == null) throw new NullPointerException();
4494 <            return new ForEachValueTask<K,V>(map, action);
4335 >        public final boolean removeAll(Collection<?> c) {
4336 >            boolean modified = false;
4337 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4338 >                if (c.contains(it.next())) {
4339 >                    it.remove();
4340 >                    modified = true;
4341 >                }
4342 >            }
4343 >            return modified;
4344          }
4345  
4346 <        /**
4347 <         * Returns a task that when invoked, performs the given action
4348 <         * for each non-null transformation of each value.
4349 <         *
4350 <         * @param map the map
4351 <         * @param transformer a function returning the transformation
4352 <         * for an element, or null of there is no transformation (in
4353 <         * which case the action is not applied).
4354 <         * @param action the action
4506 <         */
4507 <        public static <K,V,U> ForkJoinTask<Void> forEachValue
4508 <            (ConcurrentHashMapV8<K,V> map,
4509 <             Fun<? super V, ? extends U> transformer,
4510 <             Action<U> action) {
4511 <            if (transformer == null || action == null)
4512 <                throw new NullPointerException();
4513 <            return new ForEachTransformedValueTask<K,V,U>
4514 <                (map, transformer, action);
4346 >        public final boolean retainAll(Collection<?> c) {
4347 >            boolean modified = false;
4348 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4349 >                if (!c.contains(it.next())) {
4350 >                    it.remove();
4351 >                    modified = true;
4352 >                }
4353 >            }
4354 >            return modified;
4355          }
4356  
4357 <        /**
4358 <         * Returns a task that when invoked, returns a non-null result
4359 <         * from applying the given search function on each value, or
4360 <         * null if none.  Upon success, further element processing is
4361 <         * suppressed and the results of any other parallel
4362 <         * invocations of the search function are ignored.
4363 <         *
4364 <         * @param map the map
4365 <         * @param searchFunction a function returning a non-null
4366 <         * result on success, else null
4367 <         * @return the task
4368 <         *
4369 <         */
4370 <        public static <K,V,U> ForkJoinTask<U> searchValues
4371 <            (ConcurrentHashMapV8<K,V> map,
4372 <             Fun<? super V, ? extends U> searchFunction) {
4373 <            if (searchFunction == null) throw new NullPointerException();
4374 <            return new SearchValuesTask<K,V,U>
4375 <                (map, searchFunction,
4376 <                 new AtomicReference<U>());
4357 >    }
4358 >
4359 >    /**
4360 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of keys, in
4361 >     * which additions may optionally be enabled by mapping to a
4362 >     * common value.  This class cannot be directly instantiated.
4363 >     * See {@link #keySet() keySet()},
4364 >     * {@link #keySet(Object) keySet(V)},
4365 >     * {@link #newKeySet() newKeySet()},
4366 >     * {@link #newKeySet(int) newKeySet(int)}.
4367 >     *
4368 >     * @since 1.8
4369 >     */
4370 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4371 >        implements Set<K>, java.io.Serializable {
4372 >        private static final long serialVersionUID = 7249069246763182397L;
4373 >        private final V value;
4374 >        KeySetView(ConcurrentHashMapV8<K,V> map, V value) {  // non-public
4375 >            super(map);
4376 >            this.value = value;
4377          }
4378  
4379          /**
4380 <         * Returns a task that when invoked, returns the result of
4381 <         * accumulating all values using the given reducer to combine
4542 <         * values, or null if none.
4380 >         * Returns the default mapped value for additions,
4381 >         * or {@code null} if additions are not supported.
4382           *
4383 <         * @param map the map
4384 <         * @param reducer a commutative associative combining function
4546 <         * @return the task
4383 >         * @return the default mapped value for additions, or {@code null}
4384 >         * if not supported
4385           */
4386 <        public static <K,V> ForkJoinTask<V> reduceValues
4549 <            (ConcurrentHashMapV8<K,V> map,
4550 <             BiFun<? super V, ? super V, ? extends V> reducer) {
4551 <            if (reducer == null) throw new NullPointerException();
4552 <            return new ReduceValuesTask<K,V>
4553 <                (map, reducer);
4554 <        }
4386 >        public V getMappedValue() { return value; }
4387  
4388          /**
4389 <         * Returns a task that when invoked, returns the result of
4390 <         * accumulating the given transformation of all values using the
4559 <         * given reducer to combine values, or null if none.
4560 <         *
4561 <         * @param map the map
4562 <         * @param transformer a function returning the transformation
4563 <         * for an element, or null of there is no transformation (in
4564 <         * which case it is not combined).
4565 <         * @param reducer a commutative associative combining function
4566 <         * @return the task
4389 >         * {@inheritDoc}
4390 >         * @throws NullPointerException if the specified key is null
4391           */
4392 <        public static <K,V,U> ForkJoinTask<U> reduceValues
4569 <            (ConcurrentHashMapV8<K,V> map,
4570 <             Fun<? super V, ? extends U> transformer,
4571 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4572 <            if (transformer == null || reducer == null)
4573 <                throw new NullPointerException();
4574 <            return new MapReduceValuesTask<K,V,U>
4575 <                (map, transformer, reducer);
4576 <        }
4392 >        public boolean contains(Object o) { return map.containsKey(o); }
4393  
4394          /**
4395 <         * Returns a task that when invoked, returns the result of
4396 <         * accumulating the given transformation of all values using the
4397 <         * given reducer to combine values, and the given basis as an
4582 <         * identity value.
4395 >         * Removes the key from this map view, by removing the key (and its
4396 >         * corresponding value) from the backing map.  This method does
4397 >         * nothing if the key is not in the map.
4398           *
4399 <         * @param map the map
4400 <         * @param transformer a function returning the transformation
4401 <         * for an element
4587 <         * @param basis the identity (initial default value) for the reduction
4588 <         * @param reducer a commutative associative combining function
4589 <         * @return the task
4399 >         * @param  o the key to be removed from the backing map
4400 >         * @return {@code true} if the backing map contained the specified key
4401 >         * @throws NullPointerException if the specified key is null
4402           */
4403 <        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4592 <            (ConcurrentHashMapV8<K,V> map,
4593 <             ObjectToDouble<? super V> transformer,
4594 <             double basis,
4595 <             DoubleByDoubleToDouble reducer) {
4596 <            if (transformer == null || reducer == null)
4597 <                throw new NullPointerException();
4598 <            return new MapReduceValuesToDoubleTask<K,V>
4599 <                (map, transformer, basis, reducer);
4600 <        }
4403 >        public boolean remove(Object o) { return map.remove(o) != null; }
4404  
4405          /**
4406 <         * Returns a task that when invoked, returns the result of
4604 <         * accumulating the given transformation of all values using the
4605 <         * given reducer to combine values, and the given basis as an
4606 <         * identity value.
4607 <         *
4608 <         * @param map the map
4609 <         * @param transformer a function returning the transformation
4610 <         * for an element
4611 <         * @param basis the identity (initial default value) for the reduction
4612 <         * @param reducer a commutative associative combining function
4613 <         * @return the task
4406 >         * @return an iterator over the keys of the backing map
4407           */
4408 <        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
4409 <            (ConcurrentHashMapV8<K,V> map,
4410 <             ObjectToLong<? super V> transformer,
4411 <             long basis,
4412 <             LongByLongToLong reducer) {
4620 <            if (transformer == null || reducer == null)
4621 <                throw new NullPointerException();
4622 <            return new MapReduceValuesToLongTask<K,V>
4623 <                (map, transformer, basis, reducer);
4408 >        public Iterator<K> iterator() {
4409 >            Node<K,V>[] t;
4410 >            ConcurrentHashMapV8<K,V> m = map;
4411 >            int f = (t = m.table) == null ? 0 : t.length;
4412 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4413          }
4414  
4415          /**
4416 <         * Returns a task that when invoked, returns the result of
4417 <         * accumulating the given transformation of all values using the
4629 <         * given reducer to combine values, and the given basis as an
4630 <         * identity value.
4416 >         * Adds the specified key to this set view by mapping the key to
4417 >         * the default mapped value in the backing map, if defined.
4418           *
4419 <         * @param map the map
4420 <         * @param transformer a function returning the transformation
4421 <         * for an element
4422 <         * @param basis the identity (initial default value) for the reduction
4423 <         * @param reducer a commutative associative combining function
4637 <         * @return the task
4419 >         * @param e key to be added
4420 >         * @return {@code true} if this set changed as a result of the call
4421 >         * @throws NullPointerException if the specified key is null
4422 >         * @throws UnsupportedOperationException if no default mapped value
4423 >         * for additions was provided
4424           */
4425 <        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
4426 <            (ConcurrentHashMapV8<K,V> map,
4427 <             ObjectToInt<? super V> transformer,
4428 <             int basis,
4429 <             IntByIntToInt reducer) {
4644 <            if (transformer == null || reducer == null)
4645 <                throw new NullPointerException();
4646 <            return new MapReduceValuesToIntTask<K,V>
4647 <                (map, transformer, basis, reducer);
4425 >        public boolean add(K e) {
4426 >            V v;
4427 >            if ((v = value) == null)
4428 >                throw new UnsupportedOperationException();
4429 >            return map.putVal(e, v, true) == null;
4430          }
4431  
4432          /**
4433 <         * Returns a task that when invoked, perform the given action
4434 <         * for each entry.
4433 >         * Adds all of the elements in the specified collection to this set,
4434 >         * as if by calling {@link #add} on each one.
4435           *
4436 <         * @param map the map
4437 <         * @param action the action
4436 >         * @param c the elements to be inserted into this set
4437 >         * @return {@code true} if this set changed as a result of the call
4438 >         * @throws NullPointerException if the collection or any of its
4439 >         * elements are {@code null}
4440 >         * @throws UnsupportedOperationException if no default mapped value
4441 >         * for additions was provided
4442           */
4443 <        public static <K,V> ForkJoinTask<Void> forEachEntry
4444 <            (ConcurrentHashMapV8<K,V> map,
4445 <             Action<Map.Entry<K,V>> action) {
4446 <            if (action == null) throw new NullPointerException();
4447 <            return new ForEachEntryTask<K,V>(map, action);
4443 >        public boolean addAll(Collection<? extends K> c) {
4444 >            boolean added = false;
4445 >            V v;
4446 >            if ((v = value) == null)
4447 >                throw new UnsupportedOperationException();
4448 >            for (K e : c) {
4449 >                if (map.putVal(e, v, true) == null)
4450 >                    added = true;
4451 >            }
4452 >            return added;
4453          }
4454  
4455 <        /**
4456 <         * Returns a task that when invoked, perform the given action
4457 <         * for each non-null transformation of each entry.
4458 <         *
4459 <         * @param map the map
4669 <         * @param transformer a function returning the transformation
4670 <         * for an element, or null of there is no transformation (in
4671 <         * which case the action is not applied).
4672 <         * @param action the action
4673 <         */
4674 <        public static <K,V,U> ForkJoinTask<Void> forEachEntry
4675 <            (ConcurrentHashMapV8<K,V> map,
4676 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4677 <             Action<U> action) {
4678 <            if (transformer == null || action == null)
4679 <                throw new NullPointerException();
4680 <            return new ForEachTransformedEntryTask<K,V,U>
4681 <                (map, transformer, action);
4455 >        public int hashCode() {
4456 >            int h = 0;
4457 >            for (K e : this)
4458 >                h += e.hashCode();
4459 >            return h;
4460          }
4461  
4462 <        /**
4463 <         * Returns a task that when invoked, returns a non-null result
4464 <         * from applying the given search function on each entry, or
4465 <         * null if none.  Upon success, further element processing is
4466 <         * suppressed and the results of any other parallel
4689 <         * invocations of the search function are ignored.
4690 <         *
4691 <         * @param map the map
4692 <         * @param searchFunction a function returning a non-null
4693 <         * result on success, else null
4694 <         * @return the task
4695 <         *
4696 <         */
4697 <        public static <K,V,U> ForkJoinTask<U> searchEntries
4698 <            (ConcurrentHashMapV8<K,V> map,
4699 <             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4700 <            if (searchFunction == null) throw new NullPointerException();
4701 <            return new SearchEntriesTask<K,V,U>
4702 <                (map, searchFunction,
4703 <                 new AtomicReference<U>());
4462 >        public boolean equals(Object o) {
4463 >            Set<?> c;
4464 >            return ((o instanceof Set) &&
4465 >                    ((c = (Set<?>)o) == this ||
4466 >                     (containsAll(c) && c.containsAll(this))));
4467          }
4468  
4469 <        /**
4470 <         * Returns a task that when invoked, returns the result of
4471 <         * accumulating all entries using the given reducer to combine
4472 <         * values, or null if none.
4473 <         *
4474 <         * @param map the map
4712 <         * @param reducer a commutative associative combining function
4713 <         * @return the task
4714 <         */
4715 <        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
4716 <            (ConcurrentHashMapV8<K,V> map,
4717 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4718 <            if (reducer == null) throw new NullPointerException();
4719 <            return new ReduceEntriesTask<K,V>
4720 <                (map, reducer);
4469 >        public ConcurrentHashMapSpliterator<K> spliterator() {
4470 >            Node<K,V>[] t;
4471 >            ConcurrentHashMapV8<K,V> m = map;
4472 >            long n = m.sumCount();
4473 >            int f = (t = m.table) == null ? 0 : t.length;
4474 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4475          }
4476  
4477 <        /**
4478 <         * Returns a task that when invoked, returns the result of
4479 <         * accumulating the given transformation of all entries using the
4480 <         * given reducer to combine values, or null if none.
4481 <         *
4482 <         * @param map the map
4483 <         * @param transformer a function returning the transformation
4484 <         * for an element, or null of there is no transformation (in
4731 <         * which case it is not combined).
4732 <         * @param reducer a commutative associative combining function
4733 <         * @return the task
4734 <         */
4735 <        public static <K,V,U> ForkJoinTask<U> reduceEntries
4736 <            (ConcurrentHashMapV8<K,V> map,
4737 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4738 <             BiFun<? super U, ? super U, ? extends U> reducer) {
4739 <            if (transformer == null || reducer == null)
4740 <                throw new NullPointerException();
4741 <            return new MapReduceEntriesTask<K,V,U>
4742 <                (map, transformer, reducer);
4477 >        public void forEach(Action<? super K> action) {
4478 >            if (action == null) throw new NullPointerException();
4479 >            Node<K,V>[] t;
4480 >            if ((t = map.table) != null) {
4481 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4482 >                for (Node<K,V> p; (p = it.advance()) != null; )
4483 >                    action.apply(p.key);
4484 >            }
4485          }
4486 +    }
4487  
4488 <        /**
4489 <         * Returns a task that when invoked, returns the result of
4490 <         * accumulating the given transformation of all entries using the
4491 <         * given reducer to combine values, and the given basis as an
4492 <         * identity value.
4493 <         *
4494 <         * @param map the map
4495 <         * @param transformer a function returning the transformation
4496 <         * for an element
4497 <         * @param basis the identity (initial default value) for the reduction
4498 <         * @param reducer a commutative associative combining function
4756 <         * @return the task
4757 <         */
4758 <        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4759 <            (ConcurrentHashMapV8<K,V> map,
4760 <             ObjectToDouble<Map.Entry<K,V>> transformer,
4761 <             double basis,
4762 <             DoubleByDoubleToDouble reducer) {
4763 <            if (transformer == null || reducer == null)
4764 <                throw new NullPointerException();
4765 <            return new MapReduceEntriesToDoubleTask<K,V>
4766 <                (map, transformer, basis, reducer);
4488 >    /**
4489 >     * A view of a ConcurrentHashMapV8 as a {@link Collection} of
4490 >     * values, in which additions are disabled. This class cannot be
4491 >     * directly instantiated. See {@link #values()}.
4492 >     */
4493 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4494 >        implements Collection<V>, java.io.Serializable {
4495 >        private static final long serialVersionUID = 2249069246763182397L;
4496 >        ValuesView(ConcurrentHashMapV8<K,V> map) { super(map); }
4497 >        public final boolean contains(Object o) {
4498 >            return map.containsValue(o);
4499          }
4500  
4501 <        /**
4502 <         * Returns a task that when invoked, returns the result of
4503 <         * accumulating the given transformation of all entries using the
4504 <         * given reducer to combine values, and the given basis as an
4505 <         * identity value.
4506 <         *
4507 <         * @param map the map
4508 <         * @param transformer a function returning the transformation
4509 <         * for an element
4510 <         * @param basis the identity (initial default value) for the reduction
4779 <         * @param reducer a commutative associative combining function
4780 <         * @return the task
4781 <         */
4782 <        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4783 <            (ConcurrentHashMapV8<K,V> map,
4784 <             ObjectToLong<Map.Entry<K,V>> transformer,
4785 <             long basis,
4786 <             LongByLongToLong reducer) {
4787 <            if (transformer == null || reducer == null)
4788 <                throw new NullPointerException();
4789 <            return new MapReduceEntriesToLongTask<K,V>
4790 <                (map, transformer, basis, reducer);
4501 >        public final boolean remove(Object o) {
4502 >            if (o != null) {
4503 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4504 >                    if (o.equals(it.next())) {
4505 >                        it.remove();
4506 >                        return true;
4507 >                    }
4508 >                }
4509 >            }
4510 >            return false;
4511          }
4512  
4513 <        /**
4514 <         * Returns a task that when invoked, returns the result of
4515 <         * accumulating the given transformation of all entries using the
4516 <         * given reducer to combine values, and the given basis as an
4517 <         * identity value.
4798 <         *
4799 <         * @param map the map
4800 <         * @param transformer a function returning the transformation
4801 <         * for an element
4802 <         * @param basis the identity (initial default value) for the reduction
4803 <         * @param reducer a commutative associative combining function
4804 <         * @return the task
4805 <         */
4806 <        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4807 <            (ConcurrentHashMapV8<K,V> map,
4808 <             ObjectToInt<Map.Entry<K,V>> transformer,
4809 <             int basis,
4810 <             IntByIntToInt reducer) {
4811 <            if (transformer == null || reducer == null)
4812 <                throw new NullPointerException();
4813 <            return new MapReduceEntriesToIntTask<K,V>
4814 <                (map, transformer, basis, reducer);
4513 >        public final Iterator<V> iterator() {
4514 >            ConcurrentHashMapV8<K,V> m = map;
4515 >            Node<K,V>[] t;
4516 >            int f = (t = m.table) == null ? 0 : t.length;
4517 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4518          }
4816    }
4519  
4520 <    // -------------------------------------------------------
4520 >        public final boolean add(V e) {
4521 >            throw new UnsupportedOperationException();
4522 >        }
4523 >        public final boolean addAll(Collection<? extends V> c) {
4524 >            throw new UnsupportedOperationException();
4525 >        }
4526 >
4527 >        public ConcurrentHashMapSpliterator<V> spliterator() {
4528 >            Node<K,V>[] t;
4529 >            ConcurrentHashMapV8<K,V> m = map;
4530 >            long n = m.sumCount();
4531 >            int f = (t = m.table) == null ? 0 : t.length;
4532 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4533 >        }
4534 >
4535 >        public void forEach(Action<? super V> action) {
4536 >            if (action == null) throw new NullPointerException();
4537 >            Node<K,V>[] t;
4538 >            if ((t = map.table) != null) {
4539 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4540 >                for (Node<K,V> p; (p = it.advance()) != null; )
4541 >                    action.apply(p.val);
4542 >            }
4543 >        }
4544 >    }
4545  
4546      /**
4547 <     * Base for FJ tasks for bulk operations. This adds a variant of
4548 <     * CountedCompleters and some split and merge bookkeeping to
4549 <     * iterator functionality. The forEach and reduce methods are
4824 <     * similar to those illustrated in CountedCompleter documentation,
4825 <     * except that bottom-up reduction completions perform them within
4826 <     * their compute methods. The search methods are like forEach
4827 <     * except they continually poll for success and exit early.  Also,
4828 <     * exceptions are handled in a simpler manner, by just trying to
4829 <     * complete root task exceptionally.
4547 >     * A view of a ConcurrentHashMapV8 as a {@link Set} of (key, value)
4548 >     * entries.  This class cannot be directly instantiated. See
4549 >     * {@link #entrySet()}.
4550       */
4551 <    @SuppressWarnings("serial")
4552 <    static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4553 <        final BulkTask<K,V,?> parent;  // completion target
4554 <        int batch;                     // split control
4835 <        int pending;                   // completion control
4551 >    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4552 >        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4553 >        private static final long serialVersionUID = 2249069246763182397L;
4554 >        EntrySetView(ConcurrentHashMapV8<K,V> map) { super(map); }
4555  
4556 <        /** Constructor for root tasks */
4557 <        BulkTask(ConcurrentHashMapV8<K,V> map) {
4558 <            super(map);
4559 <            this.parent = null;
4560 <            this.batch = -1; // force call to batch() on execution
4556 >        public boolean contains(Object o) {
4557 >            Object k, v, r; Map.Entry<?,?> e;
4558 >            return ((o instanceof Map.Entry) &&
4559 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4560 >                    (r = map.get(k)) != null &&
4561 >                    (v = e.getValue()) != null &&
4562 >                    (v == r || v.equals(r)));
4563          }
4564  
4565 <        /** Constructor for subtasks */
4566 <        BulkTask(BulkTask<K,V,?> parent, int batch, boolean split) {
4567 <            super(parent, split);
4568 <            this.parent = parent;
4569 <            this.batch = batch;
4565 >        public boolean remove(Object o) {
4566 >            Object k, v; Map.Entry<?,?> e;
4567 >            return ((o instanceof Map.Entry) &&
4568 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4569 >                    (v = e.getValue()) != null &&
4570 >                    map.remove(k, v));
4571          }
4572  
4851        // FJ methods
4852
4573          /**
4574 <         * Propagates completion. Note that all reduce actions
4855 <         * bypass this method to combine while completing.
4574 >         * @return an iterator over the entries of the backing map
4575           */
4576 <        final void tryComplete() {
4577 <            BulkTask<K,V,?> a = this, s = a;
4578 <            for (int c;;) {
4579 <                if ((c = a.pending) == 0) {
4580 <                    if ((a = (s = a).parent) == null) {
4862 <                        s.quietlyComplete();
4863 <                        break;
4864 <                    }
4865 <                }
4866 <                else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
4867 <                    break;
4868 <            }
4576 >        public Iterator<Map.Entry<K,V>> iterator() {
4577 >            ConcurrentHashMapV8<K,V> m = map;
4578 >            Node<K,V>[] t;
4579 >            int f = (t = m.table) == null ? 0 : t.length;
4580 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4581          }
4582  
4583 <        /**
4584 <         * Forces root task to throw exception unless already complete.
4873 <         */
4874 <        final void tryAbortComputation(Throwable ex) {
4875 <            for (BulkTask<K,V,?> a = this;;) {
4876 <                BulkTask<K,V,?> p = a.parent;
4877 <                if (p == null) {
4878 <                    a.completeExceptionally(ex);
4879 <                    break;
4880 <                }
4881 <                a = p;
4882 <            }
4583 >        public boolean add(Entry<K,V> e) {
4584 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4585          }
4586  
4587 <        public final boolean exec() {
4588 <            try {
4589 <                compute();
4590 <            }
4591 <            catch (Throwable ex) {
4890 <                tryAbortComputation(ex);
4587 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4588 >            boolean added = false;
4589 >            for (Entry<K,V> e : c) {
4590 >                if (add(e))
4591 >                    added = true;
4592              }
4593 <            return false;
4593 >            return added;
4594          }
4595  
4596 <        public abstract void compute();
4596 >        public final int hashCode() {
4597 >            int h = 0;
4598 >            Node<K,V>[] t;
4599 >            if ((t = map.table) != null) {
4600 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4601 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4602 >                    h += p.hashCode();
4603 >                }
4604 >            }
4605 >            return h;
4606 >        }
4607  
4608 <        // utilities
4608 >        public final boolean equals(Object o) {
4609 >            Set<?> c;
4610 >            return ((o instanceof Set) &&
4611 >                    ((c = (Set<?>)o) == this ||
4612 >                     (containsAll(c) && c.containsAll(this))));
4613 >        }
4614  
4615 <        /** CompareAndSet pending count */
4616 <        final boolean casPending(int cmp, int val) {
4617 <            return U.compareAndSwapInt(this, PENDING, cmp, val);
4615 >        public ConcurrentHashMapSpliterator<Map.Entry<K,V>> spliterator() {
4616 >            Node<K,V>[] t;
4617 >            ConcurrentHashMapV8<K,V> m = map;
4618 >            long n = m.sumCount();
4619 >            int f = (t = m.table) == null ? 0 : t.length;
4620 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4621          }
4622  
4623 <        /**
4624 <         * Returns approx exp2 of the number of times (minus one) to
4625 <         * split task by two before executing leaf action. This value
4626 <         * is faster to compute and more convenient to use as a guide
4627 <         * to splitting than is the depth, since it is used while
4628 <         * dividing by two anyway.
4629 <         */
4911 <        final int batch() {
4912 <            int b = batch;
4913 <            if (b < 0) {
4914 <                long n = map.counter.sum();
4915 <                int sp = getPool().getParallelism() << 3; // slack of 8
4916 <                b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4623 >        public void forEach(Action<? super Map.Entry<K,V>> action) {
4624 >            if (action == null) throw new NullPointerException();
4625 >            Node<K,V>[] t;
4626 >            if ((t = map.table) != null) {
4627 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4628 >                for (Node<K,V> p; (p = it.advance()) != null; )
4629 >                    action.apply(new MapEntry<K,V>(p.key, p.val, map));
4630              }
4918            return b;
4631          }
4632  
4633 <        /**
4922 <         * Error message for hoisted null checks of functions
4923 <         */
4924 <        static final String NullFunctionMessage =
4925 <            "Unexpected null function";
4633 >    }
4634  
4635 <        /**
4636 <         * Returns exportable snapshot entry.
4637 <         */
4638 <        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4639 <            return new AbstractMap.SimpleEntry<K,V>(k, v);
4635 >    // -------------------------------------------------------
4636 >
4637 >    /**
4638 >     * Base class for bulk tasks. Repeats some fields and code from
4639 >     * class Traverser, because we need to subclass CountedCompleter.
4640 >     */
4641 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4642 >        Node<K,V>[] tab;        // same as Traverser
4643 >        Node<K,V> next;
4644 >        int index;
4645 >        int baseIndex;
4646 >        int baseLimit;
4647 >        final int baseSize;
4648 >        int batch;              // split control
4649 >
4650 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4651 >            super(par);
4652 >            this.batch = b;
4653 >            this.index = this.baseIndex = i;
4654 >            if ((this.tab = t) == null)
4655 >                this.baseSize = this.baseLimit = 0;
4656 >            else if (par == null)
4657 >                this.baseSize = this.baseLimit = t.length;
4658 >            else {
4659 >                this.baseLimit = f;
4660 >                this.baseSize = par.baseSize;
4661 >            }
4662          }
4663  
4664 <        // Unsafe mechanics
4665 <        private static final sun.misc.Unsafe U;
4666 <        private static final long PENDING;
4667 <        static {
4668 <            try {
4669 <                U = getUnsafe();
4670 <                PENDING = U.objectFieldOffset
4671 <                    (BulkTask.class.getDeclaredField("pending"));
4672 <            } catch (Exception e) {
4673 <                throw new Error(e);
4664 >        /**
4665 >         * Same as Traverser version
4666 >         */
4667 >        final Node<K,V> advance() {
4668 >            Node<K,V> e;
4669 >            if ((e = next) != null)
4670 >                e = e.next;
4671 >            for (;;) {
4672 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4673 >                if (e != null)
4674 >                    return next = e;
4675 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4676 >                    (n = t.length) <= (i = index) || i < 0)
4677 >                    return next = null;
4678 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4679 >                    if (e instanceof ForwardingNode) {
4680 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4681 >                        e = null;
4682 >                        continue;
4683 >                    }
4684 >                    else if (e instanceof TreeBin)
4685 >                        e = ((TreeBin<K,V>)e).first;
4686 >                    else
4687 >                        e = null;
4688 >                }
4689 >                if ((index += baseSize) >= n)
4690 >                    index = ++baseIndex;    // visit upper slots if present
4691              }
4692          }
4693      }
# Line 4948 | Line 4695 | public class ConcurrentHashMapV8<K, V>
4695      /*
4696       * Task classes. Coded in a regular but ugly format/style to
4697       * simplify checks that each variant differs in the right way from
4698 <     * others.
4698 >     * others. The null screenings exist because compilers cannot tell
4699 >     * that we've already null-checked task arguments, so we force
4700 >     * simplest hoisted bypass to help avoid convoluted traps.
4701       */
4953
4702      @SuppressWarnings("serial")
4703      static final class ForEachKeyTask<K,V>
4704          extends BulkTask<K,V,Void> {
4705 <        final Action<K> action;
4705 >        final Action<? super K> action;
4706          ForEachKeyTask
4707 <            (ConcurrentHashMapV8<K,V> m,
4708 <             Action<K> action) {
4709 <            super(m);
4707 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4708 >             Action<? super K> action) {
4709 >            super(p, b, i, f, t);
4710              this.action = action;
4711          }
4712 <        ForEachKeyTask
4713 <            (BulkTask<K,V,?> p, int b, boolean split,
4714 <             Action<K> action) {
4715 <            super(p, b, split);
4716 <            this.action = action;
4717 <        }
4718 <        @SuppressWarnings("unchecked") public final void compute() {
4719 <            final Action<K> action = this.action;
4720 <            if (action == null)
4721 <                throw new Error(NullFunctionMessage);
4722 <            int b = batch(), c;
4723 <            while (b > 1 && baseIndex != baseLimit) {
4724 <                do {} while (!casPending(c = pending, c+1));
4725 <                new ForEachKeyTask<K,V>(this, b >>>= 1, true, action).fork();
4978 <            }
4979 <            while (advance() != null)
4980 <                action.apply((K)nextKey);
4981 <            tryComplete();
4712 >        public final void compute() {
4713 >            final Action<? super K> action;
4714 >            if ((action = this.action) != null) {
4715 >                for (int i = baseIndex, f, h; batch > 0 &&
4716 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4717 >                    addToPendingCount(1);
4718 >                    new ForEachKeyTask<K,V>
4719 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4720 >                         action).fork();
4721 >                }
4722 >                for (Node<K,V> p; (p = advance()) != null;)
4723 >                    action.apply(p.key);
4724 >                propagateCompletion();
4725 >            }
4726          }
4727      }
4728  
4729      @SuppressWarnings("serial")
4730      static final class ForEachValueTask<K,V>
4731          extends BulkTask<K,V,Void> {
4732 <        final Action<V> action;
4989 <        ForEachValueTask
4990 <            (ConcurrentHashMapV8<K,V> m,
4991 <             Action<V> action) {
4992 <            super(m);
4993 <            this.action = action;
4994 <        }
4732 >        final Action<? super V> action;
4733          ForEachValueTask
4734 <            (BulkTask<K,V,?> p, int b, boolean split,
4735 <             Action<V> action) {
4736 <            super(p, b, split);
4734 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4735 >             Action<? super V> action) {
4736 >            super(p, b, i, f, t);
4737              this.action = action;
4738          }
4739 <        @SuppressWarnings("unchecked") public final void compute() {
4740 <            final Action<V> action = this.action;
4741 <            if (action == null)
4742 <                throw new Error(NullFunctionMessage);
4743 <            int b = batch(), c;
4744 <            while (b > 1 && baseIndex != baseLimit) {
4745 <                do {} while (!casPending(c = pending, c+1));
4746 <                new ForEachValueTask<K,V>(this, b >>>= 1, true, action).fork();
4747 <            }
4748 <            Object v;
4749 <            while ((v = advance()) != null)
4750 <                action.apply((V)v);
4751 <            tryComplete();
4739 >        public final void compute() {
4740 >            final Action<? super V> action;
4741 >            if ((action = this.action) != null) {
4742 >                for (int i = baseIndex, f, h; batch > 0 &&
4743 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4744 >                    addToPendingCount(1);
4745 >                    new ForEachValueTask<K,V>
4746 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4747 >                         action).fork();
4748 >                }
4749 >                for (Node<K,V> p; (p = advance()) != null;)
4750 >                    action.apply(p.val);
4751 >                propagateCompletion();
4752 >            }
4753          }
4754      }
4755  
4756      @SuppressWarnings("serial")
4757      static final class ForEachEntryTask<K,V>
4758          extends BulkTask<K,V,Void> {
4759 <        final Action<Entry<K,V>> action;
5021 <        ForEachEntryTask
5022 <            (ConcurrentHashMapV8<K,V> m,
5023 <             Action<Entry<K,V>> action) {
5024 <            super(m);
5025 <            this.action = action;
5026 <        }
4759 >        final Action<? super Entry<K,V>> action;
4760          ForEachEntryTask
4761 <            (BulkTask<K,V,?> p, int b, boolean split,
4762 <             Action<Entry<K,V>> action) {
4763 <            super(p, b, split);
4761 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4762 >             Action<? super Entry<K,V>> action) {
4763 >            super(p, b, i, f, t);
4764              this.action = action;
4765          }
4766 <        @SuppressWarnings("unchecked") public final void compute() {
4767 <            final Action<Entry<K,V>> action = this.action;
4768 <            if (action == null)
4769 <                throw new Error(NullFunctionMessage);
4770 <            int b = batch(), c;
4771 <            while (b > 1 && baseIndex != baseLimit) {
4772 <                do {} while (!casPending(c = pending, c+1));
4773 <                new ForEachEntryTask<K,V>(this, b >>>= 1, true, action).fork();
4774 <            }
4775 <            Object v;
4776 <            while ((v = advance()) != null)
4777 <                action.apply(entryFor((K)nextKey, (V)v));
4778 <            tryComplete();
4766 >        public final void compute() {
4767 >            final Action<? super Entry<K,V>> action;
4768 >            if ((action = this.action) != null) {
4769 >                for (int i = baseIndex, f, h; batch > 0 &&
4770 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4771 >                    addToPendingCount(1);
4772 >                    new ForEachEntryTask<K,V>
4773 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4774 >                         action).fork();
4775 >                }
4776 >                for (Node<K,V> p; (p = advance()) != null; )
4777 >                    action.apply(p);
4778 >                propagateCompletion();
4779 >            }
4780          }
4781      }
4782  
4783      @SuppressWarnings("serial")
4784      static final class ForEachMappingTask<K,V>
4785          extends BulkTask<K,V,Void> {
4786 <        final BiAction<K,V> action;
5053 <        ForEachMappingTask
5054 <            (ConcurrentHashMapV8<K,V> m,
5055 <             BiAction<K,V> action) {
5056 <            super(m);
5057 <            this.action = action;
5058 <        }
4786 >        final BiAction<? super K, ? super V> action;
4787          ForEachMappingTask
4788 <            (BulkTask<K,V,?> p, int b, boolean split,
4789 <             BiAction<K,V> action) {
4790 <            super(p, b, split);
4788 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4789 >             BiAction<? super K,? super V> action) {
4790 >            super(p, b, i, f, t);
4791              this.action = action;
4792          }
4793 <
4794 <        @SuppressWarnings("unchecked") public final void compute() {
4795 <            final BiAction<K,V> action = this.action;
4796 <            if (action == null)
4797 <                throw new Error(NullFunctionMessage);
4798 <            int b = batch(), c;
4799 <            while (b > 1 && baseIndex != baseLimit) {
4800 <                do {} while (!casPending(c = pending, c+1));
4801 <                new ForEachMappingTask<K,V>(this, b >>>= 1, true,
4802 <                                            action).fork();
4803 <            }
4804 <            Object v;
4805 <            while ((v = advance()) != null)
4806 <                action.apply((K)nextKey, (V)v);
5079 <            tryComplete();
4793 >        public final void compute() {
4794 >            final BiAction<? super K, ? super V> action;
4795 >            if ((action = this.action) != null) {
4796 >                for (int i = baseIndex, f, h; batch > 0 &&
4797 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4798 >                    addToPendingCount(1);
4799 >                    new ForEachMappingTask<K,V>
4800 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4801 >                         action).fork();
4802 >                }
4803 >                for (Node<K,V> p; (p = advance()) != null; )
4804 >                    action.apply(p.key, p.val);
4805 >                propagateCompletion();
4806 >            }
4807          }
4808      }
4809  
# Line 5084 | Line 4811 | public class ConcurrentHashMapV8<K, V>
4811      static final class ForEachTransformedKeyTask<K,V,U>
4812          extends BulkTask<K,V,Void> {
4813          final Fun<? super K, ? extends U> transformer;
4814 <        final Action<U> action;
4814 >        final Action<? super U> action;
4815          ForEachTransformedKeyTask
4816 <            (ConcurrentHashMapV8<K,V> m,
4817 <             Fun<? super K, ? extends U> transformer,
4818 <             Action<U> action) {
4819 <            super(m);
4820 <            this.transformer = transformer;
4821 <            this.action = action;
4822 <
4823 <        }
4824 <        ForEachTransformedKeyTask
4825 <            (BulkTask<K,V,?> p, int b, boolean split,
4826 <             Fun<? super K, ? extends U> transformer,
4827 <             Action<U> action) {
4828 <            super(p, b, split);
4829 <            this.transformer = transformer;
4830 <            this.action = action;
4831 <        }
4832 <        @SuppressWarnings("unchecked") public final void compute() {
4833 <            final Fun<? super K, ? extends U> transformer =
4834 <                this.transformer;
4835 <            final Action<U> action = this.action;
4836 <            if (transformer == null || action == null)
4837 <                throw new Error(NullFunctionMessage);
4838 <            int b = batch(), c;
5112 <            while (b > 1 && baseIndex != baseLimit) {
5113 <                do {} while (!casPending(c = pending, c+1));
5114 <                new ForEachTransformedKeyTask<K,V,U>
5115 <                    (this, b >>>= 1, true, transformer, action).fork();
5116 <            }
5117 <            U u;
5118 <            while (advance() != null) {
5119 <                if ((u = transformer.apply((K)nextKey)) != null)
5120 <                    action.apply(u);
4816 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4817 >             Fun<? super K, ? extends U> transformer, Action<? super U> action) {
4818 >            super(p, b, i, f, t);
4819 >            this.transformer = transformer; this.action = action;
4820 >        }
4821 >        public final void compute() {
4822 >            final Fun<? super K, ? extends U> transformer;
4823 >            final Action<? super U> action;
4824 >            if ((transformer = this.transformer) != null &&
4825 >                (action = this.action) != null) {
4826 >                for (int i = baseIndex, f, h; batch > 0 &&
4827 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4828 >                    addToPendingCount(1);
4829 >                    new ForEachTransformedKeyTask<K,V,U>
4830 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4831 >                         transformer, action).fork();
4832 >                }
4833 >                for (Node<K,V> p; (p = advance()) != null; ) {
4834 >                    U u;
4835 >                    if ((u = transformer.apply(p.key)) != null)
4836 >                        action.apply(u);
4837 >                }
4838 >                propagateCompletion();
4839              }
5122            tryComplete();
4840          }
4841      }
4842  
# Line 5127 | Line 4844 | public class ConcurrentHashMapV8<K, V>
4844      static final class ForEachTransformedValueTask<K,V,U>
4845          extends BulkTask<K,V,Void> {
4846          final Fun<? super V, ? extends U> transformer;
4847 <        final Action<U> action;
5131 <        ForEachTransformedValueTask
5132 <            (ConcurrentHashMapV8<K,V> m,
5133 <             Fun<? super V, ? extends U> transformer,
5134 <             Action<U> action) {
5135 <            super(m);
5136 <            this.transformer = transformer;
5137 <            this.action = action;
5138 <
5139 <        }
4847 >        final Action<? super U> action;
4848          ForEachTransformedValueTask
4849 <            (BulkTask<K,V,?> p, int b, boolean split,
4850 <             Fun<? super V, ? extends U> transformer,
4851 <             Action<U> action) {
4852 <            super(p, b, split);
4853 <            this.transformer = transformer;
4854 <            this.action = action;
4855 <        }
4856 <        @SuppressWarnings("unchecked") public final void compute() {
4857 <            final Fun<? super V, ? extends U> transformer =
4858 <                this.transformer;
4859 <            final Action<U> action = this.action;
4860 <            if (transformer == null || action == null)
4861 <                throw new Error(NullFunctionMessage);
4862 <            int b = batch(), c;
4863 <            while (b > 1 && baseIndex != baseLimit) {
4864 <                do {} while (!casPending(c = pending, c+1));
4865 <                new ForEachTransformedValueTask<K,V,U>
4866 <                    (this, b >>>= 1, true, transformer, action).fork();
4867 <            }
4868 <            Object v; U u;
4869 <            while ((v = advance()) != null) {
4870 <                if ((u = transformer.apply((V)v)) != null)
4871 <                    action.apply(u);
4849 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4850 >             Fun<? super V, ? extends U> transformer, Action<? super U> action) {
4851 >            super(p, b, i, f, t);
4852 >            this.transformer = transformer; this.action = action;
4853 >        }
4854 >        public final void compute() {
4855 >            final Fun<? super V, ? extends U> transformer;
4856 >            final Action<? super U> action;
4857 >            if ((transformer = this.transformer) != null &&
4858 >                (action = this.action) != null) {
4859 >                for (int i = baseIndex, f, h; batch > 0 &&
4860 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4861 >                    addToPendingCount(1);
4862 >                    new ForEachTransformedValueTask<K,V,U>
4863 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4864 >                         transformer, action).fork();
4865 >                }
4866 >                for (Node<K,V> p; (p = advance()) != null; ) {
4867 >                    U u;
4868 >                    if ((u = transformer.apply(p.val)) != null)
4869 >                        action.apply(u);
4870 >                }
4871 >                propagateCompletion();
4872              }
5165            tryComplete();
4873          }
4874      }
4875  
# Line 5170 | Line 4877 | public class ConcurrentHashMapV8<K, V>
4877      static final class ForEachTransformedEntryTask<K,V,U>
4878          extends BulkTask<K,V,Void> {
4879          final Fun<Map.Entry<K,V>, ? extends U> transformer;
4880 <        final Action<U> action;
4880 >        final Action<? super U> action;
4881          ForEachTransformedEntryTask
4882 <            (ConcurrentHashMapV8<K,V> m,
4883 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4884 <             Action<U> action) {
4885 <            super(m);
4886 <            this.transformer = transformer;
4887 <            this.action = action;
4888 <
4889 <        }
4890 <        ForEachTransformedEntryTask
4891 <            (BulkTask<K,V,?> p, int b, boolean split,
4892 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
4893 <             Action<U> action) {
4894 <            super(p, b, split);
4895 <            this.transformer = transformer;
4896 <            this.action = action;
4897 <        }
4898 <        @SuppressWarnings("unchecked") public final void compute() {
4899 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
4900 <                this.transformer;
4901 <            final Action<U> action = this.action;
4902 <            if (transformer == null || action == null)
4903 <                throw new Error(NullFunctionMessage);
4904 <            int b = batch(), c;
5198 <            while (b > 1 && baseIndex != baseLimit) {
5199 <                do {} while (!casPending(c = pending, c+1));
5200 <                new ForEachTransformedEntryTask<K,V,U>
5201 <                    (this, b >>>= 1, true, transformer, action).fork();
5202 <            }
5203 <            Object v; U u;
5204 <            while ((v = advance()) != null) {
5205 <                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5206 <                    action.apply(u);
4882 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4883 >             Fun<Map.Entry<K,V>, ? extends U> transformer, Action<? super U> action) {
4884 >            super(p, b, i, f, t);
4885 >            this.transformer = transformer; this.action = action;
4886 >        }
4887 >        public final void compute() {
4888 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
4889 >            final Action<? super U> action;
4890 >            if ((transformer = this.transformer) != null &&
4891 >                (action = this.action) != null) {
4892 >                for (int i = baseIndex, f, h; batch > 0 &&
4893 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4894 >                    addToPendingCount(1);
4895 >                    new ForEachTransformedEntryTask<K,V,U>
4896 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4897 >                         transformer, action).fork();
4898 >                }
4899 >                for (Node<K,V> p; (p = advance()) != null; ) {
4900 >                    U u;
4901 >                    if ((u = transformer.apply(p)) != null)
4902 >                        action.apply(u);
4903 >                }
4904 >                propagateCompletion();
4905              }
5208            tryComplete();
4906          }
4907      }
4908  
# Line 5213 | Line 4910 | public class ConcurrentHashMapV8<K, V>
4910      static final class ForEachTransformedMappingTask<K,V,U>
4911          extends BulkTask<K,V,Void> {
4912          final BiFun<? super K, ? super V, ? extends U> transformer;
4913 <        final Action<U> action;
5217 <        ForEachTransformedMappingTask
5218 <            (ConcurrentHashMapV8<K,V> m,
5219 <             BiFun<? super K, ? super V, ? extends U> transformer,
5220 <             Action<U> action) {
5221 <            super(m);
5222 <            this.transformer = transformer;
5223 <            this.action = action;
5224 <
5225 <        }
4913 >        final Action<? super U> action;
4914          ForEachTransformedMappingTask
4915 <            (BulkTask<K,V,?> p, int b, boolean split,
4915 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4916               BiFun<? super K, ? super V, ? extends U> transformer,
4917 <             Action<U> action) {
4918 <            super(p, b, split);
4919 <            this.transformer = transformer;
4920 <            this.action = action;
4921 <        }
4922 <        @SuppressWarnings("unchecked") public final void compute() {
4923 <            final BiFun<? super K, ? super V, ? extends U> transformer =
4924 <                this.transformer;
4925 <            final Action<U> action = this.action;
4926 <            if (transformer == null || action == null)
4927 <                throw new Error(NullFunctionMessage);
4928 <            int b = batch(), c;
4929 <            while (b > 1 && baseIndex != baseLimit) {
4930 <                do {} while (!casPending(c = pending, c+1));
4931 <                new ForEachTransformedMappingTask<K,V,U>
4932 <                    (this, b >>>= 1, true, transformer, action).fork();
4933 <            }
4934 <            Object v; U u;
4935 <            while ((v = advance()) != null) {
4936 <                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
4937 <                    action.apply(u);
4917 >             Action<? super U> action) {
4918 >            super(p, b, i, f, t);
4919 >            this.transformer = transformer; this.action = action;
4920 >        }
4921 >        public final void compute() {
4922 >            final BiFun<? super K, ? super V, ? extends U> transformer;
4923 >            final Action<? super U> action;
4924 >            if ((transformer = this.transformer) != null &&
4925 >                (action = this.action) != null) {
4926 >                for (int i = baseIndex, f, h; batch > 0 &&
4927 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4928 >                    addToPendingCount(1);
4929 >                    new ForEachTransformedMappingTask<K,V,U>
4930 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4931 >                         transformer, action).fork();
4932 >                }
4933 >                for (Node<K,V> p; (p = advance()) != null; ) {
4934 >                    U u;
4935 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4936 >                        action.apply(u);
4937 >                }
4938 >                propagateCompletion();
4939              }
5251            tryComplete();
4940          }
4941      }
4942  
# Line 5258 | Line 4946 | public class ConcurrentHashMapV8<K, V>
4946          final Fun<? super K, ? extends U> searchFunction;
4947          final AtomicReference<U> result;
4948          SearchKeysTask
4949 <            (ConcurrentHashMapV8<K,V> m,
5262 <             Fun<? super K, ? extends U> searchFunction,
5263 <             AtomicReference<U> result) {
5264 <            super(m);
5265 <            this.searchFunction = searchFunction; this.result = result;
5266 <        }
5267 <        SearchKeysTask
5268 <            (BulkTask<K,V,?> p, int b, boolean split,
4949 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4950               Fun<? super K, ? extends U> searchFunction,
4951               AtomicReference<U> result) {
4952 <            super(p, b, split);
4952 >            super(p, b, i, f, t);
4953              this.searchFunction = searchFunction; this.result = result;
4954          }
4955 <        @SuppressWarnings("unchecked") public final void compute() {
4956 <            AtomicReference<U> result = this.result;
4957 <            final Fun<? super K, ? extends U> searchFunction =
4958 <                this.searchFunction;
4959 <            if (searchFunction == null || result == null)
4960 <                throw new Error(NullFunctionMessage);
4961 <            int b = batch(), c;
4962 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
4963 <                do {} while (!casPending(c = pending, c+1));
4964 <                new SearchKeysTask<K,V,U>(this, b >>>= 1, true,
4965 <                                          searchFunction, result).fork();
4966 <            }
4967 <            U u;
4968 <            while (result.get() == null && advance() != null) {
4969 <                if ((u = searchFunction.apply((K)nextKey)) != null) {
4970 <                    if (result.compareAndSet(null, u)) {
4971 <                        for (BulkTask<K,V,?> a = this, p;;) {
4972 <                            if ((p = a.parent) == null) {
4973 <                                a.quietlyComplete();
4974 <                                break;
4975 <                            }
4976 <                            a = p;
4977 <                        }
4955 >        public final U getRawResult() { return result.get(); }
4956 >        public final void compute() {
4957 >            final Fun<? super K, ? extends U> searchFunction;
4958 >            final AtomicReference<U> result;
4959 >            if ((searchFunction = this.searchFunction) != null &&
4960 >                (result = this.result) != null) {
4961 >                for (int i = baseIndex, f, h; batch > 0 &&
4962 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4963 >                    if (result.get() != null)
4964 >                        return;
4965 >                    addToPendingCount(1);
4966 >                    new SearchKeysTask<K,V,U>
4967 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4968 >                         searchFunction, result).fork();
4969 >                }
4970 >                while (result.get() == null) {
4971 >                    U u;
4972 >                    Node<K,V> p;
4973 >                    if ((p = advance()) == null) {
4974 >                        propagateCompletion();
4975 >                        break;
4976 >                    }
4977 >                    if ((u = searchFunction.apply(p.key)) != null) {
4978 >                        if (result.compareAndSet(null, u))
4979 >                            quietlyCompleteRoot();
4980 >                        break;
4981                      }
5298                    break;
4982                  }
4983              }
5301            tryComplete();
4984          }
5303        public final U getRawResult() { return result.get(); }
4985      }
4986  
4987      @SuppressWarnings("serial")
# Line 5309 | Line 4990 | public class ConcurrentHashMapV8<K, V>
4990          final Fun<? super V, ? extends U> searchFunction;
4991          final AtomicReference<U> result;
4992          SearchValuesTask
4993 <            (ConcurrentHashMapV8<K,V> m,
4993 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4994               Fun<? super V, ? extends U> searchFunction,
4995               AtomicReference<U> result) {
4996 <            super(m);
4996 >            super(p, b, i, f, t);
4997              this.searchFunction = searchFunction; this.result = result;
4998          }
4999 <        SearchValuesTask
5000 <            (BulkTask<K,V,?> p, int b, boolean split,
5001 <             Fun<? super V, ? extends U> searchFunction,
5002 <             AtomicReference<U> result) {
5003 <            super(p, b, split);
5004 <            this.searchFunction = searchFunction; this.result = result;
5005 <        }
5006 <        @SuppressWarnings("unchecked") public final void compute() {
5007 <            AtomicReference<U> result = this.result;
5008 <            final Fun<? super V, ? extends U> searchFunction =
5009 <                this.searchFunction;
5010 <            if (searchFunction == null || result == null)
5011 <                throw new Error(NullFunctionMessage);
5012 <            int b = batch(), c;
5013 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5014 <                do {} while (!casPending(c = pending, c+1));
5015 <                new SearchValuesTask<K,V,U>(this, b >>>= 1, true,
5016 <                                            searchFunction, result).fork();
5017 <            }
5018 <            Object v; U u;
5019 <            while (result.get() == null && (v = advance()) != null) {
5020 <                if ((u = searchFunction.apply((V)v)) != null) {
5021 <                    if (result.compareAndSet(null, u)) {
5022 <                        for (BulkTask<K,V,?> a = this, p;;) {
5023 <                            if ((p = a.parent) == null) {
5024 <                                a.quietlyComplete();
5344 <                                break;
5345 <                            }
5346 <                            a = p;
5347 <                        }
4999 >        public final U getRawResult() { return result.get(); }
5000 >        public final void compute() {
5001 >            final Fun<? super V, ? extends U> searchFunction;
5002 >            final AtomicReference<U> result;
5003 >            if ((searchFunction = this.searchFunction) != null &&
5004 >                (result = this.result) != null) {
5005 >                for (int i = baseIndex, f, h; batch > 0 &&
5006 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5007 >                    if (result.get() != null)
5008 >                        return;
5009 >                    addToPendingCount(1);
5010 >                    new SearchValuesTask<K,V,U>
5011 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5012 >                         searchFunction, result).fork();
5013 >                }
5014 >                while (result.get() == null) {
5015 >                    U u;
5016 >                    Node<K,V> p;
5017 >                    if ((p = advance()) == null) {
5018 >                        propagateCompletion();
5019 >                        break;
5020 >                    }
5021 >                    if ((u = searchFunction.apply(p.val)) != null) {
5022 >                        if (result.compareAndSet(null, u))
5023 >                            quietlyCompleteRoot();
5024 >                        break;
5025                      }
5349                    break;
5026                  }
5027              }
5352            tryComplete();
5028          }
5354        public final U getRawResult() { return result.get(); }
5029      }
5030  
5031      @SuppressWarnings("serial")
# Line 5360 | Line 5034 | public class ConcurrentHashMapV8<K, V>
5034          final Fun<Entry<K,V>, ? extends U> searchFunction;
5035          final AtomicReference<U> result;
5036          SearchEntriesTask
5037 <            (ConcurrentHashMapV8<K,V> m,
5037 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5038               Fun<Entry<K,V>, ? extends U> searchFunction,
5039               AtomicReference<U> result) {
5040 <            super(m);
5040 >            super(p, b, i, f, t);
5041              this.searchFunction = searchFunction; this.result = result;
5042          }
5043 <        SearchEntriesTask
5044 <            (BulkTask<K,V,?> p, int b, boolean split,
5045 <             Fun<Entry<K,V>, ? extends U> searchFunction,
5046 <             AtomicReference<U> result) {
5047 <            super(p, b, split);
5048 <            this.searchFunction = searchFunction; this.result = result;
5049 <        }
5050 <        @SuppressWarnings("unchecked") public final void compute() {
5051 <            AtomicReference<U> result = this.result;
5052 <            final Fun<Entry<K,V>, ? extends U> searchFunction =
5053 <                this.searchFunction;
5054 <            if (searchFunction == null || result == null)
5055 <                throw new Error(NullFunctionMessage);
5056 <            int b = batch(), c;
5057 <            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5058 <                do {} while (!casPending(c = pending, c+1));
5059 <                new SearchEntriesTask<K,V,U>(this, b >>>= 1, true,
5060 <                                             searchFunction, result).fork();
5061 <            }
5062 <            Object v; U u;
5063 <            while (result.get() == null && (v = advance()) != null) {
5064 <                if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5065 <                    if (result.compareAndSet(null, u)) {
5066 <                        for (BulkTask<K,V,?> a = this, p;;) {
5067 <                            if ((p = a.parent) == null) {
5068 <                                a.quietlyComplete();
5395 <                                break;
5396 <                            }
5397 <                            a = p;
5398 <                        }
5043 >        public final U getRawResult() { return result.get(); }
5044 >        public final void compute() {
5045 >            final Fun<Entry<K,V>, ? extends U> searchFunction;
5046 >            final AtomicReference<U> result;
5047 >            if ((searchFunction = this.searchFunction) != null &&
5048 >                (result = this.result) != null) {
5049 >                for (int i = baseIndex, f, h; batch > 0 &&
5050 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5051 >                    if (result.get() != null)
5052 >                        return;
5053 >                    addToPendingCount(1);
5054 >                    new SearchEntriesTask<K,V,U>
5055 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5056 >                         searchFunction, result).fork();
5057 >                }
5058 >                while (result.get() == null) {
5059 >                    U u;
5060 >                    Node<K,V> p;
5061 >                    if ((p = advance()) == null) {
5062 >                        propagateCompletion();
5063 >                        break;
5064 >                    }
5065 >                    if ((u = searchFunction.apply(p)) != null) {
5066 >                        if (result.compareAndSet(null, u))
5067 >                            quietlyCompleteRoot();
5068 >                        return;
5069                      }
5400                    break;
5070                  }
5071              }
5403            tryComplete();
5072          }
5405        public final U getRawResult() { return result.get(); }
5073      }
5074  
5075      @SuppressWarnings("serial")
# Line 5411 | Line 5078 | public class ConcurrentHashMapV8<K, V>
5078          final BiFun<? super K, ? super V, ? extends U> searchFunction;
5079          final AtomicReference<U> result;
5080          SearchMappingsTask
5081 <            (ConcurrentHashMapV8<K,V> m,
5415 <             BiFun<? super K, ? super V, ? extends U> searchFunction,
5416 <             AtomicReference<U> result) {
5417 <            super(m);
5418 <            this.searchFunction = searchFunction; this.result = result;
5419 <        }
5420 <        SearchMappingsTask
5421 <            (BulkTask<K,V,?> p, int b, boolean split,
5081 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5082               BiFun<? super K, ? super V, ? extends U> searchFunction,
5083               AtomicReference<U> result) {
5084 <            super(p, b, split);
5084 >            super(p, b, i, f, t);
5085              this.searchFunction = searchFunction; this.result = result;
5086          }
5087 <        @SuppressWarnings("unchecked") public final void compute() {
5088 <            AtomicReference<U> result = this.result;
5089 <            final BiFun<? super K, ? super 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 SearchMappingsTask<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((K)nextKey, (V)v)) != null) {
5102 <                    if (result.compareAndSet(null, u)) {
5103 <                        for (BulkTask<K,V,?> a = this, p;;) {
5104 <                            if ((p = a.parent) == null) {
5105 <                                a.quietlyComplete();
5106 <                                break;
5107 <                            }
5108 <                            a = p;
5109 <                        }
5087 >        public final U getRawResult() { return result.get(); }
5088 >        public final void compute() {
5089 >            final BiFun<? super K, ? super V, ? extends U> searchFunction;
5090 >            final AtomicReference<U> result;
5091 >            if ((searchFunction = this.searchFunction) != null &&
5092 >                (result = this.result) != null) {
5093 >                for (int i = baseIndex, f, h; batch > 0 &&
5094 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5095 >                    if (result.get() != null)
5096 >                        return;
5097 >                    addToPendingCount(1);
5098 >                    new SearchMappingsTask<K,V,U>
5099 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5100 >                         searchFunction, result).fork();
5101 >                }
5102 >                while (result.get() == null) {
5103 >                    U u;
5104 >                    Node<K,V> p;
5105 >                    if ((p = advance()) == null) {
5106 >                        propagateCompletion();
5107 >                        break;
5108 >                    }
5109 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5110 >                        if (result.compareAndSet(null, u))
5111 >                            quietlyCompleteRoot();
5112 >                        break;
5113                      }
5451                    break;
5114                  }
5115              }
5454            tryComplete();
5116          }
5456        public final U getRawResult() { return result.get(); }
5117      }
5118  
5119      @SuppressWarnings("serial")
# Line 5461 | Line 5121 | public class ConcurrentHashMapV8<K, V>
5121          extends BulkTask<K,V,K> {
5122          final BiFun<? super K, ? super K, ? extends K> reducer;
5123          K result;
5124 <        ReduceKeysTask<K,V> sibling;
5465 <        ReduceKeysTask
5466 <            (ConcurrentHashMapV8<K,V> m,
5467 <             BiFun<? super K, ? super K, ? extends K> reducer) {
5468 <            super(m);
5469 <            this.reducer = reducer;
5470 <        }
5124 >        ReduceKeysTask<K,V> rights, nextRight;
5125          ReduceKeysTask
5126 <            (BulkTask<K,V,?> p, int b, boolean split,
5126 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5127 >             ReduceKeysTask<K,V> nextRight,
5128               BiFun<? super K, ? super K, ? extends K> reducer) {
5129 <            super(p, b, split);
5129 >            super(p, b, i, f, t); this.nextRight = nextRight;
5130              this.reducer = reducer;
5131          }
5132 <
5133 <        @SuppressWarnings("unchecked") public final void compute() {
5134 <            ReduceKeysTask<K,V> t = this;
5135 <            final BiFun<? super K, ? super K, ? extends K> reducer =
5136 <                this.reducer;
5137 <            if (reducer == null)
5138 <                throw new Error(NullFunctionMessage);
5139 <            int b = batch();
5140 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5141 <                b >>>= 1;
5142 <                t.pending = 1;
5143 <                ReduceKeysTask<K,V> rt =
5144 <                    new ReduceKeysTask<K,V>
5145 <                    (t, b, true, reducer);
5146 <                t = new ReduceKeysTask<K,V>
5147 <                    (t, b, false, reducer);
5148 <                t.sibling = rt;
5149 <                rt.sibling = t;
5150 <                rt.fork();
5151 <            }
5152 <            K r = null;
5153 <            while (t.advance() != null) {
5154 <                K u = (K)t.nextKey;
5155 <                r = (r == null) ? u : reducer.apply(r, u);
5156 <            }
5157 <            t.result = r;
5158 <            for (;;) {
5159 <                int c; BulkTask<K,V,?> par; ReduceKeysTask<K,V> s, p; K u;
5160 <                if ((par = t.parent) == null ||
5506 <                    !(par instanceof ReduceKeysTask)) {
5507 <                    t.quietlyComplete();
5508 <                    break;
5509 <                }
5510 <                else if ((c = (p = (ReduceKeysTask<K,V>)par).pending) == 0) {
5511 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5512 <                        r = (r == null) ? u : reducer.apply(r, u);
5513 <                    (t = p).result = r;
5132 >        public final K getRawResult() { return result; }
5133 >        public final void compute() {
5134 >            final BiFun<? super K, ? super K, ? extends K> reducer;
5135 >            if ((reducer = this.reducer) != null) {
5136 >                for (int i = baseIndex, f, h; batch > 0 &&
5137 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5138 >                    addToPendingCount(1);
5139 >                    (rights = new ReduceKeysTask<K,V>
5140 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5141 >                      rights, reducer)).fork();
5142 >                }
5143 >                K r = null;
5144 >                for (Node<K,V> p; (p = advance()) != null; ) {
5145 >                    K u = p.key;
5146 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5147 >                }
5148 >                result = r;
5149 >                CountedCompleter<?> c;
5150 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5151 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5152 >                        t = (ReduceKeysTask<K,V>)c,
5153 >                        s = t.rights;
5154 >                    while (s != null) {
5155 >                        K tr, sr;
5156 >                        if ((sr = s.result) != null)
5157 >                            t.result = (((tr = t.result) == null) ? sr :
5158 >                                        reducer.apply(tr, sr));
5159 >                        s = t.rights = s.nextRight;
5160 >                    }
5161                  }
5515                else if (p.casPending(c, 0))
5516                    break;
5162              }
5163          }
5519        public final K getRawResult() { return result; }
5164      }
5165  
5166      @SuppressWarnings("serial")
# Line 5524 | Line 5168 | public class ConcurrentHashMapV8<K, V>
5168          extends BulkTask<K,V,V> {
5169          final BiFun<? super V, ? super V, ? extends V> reducer;
5170          V result;
5171 <        ReduceValuesTask<K,V> sibling;
5528 <        ReduceValuesTask
5529 <            (ConcurrentHashMapV8<K,V> m,
5530 <             BiFun<? super V, ? super V, ? extends V> reducer) {
5531 <            super(m);
5532 <            this.reducer = reducer;
5533 <        }
5171 >        ReduceValuesTask<K,V> rights, nextRight;
5172          ReduceValuesTask
5173 <            (BulkTask<K,V,?> p, int b, boolean split,
5173 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5174 >             ReduceValuesTask<K,V> nextRight,
5175               BiFun<? super V, ? super V, ? extends V> reducer) {
5176 <            super(p, b, split);
5176 >            super(p, b, i, f, t); this.nextRight = nextRight;
5177              this.reducer = reducer;
5178          }
5179 <
5180 <        @SuppressWarnings("unchecked") public final void compute() {
5181 <            ReduceValuesTask<K,V> t = this;
5182 <            final BiFun<? super V, ? super V, ? extends V> reducer =
5183 <                this.reducer;
5184 <            if (reducer == null)
5185 <                throw new Error(NullFunctionMessage);
5186 <            int b = batch();
5187 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5188 <                b >>>= 1;
5189 <                t.pending = 1;
5190 <                ReduceValuesTask<K,V> rt =
5191 <                    new ReduceValuesTask<K,V>
5192 <                    (t, b, true, reducer);
5193 <                t = new ReduceValuesTask<K,V>
5194 <                    (t, b, false, reducer);
5195 <                t.sibling = rt;
5196 <                rt.sibling = t;
5197 <                rt.fork();
5198 <            }
5199 <            V r = null;
5200 <            Object v;
5201 <            while ((v = t.advance()) != null) {
5202 <                V u = (V)v;
5203 <                r = (r == null) ? u : reducer.apply(r, u);
5204 <            }
5205 <            t.result = r;
5206 <            for (;;) {
5207 <                int c; BulkTask<K,V,?> par; ReduceValuesTask<K,V> s, p; V u;
5569 <                if ((par = t.parent) == null ||
5570 <                    !(par instanceof ReduceValuesTask)) {
5571 <                    t.quietlyComplete();
5572 <                    break;
5573 <                }
5574 <                else if ((c = (p = (ReduceValuesTask<K,V>)par).pending) == 0) {
5575 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5576 <                        r = (r == null) ? u : reducer.apply(r, u);
5577 <                    (t = p).result = r;
5179 >        public final V getRawResult() { return result; }
5180 >        public final void compute() {
5181 >            final BiFun<? super V, ? super V, ? extends V> reducer;
5182 >            if ((reducer = this.reducer) != null) {
5183 >                for (int i = baseIndex, f, h; batch > 0 &&
5184 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5185 >                    addToPendingCount(1);
5186 >                    (rights = new ReduceValuesTask<K,V>
5187 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5188 >                      rights, reducer)).fork();
5189 >                }
5190 >                V r = null;
5191 >                for (Node<K,V> p; (p = advance()) != null; ) {
5192 >                    V v = p.val;
5193 >                    r = (r == null) ? v : reducer.apply(r, v);
5194 >                }
5195 >                result = r;
5196 >                CountedCompleter<?> c;
5197 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5198 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5199 >                        t = (ReduceValuesTask<K,V>)c,
5200 >                        s = t.rights;
5201 >                    while (s != null) {
5202 >                        V tr, sr;
5203 >                        if ((sr = s.result) != null)
5204 >                            t.result = (((tr = t.result) == null) ? sr :
5205 >                                        reducer.apply(tr, sr));
5206 >                        s = t.rights = s.nextRight;
5207 >                    }
5208                  }
5579                else if (p.casPending(c, 0))
5580                    break;
5209              }
5210          }
5583        public final V getRawResult() { return result; }
5211      }
5212  
5213      @SuppressWarnings("serial")
# Line 5588 | Line 5215 | public class ConcurrentHashMapV8<K, V>
5215          extends BulkTask<K,V,Map.Entry<K,V>> {
5216          final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5217          Map.Entry<K,V> result;
5218 <        ReduceEntriesTask<K,V> sibling;
5218 >        ReduceEntriesTask<K,V> rights, nextRight;
5219          ReduceEntriesTask
5220 <            (ConcurrentHashMapV8<K,V> m,
5220 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5221 >             ReduceEntriesTask<K,V> nextRight,
5222               BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5223 <            super(m);
5223 >            super(p, b, i, f, t); this.nextRight = nextRight;
5224              this.reducer = reducer;
5225          }
5226 <        ReduceEntriesTask
5227 <            (BulkTask<K,V,?> p, int b, boolean split,
5228 <             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5229 <            super(p, b, split);
5230 <            this.reducer = reducer;
5231 <        }
5232 <
5233 <        @SuppressWarnings("unchecked") public final void compute() {
5234 <            ReduceEntriesTask<K,V> t = this;
5235 <            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5236 <                this.reducer;
5237 <            if (reducer == null)
5238 <                throw new Error(NullFunctionMessage);
5239 <            int b = batch();
5240 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5241 <                b >>>= 1;
5242 <                t.pending = 1;
5243 <                ReduceEntriesTask<K,V> rt =
5244 <                    new ReduceEntriesTask<K,V>
5245 <                    (t, b, true, reducer);
5246 <                t = new ReduceEntriesTask<K,V>
5247 <                    (t, b, false, reducer);
5248 <                t.sibling = rt;
5249 <                rt.sibling = t;
5250 <                rt.fork();
5251 <            }
5252 <            Map.Entry<K,V> r = null;
5625 <            Object v;
5626 <            while ((v = t.advance()) != null) {
5627 <                Map.Entry<K,V> u = entryFor((K)t.nextKey, (V)v);
5628 <                r = (r == null) ? u : reducer.apply(r, u);
5629 <            }
5630 <            t.result = r;
5631 <            for (;;) {
5632 <                int c; BulkTask<K,V,?> par; ReduceEntriesTask<K,V> s, p;
5633 <                Map.Entry<K,V> u;
5634 <                if ((par = t.parent) == null ||
5635 <                    !(par instanceof ReduceEntriesTask)) {
5636 <                    t.quietlyComplete();
5637 <                    break;
5638 <                }
5639 <                else if ((c = (p = (ReduceEntriesTask<K,V>)par).pending) == 0) {
5640 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5641 <                        r = (r == null) ? u : reducer.apply(r, u);
5642 <                    (t = p).result = r;
5226 >        public final Map.Entry<K,V> getRawResult() { return result; }
5227 >        public final void compute() {
5228 >            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5229 >            if ((reducer = this.reducer) != null) {
5230 >                for (int i = baseIndex, f, h; batch > 0 &&
5231 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5232 >                    addToPendingCount(1);
5233 >                    (rights = new ReduceEntriesTask<K,V>
5234 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5235 >                      rights, reducer)).fork();
5236 >                }
5237 >                Map.Entry<K,V> r = null;
5238 >                for (Node<K,V> p; (p = advance()) != null; )
5239 >                    r = (r == null) ? p : reducer.apply(r, p);
5240 >                result = r;
5241 >                CountedCompleter<?> c;
5242 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5243 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5244 >                        t = (ReduceEntriesTask<K,V>)c,
5245 >                        s = t.rights;
5246 >                    while (s != null) {
5247 >                        Map.Entry<K,V> tr, sr;
5248 >                        if ((sr = s.result) != null)
5249 >                            t.result = (((tr = t.result) == null) ? sr :
5250 >                                        reducer.apply(tr, sr));
5251 >                        s = t.rights = s.nextRight;
5252 >                    }
5253                  }
5644                else if (p.casPending(c, 0))
5645                    break;
5254              }
5255          }
5648        public final Map.Entry<K,V> getRawResult() { return result; }
5256      }
5257  
5258      @SuppressWarnings("serial")
# Line 5654 | Line 5261 | public class ConcurrentHashMapV8<K, V>
5261          final Fun<? super K, ? extends U> transformer;
5262          final BiFun<? super U, ? super U, ? extends U> reducer;
5263          U result;
5264 <        MapReduceKeysTask<K,V,U> sibling;
5658 <        MapReduceKeysTask
5659 <            (ConcurrentHashMapV8<K,V> m,
5660 <             Fun<? super K, ? extends U> transformer,
5661 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5662 <            super(m);
5663 <            this.transformer = transformer;
5664 <            this.reducer = reducer;
5665 <        }
5264 >        MapReduceKeysTask<K,V,U> rights, nextRight;
5265          MapReduceKeysTask
5266 <            (BulkTask<K,V,?> p, int b, boolean split,
5266 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5267 >             MapReduceKeysTask<K,V,U> nextRight,
5268               Fun<? super K, ? extends U> transformer,
5269               BiFun<? super U, ? super U, ? extends U> reducer) {
5270 <            super(p, b, split);
5270 >            super(p, b, i, f, t); this.nextRight = nextRight;
5271              this.transformer = transformer;
5272              this.reducer = reducer;
5273          }
5274 <        @SuppressWarnings("unchecked") public final void compute() {
5275 <            MapReduceKeysTask<K,V,U> t = this;
5276 <            final Fun<? super K, ? extends U> transformer =
5277 <                this.transformer;
5278 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5279 <                this.reducer;
5280 <            if (transformer == null || reducer == null)
5281 <                throw new Error(NullFunctionMessage);
5282 <            int b = batch();
5283 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5284 <                b >>>= 1;
5285 <                t.pending = 1;
5286 <                MapReduceKeysTask<K,V,U> rt =
5287 <                    new MapReduceKeysTask<K,V,U>
5288 <                    (t, b, true, transformer, reducer);
5289 <                t = new MapReduceKeysTask<K,V,U>
5290 <                    (t, b, false, transformer, reducer);
5691 <                t.sibling = rt;
5692 <                rt.sibling = t;
5693 <                rt.fork();
5694 <            }
5695 <            U r = null, u;
5696 <            while (t.advance() != null) {
5697 <                if ((u = transformer.apply((K)t.nextKey)) != null)
5698 <                    r = (r == null) ? u : reducer.apply(r, u);
5699 <            }
5700 <            t.result = r;
5701 <            for (;;) {
5702 <                int c; BulkTask<K,V,?> par; MapReduceKeysTask<K,V,U> s, p;
5703 <                if ((par = t.parent) == null ||
5704 <                    !(par instanceof MapReduceKeysTask)) {
5705 <                    t.quietlyComplete();
5706 <                    break;
5707 <                }
5708 <                else if ((c = (p = (MapReduceKeysTask<K,V,U>)par).pending) == 0) {
5709 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5274 >        public final U getRawResult() { return result; }
5275 >        public final void compute() {
5276 >            final Fun<? super K, ? extends U> transformer;
5277 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5278 >            if ((transformer = this.transformer) != null &&
5279 >                (reducer = this.reducer) != null) {
5280 >                for (int i = baseIndex, f, h; batch > 0 &&
5281 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5282 >                    addToPendingCount(1);
5283 >                    (rights = new MapReduceKeysTask<K,V,U>
5284 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5285 >                      rights, transformer, reducer)).fork();
5286 >                }
5287 >                U r = null;
5288 >                for (Node<K,V> p; (p = advance()) != null; ) {
5289 >                    U u;
5290 >                    if ((u = transformer.apply(p.key)) != null)
5291                          r = (r == null) ? u : reducer.apply(r, u);
5711                    (t = p).result = r;
5292                  }
5293 <                else if (p.casPending(c, 0))
5294 <                    break;
5293 >                result = r;
5294 >                CountedCompleter<?> c;
5295 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5296 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5297 >                        t = (MapReduceKeysTask<K,V,U>)c,
5298 >                        s = t.rights;
5299 >                    while (s != null) {
5300 >                        U tr, sr;
5301 >                        if ((sr = s.result) != null)
5302 >                            t.result = (((tr = t.result) == null) ? sr :
5303 >                                        reducer.apply(tr, sr));
5304 >                        s = t.rights = s.nextRight;
5305 >                    }
5306 >                }
5307              }
5308          }
5717        public final U getRawResult() { return result; }
5309      }
5310  
5311      @SuppressWarnings("serial")
# Line 5723 | Line 5314 | public class ConcurrentHashMapV8<K, V>
5314          final Fun<? super V, ? extends U> transformer;
5315          final BiFun<? super U, ? super U, ? extends U> reducer;
5316          U result;
5317 <        MapReduceValuesTask<K,V,U> sibling;
5317 >        MapReduceValuesTask<K,V,U> rights, nextRight;
5318          MapReduceValuesTask
5319 <            (ConcurrentHashMapV8<K,V> m,
5319 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5320 >             MapReduceValuesTask<K,V,U> nextRight,
5321               Fun<? super V, ? extends U> transformer,
5322               BiFun<? super U, ? super U, ? extends U> reducer) {
5323 <            super(m);
5323 >            super(p, b, i, f, t); this.nextRight = nextRight;
5324              this.transformer = transformer;
5325              this.reducer = reducer;
5326          }
5327 <        MapReduceValuesTask
5328 <            (BulkTask<K,V,?> p, int b, boolean split,
5329 <             Fun<? super V, ? extends U> transformer,
5330 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5331 <            super(p, b, split);
5332 <            this.transformer = transformer;
5333 <            this.reducer = reducer;
5334 <        }
5335 <        @SuppressWarnings("unchecked") public final void compute() {
5336 <            MapReduceValuesTask<K,V,U> t = this;
5337 <            final Fun<? super V, ? extends U> transformer =
5338 <                this.transformer;
5339 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5340 <                this.reducer;
5341 <            if (transformer == null || reducer == null)
5342 <                throw new Error(NullFunctionMessage);
5343 <            int b = batch();
5752 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5753 <                b >>>= 1;
5754 <                t.pending = 1;
5755 <                MapReduceValuesTask<K,V,U> rt =
5756 <                    new MapReduceValuesTask<K,V,U>
5757 <                    (t, b, true, transformer, reducer);
5758 <                t = new MapReduceValuesTask<K,V,U>
5759 <                    (t, b, false, transformer, reducer);
5760 <                t.sibling = rt;
5761 <                rt.sibling = t;
5762 <                rt.fork();
5763 <            }
5764 <            U r = null, u;
5765 <            Object v;
5766 <            while ((v = t.advance()) != null) {
5767 <                if ((u = transformer.apply((V)v)) != null)
5768 <                    r = (r == null) ? u : reducer.apply(r, u);
5769 <            }
5770 <            t.result = r;
5771 <            for (;;) {
5772 <                int c; BulkTask<K,V,?> par; MapReduceValuesTask<K,V,U> s, p;
5773 <                if ((par = t.parent) == null ||
5774 <                    !(par instanceof MapReduceValuesTask)) {
5775 <                    t.quietlyComplete();
5776 <                    break;
5777 <                }
5778 <                else if ((c = (p = (MapReduceValuesTask<K,V,U>)par).pending) == 0) {
5779 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5327 >        public final U getRawResult() { return result; }
5328 >        public final void compute() {
5329 >            final Fun<? super V, ? extends U> transformer;
5330 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5331 >            if ((transformer = this.transformer) != null &&
5332 >                (reducer = this.reducer) != null) {
5333 >                for (int i = baseIndex, f, h; batch > 0 &&
5334 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5335 >                    addToPendingCount(1);
5336 >                    (rights = new MapReduceValuesTask<K,V,U>
5337 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5338 >                      rights, transformer, reducer)).fork();
5339 >                }
5340 >                U r = null;
5341 >                for (Node<K,V> p; (p = advance()) != null; ) {
5342 >                    U u;
5343 >                    if ((u = transformer.apply(p.val)) != null)
5344                          r = (r == null) ? u : reducer.apply(r, u);
5781                    (t = p).result = r;
5345                  }
5346 <                else if (p.casPending(c, 0))
5347 <                    break;
5346 >                result = r;
5347 >                CountedCompleter<?> c;
5348 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5349 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5350 >                        t = (MapReduceValuesTask<K,V,U>)c,
5351 >                        s = t.rights;
5352 >                    while (s != null) {
5353 >                        U tr, sr;
5354 >                        if ((sr = s.result) != null)
5355 >                            t.result = (((tr = t.result) == null) ? sr :
5356 >                                        reducer.apply(tr, sr));
5357 >                        s = t.rights = s.nextRight;
5358 >                    }
5359 >                }
5360              }
5361          }
5787        public final U getRawResult() { return result; }
5362      }
5363  
5364      @SuppressWarnings("serial")
# Line 5793 | Line 5367 | public class ConcurrentHashMapV8<K, V>
5367          final Fun<Map.Entry<K,V>, ? extends U> transformer;
5368          final BiFun<? super U, ? super U, ? extends U> reducer;
5369          U result;
5370 <        MapReduceEntriesTask<K,V,U> sibling;
5370 >        MapReduceEntriesTask<K,V,U> rights, nextRight;
5371          MapReduceEntriesTask
5372 <            (ConcurrentHashMapV8<K,V> m,
5372 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5373 >             MapReduceEntriesTask<K,V,U> nextRight,
5374               Fun<Map.Entry<K,V>, ? extends U> transformer,
5375               BiFun<? super U, ? super U, ? extends U> reducer) {
5376 <            super(m);
5376 >            super(p, b, i, f, t); this.nextRight = nextRight;
5377              this.transformer = transformer;
5378              this.reducer = reducer;
5379          }
5380 <        MapReduceEntriesTask
5381 <            (BulkTask<K,V,?> p, int b, boolean split,
5382 <             Fun<Map.Entry<K,V>, ? extends U> transformer,
5383 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5384 <            super(p, b, split);
5385 <            this.transformer = transformer;
5386 <            this.reducer = reducer;
5387 <        }
5388 <        @SuppressWarnings("unchecked") public final void compute() {
5389 <            MapReduceEntriesTask<K,V,U> t = this;
5390 <            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5391 <                this.transformer;
5392 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5393 <                this.reducer;
5394 <            if (transformer == null || reducer == null)
5395 <                throw new Error(NullFunctionMessage);
5396 <            int b = batch();
5822 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5823 <                b >>>= 1;
5824 <                t.pending = 1;
5825 <                MapReduceEntriesTask<K,V,U> rt =
5826 <                    new MapReduceEntriesTask<K,V,U>
5827 <                    (t, b, true, transformer, reducer);
5828 <                t = new MapReduceEntriesTask<K,V,U>
5829 <                    (t, b, false, transformer, reducer);
5830 <                t.sibling = rt;
5831 <                rt.sibling = t;
5832 <                rt.fork();
5833 <            }
5834 <            U r = null, u;
5835 <            Object v;
5836 <            while ((v = t.advance()) != null) {
5837 <                if ((u = transformer.apply(entryFor((K)t.nextKey, (V)v))) != null)
5838 <                    r = (r == null) ? u : reducer.apply(r, u);
5839 <            }
5840 <            t.result = r;
5841 <            for (;;) {
5842 <                int c; BulkTask<K,V,?> par; MapReduceEntriesTask<K,V,U> s, p;
5843 <                if ((par = t.parent) == null ||
5844 <                    !(par instanceof MapReduceEntriesTask)) {
5845 <                    t.quietlyComplete();
5846 <                    break;
5847 <                }
5848 <                else if ((c = (p = (MapReduceEntriesTask<K,V,U>)par).pending) == 0) {
5849 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5380 >        public final U getRawResult() { return result; }
5381 >        public final void compute() {
5382 >            final Fun<Map.Entry<K,V>, ? extends U> transformer;
5383 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5384 >            if ((transformer = this.transformer) != null &&
5385 >                (reducer = this.reducer) != null) {
5386 >                for (int i = baseIndex, f, h; batch > 0 &&
5387 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5388 >                    addToPendingCount(1);
5389 >                    (rights = new MapReduceEntriesTask<K,V,U>
5390 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5391 >                      rights, transformer, reducer)).fork();
5392 >                }
5393 >                U r = null;
5394 >                for (Node<K,V> p; (p = advance()) != null; ) {
5395 >                    U u;
5396 >                    if ((u = transformer.apply(p)) != null)
5397                          r = (r == null) ? u : reducer.apply(r, u);
5851                    (t = p).result = r;
5398                  }
5399 <                else if (p.casPending(c, 0))
5400 <                    break;
5399 >                result = r;
5400 >                CountedCompleter<?> c;
5401 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5402 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5403 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5404 >                        s = t.rights;
5405 >                    while (s != null) {
5406 >                        U tr, sr;
5407 >                        if ((sr = s.result) != null)
5408 >                            t.result = (((tr = t.result) == null) ? sr :
5409 >                                        reducer.apply(tr, sr));
5410 >                        s = t.rights = s.nextRight;
5411 >                    }
5412 >                }
5413              }
5414          }
5857        public final U getRawResult() { return result; }
5415      }
5416  
5417      @SuppressWarnings("serial")
# Line 5863 | Line 5420 | public class ConcurrentHashMapV8<K, V>
5420          final BiFun<? super K, ? super V, ? extends U> transformer;
5421          final BiFun<? super U, ? super U, ? extends U> reducer;
5422          U result;
5423 <        MapReduceMappingsTask<K,V,U> sibling;
5867 <        MapReduceMappingsTask
5868 <            (ConcurrentHashMapV8<K,V> m,
5869 <             BiFun<? super K, ? super V, ? extends U> transformer,
5870 <             BiFun<? super U, ? super U, ? extends U> reducer) {
5871 <            super(m);
5872 <            this.transformer = transformer;
5873 <            this.reducer = reducer;
5874 <        }
5423 >        MapReduceMappingsTask<K,V,U> rights, nextRight;
5424          MapReduceMappingsTask
5425 <            (BulkTask<K,V,?> p, int b, boolean split,
5425 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5426 >             MapReduceMappingsTask<K,V,U> nextRight,
5427               BiFun<? super K, ? super V, ? extends U> transformer,
5428               BiFun<? super U, ? super U, ? extends U> reducer) {
5429 <            super(p, b, split);
5429 >            super(p, b, i, f, t); this.nextRight = nextRight;
5430              this.transformer = transformer;
5431              this.reducer = reducer;
5432          }
5433 <        @SuppressWarnings("unchecked") public final void compute() {
5434 <            MapReduceMappingsTask<K,V,U> t = this;
5435 <            final BiFun<? super K, ? super V, ? extends U> transformer =
5436 <                this.transformer;
5437 <            final BiFun<? super U, ? super U, ? extends U> reducer =
5438 <                this.reducer;
5439 <            if (transformer == null || reducer == null)
5440 <                throw new Error(NullFunctionMessage);
5441 <            int b = batch();
5442 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5443 <                b >>>= 1;
5444 <                t.pending = 1;
5445 <                MapReduceMappingsTask<K,V,U> rt =
5446 <                    new MapReduceMappingsTask<K,V,U>
5447 <                    (t, b, true, transformer, reducer);
5448 <                t = new MapReduceMappingsTask<K,V,U>
5449 <                    (t, b, false, transformer, reducer);
5900 <                t.sibling = rt;
5901 <                rt.sibling = t;
5902 <                rt.fork();
5903 <            }
5904 <            U r = null, u;
5905 <            Object v;
5906 <            while ((v = t.advance()) != null) {
5907 <                if ((u = transformer.apply((K)t.nextKey, (V)v)) != null)
5908 <                    r = (r == null) ? u : reducer.apply(r, u);
5909 <            }
5910 <            for (;;) {
5911 <                int c; BulkTask<K,V,?> par; MapReduceMappingsTask<K,V,U> s, p;
5912 <                if ((par = t.parent) == null ||
5913 <                    !(par instanceof MapReduceMappingsTask)) {
5914 <                    t.quietlyComplete();
5915 <                    break;
5916 <                }
5917 <                else if ((c = (p = (MapReduceMappingsTask<K,V,U>)par).pending) == 0) {
5918 <                    if ((s = t.sibling) != null && (u = s.result) != null)
5433 >        public final U getRawResult() { return result; }
5434 >        public final void compute() {
5435 >            final BiFun<? super K, ? super V, ? extends U> transformer;
5436 >            final BiFun<? super U, ? super U, ? extends U> reducer;
5437 >            if ((transformer = this.transformer) != null &&
5438 >                (reducer = this.reducer) != null) {
5439 >                for (int i = baseIndex, f, h; batch > 0 &&
5440 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5441 >                    addToPendingCount(1);
5442 >                    (rights = new MapReduceMappingsTask<K,V,U>
5443 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5444 >                      rights, transformer, reducer)).fork();
5445 >                }
5446 >                U r = null;
5447 >                for (Node<K,V> p; (p = advance()) != null; ) {
5448 >                    U u;
5449 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5450                          r = (r == null) ? u : reducer.apply(r, u);
5920                    (t = p).result = r;
5451                  }
5452 <                else if (p.casPending(c, 0))
5453 <                    break;
5452 >                result = r;
5453 >                CountedCompleter<?> c;
5454 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5455 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5456 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5457 >                        s = t.rights;
5458 >                    while (s != null) {
5459 >                        U tr, sr;
5460 >                        if ((sr = s.result) != null)
5461 >                            t.result = (((tr = t.result) == null) ? sr :
5462 >                                        reducer.apply(tr, sr));
5463 >                        s = t.rights = s.nextRight;
5464 >                    }
5465 >                }
5466              }
5467          }
5926        public final U getRawResult() { return result; }
5468      }
5469  
5470      @SuppressWarnings("serial")
# Line 5933 | Line 5474 | public class ConcurrentHashMapV8<K, V>
5474          final DoubleByDoubleToDouble reducer;
5475          final double basis;
5476          double result;
5477 <        MapReduceKeysToDoubleTask<K,V> sibling;
5477 >        MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5478          MapReduceKeysToDoubleTask
5479 <            (ConcurrentHashMapV8<K,V> m,
5479 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5480 >             MapReduceKeysToDoubleTask<K,V> nextRight,
5481               ObjectToDouble<? super K> transformer,
5482               double basis,
5483               DoubleByDoubleToDouble reducer) {
5484 <            super(m);
5484 >            super(p, b, i, f, t); this.nextRight = nextRight;
5485              this.transformer = transformer;
5486              this.basis = basis; this.reducer = reducer;
5487          }
5488 <        MapReduceKeysToDoubleTask
5489 <            (BulkTask<K,V,?> p, int b, boolean split,
5490 <             ObjectToDouble<? super K> transformer,
5491 <             double basis,
5492 <             DoubleByDoubleToDouble reducer) {
5493 <            super(p, b, split);
5494 <            this.transformer = transformer;
5495 <            this.basis = basis; this.reducer = reducer;
5496 <        }
5497 <        @SuppressWarnings("unchecked") public final void compute() {
5498 <            MapReduceKeysToDoubleTask<K,V> t = this;
5499 <            final ObjectToDouble<? super K> transformer =
5500 <                this.transformer;
5501 <            final DoubleByDoubleToDouble reducer = this.reducer;
5502 <            if (transformer == null || reducer == null)
5503 <                throw new Error(NullFunctionMessage);
5504 <            final double id = this.basis;
5505 <            int b = batch();
5506 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5507 <                b >>>= 1;
5508 <                t.pending = 1;
5509 <                MapReduceKeysToDoubleTask<K,V> rt =
5510 <                    new MapReduceKeysToDoubleTask<K,V>
5511 <                    (t, b, true, transformer, id, reducer);
5512 <                t = new MapReduceKeysToDoubleTask<K,V>
5513 <                    (t, b, false, transformer, id, reducer);
5972 <                t.sibling = rt;
5973 <                rt.sibling = t;
5974 <                rt.fork();
5975 <            }
5976 <            double r = id;
5977 <            while (t.advance() != null)
5978 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5979 <            t.result = r;
5980 <            for (;;) {
5981 <                int c; BulkTask<K,V,?> par; MapReduceKeysToDoubleTask<K,V> s, p;
5982 <                if ((par = t.parent) == null ||
5983 <                    !(par instanceof MapReduceKeysToDoubleTask)) {
5984 <                    t.quietlyComplete();
5985 <                    break;
5986 <                }
5987 <                else if ((c = (p = (MapReduceKeysToDoubleTask<K,V>)par).pending) == 0) {
5988 <                    if ((s = t.sibling) != null)
5989 <                        r = reducer.apply(r, s.result);
5990 <                    (t = p).result = r;
5488 >        public final Double getRawResult() { return result; }
5489 >        public final void compute() {
5490 >            final ObjectToDouble<? super K> transformer;
5491 >            final DoubleByDoubleToDouble reducer;
5492 >            if ((transformer = this.transformer) != null &&
5493 >                (reducer = this.reducer) != null) {
5494 >                double r = this.basis;
5495 >                for (int i = baseIndex, f, h; batch > 0 &&
5496 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5497 >                    addToPendingCount(1);
5498 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
5499 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5500 >                      rights, transformer, r, reducer)).fork();
5501 >                }
5502 >                for (Node<K,V> p; (p = advance()) != null; )
5503 >                    r = reducer.apply(r, transformer.apply(p.key));
5504 >                result = r;
5505 >                CountedCompleter<?> c;
5506 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5507 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5508 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5509 >                        s = t.rights;
5510 >                    while (s != null) {
5511 >                        t.result = reducer.apply(t.result, s.result);
5512 >                        s = t.rights = s.nextRight;
5513 >                    }
5514                  }
5992                else if (p.casPending(c, 0))
5993                    break;
5515              }
5516          }
5996        public final Double getRawResult() { return result; }
5517      }
5518  
5519      @SuppressWarnings("serial")
# Line 6003 | Line 5523 | public class ConcurrentHashMapV8<K, V>
5523          final DoubleByDoubleToDouble reducer;
5524          final double basis;
5525          double result;
5526 <        MapReduceValuesToDoubleTask<K,V> sibling;
5526 >        MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5527          MapReduceValuesToDoubleTask
5528 <            (ConcurrentHashMapV8<K,V> m,
5528 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5529 >             MapReduceValuesToDoubleTask<K,V> nextRight,
5530               ObjectToDouble<? super V> transformer,
5531               double basis,
5532               DoubleByDoubleToDouble reducer) {
5533 <            super(m);
5533 >            super(p, b, i, f, t); this.nextRight = nextRight;
5534              this.transformer = transformer;
5535              this.basis = basis; this.reducer = reducer;
5536          }
5537 <        MapReduceValuesToDoubleTask
5538 <            (BulkTask<K,V,?> p, int b, boolean split,
5539 <             ObjectToDouble<? super V> transformer,
5540 <             double basis,
5541 <             DoubleByDoubleToDouble reducer) {
5542 <            super(p, b, split);
5543 <            this.transformer = transformer;
5544 <            this.basis = basis; this.reducer = reducer;
5545 <        }
5546 <        @SuppressWarnings("unchecked") public final void compute() {
5547 <            MapReduceValuesToDoubleTask<K,V> t = this;
5548 <            final ObjectToDouble<? super V> transformer =
5549 <                this.transformer;
5550 <            final DoubleByDoubleToDouble reducer = this.reducer;
5551 <            if (transformer == null || reducer == null)
5552 <                throw new Error(NullFunctionMessage);
5553 <            final double id = this.basis;
5554 <            int b = batch();
5555 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5556 <                b >>>= 1;
5557 <                t.pending = 1;
5558 <                MapReduceValuesToDoubleTask<K,V> rt =
5559 <                    new MapReduceValuesToDoubleTask<K,V>
5560 <                    (t, b, true, transformer, id, reducer);
5561 <                t = new MapReduceValuesToDoubleTask<K,V>
5562 <                    (t, b, false, transformer, id, reducer);
6042 <                t.sibling = rt;
6043 <                rt.sibling = t;
6044 <                rt.fork();
6045 <            }
6046 <            double r = id;
6047 <            Object v;
6048 <            while ((v = t.advance()) != null)
6049 <                r = reducer.apply(r, transformer.apply((V)v));
6050 <            t.result = r;
6051 <            for (;;) {
6052 <                int c; BulkTask<K,V,?> par; MapReduceValuesToDoubleTask<K,V> s, p;
6053 <                if ((par = t.parent) == null ||
6054 <                    !(par instanceof MapReduceValuesToDoubleTask)) {
6055 <                    t.quietlyComplete();
6056 <                    break;
6057 <                }
6058 <                else if ((c = (p = (MapReduceValuesToDoubleTask<K,V>)par).pending) == 0) {
6059 <                    if ((s = t.sibling) != null)
6060 <                        r = reducer.apply(r, s.result);
6061 <                    (t = p).result = r;
5537 >        public final Double getRawResult() { return result; }
5538 >        public final void compute() {
5539 >            final ObjectToDouble<? super V> transformer;
5540 >            final DoubleByDoubleToDouble reducer;
5541 >            if ((transformer = this.transformer) != null &&
5542 >                (reducer = this.reducer) != null) {
5543 >                double r = this.basis;
5544 >                for (int i = baseIndex, f, h; batch > 0 &&
5545 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5546 >                    addToPendingCount(1);
5547 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
5548 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5549 >                      rights, transformer, r, reducer)).fork();
5550 >                }
5551 >                for (Node<K,V> p; (p = advance()) != null; )
5552 >                    r = reducer.apply(r, transformer.apply(p.val));
5553 >                result = r;
5554 >                CountedCompleter<?> c;
5555 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5556 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5557 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5558 >                        s = t.rights;
5559 >                    while (s != null) {
5560 >                        t.result = reducer.apply(t.result, s.result);
5561 >                        s = t.rights = s.nextRight;
5562 >                    }
5563                  }
6063                else if (p.casPending(c, 0))
6064                    break;
5564              }
5565          }
6067        public final Double getRawResult() { return result; }
5566      }
5567  
5568      @SuppressWarnings("serial")
# Line 6074 | Line 5572 | public class ConcurrentHashMapV8<K, V>
5572          final DoubleByDoubleToDouble reducer;
5573          final double basis;
5574          double result;
5575 <        MapReduceEntriesToDoubleTask<K,V> sibling;
6078 <        MapReduceEntriesToDoubleTask
6079 <            (ConcurrentHashMapV8<K,V> m,
6080 <             ObjectToDouble<Map.Entry<K,V>> transformer,
6081 <             double basis,
6082 <             DoubleByDoubleToDouble reducer) {
6083 <            super(m);
6084 <            this.transformer = transformer;
6085 <            this.basis = basis; this.reducer = reducer;
6086 <        }
5575 >        MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5576          MapReduceEntriesToDoubleTask
5577 <            (BulkTask<K,V,?> p, int b, boolean split,
5577 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5578 >             MapReduceEntriesToDoubleTask<K,V> nextRight,
5579               ObjectToDouble<Map.Entry<K,V>> transformer,
5580               double basis,
5581               DoubleByDoubleToDouble reducer) {
5582 <            super(p, b, split);
5582 >            super(p, b, i, f, t); this.nextRight = nextRight;
5583              this.transformer = transformer;
5584              this.basis = basis; this.reducer = reducer;
5585          }
5586 <        @SuppressWarnings("unchecked") public final void compute() {
5587 <            MapReduceEntriesToDoubleTask<K,V> t = this;
5588 <            final ObjectToDouble<Map.Entry<K,V>> transformer =
5589 <                this.transformer;
5590 <            final DoubleByDoubleToDouble reducer = this.reducer;
5591 <            if (transformer == null || reducer == null)
5592 <                throw new Error(NullFunctionMessage);
5593 <            final double id = this.basis;
5594 <            int b = batch();
5595 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5596 <                b >>>= 1;
5597 <                t.pending = 1;
5598 <                MapReduceEntriesToDoubleTask<K,V> rt =
5599 <                    new MapReduceEntriesToDoubleTask<K,V>
5600 <                    (t, b, true, transformer, id, reducer);
5601 <                t = new MapReduceEntriesToDoubleTask<K,V>
5602 <                    (t, b, false, transformer, id, reducer);
5603 <                t.sibling = rt;
5604 <                rt.sibling = t;
5605 <                rt.fork();
5606 <            }
5607 <            double r = id;
5608 <            Object v;
5609 <            while ((v = t.advance()) != null)
5610 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
5611 <            t.result = r;
6122 <            for (;;) {
6123 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToDoubleTask<K,V> s, p;
6124 <                if ((par = t.parent) == null ||
6125 <                    !(par instanceof MapReduceEntriesToDoubleTask)) {
6126 <                    t.quietlyComplete();
6127 <                    break;
6128 <                }
6129 <                else if ((c = (p = (MapReduceEntriesToDoubleTask<K,V>)par).pending) == 0) {
6130 <                    if ((s = t.sibling) != null)
6131 <                        r = reducer.apply(r, s.result);
6132 <                    (t = p).result = r;
5586 >        public final Double getRawResult() { return result; }
5587 >        public final void compute() {
5588 >            final ObjectToDouble<Map.Entry<K,V>> transformer;
5589 >            final DoubleByDoubleToDouble reducer;
5590 >            if ((transformer = this.transformer) != null &&
5591 >                (reducer = this.reducer) != null) {
5592 >                double r = this.basis;
5593 >                for (int i = baseIndex, f, h; batch > 0 &&
5594 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5595 >                    addToPendingCount(1);
5596 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
5597 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5598 >                      rights, transformer, r, reducer)).fork();
5599 >                }
5600 >                for (Node<K,V> p; (p = advance()) != null; )
5601 >                    r = reducer.apply(r, transformer.apply(p));
5602 >                result = r;
5603 >                CountedCompleter<?> c;
5604 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5605 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5606 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5607 >                        s = t.rights;
5608 >                    while (s != null) {
5609 >                        t.result = reducer.apply(t.result, s.result);
5610 >                        s = t.rights = s.nextRight;
5611 >                    }
5612                  }
6134                else if (p.casPending(c, 0))
6135                    break;
5613              }
5614          }
6138        public final Double getRawResult() { return result; }
5615      }
5616  
5617      @SuppressWarnings("serial")
# Line 6145 | Line 5621 | public class ConcurrentHashMapV8<K, V>
5621          final DoubleByDoubleToDouble reducer;
5622          final double basis;
5623          double result;
5624 <        MapReduceMappingsToDoubleTask<K,V> sibling;
6149 <        MapReduceMappingsToDoubleTask
6150 <            (ConcurrentHashMapV8<K,V> m,
6151 <             ObjectByObjectToDouble<? super K, ? super V> transformer,
6152 <             double basis,
6153 <             DoubleByDoubleToDouble reducer) {
6154 <            super(m);
6155 <            this.transformer = transformer;
6156 <            this.basis = basis; this.reducer = reducer;
6157 <        }
5624 >        MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5625          MapReduceMappingsToDoubleTask
5626 <            (BulkTask<K,V,?> p, int b, boolean split,
5626 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5627 >             MapReduceMappingsToDoubleTask<K,V> nextRight,
5628               ObjectByObjectToDouble<? super K, ? super V> transformer,
5629               double basis,
5630               DoubleByDoubleToDouble reducer) {
5631 <            super(p, b, split);
5631 >            super(p, b, i, f, t); this.nextRight = nextRight;
5632              this.transformer = transformer;
5633              this.basis = basis; this.reducer = reducer;
5634          }
5635 <        @SuppressWarnings("unchecked") public final void compute() {
5636 <            MapReduceMappingsToDoubleTask<K,V> t = this;
5637 <            final ObjectByObjectToDouble<? super K, ? super V> transformer =
5638 <                this.transformer;
5639 <            final DoubleByDoubleToDouble reducer = this.reducer;
5640 <            if (transformer == null || reducer == null)
5641 <                throw new Error(NullFunctionMessage);
5642 <            final double id = this.basis;
5643 <            int b = batch();
5644 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5645 <                b >>>= 1;
5646 <                t.pending = 1;
5647 <                MapReduceMappingsToDoubleTask<K,V> rt =
5648 <                    new MapReduceMappingsToDoubleTask<K,V>
5649 <                    (t, b, true, transformer, id, reducer);
5650 <                t = new MapReduceMappingsToDoubleTask<K,V>
5651 <                    (t, b, false, transformer, id, reducer);
5652 <                t.sibling = rt;
5653 <                rt.sibling = t;
5654 <                rt.fork();
5655 <            }
5656 <            double r = id;
5657 <            Object v;
5658 <            while ((v = t.advance()) != null)
5659 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
5660 <            t.result = r;
6193 <            for (;;) {
6194 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToDoubleTask<K,V> s, p;
6195 <                if ((par = t.parent) == null ||
6196 <                    !(par instanceof MapReduceMappingsToDoubleTask)) {
6197 <                    t.quietlyComplete();
6198 <                    break;
6199 <                }
6200 <                else if ((c = (p = (MapReduceMappingsToDoubleTask<K,V>)par).pending) == 0) {
6201 <                    if ((s = t.sibling) != null)
6202 <                        r = reducer.apply(r, s.result);
6203 <                    (t = p).result = r;
5635 >        public final Double getRawResult() { return result; }
5636 >        public final void compute() {
5637 >            final ObjectByObjectToDouble<? super K, ? super V> transformer;
5638 >            final DoubleByDoubleToDouble reducer;
5639 >            if ((transformer = this.transformer) != null &&
5640 >                (reducer = this.reducer) != null) {
5641 >                double r = this.basis;
5642 >                for (int i = baseIndex, f, h; batch > 0 &&
5643 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5644 >                    addToPendingCount(1);
5645 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
5646 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5647 >                      rights, transformer, r, reducer)).fork();
5648 >                }
5649 >                for (Node<K,V> p; (p = advance()) != null; )
5650 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5651 >                result = r;
5652 >                CountedCompleter<?> c;
5653 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5654 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5655 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5656 >                        s = t.rights;
5657 >                    while (s != null) {
5658 >                        t.result = reducer.apply(t.result, s.result);
5659 >                        s = t.rights = s.nextRight;
5660 >                    }
5661                  }
6205                else if (p.casPending(c, 0))
6206                    break;
5662              }
5663          }
6209        public final Double getRawResult() { return result; }
5664      }
5665  
5666      @SuppressWarnings("serial")
# Line 6216 | Line 5670 | public class ConcurrentHashMapV8<K, V>
5670          final LongByLongToLong reducer;
5671          final long basis;
5672          long result;
5673 <        MapReduceKeysToLongTask<K,V> sibling;
5673 >        MapReduceKeysToLongTask<K,V> rights, nextRight;
5674          MapReduceKeysToLongTask
5675 <            (ConcurrentHashMapV8<K,V> m,
5675 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5676 >             MapReduceKeysToLongTask<K,V> nextRight,
5677               ObjectToLong<? super K> transformer,
5678               long basis,
5679               LongByLongToLong reducer) {
5680 <            super(m);
5680 >            super(p, b, i, f, t); this.nextRight = nextRight;
5681              this.transformer = transformer;
5682              this.basis = basis; this.reducer = reducer;
5683          }
5684 <        MapReduceKeysToLongTask
5685 <            (BulkTask<K,V,?> p, int b, boolean split,
5686 <             ObjectToLong<? super K> transformer,
5687 <             long basis,
5688 <             LongByLongToLong reducer) {
5689 <            super(p, b, split);
5690 <            this.transformer = transformer;
5691 <            this.basis = basis; this.reducer = reducer;
5692 <        }
5693 <        @SuppressWarnings("unchecked") public final void compute() {
5694 <            MapReduceKeysToLongTask<K,V> t = this;
5695 <            final ObjectToLong<? super K> transformer =
5696 <                this.transformer;
5697 <            final LongByLongToLong reducer = this.reducer;
5698 <            if (transformer == null || reducer == null)
5699 <                throw new Error(NullFunctionMessage);
5700 <            final long id = this.basis;
5701 <            int b = batch();
5702 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5703 <                b >>>= 1;
5704 <                t.pending = 1;
5705 <                MapReduceKeysToLongTask<K,V> rt =
5706 <                    new MapReduceKeysToLongTask<K,V>
5707 <                    (t, b, true, transformer, id, reducer);
5708 <                t = new MapReduceKeysToLongTask<K,V>
5709 <                    (t, b, false, transformer, id, reducer);
6255 <                t.sibling = rt;
6256 <                rt.sibling = t;
6257 <                rt.fork();
6258 <            }
6259 <            long r = id;
6260 <            while (t.advance() != null)
6261 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
6262 <            t.result = r;
6263 <            for (;;) {
6264 <                int c; BulkTask<K,V,?> par; MapReduceKeysToLongTask<K,V> s, p;
6265 <                if ((par = t.parent) == null ||
6266 <                    !(par instanceof MapReduceKeysToLongTask)) {
6267 <                    t.quietlyComplete();
6268 <                    break;
6269 <                }
6270 <                else if ((c = (p = (MapReduceKeysToLongTask<K,V>)par).pending) == 0) {
6271 <                    if ((s = t.sibling) != null)
6272 <                        r = reducer.apply(r, s.result);
6273 <                    (t = p).result = r;
5684 >        public final Long getRawResult() { return result; }
5685 >        public final void compute() {
5686 >            final ObjectToLong<? super K> transformer;
5687 >            final LongByLongToLong reducer;
5688 >            if ((transformer = this.transformer) != null &&
5689 >                (reducer = this.reducer) != null) {
5690 >                long r = this.basis;
5691 >                for (int i = baseIndex, f, h; batch > 0 &&
5692 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5693 >                    addToPendingCount(1);
5694 >                    (rights = new MapReduceKeysToLongTask<K,V>
5695 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5696 >                      rights, transformer, r, reducer)).fork();
5697 >                }
5698 >                for (Node<K,V> p; (p = advance()) != null; )
5699 >                    r = reducer.apply(r, transformer.apply(p.key));
5700 >                result = r;
5701 >                CountedCompleter<?> c;
5702 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5703 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5704 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5705 >                        s = t.rights;
5706 >                    while (s != null) {
5707 >                        t.result = reducer.apply(t.result, s.result);
5708 >                        s = t.rights = s.nextRight;
5709 >                    }
5710                  }
6275                else if (p.casPending(c, 0))
6276                    break;
5711              }
5712          }
6279        public final Long getRawResult() { return result; }
5713      }
5714  
5715      @SuppressWarnings("serial")
# Line 6286 | Line 5719 | public class ConcurrentHashMapV8<K, V>
5719          final LongByLongToLong reducer;
5720          final long basis;
5721          long result;
5722 <        MapReduceValuesToLongTask<K,V> sibling;
6290 <        MapReduceValuesToLongTask
6291 <            (ConcurrentHashMapV8<K,V> m,
6292 <             ObjectToLong<? super V> transformer,
6293 <             long basis,
6294 <             LongByLongToLong reducer) {
6295 <            super(m);
6296 <            this.transformer = transformer;
6297 <            this.basis = basis; this.reducer = reducer;
6298 <        }
5722 >        MapReduceValuesToLongTask<K,V> rights, nextRight;
5723          MapReduceValuesToLongTask
5724 <            (BulkTask<K,V,?> p, int b, boolean split,
5724 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5725 >             MapReduceValuesToLongTask<K,V> nextRight,
5726               ObjectToLong<? super V> transformer,
5727               long basis,
5728               LongByLongToLong reducer) {
5729 <            super(p, b, split);
5729 >            super(p, b, i, f, t); this.nextRight = nextRight;
5730              this.transformer = transformer;
5731              this.basis = basis; this.reducer = reducer;
5732          }
5733 <        @SuppressWarnings("unchecked") public final void compute() {
5734 <            MapReduceValuesToLongTask<K,V> t = this;
5735 <            final ObjectToLong<? super V> transformer =
5736 <                this.transformer;
5737 <            final LongByLongToLong reducer = this.reducer;
5738 <            if (transformer == null || reducer == null)
5739 <                throw new Error(NullFunctionMessage);
5740 <            final long id = this.basis;
5741 <            int b = batch();
5742 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5743 <                b >>>= 1;
5744 <                t.pending = 1;
5745 <                MapReduceValuesToLongTask<K,V> rt =
5746 <                    new MapReduceValuesToLongTask<K,V>
5747 <                    (t, b, true, transformer, id, reducer);
5748 <                t = new MapReduceValuesToLongTask<K,V>
5749 <                    (t, b, false, transformer, id, reducer);
5750 <                t.sibling = rt;
5751 <                rt.sibling = t;
5752 <                rt.fork();
5753 <            }
5754 <            long r = id;
5755 <            Object v;
5756 <            while ((v = t.advance()) != null)
5757 <                r = reducer.apply(r, transformer.apply((V)v));
5758 <            t.result = r;
6334 <            for (;;) {
6335 <                int c; BulkTask<K,V,?> par; MapReduceValuesToLongTask<K,V> s, p;
6336 <                if ((par = t.parent) == null ||
6337 <                    !(par instanceof MapReduceValuesToLongTask)) {
6338 <                    t.quietlyComplete();
6339 <                    break;
6340 <                }
6341 <                else if ((c = (p = (MapReduceValuesToLongTask<K,V>)par).pending) == 0) {
6342 <                    if ((s = t.sibling) != null)
6343 <                        r = reducer.apply(r, s.result);
6344 <                    (t = p).result = r;
5733 >        public final Long getRawResult() { return result; }
5734 >        public final void compute() {
5735 >            final ObjectToLong<? super V> transformer;
5736 >            final LongByLongToLong reducer;
5737 >            if ((transformer = this.transformer) != null &&
5738 >                (reducer = this.reducer) != null) {
5739 >                long r = this.basis;
5740 >                for (int i = baseIndex, f, h; batch > 0 &&
5741 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5742 >                    addToPendingCount(1);
5743 >                    (rights = new MapReduceValuesToLongTask<K,V>
5744 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5745 >                      rights, transformer, r, reducer)).fork();
5746 >                }
5747 >                for (Node<K,V> p; (p = advance()) != null; )
5748 >                    r = reducer.apply(r, transformer.apply(p.val));
5749 >                result = r;
5750 >                CountedCompleter<?> c;
5751 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5752 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5753 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5754 >                        s = t.rights;
5755 >                    while (s != null) {
5756 >                        t.result = reducer.apply(t.result, s.result);
5757 >                        s = t.rights = s.nextRight;
5758 >                    }
5759                  }
6346                else if (p.casPending(c, 0))
6347                    break;
5760              }
5761          }
6350        public final Long getRawResult() { return result; }
5762      }
5763  
5764      @SuppressWarnings("serial")
# Line 6357 | Line 5768 | public class ConcurrentHashMapV8<K, V>
5768          final LongByLongToLong reducer;
5769          final long basis;
5770          long result;
5771 <        MapReduceEntriesToLongTask<K,V> sibling;
5771 >        MapReduceEntriesToLongTask<K,V> rights, nextRight;
5772          MapReduceEntriesToLongTask
5773 <            (ConcurrentHashMapV8<K,V> m,
5773 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5774 >             MapReduceEntriesToLongTask<K,V> nextRight,
5775               ObjectToLong<Map.Entry<K,V>> transformer,
5776               long basis,
5777               LongByLongToLong reducer) {
5778 <            super(m);
5778 >            super(p, b, i, f, t); this.nextRight = nextRight;
5779              this.transformer = transformer;
5780              this.basis = basis; this.reducer = reducer;
5781          }
5782 <        MapReduceEntriesToLongTask
5783 <            (BulkTask<K,V,?> p, int b, boolean split,
5784 <             ObjectToLong<Map.Entry<K,V>> transformer,
5785 <             long basis,
5786 <             LongByLongToLong reducer) {
5787 <            super(p, b, split);
5788 <            this.transformer = transformer;
5789 <            this.basis = basis; this.reducer = reducer;
5790 <        }
5791 <        @SuppressWarnings("unchecked") public final void compute() {
5792 <            MapReduceEntriesToLongTask<K,V> t = this;
5793 <            final ObjectToLong<Map.Entry<K,V>> transformer =
5794 <                this.transformer;
5795 <            final LongByLongToLong reducer = this.reducer;
5796 <            if (transformer == null || reducer == null)
5797 <                throw new Error(NullFunctionMessage);
5798 <            final long id = this.basis;
5799 <            int b = batch();
5800 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5801 <                b >>>= 1;
5802 <                t.pending = 1;
5803 <                MapReduceEntriesToLongTask<K,V> rt =
5804 <                    new MapReduceEntriesToLongTask<K,V>
5805 <                    (t, b, true, transformer, id, reducer);
5806 <                t = new MapReduceEntriesToLongTask<K,V>
5807 <                    (t, b, false, transformer, id, reducer);
6396 <                t.sibling = rt;
6397 <                rt.sibling = t;
6398 <                rt.fork();
6399 <            }
6400 <            long r = id;
6401 <            Object v;
6402 <            while ((v = t.advance()) != null)
6403 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6404 <            t.result = r;
6405 <            for (;;) {
6406 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToLongTask<K,V> s, p;
6407 <                if ((par = t.parent) == null ||
6408 <                    !(par instanceof MapReduceEntriesToLongTask)) {
6409 <                    t.quietlyComplete();
6410 <                    break;
6411 <                }
6412 <                else if ((c = (p = (MapReduceEntriesToLongTask<K,V>)par).pending) == 0) {
6413 <                    if ((s = t.sibling) != null)
6414 <                        r = reducer.apply(r, s.result);
6415 <                    (t = p).result = r;
5782 >        public final Long getRawResult() { return result; }
5783 >        public final void compute() {
5784 >            final ObjectToLong<Map.Entry<K,V>> transformer;
5785 >            final LongByLongToLong reducer;
5786 >            if ((transformer = this.transformer) != null &&
5787 >                (reducer = this.reducer) != null) {
5788 >                long r = this.basis;
5789 >                for (int i = baseIndex, f, h; batch > 0 &&
5790 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5791 >                    addToPendingCount(1);
5792 >                    (rights = new MapReduceEntriesToLongTask<K,V>
5793 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5794 >                      rights, transformer, r, reducer)).fork();
5795 >                }
5796 >                for (Node<K,V> p; (p = advance()) != null; )
5797 >                    r = reducer.apply(r, transformer.apply(p));
5798 >                result = r;
5799 >                CountedCompleter<?> c;
5800 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5801 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5802 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5803 >                        s = t.rights;
5804 >                    while (s != null) {
5805 >                        t.result = reducer.apply(t.result, s.result);
5806 >                        s = t.rights = s.nextRight;
5807 >                    }
5808                  }
6417                else if (p.casPending(c, 0))
6418                    break;
5809              }
5810          }
6421        public final Long getRawResult() { return result; }
5811      }
5812  
5813      @SuppressWarnings("serial")
# Line 6428 | Line 5817 | public class ConcurrentHashMapV8<K, V>
5817          final LongByLongToLong reducer;
5818          final long basis;
5819          long result;
5820 <        MapReduceMappingsToLongTask<K,V> sibling;
6432 <        MapReduceMappingsToLongTask
6433 <            (ConcurrentHashMapV8<K,V> m,
6434 <             ObjectByObjectToLong<? super K, ? super V> transformer,
6435 <             long basis,
6436 <             LongByLongToLong reducer) {
6437 <            super(m);
6438 <            this.transformer = transformer;
6439 <            this.basis = basis; this.reducer = reducer;
6440 <        }
5820 >        MapReduceMappingsToLongTask<K,V> rights, nextRight;
5821          MapReduceMappingsToLongTask
5822 <            (BulkTask<K,V,?> p, int b, boolean split,
5822 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5823 >             MapReduceMappingsToLongTask<K,V> nextRight,
5824               ObjectByObjectToLong<? super K, ? super V> transformer,
5825               long basis,
5826               LongByLongToLong reducer) {
5827 <            super(p, b, split);
5827 >            super(p, b, i, f, t); this.nextRight = nextRight;
5828              this.transformer = transformer;
5829              this.basis = basis; this.reducer = reducer;
5830          }
5831 <        @SuppressWarnings("unchecked") public final void compute() {
5832 <            MapReduceMappingsToLongTask<K,V> t = this;
5833 <            final ObjectByObjectToLong<? super K, ? super V> transformer =
5834 <                this.transformer;
5835 <            final LongByLongToLong reducer = this.reducer;
5836 <            if (transformer == null || reducer == null)
5837 <                throw new Error(NullFunctionMessage);
5838 <            final long id = this.basis;
5839 <            int b = batch();
5840 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5841 <                b >>>= 1;
5842 <                t.pending = 1;
5843 <                MapReduceMappingsToLongTask<K,V> rt =
5844 <                    new MapReduceMappingsToLongTask<K,V>
5845 <                    (t, b, true, transformer, id, reducer);
5846 <                t = new MapReduceMappingsToLongTask<K,V>
5847 <                    (t, b, false, transformer, id, reducer);
5848 <                t.sibling = rt;
5849 <                rt.sibling = t;
5850 <                rt.fork();
5851 <            }
5852 <            long r = id;
5853 <            Object v;
5854 <            while ((v = t.advance()) != null)
5855 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
5856 <            t.result = r;
6476 <            for (;;) {
6477 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToLongTask<K,V> s, p;
6478 <                if ((par = t.parent) == null ||
6479 <                    !(par instanceof MapReduceMappingsToLongTask)) {
6480 <                    t.quietlyComplete();
6481 <                    break;
6482 <                }
6483 <                else if ((c = (p = (MapReduceMappingsToLongTask<K,V>)par).pending) == 0) {
6484 <                    if ((s = t.sibling) != null)
6485 <                        r = reducer.apply(r, s.result);
6486 <                    (t = p).result = r;
5831 >        public final Long getRawResult() { return result; }
5832 >        public final void compute() {
5833 >            final ObjectByObjectToLong<? super K, ? super V> transformer;
5834 >            final LongByLongToLong reducer;
5835 >            if ((transformer = this.transformer) != null &&
5836 >                (reducer = this.reducer) != null) {
5837 >                long r = this.basis;
5838 >                for (int i = baseIndex, f, h; batch > 0 &&
5839 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5840 >                    addToPendingCount(1);
5841 >                    (rights = new MapReduceMappingsToLongTask<K,V>
5842 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5843 >                      rights, transformer, r, reducer)).fork();
5844 >                }
5845 >                for (Node<K,V> p; (p = advance()) != null; )
5846 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
5847 >                result = r;
5848 >                CountedCompleter<?> c;
5849 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5850 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5851 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5852 >                        s = t.rights;
5853 >                    while (s != null) {
5854 >                        t.result = reducer.apply(t.result, s.result);
5855 >                        s = t.rights = s.nextRight;
5856 >                    }
5857                  }
6488                else if (p.casPending(c, 0))
6489                    break;
5858              }
5859          }
6492        public final Long getRawResult() { return result; }
5860      }
5861  
5862      @SuppressWarnings("serial")
# Line 6499 | Line 5866 | public class ConcurrentHashMapV8<K, V>
5866          final IntByIntToInt reducer;
5867          final int basis;
5868          int result;
5869 <        MapReduceKeysToIntTask<K,V> sibling;
6503 <        MapReduceKeysToIntTask
6504 <            (ConcurrentHashMapV8<K,V> m,
6505 <             ObjectToInt<? super K> transformer,
6506 <             int basis,
6507 <             IntByIntToInt reducer) {
6508 <            super(m);
6509 <            this.transformer = transformer;
6510 <            this.basis = basis; this.reducer = reducer;
6511 <        }
5869 >        MapReduceKeysToIntTask<K,V> rights, nextRight;
5870          MapReduceKeysToIntTask
5871 <            (BulkTask<K,V,?> p, int b, boolean split,
5871 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5872 >             MapReduceKeysToIntTask<K,V> nextRight,
5873               ObjectToInt<? super K> transformer,
5874               int basis,
5875               IntByIntToInt reducer) {
5876 <            super(p, b, split);
5876 >            super(p, b, i, f, t); this.nextRight = nextRight;
5877              this.transformer = transformer;
5878              this.basis = basis; this.reducer = reducer;
5879          }
5880 <        @SuppressWarnings("unchecked") public final void compute() {
5881 <            MapReduceKeysToIntTask<K,V> t = this;
5882 <            final ObjectToInt<? super K> transformer =
5883 <                this.transformer;
5884 <            final IntByIntToInt reducer = this.reducer;
5885 <            if (transformer == null || reducer == null)
5886 <                throw new Error(NullFunctionMessage);
5887 <            final int id = this.basis;
5888 <            int b = batch();
5889 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5890 <                b >>>= 1;
5891 <                t.pending = 1;
5892 <                MapReduceKeysToIntTask<K,V> rt =
5893 <                    new MapReduceKeysToIntTask<K,V>
5894 <                    (t, b, true, transformer, id, reducer);
5895 <                t = new MapReduceKeysToIntTask<K,V>
5896 <                    (t, b, false, transformer, id, reducer);
5897 <                t.sibling = rt;
5898 <                rt.sibling = t;
5899 <                rt.fork();
5900 <            }
5901 <            int r = id;
5902 <            while (t.advance() != null)
5903 <                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5904 <            t.result = r;
5905 <            for (;;) {
6547 <                int c; BulkTask<K,V,?> par; MapReduceKeysToIntTask<K,V> s, p;
6548 <                if ((par = t.parent) == null ||
6549 <                    !(par instanceof MapReduceKeysToIntTask)) {
6550 <                    t.quietlyComplete();
6551 <                    break;
6552 <                }
6553 <                else if ((c = (p = (MapReduceKeysToIntTask<K,V>)par).pending) == 0) {
6554 <                    if ((s = t.sibling) != null)
6555 <                        r = reducer.apply(r, s.result);
6556 <                    (t = p).result = r;
5880 >        public final Integer getRawResult() { return result; }
5881 >        public final void compute() {
5882 >            final ObjectToInt<? super K> transformer;
5883 >            final IntByIntToInt reducer;
5884 >            if ((transformer = this.transformer) != null &&
5885 >                (reducer = this.reducer) != null) {
5886 >                int r = this.basis;
5887 >                for (int i = baseIndex, f, h; batch > 0 &&
5888 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5889 >                    addToPendingCount(1);
5890 >                    (rights = new MapReduceKeysToIntTask<K,V>
5891 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5892 >                      rights, transformer, r, reducer)).fork();
5893 >                }
5894 >                for (Node<K,V> p; (p = advance()) != null; )
5895 >                    r = reducer.apply(r, transformer.apply(p.key));
5896 >                result = r;
5897 >                CountedCompleter<?> c;
5898 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5899 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5900 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5901 >                        s = t.rights;
5902 >                    while (s != null) {
5903 >                        t.result = reducer.apply(t.result, s.result);
5904 >                        s = t.rights = s.nextRight;
5905 >                    }
5906                  }
6558                else if (p.casPending(c, 0))
6559                    break;
5907              }
5908          }
6562        public final Integer getRawResult() { return result; }
5909      }
5910  
5911      @SuppressWarnings("serial")
# Line 6569 | Line 5915 | public class ConcurrentHashMapV8<K, V>
5915          final IntByIntToInt reducer;
5916          final int basis;
5917          int result;
5918 <        MapReduceValuesToIntTask<K,V> sibling;
6573 <        MapReduceValuesToIntTask
6574 <            (ConcurrentHashMapV8<K,V> m,
6575 <             ObjectToInt<? super V> transformer,
6576 <             int basis,
6577 <             IntByIntToInt reducer) {
6578 <            super(m);
6579 <            this.transformer = transformer;
6580 <            this.basis = basis; this.reducer = reducer;
6581 <        }
5918 >        MapReduceValuesToIntTask<K,V> rights, nextRight;
5919          MapReduceValuesToIntTask
5920 <            (BulkTask<K,V,?> p, int b, boolean split,
5920 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5921 >             MapReduceValuesToIntTask<K,V> nextRight,
5922               ObjectToInt<? super V> transformer,
5923               int basis,
5924               IntByIntToInt reducer) {
5925 <            super(p, b, split);
5925 >            super(p, b, i, f, t); this.nextRight = nextRight;
5926              this.transformer = transformer;
5927              this.basis = basis; this.reducer = reducer;
5928          }
5929 <        @SuppressWarnings("unchecked") public final void compute() {
5930 <            MapReduceValuesToIntTask<K,V> t = this;
5931 <            final ObjectToInt<? super V> transformer =
5932 <                this.transformer;
5933 <            final IntByIntToInt reducer = this.reducer;
5934 <            if (transformer == null || reducer == null)
5935 <                throw new Error(NullFunctionMessage);
5936 <            final int id = this.basis;
5937 <            int b = batch();
5938 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5939 <                b >>>= 1;
5940 <                t.pending = 1;
5941 <                MapReduceValuesToIntTask<K,V> rt =
5942 <                    new MapReduceValuesToIntTask<K,V>
5943 <                    (t, b, true, transformer, id, reducer);
5944 <                t = new MapReduceValuesToIntTask<K,V>
5945 <                    (t, b, false, transformer, id, reducer);
5946 <                t.sibling = rt;
5947 <                rt.sibling = t;
5948 <                rt.fork();
5949 <            }
5950 <            int r = id;
5951 <            Object v;
5952 <            while ((v = t.advance()) != null)
5953 <                r = reducer.apply(r, transformer.apply((V)v));
5954 <            t.result = r;
6617 <            for (;;) {
6618 <                int c; BulkTask<K,V,?> par; MapReduceValuesToIntTask<K,V> s, p;
6619 <                if ((par = t.parent) == null ||
6620 <                    !(par instanceof MapReduceValuesToIntTask)) {
6621 <                    t.quietlyComplete();
6622 <                    break;
6623 <                }
6624 <                else if ((c = (p = (MapReduceValuesToIntTask<K,V>)par).pending) == 0) {
6625 <                    if ((s = t.sibling) != null)
6626 <                        r = reducer.apply(r, s.result);
6627 <                    (t = p).result = r;
5929 >        public final Integer getRawResult() { return result; }
5930 >        public final void compute() {
5931 >            final ObjectToInt<? super V> transformer;
5932 >            final IntByIntToInt reducer;
5933 >            if ((transformer = this.transformer) != null &&
5934 >                (reducer = this.reducer) != null) {
5935 >                int r = this.basis;
5936 >                for (int i = baseIndex, f, h; batch > 0 &&
5937 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5938 >                    addToPendingCount(1);
5939 >                    (rights = new MapReduceValuesToIntTask<K,V>
5940 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5941 >                      rights, transformer, r, reducer)).fork();
5942 >                }
5943 >                for (Node<K,V> p; (p = advance()) != null; )
5944 >                    r = reducer.apply(r, transformer.apply(p.val));
5945 >                result = r;
5946 >                CountedCompleter<?> c;
5947 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5948 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5949 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5950 >                        s = t.rights;
5951 >                    while (s != null) {
5952 >                        t.result = reducer.apply(t.result, s.result);
5953 >                        s = t.rights = s.nextRight;
5954 >                    }
5955                  }
6629                else if (p.casPending(c, 0))
6630                    break;
5956              }
5957          }
6633        public final Integer getRawResult() { return result; }
5958      }
5959  
5960      @SuppressWarnings("serial")
# Line 6640 | Line 5964 | public class ConcurrentHashMapV8<K, V>
5964          final IntByIntToInt reducer;
5965          final int basis;
5966          int result;
5967 <        MapReduceEntriesToIntTask<K,V> sibling;
5967 >        MapReduceEntriesToIntTask<K,V> rights, nextRight;
5968          MapReduceEntriesToIntTask
5969 <            (ConcurrentHashMapV8<K,V> m,
5969 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5970 >             MapReduceEntriesToIntTask<K,V> nextRight,
5971               ObjectToInt<Map.Entry<K,V>> transformer,
5972               int basis,
5973               IntByIntToInt reducer) {
5974 <            super(m);
5974 >            super(p, b, i, f, t); this.nextRight = nextRight;
5975              this.transformer = transformer;
5976              this.basis = basis; this.reducer = reducer;
5977          }
5978 <        MapReduceEntriesToIntTask
5979 <            (BulkTask<K,V,?> p, int b, boolean split,
5980 <             ObjectToInt<Map.Entry<K,V>> transformer,
5981 <             int basis,
5982 <             IntByIntToInt reducer) {
5983 <            super(p, b, split);
5984 <            this.transformer = transformer;
5985 <            this.basis = basis; this.reducer = reducer;
5986 <        }
5987 <        @SuppressWarnings("unchecked") public final void compute() {
5988 <            MapReduceEntriesToIntTask<K,V> t = this;
5989 <            final ObjectToInt<Map.Entry<K,V>> transformer =
5990 <                this.transformer;
5991 <            final IntByIntToInt reducer = this.reducer;
5992 <            if (transformer == null || reducer == null)
5993 <                throw new Error(NullFunctionMessage);
5994 <            final int id = this.basis;
5995 <            int b = batch();
5996 <            while (b > 1 && t.baseIndex != t.baseLimit) {
5997 <                b >>>= 1;
5998 <                t.pending = 1;
5999 <                MapReduceEntriesToIntTask<K,V> rt =
6000 <                    new MapReduceEntriesToIntTask<K,V>
6001 <                    (t, b, true, transformer, id, reducer);
6002 <                t = new MapReduceEntriesToIntTask<K,V>
6003 <                    (t, b, false, transformer, id, reducer);
6679 <                t.sibling = rt;
6680 <                rt.sibling = t;
6681 <                rt.fork();
6682 <            }
6683 <            int r = id;
6684 <            Object v;
6685 <            while ((v = t.advance()) != null)
6686 <                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6687 <            t.result = r;
6688 <            for (;;) {
6689 <                int c; BulkTask<K,V,?> par; MapReduceEntriesToIntTask<K,V> s, p;
6690 <                if ((par = t.parent) == null ||
6691 <                    !(par instanceof MapReduceEntriesToIntTask)) {
6692 <                    t.quietlyComplete();
6693 <                    break;
6694 <                }
6695 <                else if ((c = (p = (MapReduceEntriesToIntTask<K,V>)par).pending) == 0) {
6696 <                    if ((s = t.sibling) != null)
6697 <                        r = reducer.apply(r, s.result);
6698 <                    (t = p).result = r;
5978 >        public final Integer getRawResult() { return result; }
5979 >        public final void compute() {
5980 >            final ObjectToInt<Map.Entry<K,V>> transformer;
5981 >            final IntByIntToInt reducer;
5982 >            if ((transformer = this.transformer) != null &&
5983 >                (reducer = this.reducer) != null) {
5984 >                int r = this.basis;
5985 >                for (int i = baseIndex, f, h; batch > 0 &&
5986 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5987 >                    addToPendingCount(1);
5988 >                    (rights = new MapReduceEntriesToIntTask<K,V>
5989 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5990 >                      rights, transformer, r, reducer)).fork();
5991 >                }
5992 >                for (Node<K,V> p; (p = advance()) != null; )
5993 >                    r = reducer.apply(r, transformer.apply(p));
5994 >                result = r;
5995 >                CountedCompleter<?> c;
5996 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5997 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5998 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
5999 >                        s = t.rights;
6000 >                    while (s != null) {
6001 >                        t.result = reducer.apply(t.result, s.result);
6002 >                        s = t.rights = s.nextRight;
6003 >                    }
6004                  }
6700                else if (p.casPending(c, 0))
6701                    break;
6005              }
6006          }
6704        public final Integer getRawResult() { return result; }
6007      }
6008  
6009      @SuppressWarnings("serial")
# Line 6711 | Line 6013 | public class ConcurrentHashMapV8<K, V>
6013          final IntByIntToInt reducer;
6014          final int basis;
6015          int result;
6016 <        MapReduceMappingsToIntTask<K,V> sibling;
6016 >        MapReduceMappingsToIntTask<K,V> rights, nextRight;
6017          MapReduceMappingsToIntTask
6018 <            (ConcurrentHashMapV8<K,V> m,
6018 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6019 >             MapReduceMappingsToIntTask<K,V> nextRight,
6020               ObjectByObjectToInt<? super K, ? super V> transformer,
6021               int basis,
6022               IntByIntToInt reducer) {
6023 <            super(m);
6023 >            super(p, b, i, f, t); this.nextRight = nextRight;
6024              this.transformer = transformer;
6025              this.basis = basis; this.reducer = reducer;
6026          }
6027 <        MapReduceMappingsToIntTask
6028 <            (BulkTask<K,V,?> p, int b, boolean split,
6029 <             ObjectByObjectToInt<? super K, ? super V> transformer,
6030 <             int basis,
6031 <             IntByIntToInt reducer) {
6032 <            super(p, b, split);
6033 <            this.transformer = transformer;
6034 <            this.basis = basis; this.reducer = reducer;
6027 >        public final Integer getRawResult() { return result; }
6028 >        public final void compute() {
6029 >            final ObjectByObjectToInt<? super K, ? super V> transformer;
6030 >            final IntByIntToInt reducer;
6031 >            if ((transformer = this.transformer) != null &&
6032 >                (reducer = this.reducer) != null) {
6033 >                int r = this.basis;
6034 >                for (int i = baseIndex, f, h; batch > 0 &&
6035 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6036 >                    addToPendingCount(1);
6037 >                    (rights = new MapReduceMappingsToIntTask<K,V>
6038 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6039 >                      rights, transformer, r, reducer)).fork();
6040 >                }
6041 >                for (Node<K,V> p; (p = advance()) != null; )
6042 >                    r = reducer.apply(r, transformer.apply(p.key, p.val));
6043 >                result = r;
6044 >                CountedCompleter<?> c;
6045 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6046 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6047 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6048 >                        s = t.rights;
6049 >                    while (s != null) {
6050 >                        t.result = reducer.apply(t.result, s.result);
6051 >                        s = t.rights = s.nextRight;
6052 >                    }
6053 >                }
6054 >            }
6055          }
6056 <        @SuppressWarnings("unchecked") public final void compute() {
6057 <            MapReduceMappingsToIntTask<K,V> t = this;
6058 <            final ObjectByObjectToInt<? super K, ? super V> transformer =
6059 <                this.transformer;
6060 <            final IntByIntToInt reducer = this.reducer;
6061 <            if (transformer == null || reducer == null)
6062 <                throw new Error(NullFunctionMessage);
6063 <            final int id = this.basis;
6064 <            int b = batch();
6065 <            while (b > 1 && t.baseIndex != t.baseLimit) {
6066 <                b >>>= 1;
6067 <                t.pending = 1;
6068 <                MapReduceMappingsToIntTask<K,V> rt =
6069 <                    new MapReduceMappingsToIntTask<K,V>
6070 <                    (t, b, true, transformer, id, reducer);
6071 <                t = new MapReduceMappingsToIntTask<K,V>
6072 <                    (t, b, false, transformer, id, reducer);
6073 <                t.sibling = rt;
6074 <                rt.sibling = t;
6075 <                rt.fork();
6076 <            }
6077 <            int r = id;
6078 <            Object v;
6079 <            while ((v = t.advance()) != null)
6080 <                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6081 <            t.result = r;
6082 <            for (;;) {
6083 <                int c; BulkTask<K,V,?> par; MapReduceMappingsToIntTask<K,V> s, p;
6084 <                if ((par = t.parent) == null ||
6085 <                    !(par instanceof MapReduceMappingsToIntTask)) {
6086 <                    t.quietlyComplete();
6056 >    }
6057 >
6058 >    /* ---------------- Counters -------------- */
6059 >
6060 >    // Adapted from LongAdder and Striped64.
6061 >    // See their internal docs for explanation.
6062 >
6063 >    // A padded cell for distributing counts
6064 >    static final class CounterCell {
6065 >        volatile long p0, p1, p2, p3, p4, p5, p6;
6066 >        volatile long value;
6067 >        volatile long q0, q1, q2, q3, q4, q5, q6;
6068 >        CounterCell(long x) { value = x; }
6069 >    }
6070 >
6071 >    /**
6072 >     * Holder for the thread-local hash code determining which
6073 >     * CounterCell to use. The code is initialized via the
6074 >     * counterHashCodeGenerator, but may be moved upon collisions.
6075 >     */
6076 >    static final class CounterHashCode {
6077 >        int code;
6078 >    }
6079 >
6080 >    /**
6081 >     * Generates initial value for per-thread CounterHashCodes.
6082 >     */
6083 >    static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
6084 >
6085 >    /**
6086 >     * Increment for counterHashCodeGenerator. See class ThreadLocal
6087 >     * for explanation.
6088 >     */
6089 >    static final int SEED_INCREMENT = 0x61c88647;
6090 >
6091 >    /**
6092 >     * Per-thread counter hash codes. Shared across all instances.
6093 >     */
6094 >    static final ThreadLocal<CounterHashCode> threadCounterHashCode =
6095 >        new ThreadLocal<CounterHashCode>();
6096 >
6097 >
6098 >    final long sumCount() {
6099 >        CounterCell[] as = counterCells; CounterCell a;
6100 >        long sum = baseCount;
6101 >        if (as != null) {
6102 >            for (int i = 0; i < as.length; ++i) {
6103 >                if ((a = as[i]) != null)
6104 >                    sum += a.value;
6105 >            }
6106 >        }
6107 >        return sum;
6108 >    }
6109 >
6110 >    // See LongAdder version for explanation
6111 >    private final void fullAddCount(long x, CounterHashCode hc,
6112 >                                    boolean wasUncontended) {
6113 >        int h;
6114 >        if (hc == null) {
6115 >            hc = new CounterHashCode();
6116 >            int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
6117 >            h = hc.code = (s == 0) ? 1 : s; // Avoid zero
6118 >            threadCounterHashCode.set(hc);
6119 >        }
6120 >        else
6121 >            h = hc.code;
6122 >        boolean collide = false;                // True if last slot nonempty
6123 >        for (;;) {
6124 >            CounterCell[] as; CounterCell a; int n; long v;
6125 >            if ((as = counterCells) != null && (n = as.length) > 0) {
6126 >                if ((a = as[(n - 1) & h]) == null) {
6127 >                    if (cellsBusy == 0) {            // Try to attach new Cell
6128 >                        CounterCell r = new CounterCell(x); // Optimistic create
6129 >                        if (cellsBusy == 0 &&
6130 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6131 >                            boolean created = false;
6132 >                            try {               // Recheck under lock
6133 >                                CounterCell[] rs; int m, j;
6134 >                                if ((rs = counterCells) != null &&
6135 >                                    (m = rs.length) > 0 &&
6136 >                                    rs[j = (m - 1) & h] == null) {
6137 >                                    rs[j] = r;
6138 >                                    created = true;
6139 >                                }
6140 >                            } finally {
6141 >                                cellsBusy = 0;
6142 >                            }
6143 >                            if (created)
6144 >                                break;
6145 >                            continue;           // Slot is now non-empty
6146 >                        }
6147 >                    }
6148 >                    collide = false;
6149 >                }
6150 >                else if (!wasUncontended)       // CAS already known to fail
6151 >                    wasUncontended = true;      // Continue after rehash
6152 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
6153                      break;
6154 +                else if (counterCells != as || n >= NCPU)
6155 +                    collide = false;            // At max size or stale
6156 +                else if (!collide)
6157 +                    collide = true;
6158 +                else if (cellsBusy == 0 &&
6159 +                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6160 +                    try {
6161 +                        if (counterCells == as) {// Expand table unless stale
6162 +                            CounterCell[] rs = new CounterCell[n << 1];
6163 +                            for (int i = 0; i < n; ++i)
6164 +                                rs[i] = as[i];
6165 +                            counterCells = rs;
6166 +                        }
6167 +                    } finally {
6168 +                        cellsBusy = 0;
6169 +                    }
6170 +                    collide = false;
6171 +                    continue;                   // Retry with expanded table
6172                  }
6173 <                else if ((c = (p = (MapReduceMappingsToIntTask<K,V>)par).pending) == 0) {
6174 <                    if ((s = t.sibling) != null)
6175 <                        r = reducer.apply(r, s.result);
6176 <                    (t = p).result = r;
6173 >                h ^= h << 13;                   // Rehash
6174 >                h ^= h >>> 17;
6175 >                h ^= h << 5;
6176 >            }
6177 >            else if (cellsBusy == 0 && counterCells == as &&
6178 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
6179 >                boolean init = false;
6180 >                try {                           // Initialize table
6181 >                    if (counterCells == as) {
6182 >                        CounterCell[] rs = new CounterCell[2];
6183 >                        rs[h & 1] = new CounterCell(x);
6184 >                        counterCells = rs;
6185 >                        init = true;
6186 >                    }
6187 >                } finally {
6188 >                    cellsBusy = 0;
6189                  }
6190 <                else if (p.casPending(c, 0))
6190 >                if (init)
6191                      break;
6192              }
6193 +            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
6194 +                break;                          // Fall back on using base
6195          }
6196 <        public final Integer getRawResult() { return result; }
6196 >        hc.code = h;                            // Record index for next time
6197      }
6198  
6778
6199      // Unsafe mechanics
6200 <    private static final sun.misc.Unsafe UNSAFE;
6201 <    private static final long counterOffset;
6202 <    private static final long sizeCtlOffset;
6200 >    private static final sun.misc.Unsafe U;
6201 >    private static final long SIZECTL;
6202 >    private static final long TRANSFERINDEX;
6203 >    private static final long BASECOUNT;
6204 >    private static final long CELLSBUSY;
6205 >    private static final long CELLVALUE;
6206      private static final long ABASE;
6207      private static final int ASHIFT;
6208  
6209      static {
6787        int ss;
6210          try {
6211 <            UNSAFE = getUnsafe();
6211 >            U = getUnsafe();
6212              Class<?> k = ConcurrentHashMapV8.class;
6213 <            counterOffset = UNSAFE.objectFieldOffset
6792 <                (k.getDeclaredField("counter"));
6793 <            sizeCtlOffset = UNSAFE.objectFieldOffset
6213 >            SIZECTL = U.objectFieldOffset
6214                  (k.getDeclaredField("sizeCtl"));
6215 <            Class<?> sc = Node[].class;
6216 <            ABASE = UNSAFE.arrayBaseOffset(sc);
6217 <            ss = UNSAFE.arrayIndexScale(sc);
6215 >            TRANSFERINDEX = U.objectFieldOffset
6216 >                (k.getDeclaredField("transferIndex"));
6217 >            BASECOUNT = U.objectFieldOffset
6218 >                (k.getDeclaredField("baseCount"));
6219 >            CELLSBUSY = U.objectFieldOffset
6220 >                (k.getDeclaredField("cellsBusy"));
6221 >            Class<?> ck = CounterCell.class;
6222 >            CELLVALUE = U.objectFieldOffset
6223 >                (ck.getDeclaredField("value"));
6224 >            Class<?> ak = Node[].class;
6225 >            ABASE = U.arrayBaseOffset(ak);
6226 >            int scale = U.arrayIndexScale(ak);
6227 >            if ((scale & (scale - 1)) != 0)
6228 >                throw new Error("data type scale not a power of two");
6229 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6230          } catch (Exception e) {
6231              throw new Error(e);
6232          }
6801        if ((ss & (ss-1)) != 0)
6802            throw new Error("data type scale not a power of two");
6803        ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6233      }
6234  
6235      /**
# Line 6813 | Line 6242 | public class ConcurrentHashMapV8<K, V>
6242      private static sun.misc.Unsafe getUnsafe() {
6243          try {
6244              return sun.misc.Unsafe.getUnsafe();
6245 <        } catch (SecurityException se) {
6246 <            try {
6247 <                return java.security.AccessController.doPrivileged
6248 <                    (new java.security
6249 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
6250 <                        public sun.misc.Unsafe run() throws Exception {
6251 <                            java.lang.reflect.Field f = sun.misc
6252 <                                .Unsafe.class.getDeclaredField("theUnsafe");
6253 <                            f.setAccessible(true);
6254 <                            return (sun.misc.Unsafe) f.get(null);
6255 <                        }});
6256 <            } catch (java.security.PrivilegedActionException e) {
6257 <                throw new RuntimeException("Could not initialize intrinsics",
6258 <                                           e.getCause());
6259 <            }
6245 >        } catch (SecurityException tryReflectionInstead) {}
6246 >        try {
6247 >            return java.security.AccessController.doPrivileged
6248 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
6249 >                public sun.misc.Unsafe run() throws Exception {
6250 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
6251 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
6252 >                        f.setAccessible(true);
6253 >                        Object x = f.get(null);
6254 >                        if (k.isInstance(x))
6255 >                            return k.cast(x);
6256 >                    }
6257 >                    throw new NoSuchFieldError("the Unsafe");
6258 >                }});
6259 >        } catch (java.security.PrivilegedActionException e) {
6260 >            throw new RuntimeException("Could not initialize intrinsics",
6261 >                                       e.getCause());
6262          }
6263      }
6264   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines