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.22 by jsr166, Sat Sep 10 19:33:14 2011 UTC vs.
Revision 1.57 by dl, Mon Aug 13 19:52:33 2012 UTC

# Line 6 | Line 6
6  
7   package jsr166e;
8   import jsr166e.LongAdder;
9 + import jsr166e.ForkJoinPool;
10 + import jsr166e.ForkJoinTask;
11 +
12 + import java.util.Comparator;
13 + import java.util.Arrays;
14   import java.util.Map;
15   import java.util.Set;
16   import java.util.Collection;
# Line 19 | Line 24 | import java.util.Enumeration;
24   import java.util.ConcurrentModificationException;
25   import java.util.NoSuchElementException;
26   import java.util.concurrent.ConcurrentMap;
27 + import java.util.concurrent.ThreadLocalRandom;
28 + import java.util.concurrent.locks.LockSupport;
29 + import java.util.concurrent.locks.AbstractQueuedSynchronizer;
30 + import java.util.concurrent.atomic.AtomicReference;
31 +
32   import java.io.Serializable;
33  
34   /**
# Line 54 | Line 64 | import java.io.Serializable;
64   * <p> The table is dynamically expanded when there are too many
65   * collisions (i.e., keys that have distinct hash codes but fall into
66   * the same slot modulo the table size), with the expected average
67 < * effect of maintaining roughly two bins per mapping. There may be
68 < * much variance around this average as mappings are added and
69 < * removed, but overall, this maintains a commonly accepted time/space
70 < * tradeoff for hash tables.  However, resizing this or any other kind
71 < * of hash table may be a relatively slow operation. When possible, it
72 < * is a good idea to provide a size estimate as an optional {@code
67 > * effect of maintaining roughly two bins per mapping (corresponding
68 > * to a 0.75 load factor threshold for resizing). There may be much
69 > * variance around this average as mappings are added and removed, but
70 > * overall, this maintains a commonly accepted time/space tradeoff for
71 > * hash tables.  However, resizing this or any other kind of hash
72 > * table may be a relatively slow operation. When possible, it is a
73 > * good idea to provide a size estimate as an optional {@code
74   * initialCapacity} constructor argument. An additional optional
75   * {@code loadFactor} constructor argument provides a further means of
76   * customizing initial table capacity by specifying the table density
# Line 68 | Line 79 | import java.io.Serializable;
79   * versions of this class, constructors may optionally specify an
80   * expected {@code concurrencyLevel} as an additional hint for
81   * internal sizing.  Note that using many keys with exactly the same
82 < * {@code hashCode{}} is a sure way to slow down performance of any
82 > * {@code hashCode()} is a sure way to slow down performance of any
83   * hash table.
84   *
85   * <p>This class and its views and iterators implement all of the
# Line 83 | Line 94 | import java.io.Serializable;
94   * Java Collections Framework</a>.
95   *
96   * <p><em>jsr166e note: This class is a candidate replacement for
97 < * java.util.concurrent.ConcurrentHashMap.<em>
97 > * java.util.concurrent.ConcurrentHashMap.  During transition, this
98 > * class declares and uses nested functional interfaces with different
99 > * names but the same forms as those expected for JDK8.<em>
100   *
101   * @since 1.5
102   * @author Doug Lea
# Line 91 | Line 104 | import java.io.Serializable;
104   * @param <V> the type of mapped values
105   */
106   public class ConcurrentHashMapV8<K, V>
107 <        implements ConcurrentMap<K, V>, Serializable {
107 >    implements ConcurrentMap<K, V>, Serializable {
108      private static final long serialVersionUID = 7249069246763182397L;
109  
110      /**
111 <     * A function computing a mapping from the given key to a value,
112 <     * or {@code null} if there is no mapping. This is a place-holder
113 <     * for an upcoming JDK8 interface.
114 <     */
115 <    public static interface MappingFunction<K, V> {
116 <        /**
117 <         * Returns a value for the given key, or null if there is no
118 <         * mapping. If this function throws an (unchecked) exception,
119 <         * the exception is rethrown to its caller, and no mapping is
120 <         * recorded.  Because this function is invoked within
121 <         * atomicity control, the computation should be short and
122 <         * simple. The most common usage is to construct a new object
123 <         * serving as an initial mapped value.
111 >     * A partitionable iterator. A Spliterator can be traversed
112 >     * directly, but can also be partitioned (before traversal) by
113 >     * creating another Spliterator that covers a non-overlapping
114 >     * portion of the elements, and so may be amenable to parallel
115 >     * execution.
116 >     *
117 >     * <p> This interface exports a subset of expected JDK8
118 >     * functionality.
119 >     *
120 >     * <p>Sample usage: Here is one (of the several) ways to compute
121 >     * the sum of the values held in a map using the ForkJoin
122 >     * framework. As illustrated here, Spliterators are well suited to
123 >     * designs in which a task repeatedly splits off half its work
124 >     * into forked subtasks until small enough to process directly,
125 >     * and then joins these subtasks. Variants of this style can also
126 >     * be used in completion-based designs.
127 >     *
128 >     * <pre>
129 >     * {@code ConcurrentHashMapV8<String, Long> m = ...
130 >     * // split as if have 8 * parallelism, for load balance
131 >     * int n = m.size();
132 >     * int p = aForkJoinPool.getParallelism() * 8;
133 >     * int split = (n < p)? n : p;
134 >     * long sum = aForkJoinPool.invoke(new SumValues(m.valueSpliterator(), split, null));
135 >     * // ...
136 >     * static class SumValues extends RecursiveTask<Long> {
137 >     *   final Spliterator<Long> s;
138 >     *   final int split;             // split while > 1
139 >     *   final SumValues nextJoin;    // records forked subtasks to join
140 >     *   SumValues(Spliterator<Long> s, int depth, SumValues nextJoin) {
141 >     *     this.s = s; this.depth = depth; this.nextJoin = nextJoin;
142 >     *   }
143 >     *   public Long compute() {
144 >     *     long sum = 0;
145 >     *     SumValues subtasks = null; // fork subtasks
146 >     *     for (int s = split >>> 1; s > 0; s >>>= 1)
147 >     *       (subtasks = new SumValues(s.split(), s, subtasks)).fork();
148 >     *     while (s.hasNext())        // directly process remaining elements
149 >     *       sum += s.next();
150 >     *     for (SumValues t = subtasks; t != null; t = t.nextJoin)
151 >     *       sum += t.join();         // collect subtask results
152 >     *     return sum;
153 >     *   }
154 >     * }
155 >     * }</pre>
156 >     */
157 >    public static interface Spliterator<T> extends Iterator<T> {
158 >        /**
159 >         * Returns a Spliterator covering approximately half of the
160 >         * elements, guaranteed not to overlap with those subsequently
161 >         * returned by this Spliterator.  After invoking this method,
162 >         * the current Spliterator will <em>not</em> produce any of
163 >         * the elements of the returned Spliterator, but the two
164 >         * Spliterators together will produce all of the elements that
165 >         * would have been produced by this Spliterator had this
166 >         * method not been called. The exact number of elements
167 >         * produced by the returned Spliterator is not guaranteed, and
168 >         * may be zero (i.e., with {@code hasNext()} reporting {@code
169 >         * false}) if this Spliterator cannot be further split.
170           *
171 <         * @param key the (non-null) key
172 <         * @return a value, or null if none
171 >         * @return a Spliterator covering approximately half of the
172 >         * elements
173 >         * @throws IllegalStateException if this Spliterator has
174 >         * already commenced traversing elements
175           */
176 <        V map(K key);
176 >        Spliterator<T> split();
177      }
178  
179      /*
# Line 121 | Line 182 | public class ConcurrentHashMapV8<K, V>
182       * The primary design goal of this hash table is to maintain
183       * concurrent readability (typically method get(), but also
184       * iterators and related methods) while minimizing update
185 <     * contention.
185 >     * contention. Secondary goals are to keep space consumption about
186 >     * the same or better than java.util.HashMap, and to support high
187 >     * initial insertion rates on an empty table by many threads.
188       *
189       * Each key-value mapping is held in a Node.  Because Node fields
190       * can contain special values, they are defined using plain Object
# Line 129 | Line 192 | public class ConcurrentHashMapV8<K, V>
192       * work off Object types. And similarly, so do the internal
193       * methods of auxiliary iterator and view classes.  All public
194       * generic typed methods relay in/out of these internal methods,
195 <     * supplying null-checks and casts as needed.
195 >     * supplying null-checks and casts as needed. This also allows
196 >     * many of the public methods to be factored into a smaller number
197 >     * of internal methods (although sadly not so for the five
198 >     * variants of put-related operations). The validation-based
199 >     * approach explained below leads to a lot of code sprawl because
200 >     * retry-control precludes factoring into smaller methods.
201       *
202       * The table is lazily initialized to a power-of-two size upon the
203 <     * first insertion.  Each bin in the table contains a list of
204 <     * Nodes (most often, zero or one Node).  Table accesses require
205 <     * volatile/atomic reads, writes, and CASes.  Because there is no
206 <     * other way to arrange this without adding further indirections,
207 <     * we use intrinsics (sun.misc.Unsafe) operations.  The lists of
208 <     * nodes within bins are always accurately traversable under
209 <     * volatile reads, so long as lookups check hash code and
210 <     * non-nullness of value before checking key equality. (All valid
211 <     * hash codes are nonnegative. Negative values are reserved for
212 <     * special forwarding nodes; see below.)
203 >     * first insertion.  Each bin in the table normally contains a
204 >     * list of Nodes (most often, the list has only zero or one Node).
205 >     * Table accesses require volatile/atomic reads, writes, and
206 >     * CASes.  Because there is no other way to arrange this without
207 >     * adding further indirections, we use intrinsics
208 >     * (sun.misc.Unsafe) operations.  The lists of nodes within bins
209 >     * are always accurately traversable under volatile reads, so long
210 >     * as lookups check hash code and non-nullness of value before
211 >     * checking key equality.
212 >     *
213 >     * We use the top two bits of Node hash fields for control
214 >     * purposes -- they are available anyway because of addressing
215 >     * constraints.  As explained further below, these top bits are
216 >     * used as follows:
217 >     *  00 - Normal
218 >     *  01 - Locked
219 >     *  11 - Locked and may have a thread waiting for lock
220 >     *  10 - Node is a forwarding node
221 >     *
222 >     * The lower 30 bits of each Node's hash field contain a
223 >     * transformation of the key's hash code, except for forwarding
224 >     * nodes, for which the lower bits are zero (and so always have
225 >     * hash field == MOVED).
226       *
227 <     * Insertion (via put or putIfAbsent) of the first node in an
227 >     * Insertion (via put or its variants) of the first node in an
228       * empty bin is performed by just CASing it to the bin.  This is
229 <     * on average by far the most common case for put operations.
230 <     * Other update operations (insert, delete, and replace) require
231 <     * locks.  We do not want to waste the space required to associate
232 <     * a distinct lock object with each bin, so instead use the first
233 <     * node of a bin list itself as a lock, using plain "synchronized"
234 <     * locks. These save space and we can live with block-structured
235 <     * lock/unlock operations. Using the first node of a list as a
236 <     * lock does not by itself suffice though: When a node is locked,
237 <     * any update must first validate that it is still the first node,
238 <     * and retry if not. Because new nodes are always appended to
239 <     * lists, once a node is first in a bin, it remains first until
240 <     * deleted or the bin becomes invalidated.  However, operations
241 <     * that only conditionally update can and sometimes do inspect
242 <     * nodes until the point of update. This is a converse of sorts to
243 <     * the lazy locking technique described by Herlihy & Shavit.
229 >     * by far the most common case for put operations under most
230 >     * key/hash distributions.  Other update operations (insert,
231 >     * delete, and replace) require locks.  We do not want to waste
232 >     * the space required to associate a distinct lock object with
233 >     * each bin, so instead use the first node of a bin list itself as
234 >     * a lock. Blocking support for these locks relies on the builtin
235 >     * "synchronized" monitors.  However, we also need a tryLock
236 >     * construction, so we overlay these by using bits of the Node
237 >     * hash field for lock control (see above), and so normally use
238 >     * builtin monitors only for blocking and signalling using
239 >     * wait/notifyAll constructions. See Node.tryAwaitLock.
240 >     *
241 >     * Using the first node of a list as a lock does not by itself
242 >     * suffice though: When a node is locked, any update must first
243 >     * validate that it is still the first node after locking it, and
244 >     * retry if not. Because new nodes are always appended to lists,
245 >     * once a node is first in a bin, it remains first until deleted
246 >     * or the bin becomes invalidated (upon resizing).  However,
247 >     * operations that only conditionally update may inspect nodes
248 >     * until the point of update. This is a converse of sorts to the
249 >     * lazy locking technique described by Herlihy & Shavit.
250       *
251 <     * The main disadvantage of this approach is that most update
251 >     * The main disadvantage of per-bin locks is that other update
252       * operations on other nodes in a bin list protected by the same
253       * lock can stall, for example when user equals() or mapping
254 <     * functions take a long time.  However, statistically, this is
255 <     * not a common enough problem to outweigh the time/space overhead
256 <     * of alternatives: Under random hash codes, the frequency of
170 <     * nodes in bins follows a Poisson distribution
254 >     * functions take a long time.  However, statistically, under
255 >     * random hash codes, this is not a common problem.  Ideally, the
256 >     * frequency of nodes in bins follows a Poisson distribution
257       * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
258       * parameter of about 0.5 on average, given the resizing threshold
259       * of 0.75, although with a large variance because of resizing
260       * granularity. Ignoring variance, the expected occurrences of
261       * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
262 <     * first few values are:
262 >     * first values are:
263       *
264 <     * 0:    0.607
265 <     * 1:    0.303
266 <     * 2:    0.076
267 <     * 3:    0.012
268 <     * more: 0.002
264 >     * 0:    0.60653066
265 >     * 1:    0.30326533
266 >     * 2:    0.07581633
267 >     * 3:    0.01263606
268 >     * 4:    0.00157952
269 >     * 5:    0.00015795
270 >     * 6:    0.00001316
271 >     * 7:    0.00000094
272 >     * 8:    0.00000006
273 >     * more: less than 1 in ten million
274       *
275       * Lock contention probability for two threads accessing distinct
276 <     * elements is roughly 1 / (8 * #elements).  Function "spread"
277 <     * performs hashCode randomization that improves the likelihood
278 <     * that these assumptions hold unless users define exactly the
279 <     * same value for too many hashCodes.
280 <     *
281 <     * The table is resized when occupancy exceeds a threshold.  Only
282 <     * a single thread performs the resize (using field "resizing", to
283 <     * arrange exclusion), but the table otherwise remains usable for
284 <     * reads and updates. Resizing proceeds by transferring bins, one
285 <     * by one, from the table to the next table.  Upon transfer, the
286 <     * old table bin contains only a special forwarding node (with
287 <     * negative hash field) that contains the next table as its
288 <     * key. On encountering a forwarding node, access and update
289 <     * operations restart, using the new table. To ensure concurrent
290 <     * readability of traversals, transfers must proceed from the last
291 <     * bin (table.length - 1) up towards the first.  Upon seeing a
292 <     * forwarding node, traversals (see class InternalIterator)
293 <     * arrange to move to the new table for the rest of the traversal
294 <     * without revisiting nodes.  This constrains bin transfers to a
295 <     * particular order, and so can block indefinitely waiting for the
296 <     * next lock, and other threads cannot help with the transfer.
297 <     * However, expected stalls are infrequent enough to not warrant
298 <     * the additional overhead of access and iteration schemes that
299 <     * could admit out-of-order or concurrent bin transfers.
300 <     *
301 <     * This traversal scheme also applies to partial traversals of
302 <     * ranges of bins (via an alternate InternalIterator constructor)
303 <     * to support partitioned aggregate operations (that are not
304 <     * otherwise implemented yet).  Also, read-only operations give up
305 <     * if ever forwarded to a null table, which provides support for
306 <     * shutdown-style clearing, which is also not currently
307 <     * implemented.
276 >     * elements is roughly 1 / (8 * #elements) under random hashes.
277 >     *
278 >     * Actual hash code distributions encountered in practice
279 >     * sometimes deviate significantly from uniform randomness.  This
280 >     * includes the case when N > (1<<30), so some keys MUST collide.
281 >     * Similarly for dumb or hostile usages in which multiple keys are
282 >     * designed to have identical hash codes. Also, although we guard
283 >     * against the worst effects of this (see method spread), sets of
284 >     * hashes may differ only in bits that do not impact their bin
285 >     * index for a given power-of-two mask.  So we use a secondary
286 >     * strategy that applies when the number of nodes in a bin exceeds
287 >     * a threshold, and at least one of the keys implements
288 >     * Comparable.  These TreeBins use a balanced tree to hold nodes
289 >     * (a specialized form of red-black trees), bounding search time
290 >     * to O(log N).  Each search step in a TreeBin is around twice as
291 >     * slow as in a regular list, but given that N cannot exceed
292 >     * (1<<64) (before running out of addresses) this bounds search
293 >     * steps, lock hold times, etc, to reasonable constants (roughly
294 >     * 100 nodes inspected per operation worst case) so long as keys
295 >     * are Comparable (which is very common -- String, Long, etc).
296 >     * TreeBin nodes (TreeNodes) also maintain the same "next"
297 >     * traversal pointers as regular nodes, so can be traversed in
298 >     * iterators in the same way.
299 >     *
300 >     * The table is resized when occupancy exceeds a percentage
301 >     * threshold (nominally, 0.75, but see below).  Only a single
302 >     * thread performs the resize (using field "sizeCtl", to arrange
303 >     * exclusion), but the table otherwise remains usable for reads
304 >     * and updates. Resizing proceeds by transferring bins, one by
305 >     * one, from the table to the next table.  Because we are using
306 >     * power-of-two expansion, the elements from each bin must either
307 >     * stay at same index, or move with a power of two offset. We
308 >     * eliminate unnecessary node creation by catching cases where old
309 >     * nodes can be reused because their next fields won't change.  On
310 >     * average, only about one-sixth of them need cloning when a table
311 >     * doubles. The nodes they replace will be garbage collectable as
312 >     * soon as they are no longer referenced by any reader thread that
313 >     * may be in the midst of concurrently traversing table.  Upon
314 >     * transfer, the old table bin contains only a special forwarding
315 >     * node (with hash field "MOVED") that contains the next table as
316 >     * its key. On encountering a forwarding node, access and update
317 >     * operations restart, using the new table.
318 >     *
319 >     * Each bin transfer requires its bin lock. However, unlike other
320 >     * cases, a transfer can skip a bin if it fails to acquire its
321 >     * lock, and revisit it later (unless it is a TreeBin). Method
322 >     * rebuild maintains a buffer of TRANSFER_BUFFER_SIZE bins that
323 >     * have been skipped because of failure to acquire a lock, and
324 >     * blocks only if none are available (i.e., only very rarely).
325 >     * The transfer operation must also ensure that all accessible
326 >     * bins in both the old and new table are usable by any traversal.
327 >     * When there are no lock acquisition failures, this is arranged
328 >     * simply by proceeding from the last bin (table.length - 1) up
329 >     * towards the first.  Upon seeing a forwarding node, traversals
330 >     * (see class Iter) arrange to move to the new table
331 >     * without revisiting nodes.  However, when any node is skipped
332 >     * during a transfer, all earlier table bins may have become
333 >     * visible, so are initialized with a reverse-forwarding node back
334 >     * to the old table until the new ones are established. (This
335 >     * sometimes requires transiently locking a forwarding node, which
336 >     * is possible under the above encoding.) These more expensive
337 >     * mechanics trigger only when necessary.
338 >     *
339 >     * The traversal scheme also applies to partial traversals of
340 >     * ranges of bins (via an alternate Traverser constructor)
341 >     * to support partitioned aggregate operations.  Also, read-only
342 >     * operations give up if ever forwarded to a null table, which
343 >     * provides support for shutdown-style clearing, which is also not
344 >     * currently implemented.
345       *
346       * Lazy table initialization minimizes footprint until first use,
347       * and also avoids resizings when the first operation is from a
348       * putAll, constructor with map argument, or deserialization.
349 <     * These cases attempt to override the targetCapacity used in
350 <     * growTable. These harmlessly fail to take effect in cases of
223 <     * races with other ongoing resizings. Uses of the threshold and
224 <     * targetCapacity during attempted initializations or resizings
225 <     * are racy but fall back on checks to preserve correctness.
349 >     * These cases attempt to override the initial capacity settings,
350 >     * but harmlessly fail to take effect in cases of races.
351       *
352       * The element count is maintained using a LongAdder, which avoids
353       * contention on updates but can encounter cache thrashing if read
354       * too frequently during concurrent access. To avoid reading so
355 <     * often, resizing is normally attempted only upon adding to a bin
356 <     * already holding two or more nodes. Under uniform hash
357 <     * distributions, the probability of this occurring at threshold
358 <     * is around 13%, meaning that only about 1 in 8 puts check
359 <     * threshold (and after resizing, many fewer do so). But this
360 <     * approximation has high variance for small table sizes, so we
361 <     * check on any collision for sizes <= 64.  Further, to increase
362 <     * the probability that a resize occurs soon enough, we offset the
363 <     * threshold (see THRESHOLD_OFFSET) by the expected number of puts
364 <     * between checks.
355 >     * often, resizing is attempted either when a bin lock is
356 >     * contended, or upon adding to a bin already holding two or more
357 >     * nodes (checked before adding in the xIfAbsent methods, after
358 >     * adding in others). Under uniform hash distributions, the
359 >     * probability of this occurring at threshold is around 13%,
360 >     * meaning that only about 1 in 8 puts check threshold (and after
361 >     * resizing, many fewer do so). But this approximation has high
362 >     * variance for small table sizes, so we check on any collision
363 >     * for sizes <= 64. The bulk putAll operation further reduces
364 >     * contention by only committing count updates upon these size
365 >     * checks.
366       *
367       * Maintaining API and serialization compatibility with previous
368       * versions of this class introduces several oddities. Mainly: We
369       * leave untouched but unused constructor arguments refering to
370 <     * concurrencyLevel. We also declare an unused "Segment" class
371 <     * that is instantiated in minimal form only when serializing.
370 >     * concurrencyLevel. We accept a loadFactor constructor argument,
371 >     * but apply it only to initial table capacity (which is the only
372 >     * time that we can guarantee to honor it.) We also declare an
373 >     * unused "Segment" class that is instantiated in minimal form
374 >     * only when serializing.
375       */
376  
377      /* ---------------- Constants -------------- */
# Line 250 | Line 379 | public class ConcurrentHashMapV8<K, V>
379      /**
380       * The largest possible table capacity.  This value must be
381       * exactly 1<<30 to stay within Java array allocation and indexing
382 <     * bounds for power of two table sizes.
382 >     * bounds for power of two table sizes, and is further required
383 >     * because the top two bits of 32bit hash fields are used for
384 >     * control purposes.
385       */
386      private static final int MAXIMUM_CAPACITY = 1 << 30;
387  
# Line 261 | Line 392 | public class ConcurrentHashMapV8<K, V>
392      private static final int DEFAULT_CAPACITY = 16;
393  
394      /**
395 <     * The load factor for this table. Overrides of this value in
396 <     * constructors affect only the initial table capacity.  The
266 <     * actual floating point value isn't normally used, because it is
267 <     * simpler to rely on the expression {@code n - (n >>> 2)} for the
268 <     * associated resizing threshold.
395 >     * The largest possible (non-power of two) array size.
396 >     * Needed by toArray and related methods.
397       */
398 <    private static final float LOAD_FACTOR = 0.75f;
398 >    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
399  
400      /**
401 <     * The count value to offset thresholds to compensate for checking
402 <     * for the need to resize only when inserting into bins with two
275 <     * or more elements. See above for explanation.
401 >     * The default concurrency level for this table. Unused but
402 >     * defined for compatibility with previous versions of this class.
403       */
404 <    private static final int THRESHOLD_OFFSET = 8;
404 >    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
405  
406      /**
407 <     * The default concurrency level for this table. Unused except as
408 <     * a sizing hint, but defined for compatibility with previous
409 <     * versions of this class.
407 >     * The load factor for this table. Overrides of this value in
408 >     * constructors affect only the initial table capacity.  The
409 >     * actual floating point value isn't normally used -- it is
410 >     * simpler to use expressions such as {@code n - (n >>> 2)} for
411 >     * the associated resizing threshold.
412       */
413 <    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
285 <
286 <    /* ---------------- Nodes -------------- */
413 >    private static final float LOAD_FACTOR = 0.75f;
414  
415      /**
416 <     * Key-value entry. Note that this is never exported out as a
417 <     * user-visible Map.Entry. Nodes with a negative hash field are
418 <     * special, and do not contain user keys or values.  Otherwise,
292 <     * keys are never null, and null val fields indicate that a node
293 <     * is in the process of being deleted or created. For purposes of
294 <     * read-only, access, a key may be read before a val, but can only
295 <     * be used after checking val.  (For an update operation, when a
296 <     * lock is held on a node, order doesn't matter.)
416 >     * The buffer size for skipped bins during transfers. The
417 >     * value is arbitrary but should be large enough to avoid
418 >     * most locking stalls during resizes.
419       */
420 <    static final class Node {
299 <        final int hash;
300 <        final Object key;
301 <        volatile Object val;
302 <        volatile Node next;
303 <
304 <        Node(int hash, Object key, Object val, Node next) {
305 <            this.hash = hash;
306 <            this.key = key;
307 <            this.val = val;
308 <            this.next = next;
309 <        }
310 <    }
420 >    private static final int TRANSFER_BUFFER_SIZE = 32;
421  
422      /**
423 <     * Sign bit of node hash value indicating to use table in node.key.
423 >     * The bin count threshold for using a tree rather than list for a
424 >     * bin.  The value reflects the approximate break-even point for
425 >     * using tree-based operations.
426 >     */
427 >    private static final int TREE_THRESHOLD = 8;
428 >
429 >    /*
430 >     * Encodings for special uses of Node hash fields. See above for
431 >     * explanation.
432       */
433 <    private static final int SIGN_BIT = 0x80000000;
433 >    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
434 >    static final int LOCKED    = 0x40000000; // set/tested only as a bit
435 >    static final int WAITING   = 0xc0000000; // both bits set/tested together
436 >    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
437  
438      /* ---------------- Fields -------------- */
439  
# Line 322 | Line 443 | public class ConcurrentHashMapV8<K, V>
443       */
444      transient volatile Node[] table;
445  
446 <    /** The counter maintaining number of elements. */
446 >    /**
447 >     * The counter maintaining number of elements.
448 >     */
449      private transient final LongAdder counter;
450 <    /** Nonzero when table is being initialized or resized. Updated via CAS. */
451 <    private transient volatile int resizing;
452 <    /** The next element count value upon which to resize the table. */
453 <    private transient int threshold;
454 <    /** The target capacity; volatile to cover initialization races. */
455 <    private transient volatile int targetCapacity;
450 >
451 >    /**
452 >     * Table initialization and resizing control.  When negative, the
453 >     * table is being initialized or resized. Otherwise, when table is
454 >     * null, holds the initial table size to use upon creation, or 0
455 >     * for default. After initialization, holds the next element count
456 >     * value upon which to resize the table.
457 >     */
458 >    private transient volatile int sizeCtl;
459  
460      // views
461      private transient KeySet<K,V> keySet;
# Line 353 | Line 479 | public class ConcurrentHashMapV8<K, V>
479       * inline assignments below.
480       */
481  
482 <    static final Node tabAt(Node[] tab, int i) { // used by InternalIterator
482 >    static final Node tabAt(Node[] tab, int i) { // used by Iter
483          return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
484      }
485  
# Line 365 | Line 491 | public class ConcurrentHashMapV8<K, V>
491          UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
492      }
493  
494 <    /* ----------------Table Initialization and Resizing -------------- */
494 >    /* ---------------- Nodes -------------- */
495  
496      /**
497 <     * Returns a power of two table size for the given desired capacity.
498 <     * See Hackers Delight, sec 3.2
497 >     * Key-value entry. Note that this is never exported out as a
498 >     * user-visible Map.Entry (see MapEntry below). Nodes with a hash
499 >     * field of MOVED are special, and do not contain user keys or
500 >     * values.  Otherwise, keys are never null, and null val fields
501 >     * indicate that a node is in the process of being deleted or
502 >     * created. For purposes of read-only access, a key may be read
503 >     * before a val, but can only be used after checking val to be
504 >     * non-null.
505       */
506 <    private static final int tableSizeFor(int c) {
507 <        int n = c - 1;
508 <        n |= n >>> 1;
509 <        n |= n >>> 2;
510 <        n |= n >>> 4;
379 <        n |= n >>> 8;
380 <        n |= n >>> 16;
381 <        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
382 <    }
506 >    static class Node {
507 >        volatile int hash;
508 >        final Object key;
509 >        volatile Object val;
510 >        volatile Node next;
511  
512 <    /**
513 <     * If not already resizing, initializes or creates next table and
514 <     * transfers bins. Initial table size uses the capacity recorded
515 <     * in targetCapacity.  Rechecks occupancy after a transfer to see
516 <     * if another resize is already needed because resizings are
517 <     * lagging additions.
518 <     *
519 <     * @return current table
520 <     */
521 <    private final Node[] growTable() {
522 <        if (resizing == 0 &&
523 <            UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
524 <            try {
525 <                for (;;) {
526 <                    Node[] tab = table;
527 <                    int n, c, m;
528 <                    if (tab == null)
529 <                        n = (c = targetCapacity) > 0 ? c : DEFAULT_CAPACITY;
530 <                    else if ((m = tab.length) < MAXIMUM_CAPACITY &&
531 <                             counter.sum() >= (long)threshold)
532 <                        n = m << 1;
533 <                    else
534 <                        break;
535 <                    threshold = n - (n >>> 2) - THRESHOLD_OFFSET;
536 <                    Node[] nextTab = new Node[n];
537 <                    if (tab != null)
538 <                        transfer(tab, nextTab,
539 <                                 new Node(SIGN_BIT, nextTab, null, null));
540 <                    table = nextTab;
541 <                    if (tab == null)
512 >        Node(int hash, Object key, Object val, Node next) {
513 >            this.hash = hash;
514 >            this.key = key;
515 >            this.val = val;
516 >            this.next = next;
517 >        }
518 >
519 >        /** CompareAndSet the hash field */
520 >        final boolean casHash(int cmp, int val) {
521 >            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
522 >        }
523 >
524 >        /** The number of spins before blocking for a lock */
525 >        static final int MAX_SPINS =
526 >            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
527 >
528 >        /**
529 >         * Spins a while if LOCKED bit set and this node is the first
530 >         * of its bin, and then sets WAITING bits on hash field and
531 >         * blocks (once) if they are still set.  It is OK for this
532 >         * method to return even if lock is not available upon exit,
533 >         * which enables these simple single-wait mechanics.
534 >         *
535 >         * The corresponding signalling operation is performed within
536 >         * callers: Upon detecting that WAITING has been set when
537 >         * unlocking lock (via a failed CAS from non-waiting LOCKED
538 >         * state), unlockers acquire the sync lock and perform a
539 >         * notifyAll.
540 >         */
541 >        final void tryAwaitLock(Node[] tab, int i) {
542 >            if (tab != null && i >= 0 && i < tab.length) { // bounds check
543 >                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
544 >                int spins = MAX_SPINS, h;
545 >                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
546 >                    if (spins >= 0) {
547 >                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
548 >                        if (r >= 0 && --spins == 0)
549 >                            Thread.yield();  // yield before block
550 >                    }
551 >                    else if (casHash(h, h | WAITING)) {
552 >                        synchronized (this) {
553 >                            if (tabAt(tab, i) == this &&
554 >                                (hash & WAITING) == WAITING) {
555 >                                try {
556 >                                    wait();
557 >                                } catch (InterruptedException ie) {
558 >                                    Thread.currentThread().interrupt();
559 >                                }
560 >                            }
561 >                            else
562 >                                notifyAll(); // possibly won race vs signaller
563 >                        }
564                          break;
565 +                    }
566                  }
416            } finally {
417                resizing = 0;
567              }
568          }
569 <        else if (table == null)
570 <            Thread.yield(); // lost initialization race; just spin
571 <        return table;
569 >
570 >        // Unsafe mechanics for casHash
571 >        private static final sun.misc.Unsafe UNSAFE;
572 >        private static final long hashOffset;
573 >
574 >        static {
575 >            try {
576 >                UNSAFE = getUnsafe();
577 >                Class<?> k = Node.class;
578 >                hashOffset = UNSAFE.objectFieldOffset
579 >                    (k.getDeclaredField("hash"));
580 >            } catch (Exception e) {
581 >                throw new Error(e);
582 >            }
583 >        }
584 >    }
585 >
586 >    /* ---------------- TreeBins -------------- */
587 >
588 >    /**
589 >     * Nodes for use in TreeBins
590 >     */
591 >    static final class TreeNode extends Node {
592 >        TreeNode parent;  // red-black tree links
593 >        TreeNode left;
594 >        TreeNode right;
595 >        TreeNode prev;    // needed to unlink next upon deletion
596 >        boolean red;
597 >
598 >        TreeNode(int hash, Object key, Object val, Node next, TreeNode parent) {
599 >            super(hash, key, val, next);
600 >            this.parent = parent;
601 >        }
602      }
603  
604      /**
605 <     * Reclassifies nodes in each bin to new table.  Because we are
606 <     * using power-of-two expansion, the elements from each bin must
428 <     * either stay at same index, or move with a power of two
429 <     * offset. We eliminate unnecessary node creation by catching
430 <     * cases where old nodes can be reused because their next fields
431 <     * won't change.  Statistically, only about one-sixth of them need
432 <     * cloning when a table doubles. The nodes they replace will be
433 <     * garbage collectable as soon as they are no longer referenced by
434 <     * any reader thread that may be in the midst of concurrently
435 <     * traversing table.
605 >     * A specialized form of red-black tree for use in bins
606 >     * whose size exceeds a threshold.
607       *
608 <     * Transfers are done from the bottom up to preserve iterator
609 <     * traversability. On each step, the old bin is locked,
610 <     * moved/copied, and then replaced with a forwarding node.
608 >     * TreeBins use a special form of comparison for search and
609 >     * related operations (which is the main reason we cannot use
610 >     * existing collections such as TreeMaps). TreeBins contain
611 >     * Comparable elements, but may contain others, as well as
612 >     * elements that are Comparable but not necessarily Comparable<T>
613 >     * for the same T, so we cannot invoke compareTo among them. To
614 >     * handle this, the tree is ordered primarily by hash value, then
615 >     * by getClass().getName() order, and then by Comparator order
616 >     * among elements of the same class.  On lookup at a node, if
617 >     * elements are not comparable or compare as 0, both left and
618 >     * right children may need to be searched in the case of tied hash
619 >     * values. (This corresponds to the full list search that would be
620 >     * necessary if all elements were non-Comparable and had tied
621 >     * hashes.)  The red-black balancing code is updated from
622 >     * pre-jdk-collections
623 >     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
624 >     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
625 >     * Algorithms" (CLR).
626 >     *
627 >     * TreeBins also maintain a separate locking discipline than
628 >     * regular bins. Because they are forwarded via special MOVED
629 >     * nodes at bin heads (which can never change once established),
630 >     * we cannot use those nodes as locks. Instead, TreeBin
631 >     * extends AbstractQueuedSynchronizer to support a simple form of
632 >     * read-write lock. For update operations and table validation,
633 >     * the exclusive form of lock behaves in the same way as bin-head
634 >     * locks. However, lookups use shared read-lock mechanics to allow
635 >     * multiple readers in the absence of writers.  Additionally,
636 >     * these lookups do not ever block: While the lock is not
637 >     * available, they proceed along the slow traversal path (via
638 >     * next-pointers) until the lock becomes available or the list is
639 >     * exhausted, whichever comes first. (These cases are not fast,
640 >     * but maximize aggregate expected throughput.)  The AQS mechanics
641 >     * for doing this are straightforward.  The lock state is held as
642 >     * AQS getState().  Read counts are negative; the write count (1)
643 >     * is positive.  There are no signalling preferences among readers
644 >     * and writers. Since we don't need to export full Lock API, we
645 >     * just override the minimal AQS methods and use them directly.
646       */
647 <    private static final void transfer(Node[] tab, Node[] nextTab, Node fwd) {
648 <        int n = tab.length;
649 <        Node ignore = nextTab[n + n - 1]; // force bounds check
650 <        for (int i = n - 1; i >= 0; --i) {
651 <            for (Node e;;) {
652 <                if ((e = tabAt(tab, i)) != null) {
653 <                    boolean validated = false;
654 <                    synchronized (e) {
655 <                        if (tabAt(tab, i) == e) {
656 <                            validated = true;
657 <                            Node lo = null, hi = null, lastRun = e;
658 <                            int runBit = e.hash & n;
659 <                            for (Node p = e.next; p != null; p = p.next) {
660 <                                int b = p.hash & n;
661 <                                if (b != runBit) {
662 <                                    runBit = b;
663 <                                    lastRun = p;
647 >    static final class TreeBin extends AbstractQueuedSynchronizer {
648 >        private static final long serialVersionUID = 2249069246763182397L;
649 >        transient TreeNode root;  // root of tree
650 >        transient TreeNode first; // head of next-pointer list
651 >
652 >        /* AQS overrides */
653 >        public final boolean isHeldExclusively() { return getState() > 0; }
654 >        public final boolean tryAcquire(int ignore) {
655 >            if (compareAndSetState(0, 1)) {
656 >                setExclusiveOwnerThread(Thread.currentThread());
657 >                return true;
658 >            }
659 >            return false;
660 >        }
661 >        public final boolean tryRelease(int ignore) {
662 >            setExclusiveOwnerThread(null);
663 >            setState(0);
664 >            return true;
665 >        }
666 >        public final int tryAcquireShared(int ignore) {
667 >            for (int c;;) {
668 >                if ((c = getState()) > 0)
669 >                    return -1;
670 >                if (compareAndSetState(c, c -1))
671 >                    return 1;
672 >            }
673 >        }
674 >        public final boolean tryReleaseShared(int ignore) {
675 >            int c;
676 >            do {} while (!compareAndSetState(c = getState(), c + 1));
677 >            return c == -1;
678 >        }
679 >
680 >        /** From CLR */
681 >        private void rotateLeft(TreeNode p) {
682 >            if (p != null) {
683 >                TreeNode r = p.right, pp, rl;
684 >                if ((rl = p.right = r.left) != null)
685 >                    rl.parent = p;
686 >                if ((pp = r.parent = p.parent) == null)
687 >                    root = r;
688 >                else if (pp.left == p)
689 >                    pp.left = r;
690 >                else
691 >                    pp.right = r;
692 >                r.left = p;
693 >                p.parent = r;
694 >            }
695 >        }
696 >
697 >        /** From CLR */
698 >        private void rotateRight(TreeNode p) {
699 >            if (p != null) {
700 >                TreeNode l = p.left, pp, lr;
701 >                if ((lr = p.left = l.right) != null)
702 >                    lr.parent = p;
703 >                if ((pp = l.parent = p.parent) == null)
704 >                    root = l;
705 >                else if (pp.right == p)
706 >                    pp.right = l;
707 >                else
708 >                    pp.left = l;
709 >                l.right = p;
710 >                p.parent = l;
711 >            }
712 >        }
713 >
714 >        /**
715 >         * Returns the TreeNode (or null if not found) for the given key
716 >         * starting at given root.
717 >         */
718 >        @SuppressWarnings("unchecked") // suppress Comparable cast warning
719 >            final TreeNode getTreeNode(int h, Object k, TreeNode p) {
720 >            Class<?> c = k.getClass();
721 >            while (p != null) {
722 >                int dir, ph;  Object pk; Class<?> pc;
723 >                if ((ph = p.hash) == h) {
724 >                    if ((pk = p.key) == k || k.equals(pk))
725 >                        return p;
726 >                    if (c != (pc = pk.getClass()) ||
727 >                        !(k instanceof Comparable) ||
728 >                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
729 >                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
730 >                        TreeNode r = null, s = null, pl, pr;
731 >                        if (dir >= 0) {
732 >                            if ((pl = p.left) != null && h <= pl.hash)
733 >                                s = pl;
734 >                        }
735 >                        else if ((pr = p.right) != null && h >= pr.hash)
736 >                            s = pr;
737 >                        if (s != null && (r = getTreeNode(h, k, s)) != null)
738 >                            return r;
739 >                    }
740 >                }
741 >                else
742 >                    dir = (h < ph) ? -1 : 1;
743 >                p = (dir > 0) ? p.right : p.left;
744 >            }
745 >            return null;
746 >        }
747 >
748 >        /**
749 >         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
750 >         * read-lock to call getTreeNode, but during failure to get
751 >         * lock, searches along next links.
752 >         */
753 >        final Object getValue(int h, Object k) {
754 >            Node r = null;
755 >            int c = getState(); // Must read lock state first
756 >            for (Node e = first; e != null; e = e.next) {
757 >                if (c <= 0 && compareAndSetState(c, c - 1)) {
758 >                    try {
759 >                        r = getTreeNode(h, k, root);
760 >                    } finally {
761 >                        releaseShared(0);
762 >                    }
763 >                    break;
764 >                }
765 >                else if ((e.hash & HASH_BITS) == h && k.equals(e.key)) {
766 >                    r = e;
767 >                    break;
768 >                }
769 >                else
770 >                    c = getState();
771 >            }
772 >            return r == null ? null : r.val;
773 >        }
774 >
775 >        /**
776 >         * Finds or adds a node.
777 >         * @return null if added
778 >         */
779 >        @SuppressWarnings("unchecked") // suppress Comparable cast warning
780 >            final TreeNode putTreeNode(int h, Object k, Object v) {
781 >            Class<?> c = k.getClass();
782 >            TreeNode pp = root, p = null;
783 >            int dir = 0;
784 >            while (pp != null) { // find existing node or leaf to insert at
785 >                int ph;  Object pk; Class<?> pc;
786 >                p = pp;
787 >                if ((ph = p.hash) == h) {
788 >                    if ((pk = p.key) == k || k.equals(pk))
789 >                        return p;
790 >                    if (c != (pc = pk.getClass()) ||
791 >                        !(k instanceof Comparable) ||
792 >                        (dir = ((Comparable)k).compareTo((Comparable)pk)) == 0) {
793 >                        dir = (c == pc) ? 0 : c.getName().compareTo(pc.getName());
794 >                        TreeNode r = null, s = null, pl, pr;
795 >                        if (dir >= 0) {
796 >                            if ((pl = p.left) != null && h <= pl.hash)
797 >                                s = pl;
798 >                        }
799 >                        else if ((pr = p.right) != null && h >= pr.hash)
800 >                            s = pr;
801 >                        if (s != null && (r = getTreeNode(h, k, s)) != null)
802 >                            return r;
803 >                    }
804 >                }
805 >                else
806 >                    dir = (h < ph) ? -1 : 1;
807 >                pp = (dir > 0) ? p.right : p.left;
808 >            }
809 >
810 >            TreeNode f = first;
811 >            TreeNode x = first = new TreeNode(h, k, v, f, p);
812 >            if (p == null)
813 >                root = x;
814 >            else { // attach and rebalance; adapted from CLR
815 >                TreeNode xp, xpp;
816 >                if (f != null)
817 >                    f.prev = x;
818 >                if (dir <= 0)
819 >                    p.left = x;
820 >                else
821 >                    p.right = x;
822 >                x.red = true;
823 >                while (x != null && (xp = x.parent) != null && xp.red &&
824 >                       (xpp = xp.parent) != null) {
825 >                    TreeNode xppl = xpp.left;
826 >                    if (xp == xppl) {
827 >                        TreeNode y = xpp.right;
828 >                        if (y != null && y.red) {
829 >                            y.red = false;
830 >                            xp.red = false;
831 >                            xpp.red = true;
832 >                            x = xpp;
833 >                        }
834 >                        else {
835 >                            if (x == xp.right) {
836 >                                rotateLeft(x = xp);
837 >                                xpp = (xp = x.parent) == null ? null : xp.parent;
838 >                            }
839 >                            if (xp != null) {
840 >                                xp.red = false;
841 >                                if (xpp != null) {
842 >                                    xpp.red = true;
843 >                                    rotateRight(xpp);
844                                  }
845                              }
846 <                            if (runBit == 0)
847 <                                lo = lastRun;
848 <                            else
849 <                                hi = lastRun;
850 <                            for (Node p = e; p != lastRun; p = p.next) {
851 <                                int ph = p.hash;
852 <                                Object pk = p.key, pv = p.val;
853 <                                if ((ph & n) == 0)
854 <                                    lo = new Node(ph, pk, pv, lo);
855 <                                else
856 <                                    hi = new Node(ph, pk, pv, hi);
846 >                        }
847 >                    }
848 >                    else {
849 >                        TreeNode y = xppl;
850 >                        if (y != null && y.red) {
851 >                            y.red = false;
852 >                            xp.red = false;
853 >                            xpp.red = true;
854 >                            x = xpp;
855 >                        }
856 >                        else {
857 >                            if (x == xp.left) {
858 >                                rotateRight(x = xp);
859 >                                xpp = (xp = x.parent) == null ? null : xp.parent;
860 >                            }
861 >                            if (xp != null) {
862 >                                xp.red = false;
863 >                                if (xpp != null) {
864 >                                    xpp.red = true;
865 >                                    rotateLeft(xpp);
866 >                                }
867                              }
472                            setTabAt(nextTab, i, lo);
473                            setTabAt(nextTab, i + n, hi);
474                            setTabAt(tab, i, fwd);
868                          }
869                      }
870 <                    if (validated)
870 >                }
871 >                TreeNode r = root;
872 >                if (r != null && r.red)
873 >                    r.red = false;
874 >            }
875 >            return null;
876 >        }
877 >
878 >        /**
879 >         * Removes the given node, that must be present before this
880 >         * call.  This is messier than typical red-black deletion code
881 >         * because we cannot swap the contents of an interior node
882 >         * with a leaf successor that is pinned by "next" pointers
883 >         * that are accessible independently of lock. So instead we
884 >         * swap the tree linkages.
885 >         */
886 >        final void deleteTreeNode(TreeNode p) {
887 >            TreeNode next = (TreeNode)p.next; // unlink traversal pointers
888 >            TreeNode pred = p.prev;
889 >            if (pred == null)
890 >                first = next;
891 >            else
892 >                pred.next = next;
893 >            if (next != null)
894 >                next.prev = pred;
895 >            TreeNode replacement;
896 >            TreeNode pl = p.left;
897 >            TreeNode pr = p.right;
898 >            if (pl != null && pr != null) {
899 >                TreeNode s = pr, sl;
900 >                while ((sl = s.left) != null) // find successor
901 >                    s = sl;
902 >                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
903 >                TreeNode sr = s.right;
904 >                TreeNode pp = p.parent;
905 >                if (s == pr) { // p was s's direct parent
906 >                    p.parent = s;
907 >                    s.right = p;
908 >                }
909 >                else {
910 >                    TreeNode sp = s.parent;
911 >                    if ((p.parent = sp) != null) {
912 >                        if (s == sp.left)
913 >                            sp.left = p;
914 >                        else
915 >                            sp.right = p;
916 >                    }
917 >                    if ((s.right = pr) != null)
918 >                        pr.parent = s;
919 >                }
920 >                p.left = null;
921 >                if ((p.right = sr) != null)
922 >                    sr.parent = p;
923 >                if ((s.left = pl) != null)
924 >                    pl.parent = s;
925 >                if ((s.parent = pp) == null)
926 >                    root = s;
927 >                else if (p == pp.left)
928 >                    pp.left = s;
929 >                else
930 >                    pp.right = s;
931 >                replacement = sr;
932 >            }
933 >            else
934 >                replacement = (pl != null) ? pl : pr;
935 >            TreeNode pp = p.parent;
936 >            if (replacement == null) {
937 >                if (pp == null) {
938 >                    root = null;
939 >                    return;
940 >                }
941 >                replacement = p;
942 >            }
943 >            else {
944 >                replacement.parent = pp;
945 >                if (pp == null)
946 >                    root = replacement;
947 >                else if (p == pp.left)
948 >                    pp.left = replacement;
949 >                else
950 >                    pp.right = replacement;
951 >                p.left = p.right = p.parent = null;
952 >            }
953 >            if (!p.red) { // rebalance, from CLR
954 >                TreeNode x = replacement;
955 >                while (x != null) {
956 >                    TreeNode xp, xpl;
957 >                    if (x.red || (xp = x.parent) == null) {
958 >                        x.red = false;
959                          break;
960 +                    }
961 +                    if (x == (xpl = xp.left)) {
962 +                        TreeNode sib = xp.right;
963 +                        if (sib != null && sib.red) {
964 +                            sib.red = false;
965 +                            xp.red = true;
966 +                            rotateLeft(xp);
967 +                            sib = (xp = x.parent) == null ? null : xp.right;
968 +                        }
969 +                        if (sib == null)
970 +                            x = xp;
971 +                        else {
972 +                            TreeNode sl = sib.left, sr = sib.right;
973 +                            if ((sr == null || !sr.red) &&
974 +                                (sl == null || !sl.red)) {
975 +                                sib.red = true;
976 +                                x = xp;
977 +                            }
978 +                            else {
979 +                                if (sr == null || !sr.red) {
980 +                                    if (sl != null)
981 +                                        sl.red = false;
982 +                                    sib.red = true;
983 +                                    rotateRight(sib);
984 +                                    sib = (xp = x.parent) == null ? null : xp.right;
985 +                                }
986 +                                if (sib != null) {
987 +                                    sib.red = (xp == null) ? false : xp.red;
988 +                                    if ((sr = sib.right) != null)
989 +                                        sr.red = false;
990 +                                }
991 +                                if (xp != null) {
992 +                                    xp.red = false;
993 +                                    rotateLeft(xp);
994 +                                }
995 +                                x = root;
996 +                            }
997 +                        }
998 +                    }
999 +                    else { // symmetric
1000 +                        TreeNode sib = xpl;
1001 +                        if (sib != null && sib.red) {
1002 +                            sib.red = false;
1003 +                            xp.red = true;
1004 +                            rotateRight(xp);
1005 +                            sib = (xp = x.parent) == null ? null : xp.left;
1006 +                        }
1007 +                        if (sib == null)
1008 +                            x = xp;
1009 +                        else {
1010 +                            TreeNode sl = sib.left, sr = sib.right;
1011 +                            if ((sl == null || !sl.red) &&
1012 +                                (sr == null || !sr.red)) {
1013 +                                sib.red = true;
1014 +                                x = xp;
1015 +                            }
1016 +                            else {
1017 +                                if (sl == null || !sl.red) {
1018 +                                    if (sr != null)
1019 +                                        sr.red = false;
1020 +                                    sib.red = true;
1021 +                                    rotateLeft(sib);
1022 +                                    sib = (xp = x.parent) == null ? null : xp.left;
1023 +                                }
1024 +                                if (sib != null) {
1025 +                                    sib.red = (xp == null) ? false : xp.red;
1026 +                                    if ((sl = sib.left) != null)
1027 +                                        sl.red = false;
1028 +                                }
1029 +                                if (xp != null) {
1030 +                                    xp.red = false;
1031 +                                    rotateRight(xp);
1032 +                                }
1033 +                                x = root;
1034 +                            }
1035 +                        }
1036 +                    }
1037                  }
1038 <                else if (casTabAt(tab, i, e, fwd))
1039 <                    break;
1038 >            }
1039 >            if (p == replacement && (pp = p.parent) != null) {
1040 >                if (p == pp.left) // detach pointers
1041 >                    pp.left = null;
1042 >                else if (p == pp.right)
1043 >                    pp.right = null;
1044 >                p.parent = null;
1045              }
1046          }
1047      }
1048  
1049 <    /* ---------------- Internal access and update methods -------------- */
1049 >    /* ---------------- Collision reduction methods -------------- */
1050  
1051      /**
1052 <     * Applies a supplemental hash function to a given hashCode, which
1053 <     * defends against poor quality hash functions.  The result must
1054 <     * be non-negative, and for reasonable performance must have good
1055 <     * avalanche properties; i.e., that each bit of the argument
1056 <     * affects each bit (except sign bit) of the result.
1052 >     * Spreads higher bits to lower, and also forces top 2 bits to 0.
1053 >     * Because the table uses power-of-two masking, sets of hashes
1054 >     * that vary only in bits above the current mask will always
1055 >     * collide. (Among known examples are sets of Float keys holding
1056 >     * consecutive whole numbers in small tables.)  To counter this,
1057 >     * we apply a transform that spreads the impact of higher bits
1058 >     * downward. There is a tradeoff between speed, utility, and
1059 >     * quality of bit-spreading. Because many common sets of hashes
1060 >     * are already reasonably distributed across bits (so don't benefit
1061 >     * from spreading), and because we use trees to handle large sets
1062 >     * of collisions in bins, we don't need excessively high quality.
1063       */
1064      private static final int spread(int h) {
1065 <        // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
1066 <        h ^= h >>> 16;
1067 <        h *= 0x85ebca6b;
1068 <        h ^= h >>> 13;
1069 <        h *= 0xc2b2ae35;
1070 <        return (h >>> 16) ^ (h & 0x7fffffff); // mask out sign bit
1065 >        h ^= (h >>> 18) ^ (h >>> 12);
1066 >        return (h ^ (h >>> 10)) & HASH_BITS;
1067 >    }
1068 >
1069 >    /**
1070 >     * Replaces a list bin with a tree bin. Call only when locked.
1071 >     * Fails to replace if the given key is non-comparable or table
1072 >     * is, or needs, resizing.
1073 >     */
1074 >    private final void replaceWithTreeBin(Node[] tab, int index, Object key) {
1075 >        if ((key instanceof Comparable) &&
1076 >            (tab.length >= MAXIMUM_CAPACITY || counter.sum() < (long)sizeCtl)) {
1077 >            TreeBin t = new TreeBin();
1078 >            for (Node e = tabAt(tab, index); e != null; e = e.next)
1079 >                t.putTreeNode(e.hash & HASH_BITS, e.key, e.val);
1080 >            setTabAt(tab, index, new Node(MOVED, t, null, null));
1081 >        }
1082      }
1083  
1084 +    /* ---------------- Internal access and update methods -------------- */
1085 +
1086      /** Implementation for get and containsKey */
1087      private final Object internalGet(Object k) {
1088          int h = spread(k.hashCode());
1089          retry: for (Node[] tab = table; tab != null;) {
1090 <            Node e; Object ek, ev; int eh;  // locals to read fields once
1090 >            Node e, p; Object ek, ev; int eh;      // locals to read fields once
1091              for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
1092 <                if ((eh = e.hash) == h) {
1093 <                    if ((ev = e.val) != null &&
1094 <                        ((ek = e.key) == k || k.equals(ek)))
1095 <                        return ev;
1096 <                }
1097 <                else if (eh < 0) {          // sign bit set
1098 <                    tab = (Node[])e.key;    // bin was moved during resize
517 <                    continue retry;
1092 >                if ((eh = e.hash) == MOVED) {
1093 >                    if ((ek = e.key) instanceof TreeBin)  // search TreeBin
1094 >                        return ((TreeBin)ek).getValue(h, k);
1095 >                    else {                        // restart with new table
1096 >                        tab = (Node[])ek;
1097 >                        continue retry;
1098 >                    }
1099                  }
1100 +                else if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
1101 +                         ((ek = e.key) == k || k.equals(ek)))
1102 +                    return ev;
1103              }
1104              break;
1105          }
1106          return null;
1107      }
1108  
1109 <    /** Implementation for put and putIfAbsent */
1110 <    private final Object internalPut(Object k, Object v, boolean replace) {
1109 >    /**
1110 >     * Implementation for the four public remove/replace methods:
1111 >     * Replaces node value with v, conditional upon match of cv if
1112 >     * non-null.  If resulting value is null, delete.
1113 >     */
1114 >    private final Object internalReplace(Object k, Object v, Object cv) {
1115          int h = spread(k.hashCode());
1116 <        Object oldVal = null;               // previous value or null if none
1116 >        Object oldVal = null;
1117          for (Node[] tab = table;;) {
1118 <            Node e; int i; Object ek, ev;
1118 >            Node f; int i, fh; Object fk;
1119 >            if (tab == null ||
1120 >                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
1121 >                break;
1122 >            else if ((fh = f.hash) == MOVED) {
1123 >                if ((fk = f.key) instanceof TreeBin) {
1124 >                    TreeBin t = (TreeBin)fk;
1125 >                    boolean validated = false;
1126 >                    boolean deleted = false;
1127 >                    t.acquire(0);
1128 >                    try {
1129 >                        if (tabAt(tab, i) == f) {
1130 >                            validated = true;
1131 >                            TreeNode p = t.getTreeNode(h, k, t.root);
1132 >                            if (p != null) {
1133 >                                Object pv = p.val;
1134 >                                if (cv == null || cv == pv || cv.equals(pv)) {
1135 >                                    oldVal = pv;
1136 >                                    if ((p.val = v) == null) {
1137 >                                        deleted = true;
1138 >                                        t.deleteTreeNode(p);
1139 >                                    }
1140 >                                }
1141 >                            }
1142 >                        }
1143 >                    } finally {
1144 >                        t.release(0);
1145 >                    }
1146 >                    if (validated) {
1147 >                        if (deleted)
1148 >                            counter.add(-1L);
1149 >                        break;
1150 >                    }
1151 >                }
1152 >                else
1153 >                    tab = (Node[])fk;
1154 >            }
1155 >            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
1156 >                break;                          // rules out possible existence
1157 >            else if ((fh & LOCKED) != 0) {
1158 >                checkForResize();               // try resizing if can't get lock
1159 >                f.tryAwaitLock(tab, i);
1160 >            }
1161 >            else if (f.casHash(fh, fh | LOCKED)) {
1162 >                boolean validated = false;
1163 >                boolean deleted = false;
1164 >                try {
1165 >                    if (tabAt(tab, i) == f) {
1166 >                        validated = true;
1167 >                        for (Node e = f, pred = null;;) {
1168 >                            Object ek, ev;
1169 >                            if ((e.hash & HASH_BITS) == h &&
1170 >                                ((ev = e.val) != null) &&
1171 >                                ((ek = e.key) == k || k.equals(ek))) {
1172 >                                if (cv == null || cv == ev || cv.equals(ev)) {
1173 >                                    oldVal = ev;
1174 >                                    if ((e.val = v) == null) {
1175 >                                        deleted = true;
1176 >                                        Node en = e.next;
1177 >                                        if (pred != null)
1178 >                                            pred.next = en;
1179 >                                        else
1180 >                                            setTabAt(tab, i, en);
1181 >                                    }
1182 >                                }
1183 >                                break;
1184 >                            }
1185 >                            pred = e;
1186 >                            if ((e = e.next) == null)
1187 >                                break;
1188 >                        }
1189 >                    }
1190 >                } finally {
1191 >                    if (!f.casHash(fh | LOCKED, fh)) {
1192 >                        f.hash = fh;
1193 >                        synchronized (f) { f.notifyAll(); };
1194 >                    }
1195 >                }
1196 >                if (validated) {
1197 >                    if (deleted)
1198 >                        counter.add(-1L);
1199 >                    break;
1200 >                }
1201 >            }
1202 >        }
1203 >        return oldVal;
1204 >    }
1205 >
1206 >    /*
1207 >     * Internal versions of the five insertion methods, each a
1208 >     * little more complicated than the last. All have
1209 >     * the same basic structure as the first (internalPut):
1210 >     *  1. If table uninitialized, create
1211 >     *  2. If bin empty, try to CAS new node
1212 >     *  3. If bin stale, use new table
1213 >     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
1214 >     *  5. Lock and validate; if valid, scan and add or update
1215 >     *
1216 >     * The others interweave other checks and/or alternative actions:
1217 >     *  * Plain put checks for and performs resize after insertion.
1218 >     *  * putIfAbsent prescans for mapping without lock (and fails to add
1219 >     *    if present), which also makes pre-emptive resize checks worthwhile.
1220 >     *  * computeIfAbsent extends form used in putIfAbsent with additional
1221 >     *    mechanics to deal with, calls, potential exceptions and null
1222 >     *    returns from function call.
1223 >     *  * compute uses the same function-call mechanics, but without
1224 >     *    the prescans
1225 >     *  * putAll attempts to pre-allocate enough table space
1226 >     *    and more lazily performs count updates and checks.
1227 >     *
1228 >     * Someday when details settle down a bit more, it might be worth
1229 >     * some factoring to reduce sprawl.
1230 >     */
1231 >
1232 >    /** Implementation for put */
1233 >    private final Object internalPut(Object k, Object v) {
1234 >        int h = spread(k.hashCode());
1235 >        int count = 0;
1236 >        for (Node[] tab = table;;) {
1237 >            int i; Node f; int fh; Object fk;
1238              if (tab == null)
1239 <                tab = growTable();
1240 <            else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1239 >                tab = initTable();
1240 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1241                  if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1242                      break;                   // no lock when adding to empty bin
1243              }
1244 <            else if (e.hash < 0)             // resized -- restart with new table
1245 <                tab = (Node[])e.key;
1246 <            else if (!replace && e.hash == h && (ev = e.val) != null &&
1247 <                     ((ek = e.key) == k || k.equals(ek))) {
1248 <                if (tabAt(tab, i) == e) {    // inspect and validate 1st node
1249 <                    oldVal = ev;             // without lock for putIfAbsent
1250 <                    break;
1244 >            else if ((fh = f.hash) == MOVED) {
1245 >                if ((fk = f.key) instanceof TreeBin) {
1246 >                    TreeBin t = (TreeBin)fk;
1247 >                    Object oldVal = null;
1248 >                    t.acquire(0);
1249 >                    try {
1250 >                        if (tabAt(tab, i) == f) {
1251 >                            count = 2;
1252 >                            TreeNode p = t.putTreeNode(h, k, v);
1253 >                            if (p != null) {
1254 >                                oldVal = p.val;
1255 >                                p.val = v;
1256 >                            }
1257 >                        }
1258 >                    } finally {
1259 >                        t.release(0);
1260 >                    }
1261 >                    if (count != 0) {
1262 >                        if (oldVal != null)
1263 >                            return oldVal;
1264 >                        break;
1265 >                    }
1266                  }
1267 +                else
1268 +                    tab = (Node[])fk;
1269              }
1270 <            else {
1271 <                boolean validated = false;
1272 <                boolean checkSize = false;
1273 <                synchronized (e) {           // lock the 1st node of bin list
1274 <                    if (tabAt(tab, i) == e) {
1275 <                        validated = true;    // retry if 1st already deleted
1276 <                        for (Node first = e;;) {
1277 <                            if (e.hash == h &&
1278 <                                ((ek = e.key) == k || k.equals(ek)) &&
1279 <                                (ev = e.val) != null) {
1270 >            else if ((fh & LOCKED) != 0) {
1271 >                checkForResize();
1272 >                f.tryAwaitLock(tab, i);
1273 >            }
1274 >            else if (f.casHash(fh, fh | LOCKED)) {
1275 >                Object oldVal = null;
1276 >                try {                        // needed in case equals() throws
1277 >                    if (tabAt(tab, i) == f) {
1278 >                        count = 1;
1279 >                        for (Node e = f;; ++count) {
1280 >                            Object ek, ev;
1281 >                            if ((e.hash & HASH_BITS) == h &&
1282 >                                (ev = e.val) != null &&
1283 >                                ((ek = e.key) == k || k.equals(ek))) {
1284                                  oldVal = ev;
1285 <                                if (replace)
558 <                                    e.val = v;
1285 >                                e.val = v;
1286                                  break;
1287                              }
1288                              Node last = e;
1289                              if ((e = e.next) == null) {
1290                                  last.next = new Node(h, k, v, null);
1291 <                                if (last != first || tab.length <= 64)
1292 <                                    checkSize = true;
1291 >                                if (count >= TREE_THRESHOLD)
1292 >                                    replaceWithTreeBin(tab, i, k);
1293                                  break;
1294                              }
1295                          }
1296                      }
1297 +                } finally {                  // unlock and signal if needed
1298 +                    if (!f.casHash(fh | LOCKED, fh)) {
1299 +                        f.hash = fh;
1300 +                        synchronized (f) { f.notifyAll(); };
1301 +                    }
1302                  }
1303 <                if (validated) {
1304 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
1305 <                        resizing == 0 && counter.sum() >= (long)threshold)
1306 <                        growTable();
1303 >                if (count != 0) {
1304 >                    if (oldVal != null)
1305 >                        return oldVal;
1306 >                    if (tab.length <= 64)
1307 >                        count = 2;
1308                      break;
1309                  }
1310              }
1311          }
1312 <        if (oldVal == null)
1313 <            counter.increment();             // update counter outside of locks
1314 <        return oldVal;
1312 >        counter.add(1L);
1313 >        if (count > 1)
1314 >            checkForResize();
1315 >        return null;
1316      }
1317  
1318 <    /**
1319 <     * Implementation for the four public remove/replace methods:
586 <     * Replaces node value with v, conditional upon match of cv if
587 <     * non-null.  If resulting value is null, delete.
588 <     */
589 <    private final Object internalReplace(Object k, Object v, Object cv) {
1318 >    /** Implementation for putIfAbsent */
1319 >    private final Object internalPutIfAbsent(Object k, Object v) {
1320          int h = spread(k.hashCode());
1321 +        int count = 0;
1322          for (Node[] tab = table;;) {
1323 <            Node e; int i;
1324 <            if (tab == null ||
1325 <                (e = tabAt(tab, i = (tab.length - 1) & h)) == null)
1326 <                return null;
1327 <            else if (e.hash < 0)
1328 <                tab = (Node[])e.key;
1323 >            int i; Node f; int fh; Object fk, fv;
1324 >            if (tab == null)
1325 >                tab = initTable();
1326 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1327 >                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
1328 >                    break;
1329 >            }
1330 >            else if ((fh = f.hash) == MOVED) {
1331 >                if ((fk = f.key) instanceof TreeBin) {
1332 >                    TreeBin t = (TreeBin)fk;
1333 >                    Object oldVal = null;
1334 >                    t.acquire(0);
1335 >                    try {
1336 >                        if (tabAt(tab, i) == f) {
1337 >                            count = 2;
1338 >                            TreeNode p = t.putTreeNode(h, k, v);
1339 >                            if (p != null)
1340 >                                oldVal = p.val;
1341 >                        }
1342 >                    } finally {
1343 >                        t.release(0);
1344 >                    }
1345 >                    if (count != 0) {
1346 >                        if (oldVal != null)
1347 >                            return oldVal;
1348 >                        break;
1349 >                    }
1350 >                }
1351 >                else
1352 >                    tab = (Node[])fk;
1353 >            }
1354 >            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1355 >                     ((fk = f.key) == k || k.equals(fk)))
1356 >                return fv;
1357              else {
1358 <                Object oldVal = null;
1359 <                boolean validated = false;
1360 <                boolean deleted = false;
1361 <                synchronized (e) {
1362 <                    if (tabAt(tab, i) == e) {
1363 <                        validated = true;
1364 <                        Node pred = null;
1365 <                        do {
1366 <                            Object ek, ev;
1367 <                            if (e.hash == h &&
1368 <                                ((ek = e.key) == k || k.equals(ek)) &&
1369 <                                ((ev = e.val) != null)) {
1370 <                                if (cv == null || cv == ev || cv.equals(ev)) {
1358 >                Node g = f.next;
1359 >                if (g != null) { // at least 2 nodes -- search and maybe resize
1360 >                    for (Node e = g;;) {
1361 >                        Object ek, ev;
1362 >                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1363 >                            ((ek = e.key) == k || k.equals(ek)))
1364 >                            return ev;
1365 >                        if ((e = e.next) == null) {
1366 >                            checkForResize();
1367 >                            break;
1368 >                        }
1369 >                    }
1370 >                }
1371 >                if (((fh = f.hash) & LOCKED) != 0) {
1372 >                    checkForResize();
1373 >                    f.tryAwaitLock(tab, i);
1374 >                }
1375 >                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1376 >                    Object oldVal = null;
1377 >                    try {
1378 >                        if (tabAt(tab, i) == f) {
1379 >                            count = 1;
1380 >                            for (Node e = f;; ++count) {
1381 >                                Object ek, ev;
1382 >                                if ((e.hash & HASH_BITS) == h &&
1383 >                                    (ev = e.val) != null &&
1384 >                                    ((ek = e.key) == k || k.equals(ek))) {
1385                                      oldVal = ev;
1386 <                                    if ((e.val = v) == null) {
1387 <                                        deleted = true;
1388 <                                        Node en = e.next;
1389 <                                        if (pred != null)
1390 <                                            pred.next = en;
1391 <                                        else
1392 <                                            setTabAt(tab, i, en);
1393 <                                    }
1386 >                                    break;
1387 >                                }
1388 >                                Node last = e;
1389 >                                if ((e = e.next) == null) {
1390 >                                    last.next = new Node(h, k, v, null);
1391 >                                    if (count >= TREE_THRESHOLD)
1392 >                                        replaceWithTreeBin(tab, i, k);
1393 >                                    break;
1394                                  }
622                                break;
1395                              }
1396 <                        } while ((e = (pred = e).next) != null);
1396 >                        }
1397 >                    } finally {
1398 >                        if (!f.casHash(fh | LOCKED, fh)) {
1399 >                            f.hash = fh;
1400 >                            synchronized (f) { f.notifyAll(); };
1401 >                        }
1402 >                    }
1403 >                    if (count != 0) {
1404 >                        if (oldVal != null)
1405 >                            return oldVal;
1406 >                        if (tab.length <= 64)
1407 >                            count = 2;
1408 >                        break;
1409                      }
1410                  }
1411 <                if (validated) {
1412 <                    if (deleted)
1413 <                        counter.decrement();
1414 <                    return oldVal;
1411 >            }
1412 >        }
1413 >        counter.add(1L);
1414 >        if (count > 1)
1415 >            checkForResize();
1416 >        return null;
1417 >    }
1418 >
1419 >    /** Implementation for computeIfAbsent */
1420 >    private final Object internalComputeIfAbsent(K k,
1421 >                                                 Fun<? super K, ?> mf) {
1422 >        int h = spread(k.hashCode());
1423 >        Object val = null;
1424 >        int count = 0;
1425 >        for (Node[] tab = table;;) {
1426 >            Node f; int i, fh; Object fk, fv;
1427 >            if (tab == null)
1428 >                tab = initTable();
1429 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1430 >                Node node = new Node(fh = h | LOCKED, k, null, null);
1431 >                if (casTabAt(tab, i, null, node)) {
1432 >                    count = 1;
1433 >                    try {
1434 >                        if ((val = mf.apply(k)) != null)
1435 >                            node.val = val;
1436 >                    } finally {
1437 >                        if (val == null)
1438 >                            setTabAt(tab, i, null);
1439 >                        if (!node.casHash(fh, h)) {
1440 >                            node.hash = h;
1441 >                            synchronized (node) { node.notifyAll(); };
1442 >                        }
1443 >                    }
1444 >                }
1445 >                if (count != 0)
1446 >                    break;
1447 >            }
1448 >            else if ((fh = f.hash) == MOVED) {
1449 >                if ((fk = f.key) instanceof TreeBin) {
1450 >                    TreeBin t = (TreeBin)fk;
1451 >                    boolean added = false;
1452 >                    t.acquire(0);
1453 >                    try {
1454 >                        if (tabAt(tab, i) == f) {
1455 >                            count = 1;
1456 >                            TreeNode p = t.getTreeNode(h, k, t.root);
1457 >                            if (p != null)
1458 >                                val = p.val;
1459 >                            else if ((val = mf.apply(k)) != null) {
1460 >                                added = true;
1461 >                                count = 2;
1462 >                                t.putTreeNode(h, k, val);
1463 >                            }
1464 >                        }
1465 >                    } finally {
1466 >                        t.release(0);
1467 >                    }
1468 >                    if (count != 0) {
1469 >                        if (!added)
1470 >                            return val;
1471 >                        break;
1472 >                    }
1473                  }
1474 +                else
1475 +                    tab = (Node[])fk;
1476              }
1477 +            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
1478 +                     ((fk = f.key) == k || k.equals(fk)))
1479 +                return fv;
1480 +            else {
1481 +                Node g = f.next;
1482 +                if (g != null) {
1483 +                    for (Node e = g;;) {
1484 +                        Object ek, ev;
1485 +                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
1486 +                            ((ek = e.key) == k || k.equals(ek)))
1487 +                            return ev;
1488 +                        if ((e = e.next) == null) {
1489 +                            checkForResize();
1490 +                            break;
1491 +                        }
1492 +                    }
1493 +                }
1494 +                if (((fh = f.hash) & LOCKED) != 0) {
1495 +                    checkForResize();
1496 +                    f.tryAwaitLock(tab, i);
1497 +                }
1498 +                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
1499 +                    boolean added = false;
1500 +                    try {
1501 +                        if (tabAt(tab, i) == f) {
1502 +                            count = 1;
1503 +                            for (Node e = f;; ++count) {
1504 +                                Object ek, ev;
1505 +                                if ((e.hash & HASH_BITS) == h &&
1506 +                                    (ev = e.val) != null &&
1507 +                                    ((ek = e.key) == k || k.equals(ek))) {
1508 +                                    val = ev;
1509 +                                    break;
1510 +                                }
1511 +                                Node last = e;
1512 +                                if ((e = e.next) == null) {
1513 +                                    if ((val = mf.apply(k)) != null) {
1514 +                                        added = true;
1515 +                                        last.next = new Node(h, k, val, null);
1516 +                                        if (count >= TREE_THRESHOLD)
1517 +                                            replaceWithTreeBin(tab, i, k);
1518 +                                    }
1519 +                                    break;
1520 +                                }
1521 +                            }
1522 +                        }
1523 +                    } finally {
1524 +                        if (!f.casHash(fh | LOCKED, fh)) {
1525 +                            f.hash = fh;
1526 +                            synchronized (f) { f.notifyAll(); };
1527 +                        }
1528 +                    }
1529 +                    if (count != 0) {
1530 +                        if (!added)
1531 +                            return val;
1532 +                        if (tab.length <= 64)
1533 +                            count = 2;
1534 +                        break;
1535 +                    }
1536 +                }
1537 +            }
1538 +        }
1539 +        if (val != null) {
1540 +            counter.add(1L);
1541 +            if (count > 1)
1542 +                checkForResize();
1543          }
1544 +        return val;
1545      }
1546  
1547 <    /** Implementation for computeIfAbsent and compute. Like put, but messier. */
1547 >    /** Implementation for compute */
1548      @SuppressWarnings("unchecked")
1549 <    private final V internalCompute(K k,
1550 <                                    MappingFunction<? super K, ? extends V> f,
640 <                                    boolean replace) {
1549 >        private final Object internalCompute(K k, boolean onlyIfPresent,
1550 >                                             BiFun<? super K, ? super V, ? extends V> mf) {
1551          int h = spread(k.hashCode());
1552 <        V val = null;
1553 <        boolean added = false;
1554 <        Node[] tab = table;
1555 <        outer:for (;;) {
1556 <            Node e; int i; Object ek, ev;
1552 >        Object val = null;
1553 >        int delta = 0;
1554 >        int count = 0;
1555 >        for (Node[] tab = table;;) {
1556 >            Node f; int i, fh; Object fk;
1557              if (tab == null)
1558 <                tab = growTable();
1559 <            else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1560 <                Node node = new Node(h, k, null, null);
1561 <                boolean validated = false;
1562 <                synchronized (node) {  // must lock while computing value
1563 <                    if (casTabAt(tab, i, null, node)) {
1564 <                        validated = true;
1565 <                        try {
1566 <                            val = f.map(k);
1567 <                            if (val != null) {
1568 <                                node.val = val;
1569 <                                added = true;
1558 >                tab = initTable();
1559 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1560 >                if (onlyIfPresent)
1561 >                    break;
1562 >                Node node = new Node(fh = h | LOCKED, k, null, null);
1563 >                if (casTabAt(tab, i, null, node)) {
1564 >                    try {
1565 >                        count = 1;
1566 >                        if ((val = mf.apply(k, null)) != null) {
1567 >                            node.val = val;
1568 >                            delta = 1;
1569 >                        }
1570 >                    } finally {
1571 >                        if (delta == 0)
1572 >                            setTabAt(tab, i, null);
1573 >                        if (!node.casHash(fh, h)) {
1574 >                            node.hash = h;
1575 >                            synchronized (node) { node.notifyAll(); };
1576 >                        }
1577 >                    }
1578 >                }
1579 >                if (count != 0)
1580 >                    break;
1581 >            }
1582 >            else if ((fh = f.hash) == MOVED) {
1583 >                if ((fk = f.key) instanceof TreeBin) {
1584 >                    TreeBin t = (TreeBin)fk;
1585 >                    t.acquire(0);
1586 >                    try {
1587 >                        if (tabAt(tab, i) == f) {
1588 >                            count = 1;
1589 >                            TreeNode p = t.getTreeNode(h, k, t.root);
1590 >                            Object pv = (p == null) ? null : p.val;
1591 >                            if ((val = mf.apply(k, (V)pv)) != null) {
1592 >                                if (p != null)
1593 >                                    p.val = val;
1594 >                                else {
1595 >                                    count = 2;
1596 >                                    delta = 1;
1597 >                                    t.putTreeNode(h, k, val);
1598 >                                }
1599 >                            }
1600 >                            else if (p != null) {
1601 >                                delta = -1;
1602 >                                t.deleteTreeNode(p);
1603                              }
661                        } finally {
662                            if (!added)
663                                setTabAt(tab, i, null);
1604                          }
1605 +                    } finally {
1606 +                        t.release(0);
1607                      }
1608 +                    if (count != 0)
1609 +                        break;
1610                  }
1611 <                if (validated)
1611 >                else
1612 >                    tab = (Node[])fk;
1613 >            }
1614 >            else if ((fh & LOCKED) != 0) {
1615 >                checkForResize();
1616 >                f.tryAwaitLock(tab, i);
1617 >            }
1618 >            else if (f.casHash(fh, fh | LOCKED)) {
1619 >                try {
1620 >                    if (tabAt(tab, i) == f) {
1621 >                        count = 1;
1622 >                        for (Node e = f, pred = null;; ++count) {
1623 >                            Object ek, ev;
1624 >                            if ((e.hash & HASH_BITS) == h &&
1625 >                                (ev = e.val) != null &&
1626 >                                ((ek = e.key) == k || k.equals(ek))) {
1627 >                                val = mf.apply(k, (V)ev);
1628 >                                if (val != null)
1629 >                                    e.val = val;
1630 >                                else {
1631 >                                    delta = -1;
1632 >                                    Node en = e.next;
1633 >                                    if (pred != null)
1634 >                                        pred.next = en;
1635 >                                    else
1636 >                                        setTabAt(tab, i, en);
1637 >                                }
1638 >                                break;
1639 >                            }
1640 >                            pred = e;
1641 >                            if ((e = e.next) == null) {
1642 >                                if (!onlyIfPresent && (val = mf.apply(k, null)) != null) {
1643 >                                    pred.next = new Node(h, k, val, null);
1644 >                                    delta = 1;
1645 >                                    if (count >= TREE_THRESHOLD)
1646 >                                        replaceWithTreeBin(tab, i, k);
1647 >                                }
1648 >                                break;
1649 >                            }
1650 >                        }
1651 >                    }
1652 >                } finally {
1653 >                    if (!f.casHash(fh | LOCKED, fh)) {
1654 >                        f.hash = fh;
1655 >                        synchronized (f) { f.notifyAll(); };
1656 >                    }
1657 >                }
1658 >                if (count != 0) {
1659 >                    if (tab.length <= 64)
1660 >                        count = 2;
1661                      break;
1662 +                }
1663              }
1664 <            else if (e.hash < 0)
1665 <                tab = (Node[])e.key;
1666 <            else if (!replace && e.hash == h && (ev = e.val) != null &&
1667 <                     ((ek = e.key) == k || k.equals(ek))) {
1668 <                if (tabAt(tab, i) == e) {
1669 <                    val = (V)ev;
1664 >        }
1665 >        if (delta != 0) {
1666 >            counter.add((long)delta);
1667 >            if (count > 1)
1668 >                checkForResize();
1669 >        }
1670 >        return val;
1671 >    }
1672 >
1673 >    private final Object internalMerge(K k, V v,
1674 >                                       BiFun<? super V, ? super V, ? extends V> mf) {
1675 >        int h = spread(k.hashCode());
1676 >        Object val = null;
1677 >        int delta = 0;
1678 >        int count = 0;
1679 >        for (Node[] tab = table;;) {
1680 >            int i; Node f; int fh; Object fk, fv;
1681 >            if (tab == null)
1682 >                tab = initTable();
1683 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
1684 >                if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1685 >                    delta = 1;
1686 >                    val = v;
1687                      break;
1688                  }
1689              }
1690 <            else if (Thread.holdsLock(e))
1691 <                throw new IllegalStateException("Recursive map computation");
1692 <            else {
1693 <                boolean validated = false;
1694 <                boolean checkSize = false;
1695 <                synchronized (e) {
1696 <                    if (tabAt(tab, i) == e) {
1697 <                        validated = true;
1698 <                        for (Node first = e;;) {
1699 <                            if (e.hash == h &&
1700 <                                ((ek = e.key) == k || k.equals(ek)) &&
1701 <                                ((ev = e.val) != null)) {
1702 <                                Object fv;
1703 <                                if (replace && (fv = f.map(k)) != null)
1704 <                                    ev = e.val = fv;
1705 <                                val = (V)ev;
1690 >            else if ((fh = f.hash) == MOVED) {
1691 >                if ((fk = f.key) instanceof TreeBin) {
1692 >                    TreeBin t = (TreeBin)fk;
1693 >                    t.acquire(0);
1694 >                    try {
1695 >                        if (tabAt(tab, i) == f) {
1696 >                            count = 1;
1697 >                            TreeNode p = t.getTreeNode(h, k, t.root);
1698 >                            val = (p == null) ? v : mf.apply((V)p.val, v);
1699 >                            if (val != null) {
1700 >                                if (p != null)
1701 >                                    p.val = val;
1702 >                                else {
1703 >                                    count = 2;
1704 >                                    delta = 1;
1705 >                                    t.putTreeNode(h, k, val);
1706 >                                }
1707 >                            }
1708 >                            else if (p != null) {
1709 >                                delta = -1;
1710 >                                t.deleteTreeNode(p);
1711 >                            }
1712 >                        }
1713 >                    } finally {
1714 >                        t.release(0);
1715 >                    }
1716 >                    if (count != 0)
1717 >                        break;
1718 >                }
1719 >                else
1720 >                    tab = (Node[])fk;
1721 >            }
1722 >            else if ((fh & LOCKED) != 0) {
1723 >                checkForResize();
1724 >                f.tryAwaitLock(tab, i);
1725 >            }
1726 >            else if (f.casHash(fh, fh | LOCKED)) {
1727 >                try {
1728 >                    if (tabAt(tab, i) == f) {
1729 >                        count = 1;
1730 >                        for (Node e = f, pred = null;; ++count) {
1731 >                            Object ek, ev;
1732 >                            if ((e.hash & HASH_BITS) == h &&
1733 >                                (ev = e.val) != null &&
1734 >                                ((ek = e.key) == k || k.equals(ek))) {
1735 >                                val = mf.apply(v, (V)ev);
1736 >                                if (val != null)
1737 >                                    e.val = val;
1738 >                                else {
1739 >                                    delta = -1;
1740 >                                    Node en = e.next;
1741 >                                    if (pred != null)
1742 >                                        pred.next = en;
1743 >                                    else
1744 >                                        setTabAt(tab, i, en);
1745 >                                }
1746                                  break;
1747                              }
1748 <                            Node last = e;
1748 >                            pred = e;
1749                              if ((e = e.next) == null) {
1750 <                                if ((val = f.map(k)) != null) {
1751 <                                    last.next = new Node(h, k, val, null);
1752 <                                    added = true;
1753 <                                    if (last != first || tab.length <= 64)
1754 <                                        checkSize = true;
704 <                                }
1750 >                                val = v;
1751 >                                pred.next = new Node(h, k, val, null);
1752 >                                delta = 1;
1753 >                                if (count >= TREE_THRESHOLD)
1754 >                                    replaceWithTreeBin(tab, i, k);
1755                                  break;
1756                              }
1757                          }
1758                      }
1759 +                } finally {
1760 +                    if (!f.casHash(fh | LOCKED, fh)) {
1761 +                        f.hash = fh;
1762 +                        synchronized (f) { f.notifyAll(); };
1763 +                    }
1764                  }
1765 <                if (validated) {
1766 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
1767 <                        resizing == 0 && counter.sum() >= (long)threshold)
713 <                        growTable();
1765 >                if (count != 0) {
1766 >                    if (tab.length <= 64)
1767 >                        count = 2;
1768                      break;
1769                  }
1770              }
1771          }
1772 <        if (added)
1773 <            counter.increment();
1772 >        if (delta != 0) {
1773 >            counter.add((long)delta);
1774 >            if (count > 1)
1775 >                checkForResize();
1776 >        }
1777          return val;
1778      }
1779  
1780 +    /** Implementation for putAll */
1781 +    private final void internalPutAll(Map<?, ?> m) {
1782 +        tryPresize(m.size());
1783 +        long delta = 0L;     // number of uncommitted additions
1784 +        boolean npe = false; // to throw exception on exit for nulls
1785 +        try {                // to clean up counts on other exceptions
1786 +            for (Map.Entry<?, ?> entry : m.entrySet()) {
1787 +                Object k, v;
1788 +                if (entry == null || (k = entry.getKey()) == null ||
1789 +                    (v = entry.getValue()) == null) {
1790 +                    npe = true;
1791 +                    break;
1792 +                }
1793 +                int h = spread(k.hashCode());
1794 +                for (Node[] tab = table;;) {
1795 +                    int i; Node f; int fh; Object fk;
1796 +                    if (tab == null)
1797 +                        tab = initTable();
1798 +                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
1799 +                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
1800 +                            ++delta;
1801 +                            break;
1802 +                        }
1803 +                    }
1804 +                    else if ((fh = f.hash) == MOVED) {
1805 +                        if ((fk = f.key) instanceof TreeBin) {
1806 +                            TreeBin t = (TreeBin)fk;
1807 +                            boolean validated = false;
1808 +                            t.acquire(0);
1809 +                            try {
1810 +                                if (tabAt(tab, i) == f) {
1811 +                                    validated = true;
1812 +                                    TreeNode p = t.getTreeNode(h, k, t.root);
1813 +                                    if (p != null)
1814 +                                        p.val = v;
1815 +                                    else {
1816 +                                        t.putTreeNode(h, k, v);
1817 +                                        ++delta;
1818 +                                    }
1819 +                                }
1820 +                            } finally {
1821 +                                t.release(0);
1822 +                            }
1823 +                            if (validated)
1824 +                                break;
1825 +                        }
1826 +                        else
1827 +                            tab = (Node[])fk;
1828 +                    }
1829 +                    else if ((fh & LOCKED) != 0) {
1830 +                        counter.add(delta);
1831 +                        delta = 0L;
1832 +                        checkForResize();
1833 +                        f.tryAwaitLock(tab, i);
1834 +                    }
1835 +                    else if (f.casHash(fh, fh | LOCKED)) {
1836 +                        int count = 0;
1837 +                        try {
1838 +                            if (tabAt(tab, i) == f) {
1839 +                                count = 1;
1840 +                                for (Node e = f;; ++count) {
1841 +                                    Object ek, ev;
1842 +                                    if ((e.hash & HASH_BITS) == h &&
1843 +                                        (ev = e.val) != null &&
1844 +                                        ((ek = e.key) == k || k.equals(ek))) {
1845 +                                        e.val = v;
1846 +                                        break;
1847 +                                    }
1848 +                                    Node last = e;
1849 +                                    if ((e = e.next) == null) {
1850 +                                        ++delta;
1851 +                                        last.next = new Node(h, k, v, null);
1852 +                                        if (count >= TREE_THRESHOLD)
1853 +                                            replaceWithTreeBin(tab, i, k);
1854 +                                        break;
1855 +                                    }
1856 +                                }
1857 +                            }
1858 +                        } finally {
1859 +                            if (!f.casHash(fh | LOCKED, fh)) {
1860 +                                f.hash = fh;
1861 +                                synchronized (f) { f.notifyAll(); };
1862 +                            }
1863 +                        }
1864 +                        if (count != 0) {
1865 +                            if (count > 1) {
1866 +                                counter.add(delta);
1867 +                                delta = 0L;
1868 +                                checkForResize();
1869 +                            }
1870 +                            break;
1871 +                        }
1872 +                    }
1873 +                }
1874 +            }
1875 +        } finally {
1876 +            if (delta != 0)
1877 +                counter.add(delta);
1878 +        }
1879 +        if (npe)
1880 +            throw new NullPointerException();
1881 +    }
1882 +
1883 +    /* ---------------- Table Initialization and Resizing -------------- */
1884 +
1885      /**
1886 <     * Implementation for clear. Steps through each bin, removing all nodes.
1886 >     * Returns a power of two table size for the given desired capacity.
1887 >     * See Hackers Delight, sec 3.2
1888 >     */
1889 >    private static final int tableSizeFor(int c) {
1890 >        int n = c - 1;
1891 >        n |= n >>> 1;
1892 >        n |= n >>> 2;
1893 >        n |= n >>> 4;
1894 >        n |= n >>> 8;
1895 >        n |= n >>> 16;
1896 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1897 >    }
1898 >
1899 >    /**
1900 >     * Initializes table, using the size recorded in sizeCtl.
1901 >     */
1902 >    private final Node[] initTable() {
1903 >        Node[] tab; int sc;
1904 >        while ((tab = table) == null) {
1905 >            if ((sc = sizeCtl) < 0)
1906 >                Thread.yield(); // lost initialization race; just spin
1907 >            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1908 >                try {
1909 >                    if ((tab = table) == null) {
1910 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1911 >                        tab = table = new Node[n];
1912 >                        sc = n - (n >>> 2);
1913 >                    }
1914 >                } finally {
1915 >                    sizeCtl = sc;
1916 >                }
1917 >                break;
1918 >            }
1919 >        }
1920 >        return tab;
1921 >    }
1922 >
1923 >    /**
1924 >     * If table is too small and not already resizing, creates next
1925 >     * table and transfers bins.  Rechecks occupancy after a transfer
1926 >     * to see if another resize is already needed because resizings
1927 >     * are lagging additions.
1928 >     */
1929 >    private final void checkForResize() {
1930 >        Node[] tab; int n, sc;
1931 >        while ((tab = table) != null &&
1932 >               (n = tab.length) < MAXIMUM_CAPACITY &&
1933 >               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1934 >               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1935 >            try {
1936 >                if (tab == table) {
1937 >                    table = rebuild(tab);
1938 >                    sc = (n << 1) - (n >>> 1);
1939 >                }
1940 >            } finally {
1941 >                sizeCtl = sc;
1942 >            }
1943 >        }
1944 >    }
1945 >
1946 >    /**
1947 >     * Tries to presize table to accommodate the given number of elements.
1948 >     *
1949 >     * @param size number of elements (doesn't need to be perfectly accurate)
1950 >     */
1951 >    private final void tryPresize(int size) {
1952 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1953 >            tableSizeFor(size + (size >>> 1) + 1);
1954 >        int sc;
1955 >        while ((sc = sizeCtl) >= 0) {
1956 >            Node[] tab = table; int n;
1957 >            if (tab == null || (n = tab.length) == 0) {
1958 >                n = (sc > c) ? sc : c;
1959 >                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1960 >                    try {
1961 >                        if (table == tab) {
1962 >                            table = new Node[n];
1963 >                            sc = n - (n >>> 2);
1964 >                        }
1965 >                    } finally {
1966 >                        sizeCtl = sc;
1967 >                    }
1968 >                }
1969 >            }
1970 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1971 >                break;
1972 >            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1973 >                try {
1974 >                    if (table == tab) {
1975 >                        table = rebuild(tab);
1976 >                        sc = (n << 1) - (n >>> 1);
1977 >                    }
1978 >                } finally {
1979 >                    sizeCtl = sc;
1980 >                }
1981 >            }
1982 >        }
1983 >    }
1984 >
1985 >    /*
1986 >     * Moves and/or copies the nodes in each bin to new table. See
1987 >     * above for explanation.
1988 >     *
1989 >     * @return the new table
1990 >     */
1991 >    private static final Node[] rebuild(Node[] tab) {
1992 >        int n = tab.length;
1993 >        Node[] nextTab = new Node[n << 1];
1994 >        Node fwd = new Node(MOVED, nextTab, null, null);
1995 >        int[] buffer = null;       // holds bins to revisit; null until needed
1996 >        Node rev = null;           // reverse forwarder; null until needed
1997 >        int nbuffered = 0;         // the number of bins in buffer list
1998 >        int bufferIndex = 0;       // buffer index of current buffered bin
1999 >        int bin = n - 1;           // current non-buffered bin or -1 if none
2000 >
2001 >        for (int i = bin;;) {      // start upwards sweep
2002 >            int fh; Node f;
2003 >            if ((f = tabAt(tab, i)) == null) {
2004 >                if (bin >= 0) {    // no lock needed (or available)
2005 >                    if (!casTabAt(tab, i, f, fwd))
2006 >                        continue;
2007 >                }
2008 >                else {             // transiently use a locked forwarding node
2009 >                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
2010 >                    if (!casTabAt(tab, i, f, g))
2011 >                        continue;
2012 >                    setTabAt(nextTab, i, null);
2013 >                    setTabAt(nextTab, i + n, null);
2014 >                    setTabAt(tab, i, fwd);
2015 >                    if (!g.casHash(MOVED|LOCKED, MOVED)) {
2016 >                        g.hash = MOVED;
2017 >                        synchronized (g) { g.notifyAll(); }
2018 >                    }
2019 >                }
2020 >            }
2021 >            else if ((fh = f.hash) == MOVED) {
2022 >                Object fk = f.key;
2023 >                if (fk instanceof TreeBin) {
2024 >                    TreeBin t = (TreeBin)fk;
2025 >                    boolean validated = false;
2026 >                    t.acquire(0);
2027 >                    try {
2028 >                        if (tabAt(tab, i) == f) {
2029 >                            validated = true;
2030 >                            splitTreeBin(nextTab, i, t);
2031 >                            setTabAt(tab, i, fwd);
2032 >                        }
2033 >                    } finally {
2034 >                        t.release(0);
2035 >                    }
2036 >                    if (!validated)
2037 >                        continue;
2038 >                }
2039 >            }
2040 >            else if ((fh & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
2041 >                boolean validated = false;
2042 >                try {              // split to lo and hi lists; copying as needed
2043 >                    if (tabAt(tab, i) == f) {
2044 >                        validated = true;
2045 >                        splitBin(nextTab, i, f);
2046 >                        setTabAt(tab, i, fwd);
2047 >                    }
2048 >                } finally {
2049 >                    if (!f.casHash(fh | LOCKED, fh)) {
2050 >                        f.hash = fh;
2051 >                        synchronized (f) { f.notifyAll(); };
2052 >                    }
2053 >                }
2054 >                if (!validated)
2055 >                    continue;
2056 >            }
2057 >            else {
2058 >                if (buffer == null) // initialize buffer for revisits
2059 >                    buffer = new int[TRANSFER_BUFFER_SIZE];
2060 >                if (bin < 0 && bufferIndex > 0) {
2061 >                    int j = buffer[--bufferIndex];
2062 >                    buffer[bufferIndex] = i;
2063 >                    i = j;         // swap with another bin
2064 >                    continue;
2065 >                }
2066 >                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
2067 >                    f.tryAwaitLock(tab, i);
2068 >                    continue;      // no other options -- block
2069 >                }
2070 >                if (rev == null)   // initialize reverse-forwarder
2071 >                    rev = new Node(MOVED, tab, null, null);
2072 >                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
2073 >                    continue;      // recheck before adding to list
2074 >                buffer[nbuffered++] = i;
2075 >                setTabAt(nextTab, i, rev);     // install place-holders
2076 >                setTabAt(nextTab, i + n, rev);
2077 >            }
2078 >
2079 >            if (bin > 0)
2080 >                i = --bin;
2081 >            else if (buffer != null && nbuffered > 0) {
2082 >                bin = -1;
2083 >                i = buffer[bufferIndex = --nbuffered];
2084 >            }
2085 >            else
2086 >                return nextTab;
2087 >        }
2088 >    }
2089 >
2090 >    /**
2091 >     * Splits a normal bin with list headed by e into lo and hi parts;
2092 >     * installs in given table.
2093 >     */
2094 >    private static void splitBin(Node[] nextTab, int i, Node e) {
2095 >        int bit = nextTab.length >>> 1; // bit to split on
2096 >        int runBit = e.hash & bit;
2097 >        Node lastRun = e, lo = null, hi = null;
2098 >        for (Node p = e.next; p != null; p = p.next) {
2099 >            int b = p.hash & bit;
2100 >            if (b != runBit) {
2101 >                runBit = b;
2102 >                lastRun = p;
2103 >            }
2104 >        }
2105 >        if (runBit == 0)
2106 >            lo = lastRun;
2107 >        else
2108 >            hi = lastRun;
2109 >        for (Node p = e; p != lastRun; p = p.next) {
2110 >            int ph = p.hash & HASH_BITS;
2111 >            Object pk = p.key, pv = p.val;
2112 >            if ((ph & bit) == 0)
2113 >                lo = new Node(ph, pk, pv, lo);
2114 >            else
2115 >                hi = new Node(ph, pk, pv, hi);
2116 >        }
2117 >        setTabAt(nextTab, i, lo);
2118 >        setTabAt(nextTab, i + bit, hi);
2119 >    }
2120 >
2121 >    /**
2122 >     * Splits a tree bin into lo and hi parts; installs in given table.
2123 >     */
2124 >    private static void splitTreeBin(Node[] nextTab, int i, TreeBin t) {
2125 >        int bit = nextTab.length >>> 1;
2126 >        TreeBin lt = new TreeBin();
2127 >        TreeBin ht = new TreeBin();
2128 >        int lc = 0, hc = 0;
2129 >        for (Node e = t.first; e != null; e = e.next) {
2130 >            int h = e.hash & HASH_BITS;
2131 >            Object k = e.key, v = e.val;
2132 >            if ((h & bit) == 0) {
2133 >                ++lc;
2134 >                lt.putTreeNode(h, k, v);
2135 >            }
2136 >            else {
2137 >                ++hc;
2138 >                ht.putTreeNode(h, k, v);
2139 >            }
2140 >        }
2141 >        Node ln, hn; // throw away trees if too small
2142 >        if (lc <= (TREE_THRESHOLD >>> 1)) {
2143 >            ln = null;
2144 >            for (Node p = lt.first; p != null; p = p.next)
2145 >                ln = new Node(p.hash, p.key, p.val, ln);
2146 >        }
2147 >        else
2148 >            ln = new Node(MOVED, lt, null, null);
2149 >        setTabAt(nextTab, i, ln);
2150 >        if (hc <= (TREE_THRESHOLD >>> 1)) {
2151 >            hn = null;
2152 >            for (Node p = ht.first; p != null; p = p.next)
2153 >                hn = new Node(p.hash, p.key, p.val, hn);
2154 >        }
2155 >        else
2156 >            hn = new Node(MOVED, ht, null, null);
2157 >        setTabAt(nextTab, i + bit, hn);
2158 >    }
2159 >
2160 >    /**
2161 >     * Implementation for clear. Steps through each bin, removing all
2162 >     * nodes.
2163       */
2164      private final void internalClear() {
2165          long delta = 0L; // negative number of deletions
2166          int i = 0;
2167          Node[] tab = table;
2168          while (tab != null && i < tab.length) {
2169 <            Node e = tabAt(tab, i);
2170 <            if (e == null)
2169 >            int fh; Object fk;
2170 >            Node f = tabAt(tab, i);
2171 >            if (f == null)
2172                  ++i;
2173 <            else if (e.hash < 0)
2174 <                tab = (Node[])e.key;
2175 <            else {
2176 <                boolean validated = false;
2177 <                synchronized (e) {
2178 <                    if (tabAt(tab, i) == e) {
2179 <                        validated = true;
2180 <                        Node en;
742 <                        do {
743 <                            en = e.next;
744 <                            if (e.val != null) { // currently always true
745 <                                e.val = null;
2173 >            else if ((fh = f.hash) == MOVED) {
2174 >                if ((fk = f.key) instanceof TreeBin) {
2175 >                    TreeBin t = (TreeBin)fk;
2176 >                    t.acquire(0);
2177 >                    try {
2178 >                        if (tabAt(tab, i) == f) {
2179 >                            for (Node p = t.first; p != null; p = p.next) {
2180 >                                p.val = null;
2181                                  --delta;
2182                              }
2183 <                        } while ((e = en) != null);
2183 >                            t.first = null;
2184 >                            t.root = null;
2185 >                            ++i;
2186 >                        }
2187 >                    } finally {
2188 >                        t.release(0);
2189 >                    }
2190 >                }
2191 >                else
2192 >                    tab = (Node[])fk;
2193 >            }
2194 >            else if ((fh & LOCKED) != 0) {
2195 >                counter.add(delta); // opportunistically update count
2196 >                delta = 0L;
2197 >                f.tryAwaitLock(tab, i);
2198 >            }
2199 >            else if (f.casHash(fh, fh | LOCKED)) {
2200 >                try {
2201 >                    if (tabAt(tab, i) == f) {
2202 >                        for (Node e = f; e != null; e = e.next) {
2203 >                            e.val = null;
2204 >                            --delta;
2205 >                        }
2206                          setTabAt(tab, i, null);
2207 +                        ++i;
2208 +                    }
2209 +                } finally {
2210 +                    if (!f.casHash(fh | LOCKED, fh)) {
2211 +                        f.hash = fh;
2212 +                        synchronized (f) { f.notifyAll(); };
2213                      }
2214                  }
752                if (validated)
753                    ++i;
2215              }
2216          }
2217 <        counter.add(delta);
2217 >        if (delta != 0)
2218 >            counter.add(delta);
2219      }
2220  
2221      /* ----------------Table Traversal -------------- */
# Line 764 | Line 2226 | public class ConcurrentHashMapV8<K, V>
2226       *
2227       * At each step, the iterator snapshots the key ("nextKey") and
2228       * value ("nextVal") of a valid node (i.e., one that, at point of
2229 <     * snapshot, has a nonnull user value). Because val fields can
2229 >     * snapshot, has a non-null user value). Because val fields can
2230       * change (including to null, indicating deletion), field nextVal
2231       * might not be accurate at point of use, but still maintains the
2232       * weak consistency property of holding a value that was once
2233       * valid.
2234       *
2235       * Internal traversals directly access these fields, as in:
2236 <     * {@code while (it.next != null) { process(nextKey); it.advance(); }}
2236 >     * {@code while (it.advance() != null) { process(it.nextKey); }}
2237       *
2238 <     * Exported iterators (subclasses of ViewIterator) extract key,
2239 <     * value, or key-value pairs as return values of Iterator.next(),
2240 <     * and encapsulate the it.next check as hasNext();
2241 <     *
2242 <     * The iterator visits each valid node that was reachable upon
2243 <     * iterator construction once. It might miss some that were added
2244 <     * to a bin after the bin was visited, which is OK wrt consistency
2245 <     * guarantees. Maintaining this property in the face of possible
2246 <     * ongoing resizes requires a fair amount of bookkeeping state
2247 <     * that is difficult to optimize away amidst volatile accesses.
2248 <     * Even so, traversal maintains reasonable throughput.
2238 >     * Exported iterators must track whether the iterator has advanced
2239 >     * (in hasNext vs next) (by setting/checking/nulling field
2240 >     * nextVal), and then extract key, value, or key-value pairs as
2241 >     * return values of next().
2242 >     *
2243 >     * The iterator visits once each still-valid node that was
2244 >     * reachable upon iterator construction. It might miss some that
2245 >     * were added to a bin after the bin was visited, which is OK wrt
2246 >     * consistency guarantees. Maintaining this property in the face
2247 >     * of possible ongoing resizes requires a fair amount of
2248 >     * bookkeeping state that is difficult to optimize away amidst
2249 >     * volatile accesses.  Even so, traversal maintains reasonable
2250 >     * throughput.
2251       *
2252       * Normally, iteration proceeds bin-by-bin traversing lists.
2253       * However, if the table has been resized, then all future steps
# Line 793 | Line 2257 | public class ConcurrentHashMapV8<K, V>
2257       * across threads, iteration terminates if a bounds checks fails
2258       * for a table read.
2259       *
2260 <     * The range-based constructor enables creation of parallel
2261 <     * range-splitting traversals. (Not yet implemented.)
2260 >     * This class extends ForkJoinTask to streamline parallel
2261 >     * iteration in bulk operations (see BulkTask). This adds only an
2262 >     * int of space overhead, which is close enough to negligible in
2263 >     * cases where it is not needed to not worry about it.
2264       */
2265 <    static class InternalIterator {
2265 >    static class Traverser<K,V,R> extends ForkJoinTask<R> {
2266 >        final ConcurrentHashMapV8<K, V> map;
2267          Node next;           // the next entry to use
2268          Node last;           // the last entry used
2269          Object nextKey;      // cached key field of next
# Line 804 | Line 2271 | public class ConcurrentHashMapV8<K, V>
2271          Node[] tab;          // current table; updated if resized
2272          int index;           // index of bin to use next
2273          int baseIndex;       // current index of initial table
2274 <        final int baseLimit; // index bound for initial table
2274 >        int baseLimit;       // index bound for initial table
2275          final int baseSize;  // initial table size
2276  
2277          /** Creates iterator for all entries in the table. */
2278 <        InternalIterator(Node[] tab) {
2279 <            this.tab = tab;
2278 >        Traverser(ConcurrentHashMapV8<K, V> map) {
2279 >            this.tab = (this.map = map).table;
2280              baseLimit = baseSize = (tab == null) ? 0 : tab.length;
814            index = baseIndex = 0;
815            next = null;
816            advance();
817        }
818
819        /** Creates iterator for the given range of the table */
820        InternalIterator(Node[] tab, int lo, int hi) {
821            this.tab = tab;
822            baseSize = (tab == null) ? 0 : tab.length;
823            baseLimit = (hi <= baseSize) ? hi : baseSize;
824            index = baseIndex = lo;
825            next = null;
826            advance();
2281          }
2282  
2283 <        /** Advances next. See above for explanation. */
2284 <        final void advance() {
2283 >        /** Creates iterator for split() methods */
2284 >        Traverser(Traverser<K,V,?> it, boolean split) {
2285 >            this.map = it.map;
2286 >            this.tab = it.tab;
2287 >            this.baseSize = it.baseSize;
2288 >            int lo = it.baseIndex;
2289 >            int hi = this.baseLimit = it.baseLimit;
2290 >            int i;
2291 >            if (split) // adjust parent
2292 >                i = it.baseLimit = (lo + hi + 1) >>> 1;
2293 >            else       // clone parent
2294 >                i = lo;
2295 >            this.index = this.baseIndex = i;
2296 >        }
2297 >
2298 >        /**
2299 >         * Advances next; returns nextVal or null if terminated.
2300 >         * See above for explanation.
2301 >         */
2302 >        final Object advance() {
2303              Node e = last = next;
2304 +            Object ev = null;
2305              outer: do {
2306 <                if (e != null)                   // pass used or skipped node
2306 >                if (e != null)                  // advance past used/skipped node
2307                      e = e.next;
2308 <                while (e == null) {              // get to next non-null bin
2309 <                    Node[] t; int b, i, n;       // checks must use locals
2308 >                while (e == null) {             // get to next non-null bin
2309 >                    Node[] t; int b, i, n; Object ek; // checks must use locals
2310                      if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
2311                          (t = tab) == null || i >= (n = t.length))
2312                          break outer;
2313 <                    else if ((e = tabAt(t, i)) != null && e.hash < 0)
2314 <                        tab = (Node[])e.key;     // restarts due to null val
2315 <                    else                         // visit upper slots if present
2316 <                        index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2313 >                    else if ((e = tabAt(t, i)) != null && e.hash == MOVED) {
2314 >                        if ((ek = e.key) instanceof TreeBin)
2315 >                            e = ((TreeBin)ek).first;
2316 >                        else {
2317 >                            tab = (Node[])ek;
2318 >                            continue;           // restarts due to null val
2319 >                        }
2320 >                    }                           // visit upper slots if present
2321 >                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2322                  }
2323                  nextKey = e.key;
2324 <            } while ((nextVal = e.val) == null); // skip deleted or special nodes
2324 >            } while ((ev = e.val) == null);    // skip deleted or special nodes
2325              next = e;
2326 +            return nextVal = ev;
2327          }
2328 +
2329 +        public final void remove() {
2330 +            if (nextVal == null && last == null)
2331 +                advance();
2332 +            Node e = last;
2333 +            if (e == null)
2334 +                throw new IllegalStateException();
2335 +            last = null;
2336 +            map.remove(e.key);
2337 +        }
2338 +
2339 +        public final boolean hasNext() {
2340 +            return nextVal != null || advance() != null;
2341 +        }
2342 +
2343 +        public final boolean hasMoreElements() { return hasNext(); }
2344 +        public final void setRawResult(Object x) { }
2345 +        public R getRawResult() { return null; }
2346 +        public boolean exec() { return true; }
2347      }
2348  
2349      /* ---------------- Public operations -------------- */
2350  
2351      /**
2352 <     * Creates a new, empty map with the default initial table size (16),
2352 >     * Creates a new, empty map with the default initial table size (16).
2353       */
2354      public ConcurrentHashMapV8() {
2355          this.counter = new LongAdder();
858        this.targetCapacity = DEFAULT_CAPACITY;
2356      }
2357  
2358      /**
# Line 875 | Line 2372 | public class ConcurrentHashMapV8<K, V>
2372                     MAXIMUM_CAPACITY :
2373                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2374          this.counter = new LongAdder();
2375 <        this.targetCapacity = cap;
2375 >        this.sizeCtl = cap;
2376      }
2377  
2378      /**
# Line 885 | Line 2382 | public class ConcurrentHashMapV8<K, V>
2382       */
2383      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
2384          this.counter = new LongAdder();
2385 <        this.targetCapacity = DEFAULT_CAPACITY;
2386 <        putAll(m);
2385 >        this.sizeCtl = DEFAULT_CAPACITY;
2386 >        internalPutAll(m);
2387      }
2388  
2389      /**
# Line 933 | Line 2430 | public class ConcurrentHashMapV8<K, V>
2430          if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2431              initialCapacity = concurrencyLevel;   // as estimated threads
2432          long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2433 <        int cap =  ((size >= (long)MAXIMUM_CAPACITY) ?
2434 <                    MAXIMUM_CAPACITY: tableSizeFor((int)size));
2433 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2434 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2435          this.counter = new LongAdder();
2436 <        this.targetCapacity = cap;
2436 >        this.sizeCtl = cap;
2437      }
2438  
2439      /**
# Line 957 | Line 2454 | public class ConcurrentHashMapV8<K, V>
2454      }
2455  
2456      /**
2457 +     * Returns the number of mappings. This method should be used
2458 +     * instead of {@link #size} because a ConcurrentHashMap may
2459 +     * contain more mappings than can be represented as an int. The
2460 +     * value returned is a snapshot; the actual count may differ if
2461 +     * there are ongoing concurrent insertions of removals.
2462 +     *
2463 +     * @return the number of mappings
2464 +     */
2465 +    public long mappingCount() {
2466 +        long n = counter.sum();
2467 +        return (n < 0L) ? 0L : n;
2468 +    }
2469 +
2470 +    /**
2471       * Returns the value to which the specified key is mapped,
2472       * or {@code null} if this map contains no mapping for the key.
2473       *
# Line 968 | Line 2479 | public class ConcurrentHashMapV8<K, V>
2479       * @throws NullPointerException if the specified key is null
2480       */
2481      @SuppressWarnings("unchecked")
2482 <    public V get(Object key) {
2482 >        public V get(Object key) {
2483          if (key == null)
2484              throw new NullPointerException();
2485          return (V)internalGet(key);
# Line 1003 | Line 2514 | public class ConcurrentHashMapV8<K, V>
2514          if (value == null)
2515              throw new NullPointerException();
2516          Object v;
2517 <        InternalIterator it = new InternalIterator(table);
2518 <        while (it.next != null) {
2519 <            if ((v = it.nextVal) == value || value.equals(v))
2517 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2518 >        while ((v = it.advance()) != null) {
2519 >            if (v == value || value.equals(v))
2520                  return true;
1010            it.advance();
2521          }
2522          return false;
2523      }
# Line 1045 | Line 2555 | public class ConcurrentHashMapV8<K, V>
2555       * @throws NullPointerException if the specified key or value is null
2556       */
2557      @SuppressWarnings("unchecked")
2558 <    public V put(K key, V value) {
2558 >        public V put(K key, V value) {
2559          if (key == null || value == null)
2560              throw new NullPointerException();
2561 <        return (V)internalPut(key, value, true);
2561 >        return (V)internalPut(key, value);
2562      }
2563  
2564      /**
# Line 1059 | Line 2569 | public class ConcurrentHashMapV8<K, V>
2569       * @throws NullPointerException if the specified key or value is null
2570       */
2571      @SuppressWarnings("unchecked")
2572 <    public V putIfAbsent(K key, V value) {
2572 >        public V putIfAbsent(K key, V value) {
2573          if (key == null || value == null)
2574              throw new NullPointerException();
2575 <        return (V)internalPut(key, value, false);
2575 >        return (V)internalPutIfAbsent(key, value);
2576      }
2577  
2578      /**
# Line 1073 | Line 2583 | public class ConcurrentHashMapV8<K, V>
2583       * @param m mappings to be stored in this map
2584       */
2585      public void putAll(Map<? extends K, ? extends V> m) {
2586 <        if (m == null)
1077 <            throw new NullPointerException();
1078 <        /*
1079 <         * If uninitialized, try to adjust targetCapacity to
1080 <         * accommodate the given number of elements.
1081 <         */
1082 <        if (table == null) {
1083 <            int size = m.size();
1084 <            int cap = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1085 <                tableSizeFor(size + (size >>> 1) + 1);
1086 <            if (cap > targetCapacity)
1087 <                targetCapacity = cap;
1088 <        }
1089 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1090 <            put(e.getKey(), e.getValue());
2586 >        internalPutAll(m);
2587      }
2588  
2589      /**
2590       * If the specified key is not already associated with a value,
2591 <     * computes its value using the given mappingFunction, and if
2592 <     * non-null, enters it into the map.  This is equivalent to
2593 <     *  <pre> {@code
2591 >     * computes its value using the given mappingFunction and enters
2592 >     * it into the map unless null.  This is equivalent to
2593 >     * <pre> {@code
2594       * if (map.containsKey(key))
2595       *   return map.get(key);
2596 <     * value = mappingFunction.map(key);
2596 >     * value = mappingFunction.apply(key);
2597       * if (value != null)
2598       *   map.put(key, value);
2599       * return value;}</pre>
2600       *
2601 <     * except that the action is performed atomically.  Some attempted
2602 <     * update operations on this map by other threads may be blocked
2603 <     * while computation is in progress, so the computation should be
2604 <     * short and simple, and must not attempt to update any other
2605 <     * mappings of this Map. The most appropriate usage is to
2601 >     * except that the action is performed atomically.  If the
2602 >     * function returns {@code null} no mapping is recorded. If the
2603 >     * function itself throws an (unchecked) exception, the exception
2604 >     * is rethrown to its caller, and no mapping is recorded.  Some
2605 >     * attempted update operations on this map by other threads may be
2606 >     * blocked while computation is in progress, so the computation
2607 >     * should be short and simple, and must not attempt to update any
2608 >     * other mappings of this Map. The most appropriate usage is to
2609       * construct a new object serving as an initial mapped value, or
2610       * memoized result, as in:
2611 +     *
2612       *  <pre> {@code
2613 <     * map.computeIfAbsent(key, new MappingFunction<K, V>() {
2613 >     * map.computeIfAbsent(key, new Fun<K, V>() {
2614       *   public V map(K k) { return new Value(f(k)); }});}</pre>
2615       *
2616       * @param key key with which the specified value is to be associated
2617       * @param mappingFunction the function to compute a value
2618       * @return the current (existing or computed) value associated with
2619 <     *         the specified key, or {@code null} if the computation
1120 <     *         returned {@code null}
2619 >     *         the specified key, or null if the computed value is null.
2620       * @throws NullPointerException if the specified key or mappingFunction
2621       *         is null
2622       * @throws IllegalStateException if the computation detectably
# Line 1126 | Line 2625 | public class ConcurrentHashMapV8<K, V>
2625       * @throws RuntimeException or Error if the mappingFunction does so,
2626       *         in which case the mapping is left unestablished
2627       */
2628 <    public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
2628 >    @SuppressWarnings("unchecked")
2629 >        public V computeIfAbsent(K key, Fun<? super K, ? extends V> mappingFunction) {
2630          if (key == null || mappingFunction == null)
2631              throw new NullPointerException();
2632 <        return internalCompute(key, mappingFunction, false);
2632 >        return (V)internalComputeIfAbsent(key, mappingFunction);
2633      }
2634  
2635      /**
2636 <     * Computes the value associated with the given key using the given
2637 <     * mappingFunction, and if non-null, enters it into the map.  This
1138 <     * is equivalent to
2636 >     * If the given key is present, computes a new mapping value given a key and
2637 >     * its current mapped value. This is equivalent to
2638       *  <pre> {@code
2639 <     * value = mappingFunction.map(key);
2640 <     * if (value != null)
2641 <     *   map.put(key, value);
2642 <     * else
2643 <     *   value = map.get(key);
2644 <     * return value;}</pre>
2639 >     *   if (map.containsKey(key)) {
2640 >     *     value = remappingFunction.apply(key, map.get(key));
2641 >     *     if (value != null)
2642 >     *       map.put(key, value);
2643 >     *     else
2644 >     *       map.remove(key);
2645 >     *   }
2646 >     * }</pre>
2647 >     *
2648 >     * except that the action is performed atomically.  If the
2649 >     * function returns {@code null}, the mapping is removed.  If the
2650 >     * function itself throws an (unchecked) exception, the exception
2651 >     * is rethrown to its caller, and the current mapping is left
2652 >     * unchanged.  Some attempted update operations on this map by
2653 >     * other threads may be blocked while computation is in progress,
2654 >     * so the computation should be short and simple, and must not
2655 >     * attempt to update any other mappings of this Map. For example,
2656 >     * to either create or append new messages to a value mapping:
2657       *
2658 <     * except that the action is performed atomically.  Some attempted
2659 <     * update operations on this map by other threads may be blocked
2660 <     * while computation is in progress, so the computation should be
2661 <     * short and simple, and must not attempt to update any other
2662 <     * mappings of this Map.
2658 >     * @param key key with which the specified value is to be associated
2659 >     * @param remappingFunction the function to compute a value
2660 >     * @return the new value associated with the specified key, or null if none
2661 >     * @throws NullPointerException if the specified key or remappingFunction
2662 >     *         is null
2663 >     * @throws IllegalStateException if the computation detectably
2664 >     *         attempts a recursive update to this map that would
2665 >     *         otherwise never complete
2666 >     * @throws RuntimeException or Error if the remappingFunction does so,
2667 >     *         in which case the mapping is unchanged
2668 >     */
2669 >    public V computeIfPresent(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2670 >        if (key == null || remappingFunction == null)
2671 >            throw new NullPointerException();
2672 >        return (V)internalCompute(key, true, remappingFunction);
2673 >    }
2674 >
2675 >    /**
2676 >     * Computes a new mapping value given a key and
2677 >     * its current mapped value (or {@code null} if there is no current
2678 >     * mapping). This is equivalent to
2679 >     *  <pre> {@code
2680 >     *   value = remappingFunction.apply(key, map.get(key));
2681 >     *   if (value != null)
2682 >     *     map.put(key, value);
2683 >     *   else
2684 >     *     map.remove(key);
2685 >     * }</pre>
2686 >     *
2687 >     * except that the action is performed atomically.  If the
2688 >     * function returns {@code null}, the mapping is removed.  If the
2689 >     * function itself throws an (unchecked) exception, the exception
2690 >     * is rethrown to its caller, and the current mapping is left
2691 >     * unchanged.  Some attempted update operations on this map by
2692 >     * other threads may be blocked while computation is in progress,
2693 >     * so the computation should be short and simple, and must not
2694 >     * attempt to update any other mappings of this Map. For example,
2695 >     * to either create or append new messages to a value mapping:
2696 >     *
2697 >     * <pre> {@code
2698 >     * Map<Key, String> map = ...;
2699 >     * final String msg = ...;
2700 >     * map.compute(key, new BiFun<Key, String, String>() {
2701 >     *   public String apply(Key k, String v) {
2702 >     *    return (v == null) ? msg : v + msg;});}}</pre>
2703       *
2704       * @param key key with which the specified value is to be associated
2705 <     * @param mappingFunction the function to compute a value
2706 <     * @return the current value associated with
2707 <     *         the specified key, or {@code null} if the computation
1157 <     *         returned {@code null} and the value was not otherwise present
1158 <     * @throws NullPointerException if the specified key or mappingFunction
2705 >     * @param remappingFunction the function to compute a value
2706 >     * @return the new value associated with the specified key, or null if none
2707 >     * @throws NullPointerException if the specified key or remappingFunction
2708       *         is null
2709       * @throws IllegalStateException if the computation detectably
2710       *         attempts a recursive update to this map that would
2711       *         otherwise never complete
2712 <     * @throws RuntimeException or Error if the mappingFunction does so,
2712 >     * @throws RuntimeException or Error if the remappingFunction does so,
2713       *         in which case the mapping is unchanged
2714       */
2715 <    public V compute(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
2716 <        if (key == null || mappingFunction == null)
2715 >    //    @SuppressWarnings("unchecked")
2716 >    public V compute(K key, BiFun<? super K, ? super V, ? extends V> remappingFunction) {
2717 >        if (key == null || remappingFunction == null)
2718 >            throw new NullPointerException();
2719 >        return (V)internalCompute(key, false, remappingFunction);
2720 >    }
2721 >
2722 >    /**
2723 >     * If the specified key is not already associated
2724 >     * with a value, associate it with the given value.
2725 >     * Otherwise, replace the value with the results of
2726 >     * the given remapping function. This is equivalent to:
2727 >     *  <pre> {@code
2728 >     *   if (!map.containsKey(key))
2729 >     *     map.put(value);
2730 >     *   else {
2731 >     *     newValue = remappingFunction.apply(map.get(key), value);
2732 >     *     if (value != null)
2733 >     *       map.put(key, value);
2734 >     *     else
2735 >     *       map.remove(key);
2736 >     *   }
2737 >     * }</pre>
2738 >     * except that the action is performed atomically.  If the
2739 >     * function returns {@code null}, the mapping is removed.  If the
2740 >     * function itself throws an (unchecked) exception, the exception
2741 >     * is rethrown to its caller, and the current mapping is left
2742 >     * unchanged.  Some attempted update operations on this map by
2743 >     * other threads may be blocked while computation is in progress,
2744 >     * so the computation should be short and simple, and must not
2745 >     * attempt to update any other mappings of this Map.
2746 >     */
2747 >    //    @SuppressWarnings("unchecked")
2748 >    public V merge(K key, V value, BiFun<? super V, ? super V, ? extends V> remappingFunction) {
2749 >        if (key == null || value == null || remappingFunction == null)
2750              throw new NullPointerException();
2751 <        return internalCompute(key, mappingFunction, true);
2751 >        return (V)internalMerge(key, value, remappingFunction);
2752      }
2753  
2754      /**
# Line 1179 | Line 2761 | public class ConcurrentHashMapV8<K, V>
2761       * @throws NullPointerException if the specified key is null
2762       */
2763      @SuppressWarnings("unchecked")
2764 <    public V remove(Object key) {
2764 >        public V remove(Object key) {
2765          if (key == null)
2766              throw new NullPointerException();
2767          return (V)internalReplace(key, null, null);
# Line 1217 | Line 2799 | public class ConcurrentHashMapV8<K, V>
2799       * @throws NullPointerException if the specified key or value is null
2800       */
2801      @SuppressWarnings("unchecked")
2802 <    public V replace(K key, V value) {
2802 >        public V replace(K key, V value) {
2803          if (key == null || value == null)
2804              throw new NullPointerException();
2805          return (V)internalReplace(key, value, null);
# Line 1314 | Line 2896 | public class ConcurrentHashMapV8<K, V>
2896      }
2897  
2898      /**
2899 +     * Returns a partitionable iterator of the keys in this map.
2900 +     *
2901 +     * @return a partitionable iterator of the keys in this map
2902 +     */
2903 +    public Spliterator<K> keySpliterator() {
2904 +        return new KeyIterator<K,V>(this);
2905 +    }
2906 +
2907 +    /**
2908 +     * Returns a partitionable iterator of the values in this map.
2909 +     *
2910 +     * @return a partitionable iterator of the values in this map
2911 +     */
2912 +    public Spliterator<V> valueSpliterator() {
2913 +        return new ValueIterator<K,V>(this);
2914 +    }
2915 +
2916 +    /**
2917 +     * Returns a partitionable iterator of the entries in this map.
2918 +     *
2919 +     * @return a partitionable iterator of the entries in this map
2920 +     */
2921 +    public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2922 +        return new EntryIterator<K,V>(this);
2923 +    }
2924 +
2925 +    /**
2926       * Returns the hash code value for this {@link Map}, i.e.,
2927       * the sum of, for each key-value pair in the map,
2928       * {@code key.hashCode() ^ value.hashCode()}.
# Line 1322 | Line 2931 | public class ConcurrentHashMapV8<K, V>
2931       */
2932      public int hashCode() {
2933          int h = 0;
2934 <        InternalIterator it = new InternalIterator(table);
2935 <        while (it.next != null) {
2936 <            h += it.nextKey.hashCode() ^ it.nextVal.hashCode();
2937 <            it.advance();
2934 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2935 >        Object v;
2936 >        while ((v = it.advance()) != null) {
2937 >            h += it.nextKey.hashCode() ^ v.hashCode();
2938          }
2939          return h;
2940      }
# Line 1342 | Line 2951 | public class ConcurrentHashMapV8<K, V>
2951       * @return a string representation of this map
2952       */
2953      public String toString() {
2954 <        InternalIterator it = new InternalIterator(table);
2954 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2955          StringBuilder sb = new StringBuilder();
2956          sb.append('{');
2957 <        if (it.next != null) {
2957 >        Object v;
2958 >        if ((v = it.advance()) != null) {
2959              for (;;) {
2960 <                Object k = it.nextKey, v = it.nextVal;
2960 >                Object k = it.nextKey;
2961                  sb.append(k == this ? "(this Map)" : k);
2962                  sb.append('=');
2963                  sb.append(v == this ? "(this Map)" : v);
2964 <                it.advance();
1355 <                if (it.next == null)
2964 >                if ((v = it.advance()) == null)
2965                      break;
2966                  sb.append(',').append(' ');
2967              }
# Line 1375 | Line 2984 | public class ConcurrentHashMapV8<K, V>
2984              if (!(o instanceof Map))
2985                  return false;
2986              Map<?,?> m = (Map<?,?>) o;
2987 <            InternalIterator it = new InternalIterator(table);
2988 <            while (it.next != null) {
2989 <                Object val = it.nextVal;
2987 >            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2988 >            Object val;
2989 >            while ((val = it.advance()) != null) {
2990                  Object v = m.get(it.nextKey);
2991                  if (v == null || (v != val && !v.equals(val)))
2992                      return false;
1384                it.advance();
2993              }
2994              for (Map.Entry<?,?> e : m.entrySet()) {
2995                  Object mk, mv, v;
# Line 1397 | Line 3005 | public class ConcurrentHashMapV8<K, V>
3005  
3006      /* ----------------Iterators -------------- */
3007  
3008 <    /**
3009 <     * Base class for key, value, and entry iterators.  Adds a map
3010 <     * reference to InternalIterator to support Iterator.remove.
3011 <     */
3012 <    static abstract class ViewIterator<K,V> extends InternalIterator {
1405 <        final ConcurrentHashMapV8<K, V> map;
1406 <        ViewIterator(ConcurrentHashMapV8<K, V> map) {
1407 <            super(map.table);
1408 <            this.map = map;
3008 >    static final class KeyIterator<K,V> extends Traverser<K,V,Object>
3009 >        implements Spliterator<K>, Enumeration<K> {
3010 >        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3011 >        KeyIterator(Traverser<K,V,Object> it, boolean split) {
3012 >            super(it, split);
3013          }
3014 <
3015 <        public final void remove() {
1412 <            if (last == null)
3014 >        public KeyIterator<K,V> split() {
3015 >            if (last != null || (next != null && nextVal == null))
3016                  throw new IllegalStateException();
3017 <            map.remove(last.key);
1415 <            last = null;
3017 >            return new KeyIterator<K,V>(this, true);
3018          }
1417
1418        public final boolean hasNext()         { return next != null; }
1419        public final boolean hasMoreElements() { return next != null; }
1420    }
1421
1422    static final class KeyIterator<K,V> extends ViewIterator<K,V>
1423        implements Iterator<K>, Enumeration<K> {
1424        KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1425
3019          @SuppressWarnings("unchecked")
3020 <        public final K next() {
3021 <            if (next == null)
3020 >            public final K next() {
3021 >            if (nextVal == null && advance() == null)
3022                  throw new NoSuchElementException();
3023              Object k = nextKey;
3024 <            advance();
3025 <            return (K)k;
3024 >            nextVal = null;
3025 >            return (K) k;
3026          }
3027  
3028          public final K nextElement() { return next(); }
3029      }
3030  
3031 <    static final class ValueIterator<K,V> extends ViewIterator<K,V>
3032 <        implements Iterator<V>, Enumeration<V> {
3031 >    static final class ValueIterator<K,V> extends Traverser<K,V,Object>
3032 >        implements Spliterator<V>, Enumeration<V> {
3033          ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3034 +        ValueIterator(Traverser<K,V,Object> it, boolean split) {
3035 +            super(it, split);
3036 +        }
3037 +        public ValueIterator<K,V> split() {
3038 +            if (last != null || (next != null && nextVal == null))
3039 +                throw new IllegalStateException();
3040 +            return new ValueIterator<K,V>(this, true);
3041 +        }
3042  
3043          @SuppressWarnings("unchecked")
3044 <        public final V next() {
3045 <            if (next == null)
3044 >            public final V next() {
3045 >            Object v;
3046 >            if ((v = nextVal) == null && (v = advance()) == null)
3047                  throw new NoSuchElementException();
3048 <            Object v = nextVal;
3049 <            advance();
1448 <            return (V)v;
3048 >            nextVal = null;
3049 >            return (V) v;
3050          }
3051  
3052          public final V nextElement() { return next(); }
3053      }
3054  
3055 <    static final class EntryIterator<K,V> extends ViewIterator<K,V>
3056 <        implements Iterator<Map.Entry<K,V>> {
3055 >    static final class EntryIterator<K,V> extends Traverser<K,V,Object>
3056 >        implements Spliterator<Map.Entry<K,V>> {
3057          EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
3058 +        EntryIterator(Traverser<K,V,Object> it, boolean split) {
3059 +            super(it, split);
3060 +        }
3061 +        public EntryIterator<K,V> split() {
3062 +            if (last != null || (next != null && nextVal == null))
3063 +                throw new IllegalStateException();
3064 +            return new EntryIterator<K,V>(this, true);
3065 +        }
3066  
3067          @SuppressWarnings("unchecked")
3068 <        public final Map.Entry<K,V> next() {
3069 <            if (next == null)
3068 >            public final Map.Entry<K,V> next() {
3069 >            Object v;
3070 >            if ((v = nextVal) == null && (v = advance()) == null)
3071                  throw new NoSuchElementException();
3072              Object k = nextKey;
3073 <            Object v = nextVal;
3074 <            advance();
1465 <            return new WriteThroughEntry<K,V>(map, (K)k, (V)v);
3073 >            nextVal = null;
3074 >            return new MapEntry<K,V>((K)k, (V)v, map);
3075          }
3076      }
3077  
3078      /**
3079 <     * Custom Entry class used by EntryIterator.next(), that relays
1471 <     * setValue changes to the underlying map.
3079 >     * Exported Entry for iterators
3080       */
3081 <    static final class WriteThroughEntry<K,V> implements Map.Entry<K, V> {
1474 <        final ConcurrentHashMapV8<K, V> map;
3081 >    static final class MapEntry<K,V> implements Map.Entry<K, V> {
3082          final K key; // non-null
3083          V val;       // non-null
3084 <        WriteThroughEntry(ConcurrentHashMapV8<K, V> map, K key, V val) {
3085 <            this.map = map; this.key = key; this.val = val;
3084 >        final ConcurrentHashMapV8<K, V> map;
3085 >        MapEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
3086 >            this.key = key;
3087 >            this.val = val;
3088 >            this.map = map;
3089          }
1480
3090          public final K getKey()       { return key; }
3091          public final V getValue()     { return val; }
3092          public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
# Line 1494 | Line 3103 | public class ConcurrentHashMapV8<K, V>
3103  
3104          /**
3105           * Sets our entry's value and writes through to the map. The
3106 <         * value to return is somewhat arbitrary here. Since a
3107 <         * WriteThroughEntry does not necessarily track asynchronous
3108 <         * changes, the most recent "previous" value could be
3109 <         * different from what we return (or could even have been
3110 <         * removed in which case the put will re-establish). We do not
1502 <         * and cannot guarantee more.
3106 >         * value to return is somewhat arbitrary here. Since we do not
3107 >         * necessarily track asynchronous changes, the most recent
3108 >         * "previous" value could be different from what we return (or
3109 >         * could even have been removed in which case the put will
3110 >         * re-establish). We do not and cannot guarantee more.
3111           */
3112          public final V setValue(V value) {
3113              if (value == null) throw new NullPointerException();
# Line 1512 | Line 3120 | public class ConcurrentHashMapV8<K, V>
3120  
3121      /* ----------------Views -------------- */
3122  
3123 <    /*
3124 <     * These currently just extend java.util.AbstractX classes, but
1517 <     * may need a new custom base to support partitioned traversal.
3123 >    /**
3124 >     * Base class for views.
3125       */
3126 <
1520 <    static final class KeySet<K,V> extends AbstractSet<K> {
3126 >    static abstract class CHMView<K, V> {
3127          final ConcurrentHashMapV8<K, V> map;
3128 <        KeySet(ConcurrentHashMapV8<K, V> map)   { this.map = map; }
1523 <
3128 >        CHMView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
3129          public final int size()                 { return map.size(); }
3130          public final boolean isEmpty()          { return map.isEmpty(); }
3131          public final void clear()               { map.clear(); }
3132 +
3133 +        // implementations below rely on concrete classes supplying these
3134 +        abstract public Iterator<?> iterator();
3135 +        abstract public boolean contains(Object o);
3136 +        abstract public boolean remove(Object o);
3137 +
3138 +        private static final String oomeMsg = "Required array size too large";
3139 +
3140 +        public final Object[] toArray() {
3141 +            long sz = map.mappingCount();
3142 +            if (sz > (long)(MAX_ARRAY_SIZE))
3143 +                throw new OutOfMemoryError(oomeMsg);
3144 +            int n = (int)sz;
3145 +            Object[] r = new Object[n];
3146 +            int i = 0;
3147 +            Iterator<?> it = iterator();
3148 +            while (it.hasNext()) {
3149 +                if (i == n) {
3150 +                    if (n >= MAX_ARRAY_SIZE)
3151 +                        throw new OutOfMemoryError(oomeMsg);
3152 +                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3153 +                        n = MAX_ARRAY_SIZE;
3154 +                    else
3155 +                        n += (n >>> 1) + 1;
3156 +                    r = Arrays.copyOf(r, n);
3157 +                }
3158 +                r[i++] = it.next();
3159 +            }
3160 +            return (i == n) ? r : Arrays.copyOf(r, i);
3161 +        }
3162 +
3163 +        @SuppressWarnings("unchecked")
3164 +            public final <T> T[] toArray(T[] a) {
3165 +            long sz = map.mappingCount();
3166 +            if (sz > (long)(MAX_ARRAY_SIZE))
3167 +                throw new OutOfMemoryError(oomeMsg);
3168 +            int m = (int)sz;
3169 +            T[] r = (a.length >= m) ? a :
3170 +                (T[])java.lang.reflect.Array
3171 +                .newInstance(a.getClass().getComponentType(), m);
3172 +            int n = r.length;
3173 +            int i = 0;
3174 +            Iterator<?> it = iterator();
3175 +            while (it.hasNext()) {
3176 +                if (i == n) {
3177 +                    if (n >= MAX_ARRAY_SIZE)
3178 +                        throw new OutOfMemoryError(oomeMsg);
3179 +                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3180 +                        n = MAX_ARRAY_SIZE;
3181 +                    else
3182 +                        n += (n >>> 1) + 1;
3183 +                    r = Arrays.copyOf(r, n);
3184 +                }
3185 +                r[i++] = (T)it.next();
3186 +            }
3187 +            if (a == r && i < n) {
3188 +                r[i] = null; // null-terminate
3189 +                return r;
3190 +            }
3191 +            return (i == n) ? r : Arrays.copyOf(r, i);
3192 +        }
3193 +
3194 +        public final int hashCode() {
3195 +            int h = 0;
3196 +            for (Iterator<?> it = iterator(); it.hasNext();)
3197 +                h += it.next().hashCode();
3198 +            return h;
3199 +        }
3200 +
3201 +        public final String toString() {
3202 +            StringBuilder sb = new StringBuilder();
3203 +            sb.append('[');
3204 +            Iterator<?> it = iterator();
3205 +            if (it.hasNext()) {
3206 +                for (;;) {
3207 +                    Object e = it.next();
3208 +                    sb.append(e == this ? "(this Collection)" : e);
3209 +                    if (!it.hasNext())
3210 +                        break;
3211 +                    sb.append(',').append(' ');
3212 +                }
3213 +            }
3214 +            return sb.append(']').toString();
3215 +        }
3216 +
3217 +        public final boolean containsAll(Collection<?> c) {
3218 +            if (c != this) {
3219 +                for (Iterator<?> it = c.iterator(); it.hasNext();) {
3220 +                    Object e = it.next();
3221 +                    if (e == null || !contains(e))
3222 +                        return false;
3223 +                }
3224 +            }
3225 +            return true;
3226 +        }
3227 +
3228 +        public final boolean removeAll(Collection<?> c) {
3229 +            boolean modified = false;
3230 +            for (Iterator<?> it = iterator(); it.hasNext();) {
3231 +                if (c.contains(it.next())) {
3232 +                    it.remove();
3233 +                    modified = true;
3234 +                }
3235 +            }
3236 +            return modified;
3237 +        }
3238 +
3239 +        public final boolean retainAll(Collection<?> c) {
3240 +            boolean modified = false;
3241 +            for (Iterator<?> it = iterator(); it.hasNext();) {
3242 +                if (!c.contains(it.next())) {
3243 +                    it.remove();
3244 +                    modified = true;
3245 +                }
3246 +            }
3247 +            return modified;
3248 +        }
3249 +
3250 +    }
3251 +
3252 +    static final class KeySet<K,V> extends CHMView<K,V> implements Set<K> {
3253 +        KeySet(ConcurrentHashMapV8<K, V> map)  {
3254 +            super(map);
3255 +        }
3256          public final boolean contains(Object o) { return map.containsKey(o); }
3257          public final boolean remove(Object o)   { return map.remove(o) != null; }
3258          public final Iterator<K> iterator() {
3259              return new KeyIterator<K,V>(map);
3260          }
3261 +        public final boolean add(K e) {
3262 +            throw new UnsupportedOperationException();
3263 +        }
3264 +        public final boolean addAll(Collection<? extends K> c) {
3265 +            throw new UnsupportedOperationException();
3266 +        }
3267 +        public boolean equals(Object o) {
3268 +            Set<?> c;
3269 +            return ((o instanceof Set) &&
3270 +                    ((c = (Set<?>)o) == this ||
3271 +                     (containsAll(c) && c.containsAll(this))));
3272 +        }
3273      }
3274  
1534    static final class Values<K,V> extends AbstractCollection<V> {
1535        final ConcurrentHashMapV8<K, V> map;
1536        Values(ConcurrentHashMapV8<K, V> map)   { this.map = map; }
3275  
3276 <        public final int size()                 { return map.size(); }
3277 <        public final boolean isEmpty()          { return map.isEmpty(); }
3278 <        public final void clear()               { map.clear(); }
3276 >    static final class Values<K,V> extends CHMView<K,V>
3277 >        implements Collection<V> {
3278 >        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
3279          public final boolean contains(Object o) { return map.containsValue(o); }
3280 +        public final boolean remove(Object o) {
3281 +            if (o != null) {
3282 +                Iterator<V> it = new ValueIterator<K,V>(map);
3283 +                while (it.hasNext()) {
3284 +                    if (o.equals(it.next())) {
3285 +                        it.remove();
3286 +                        return true;
3287 +                    }
3288 +                }
3289 +            }
3290 +            return false;
3291 +        }
3292          public final Iterator<V> iterator() {
3293              return new ValueIterator<K,V>(map);
3294          }
3295 <    }
3296 <
1547 <    static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> {
1548 <        final ConcurrentHashMapV8<K, V> map;
1549 <        EntrySet(ConcurrentHashMapV8<K, V> map) { this.map = map; }
1550 <
1551 <        public final int size()                 { return map.size(); }
1552 <        public final boolean isEmpty()          { return map.isEmpty(); }
1553 <        public final void clear()               { map.clear(); }
1554 <        public final Iterator<Map.Entry<K,V>> iterator() {
1555 <            return new EntryIterator<K,V>(map);
3295 >        public final boolean add(V e) {
3296 >            throw new UnsupportedOperationException();
3297          }
3298 +        public final boolean addAll(Collection<? extends V> c) {
3299 +            throw new UnsupportedOperationException();
3300 +        }
3301 +
3302 +    }
3303  
3304 +    static final class EntrySet<K,V> extends CHMView<K,V>
3305 +        implements Set<Map.Entry<K,V>> {
3306 +        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
3307          public final boolean contains(Object o) {
3308              Object k, v, r; Map.Entry<?,?> e;
3309              return ((o instanceof Map.Entry) &&
# Line 1563 | Line 3312 | public class ConcurrentHashMapV8<K, V>
3312                      (v = e.getValue()) != null &&
3313                      (v == r || v.equals(r)));
3314          }
1566
3315          public final boolean remove(Object o) {
3316              Object k, v; Map.Entry<?,?> e;
3317              return ((o instanceof Map.Entry) &&
# Line 1571 | Line 3319 | public class ConcurrentHashMapV8<K, V>
3319                      (v = e.getValue()) != null &&
3320                      map.remove(k, v));
3321          }
3322 +        public final Iterator<Map.Entry<K,V>> iterator() {
3323 +            return new EntryIterator<K,V>(map);
3324 +        }
3325 +        public final boolean add(Entry<K,V> e) {
3326 +            throw new UnsupportedOperationException();
3327 +        }
3328 +        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
3329 +            throw new UnsupportedOperationException();
3330 +        }
3331 +        public boolean equals(Object o) {
3332 +            Set<?> c;
3333 +            return ((o instanceof Set) &&
3334 +                    ((c = (Set<?>)o) == this ||
3335 +                     (containsAll(c) && c.containsAll(this))));
3336 +        }
3337      }
3338  
3339      /* ---------------- Serialization Support -------------- */
# Line 1595 | Line 3358 | public class ConcurrentHashMapV8<K, V>
3358       * The key-value mappings are emitted in no particular order.
3359       */
3360      @SuppressWarnings("unchecked")
3361 <    private void writeObject(java.io.ObjectOutputStream s)
3362 <            throws java.io.IOException {
3361 >        private void writeObject(java.io.ObjectOutputStream s)
3362 >        throws java.io.IOException {
3363          if (segments == null) { // for serialization compatibility
3364              segments = (Segment<K,V>[])
3365                  new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
# Line 1604 | Line 3367 | public class ConcurrentHashMapV8<K, V>
3367                  segments[i] = new Segment<K,V>(LOAD_FACTOR);
3368          }
3369          s.defaultWriteObject();
3370 <        InternalIterator it = new InternalIterator(table);
3371 <        while (it.next != null) {
3370 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3371 >        Object v;
3372 >        while ((v = it.advance()) != null) {
3373              s.writeObject(it.nextKey);
3374 <            s.writeObject(it.nextVal);
1611 <            it.advance();
3374 >            s.writeObject(v);
3375          }
3376          s.writeObject(null);
3377          s.writeObject(null);
# Line 1620 | Line 3383 | public class ConcurrentHashMapV8<K, V>
3383       * @param s the stream
3384       */
3385      @SuppressWarnings("unchecked")
3386 <    private void readObject(java.io.ObjectInputStream s)
3387 <            throws java.io.IOException, ClassNotFoundException {
3386 >        private void readObject(java.io.ObjectInputStream s)
3387 >        throws java.io.IOException, ClassNotFoundException {
3388          s.defaultReadObject();
3389          this.segments = null; // unneeded
3390          // initialize transient final field
3391          UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
1629        this.targetCapacity = DEFAULT_CAPACITY;
3392  
3393          // Create all nodes, then place in table once size is known
3394          long size = 0L;
# Line 1635 | Line 3397 | public class ConcurrentHashMapV8<K, V>
3397              K k = (K) s.readObject();
3398              V v = (V) s.readObject();
3399              if (k != null && v != null) {
3400 <                p = new Node(spread(k.hashCode()), k, v, p);
3400 >                int h = spread(k.hashCode());
3401 >                p = new Node(h, k, v, p);
3402                  ++size;
3403              }
3404              else
# Line 1643 | Line 3406 | public class ConcurrentHashMapV8<K, V>
3406          }
3407          if (p != null) {
3408              boolean init = false;
3409 <            if (resizing == 0 &&
3410 <                UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
3409 >            int n;
3410 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3411 >                n = MAXIMUM_CAPACITY;
3412 >            else {
3413 >                int sz = (int)size;
3414 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
3415 >            }
3416 >            int sc = sizeCtl;
3417 >            boolean collide = false;
3418 >            if (n > sc &&
3419 >                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
3420                  try {
3421                      if (table == null) {
3422                          init = true;
1651                        int n;
1652                        if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1653                            n = MAXIMUM_CAPACITY;
1654                        else {
1655                            int sz = (int)size;
1656                            n = tableSizeFor(sz + (sz >>> 1) + 1);
1657                        }
1658                        threshold = n - (n >>> 2) - THRESHOLD_OFFSET;
3423                          Node[] tab = new Node[n];
3424                          int mask = n - 1;
3425                          while (p != null) {
3426                              int j = p.hash & mask;
3427                              Node next = p.next;
3428 <                            p.next = tabAt(tab, j);
3428 >                            Node q = p.next = tabAt(tab, j);
3429                              setTabAt(tab, j, p);
3430 +                            if (!collide && q != null && q.hash == p.hash)
3431 +                                collide = true;
3432                              p = next;
3433                          }
3434                          table = tab;
3435                          counter.add(size);
3436 +                        sc = n - (n >>> 2);
3437                      }
3438                  } finally {
3439 <                    resizing = 0;
3439 >                    sizeCtl = sc;
3440 >                }
3441 >                if (collide) { // rescan and convert to TreeBins
3442 >                    Node[] tab = table;
3443 >                    for (int i = 0; i < tab.length; ++i) {
3444 >                        int c = 0;
3445 >                        for (Node e = tabAt(tab, i); e != null; e = e.next) {
3446 >                            if (++c > TREE_THRESHOLD &&
3447 >                                (e.key instanceof Comparable)) {
3448 >                                replaceWithTreeBin(tab, i, e.key);
3449 >                                break;
3450 >                            }
3451 >                        }
3452 >                    }
3453                  }
3454              }
3455              if (!init) { // Can only happen if unsafely published.
3456                  while (p != null) {
3457 <                    internalPut(p.key, p.val, true);
3457 >                    internalPut(p.key, p.val);
3458                      p = p.next;
3459                  }
3460              }
3461          }
3462      }
3463  
3464 +
3465 +    // -------------------------------------------------------
3466 +
3467 +    // Sams
3468 +    /** Interface describing a void action of one argument */
3469 +    public interface Action<A> { void apply(A a); }
3470 +    /** Interface describing a void action of two arguments */
3471 +    public interface BiAction<A,B> { void apply(A a, B b); }
3472 +    /** Interface describing a function of one argument */
3473 +    public interface Fun<A,T> { T apply(A a); }
3474 +    /** Interface describing a function of two arguments */
3475 +    public interface BiFun<A,B,T> { T apply(A a, B b); }
3476 +    /** Interface describing a function of no arguments */
3477 +    public interface Generator<T> { T apply(); }
3478 +    /** Interface describing a function mapping its argument to a double */
3479 +    public interface ObjectToDouble<A> { double apply(A a); }
3480 +    /** Interface describing a function mapping its argument to a long */
3481 +    public interface ObjectToLong<A> { long apply(A a); }
3482 +    /** Interface describing a function mapping its argument to an int */
3483 +    public interface ObjectToInt<A> {int apply(A a); }
3484 +    /** Interface describing a function mapping two arguments to a double */
3485 +    public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3486 +    /** Interface describing a function mapping two arguments to a long */
3487 +    public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3488 +    /** Interface describing a function mapping two arguments to an int */
3489 +    public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3490 +    /** Interface describing a function mapping a double to a double */
3491 +    public interface DoubleToDouble { double apply(double a); }
3492 +    /** Interface describing a function mapping a long to a long */
3493 +    public interface LongToLong { long apply(long a); }
3494 +    /** Interface describing a function mapping an int to an int */
3495 +    public interface IntToInt { int apply(int a); }
3496 +    /** Interface describing a function mapping two doubles to a double */
3497 +    public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3498 +    /** Interface describing a function mapping two longs to a long */
3499 +    public interface LongByLongToLong { long apply(long a, long b); }
3500 +    /** Interface describing a function mapping two ints to an int */
3501 +    public interface IntByIntToInt { int apply(int a, int b); }
3502 +
3503 +
3504 +    // -------------------------------------------------------
3505 +
3506 +    /**
3507 +     * Returns an extended {@link Parallel} view of this map using the
3508 +     * given executor for bulk parallel operations.
3509 +     *
3510 +     * @param executor the executor
3511 +     * @return a parallel view
3512 +     */
3513 +    public Parallel parallel(ForkJoinPool executor)  {
3514 +        return new Parallel(executor);
3515 +    }
3516 +
3517 +    /**
3518 +     * An extended view of a ConcurrentHashMap supporting bulk
3519 +     * parallel operations. These operations are designed to be
3520 +     * safely, and often sensibly, applied even with maps that are
3521 +     * being concurrently updated by other threads; for example, when
3522 +     * computing a snapshot summary of the values in a shared
3523 +     * registry.  There are three kinds of operation, each with four
3524 +     * forms, accepting functions with Keys, Values, Entries, and
3525 +     * (Key, Value) arguments and/or return values. Because the
3526 +     * elements of a ConcurrentHashMap are not ordered in any
3527 +     * particular way, and may be processed in different orders in
3528 +     * different parallel executions, the correctness of supplied
3529 +     * functions should not depend on any ordering, or on any other
3530 +     * objects or values that may transiently change while computation
3531 +     * is in progress; and except for forEach actions, should ideally
3532 +     * be side-effect-free.
3533 +     *
3534 +     * <ul>
3535 +     * <li> forEach: Perform a given action on each element.
3536 +     * A variant form applies a given transformation on each element
3537 +     * before performing the action.</li>
3538 +     *
3539 +     * <li> search: Return the first available non-null result of
3540 +     * applying a given function on each element; skipping further
3541 +     * search when a result is found.</li>
3542 +     *
3543 +     * <li> reduce: Accumulate each element.  The supplied reduction
3544 +     * function cannot rely on ordering (more formally, it should be
3545 +     * both associative and commutative).  There are five variants:
3546 +     *
3547 +     * <ul>
3548 +     *
3549 +     * <li> Plain reductions. (There is not a form of this method for
3550 +     * (key, value) function arguments since there is no corresponding
3551 +     * return type.)</li>
3552 +     *
3553 +     * <li> Mapped reductions that accumulate the results of a given
3554 +     * function applied to each element.</li>
3555 +     *
3556 +     * <li> Reductions to scalar doubles, longs, and ints, using a
3557 +     * given basis value.</li>
3558 +     *
3559 +     * </li>
3560 +     * </ul>
3561 +     * </ul>
3562 +     *
3563 +     * <p>The concurrency properties of the bulk operations follow
3564 +     * from those of ConcurrentHashMap: Any non-null result returned
3565 +     * from {@code get(key)} and related access methods bears a
3566 +     * happens-before relation with the associated insertion or
3567 +     * update.  The result of any bulk operation reflects the
3568 +     * composition of these per-element relations (but is not
3569 +     * necessarily atomic with respect to the map as a whole unless it
3570 +     * is somehow known to be quiescent).  Conversely, because keys
3571 +     * and values in the map are never null, null serves as a reliable
3572 +     * atomic indicator of the current lack of any result.  To
3573 +     * maintain this property, null serves as an implicit basis for
3574 +     * all non-scalar reduction operations. For the double, long, and
3575 +     * int versions, the basis should be one that, when combined with
3576 +     * any other value, returns that other value (more formally, it
3577 +     * should be the identity element for the reduction). Most common
3578 +     * reductions have these properties; for example, computing a sum
3579 +     * with basis 0 or a minimum with basis MAX_VALUE.
3580 +     *
3581 +     * <p>Search and transformation functions provided as arguments
3582 +     * should similarly return null to indicate the lack of any result
3583 +     * (in which case it is not used). In the case of mapped
3584 +     * reductions, this also enables transformations to serve as
3585 +     * filters, returning null (or, in the case of primitive
3586 +     * specializations, the identity basis) if the element should not
3587 +     * be combined. You can create compound transformations and
3588 +     * filterings by composing them yourself under this "null means
3589 +     * there is nothing there now" rule before using them in search or
3590 +     * reduce operations.
3591 +     *
3592 +     * <p>Methods accepting and/or returning Entry arguments maintain
3593 +     * key-value associations. They may be useful for example when
3594 +     * finding the key for the greatest value. Note that "plain" Entry
3595 +     * arguments can be supplied using {@code new
3596 +     * AbstractMap.SimpleEntry(k,v)}.
3597 +     *
3598 +     * <p> Bulk operations may complete abruptly, throwing an
3599 +     * exception encountered in the application of a supplied
3600 +     * function. Bear in mind when handling such exceptions that other
3601 +     * concurrently executing functions could also have thrown
3602 +     * exceptions, or would have done so if the first exception had
3603 +     * not occurred.
3604 +     *
3605 +     * <p>Parallel speedups compared to sequential processing are
3606 +     * common but not guaranteed.  Operations involving brief
3607 +     * functions on small maps may execute more slowly than sequential
3608 +     * loops if the underlying work to parallelize the computation is
3609 +     * more expensive than the computation itself. Similarly,
3610 +     * parallelization may not lead to much actual parallelism if all
3611 +     * processors are busy performing unrelated tasks.
3612 +     *
3613 +     * <p> All arguments to all task methods must be non-null.
3614 +     *
3615 +     * <p><em>jsr166e note: During transition, this class
3616 +     * uses nested functional interfaces with different names but the
3617 +     * same forms as those expected for JDK8.<em>
3618 +     */
3619 +    public class Parallel {
3620 +        final ForkJoinPool fjp;
3621 +
3622 +        /**
3623 +         * Returns an extended view of this map using the given
3624 +         * executor for bulk parallel operations.
3625 +         *
3626 +         * @param executor the executor
3627 +         */
3628 +        public Parallel(ForkJoinPool executor)  {
3629 +            this.fjp = executor;
3630 +        }
3631 +
3632 +        /**
3633 +         * Performs the given action for each (key, value).
3634 +         *
3635 +         * @param action the action
3636 +         */
3637 +        public void forEach(BiAction<K,V> action) {
3638 +            fjp.invoke(ForkJoinTasks.forEach
3639 +                       (ConcurrentHashMapV8.this, action));
3640 +        }
3641 +
3642 +        /**
3643 +         * Performs the given action for each non-null transformation
3644 +         * of each (key, value).
3645 +         *
3646 +         * @param transformer a function returning the transformation
3647 +         * for an element, or null of there is no transformation (in
3648 +         * which case the action is not applied).
3649 +         * @param action the action
3650 +         */
3651 +        public <U> void forEach(BiFun<? super K, ? super V, ? extends U> transformer,
3652 +                                Action<U> action) {
3653 +            fjp.invoke(ForkJoinTasks.forEach
3654 +                       (ConcurrentHashMapV8.this, transformer, action));
3655 +        }
3656 +
3657 +        /**
3658 +         * Returns a non-null result from applying the given search
3659 +         * function on each (key, value), or null if none.  Further
3660 +         * element processing is suppressed upon success. However,
3661 +         * this method does not return until other in-progress
3662 +         * parallel invocations of the search function also complete.
3663 +         *
3664 +         * @param searchFunction a function returning a non-null
3665 +         * result on success, else null
3666 +         * @return a non-null result from applying the given search
3667 +         * function on each (key, value), or null if none
3668 +         */
3669 +        public <U> U search(BiFun<? super K, ? super V, ? extends U> searchFunction) {
3670 +            return fjp.invoke(ForkJoinTasks.search
3671 +                              (ConcurrentHashMapV8.this, searchFunction));
3672 +        }
3673 +
3674 +        /**
3675 +         * Returns the result of accumulating the given transformation
3676 +         * of all (key, value) pairs using the given reducer to
3677 +         * combine values, or null if none.
3678 +         *
3679 +         * @param transformer a function returning the transformation
3680 +         * for an element, or null of there is no transformation (in
3681 +         * which case it is not combined).
3682 +         * @param reducer a commutative associative combining function
3683 +         * @return the result of accumulating the given transformation
3684 +         * of all (key, value) pairs
3685 +         */
3686 +        public <U> U reduce(BiFun<? super K, ? super V, ? extends U> transformer,
3687 +                            BiFun<? super U, ? super U, ? extends U> reducer) {
3688 +            return fjp.invoke(ForkJoinTasks.reduce
3689 +                              (ConcurrentHashMapV8.this, transformer, reducer));
3690 +        }
3691 +
3692 +        /**
3693 +         * Returns the result of accumulating the given transformation
3694 +         * of all (key, value) pairs using the given reducer to
3695 +         * combine values, and the given basis as an identity value.
3696 +         *
3697 +         * @param transformer a function returning the transformation
3698 +         * for an element
3699 +         * @param basis the identity (initial default value) for the reduction
3700 +         * @param reducer a commutative associative combining function
3701 +         * @return the result of accumulating the given transformation
3702 +         * of all (key, value) pairs
3703 +         */
3704 +        public double reduceToDouble(ObjectByObjectToDouble<? super K, ? super V> transformer,
3705 +                                     double basis,
3706 +                                     DoubleByDoubleToDouble reducer) {
3707 +            return fjp.invoke(ForkJoinTasks.reduceToDouble
3708 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3709 +        }
3710 +
3711 +        /**
3712 +         * Returns the result of accumulating the given transformation
3713 +         * of all (key, value) pairs using the given reducer to
3714 +         * combine values, and the given basis as an identity value.
3715 +         *
3716 +         * @param transformer a function returning the transformation
3717 +         * for an element
3718 +         * @param basis the identity (initial default value) for the reduction
3719 +         * @param reducer a commutative associative combining function
3720 +         * @return the result of accumulating the given transformation
3721 +         * of all (key, value) pairs using the given reducer to
3722 +         * combine values, and the given basis as an identity value.
3723 +         */
3724 +        public long reduceToLong(ObjectByObjectToLong<? super K, ? super V> transformer,
3725 +                                 long basis,
3726 +                                 LongByLongToLong reducer) {
3727 +            return fjp.invoke(ForkJoinTasks.reduceToLong
3728 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3729 +        }
3730 +
3731 +        /**
3732 +         * Returns the result of accumulating the given transformation
3733 +         * of all (key, value) pairs using the given reducer to
3734 +         * combine values, and the given basis as an identity value.
3735 +         *
3736 +         * @param transformer a function returning the transformation
3737 +         * for an element
3738 +         * @param basis the identity (initial default value) for the reduction
3739 +         * @param reducer a commutative associative combining function
3740 +         * @return the result of accumulating the given transformation
3741 +         * of all (key, value) pairs
3742 +         */
3743 +        public int reduceToInt(ObjectByObjectToInt<? super K, ? super V> transformer,
3744 +                               int basis,
3745 +                               IntByIntToInt reducer) {
3746 +            return fjp.invoke(ForkJoinTasks.reduceToInt
3747 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3748 +        }
3749 +
3750 +        /**
3751 +         * Performs the given action for each key.
3752 +         *
3753 +         * @param action the action
3754 +         */
3755 +        public void forEachKey(Action<K> action) {
3756 +            fjp.invoke(ForkJoinTasks.forEachKey
3757 +                       (ConcurrentHashMapV8.this, action));
3758 +        }
3759 +
3760 +        /**
3761 +         * Performs the given action for each non-null transformation
3762 +         * of each key.
3763 +         *
3764 +         * @param transformer a function returning the transformation
3765 +         * for an element, or null of there is no transformation (in
3766 +         * which case the action is not applied).
3767 +         * @param action the action
3768 +         */
3769 +        public <U> void forEachKey(Fun<? super K, ? extends U> transformer,
3770 +                                   Action<U> action) {
3771 +            fjp.invoke(ForkJoinTasks.forEachKey
3772 +                       (ConcurrentHashMapV8.this, transformer, action));
3773 +        }
3774 +
3775 +        /**
3776 +         * Returns a non-null result from applying the given search
3777 +         * function on each key, or null if none.  Further element
3778 +         * processing is suppressed upon success. However, this method
3779 +         * does not return until other in-progress parallel
3780 +         * invocations of the search function also complete.
3781 +         *
3782 +         * @param searchFunction a function returning a non-null
3783 +         * result on success, else null
3784 +         * @return a non-null result from applying the given search
3785 +         * function on each key, or null if none
3786 +         */
3787 +        public <U> U searchKeys(Fun<? super K, ? extends U> searchFunction) {
3788 +            return fjp.invoke(ForkJoinTasks.searchKeys
3789 +                              (ConcurrentHashMapV8.this, searchFunction));
3790 +        }
3791 +
3792 +        /**
3793 +         * Returns the result of accumulating all keys using the given
3794 +         * reducer to combine values, or null if none.
3795 +         *
3796 +         * @param reducer a commutative associative combining function
3797 +         * @return the result of accumulating all keys using the given
3798 +         * reducer to combine values, or null if none
3799 +         */
3800 +        public K reduceKeys(BiFun<? super K, ? super K, ? extends K> reducer) {
3801 +            return fjp.invoke(ForkJoinTasks.reduceKeys
3802 +                              (ConcurrentHashMapV8.this, reducer));
3803 +        }
3804 +
3805 +        /**
3806 +         * Returns the result of accumulating the given transformation
3807 +         * of all keys using the given reducer to combine values, or
3808 +         * null if none.
3809 +         *
3810 +         * @param transformer a function returning the transformation
3811 +         * for an element, or null of there is no transformation (in
3812 +         * which case it is not combined).
3813 +         * @param reducer a commutative associative combining function
3814 +         * @return the result of accumulating the given transformation
3815 +         * of all keys
3816 +         */
3817 +        public <U> U reduceKeys(Fun<? super K, ? extends U> transformer,
3818 +                                BiFun<? super U, ? super U, ? extends U> reducer) {
3819 +            return fjp.invoke(ForkJoinTasks.reduceKeys
3820 +                              (ConcurrentHashMapV8.this, transformer, reducer));
3821 +        }
3822 +
3823 +        /**
3824 +         * Returns the result of accumulating the given transformation
3825 +         * of all keys using the given reducer to combine values, and
3826 +         * the given basis as an identity value.
3827 +         *
3828 +         * @param transformer a function returning the transformation
3829 +         * for an element
3830 +         * @param basis the identity (initial default value) for the reduction
3831 +         * @param reducer a commutative associative combining function
3832 +         * @return  the result of accumulating the given transformation
3833 +         * of all keys
3834 +         */
3835 +        public double reduceKeysToDouble(ObjectToDouble<? super K> transformer,
3836 +                                         double basis,
3837 +                                         DoubleByDoubleToDouble reducer) {
3838 +            return fjp.invoke(ForkJoinTasks.reduceKeysToDouble
3839 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3840 +        }
3841 +
3842 +        /**
3843 +         * Returns the result of accumulating the given transformation
3844 +         * of all keys using the given reducer to combine values, and
3845 +         * the given basis as an identity value.
3846 +         *
3847 +         * @param transformer a function returning the transformation
3848 +         * for an element
3849 +         * @param basis the identity (initial default value) for the reduction
3850 +         * @param reducer a commutative associative combining function
3851 +         * @return the result of accumulating the given transformation
3852 +         * of all keys
3853 +         */
3854 +        public long reduceKeysToLong(ObjectToLong<? super K> transformer,
3855 +                                     long basis,
3856 +                                     LongByLongToLong reducer) {
3857 +            return fjp.invoke(ForkJoinTasks.reduceKeysToLong
3858 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3859 +        }
3860 +
3861 +        /**
3862 +         * Returns the result of accumulating the given transformation
3863 +         * of all keys using the given reducer to combine values, and
3864 +         * the given basis as an identity value.
3865 +         *
3866 +         * @param transformer a function returning the transformation
3867 +         * for an element
3868 +         * @param basis the identity (initial default value) for the reduction
3869 +         * @param reducer a commutative associative combining function
3870 +         * @return the result of accumulating the given transformation
3871 +         * of all keys
3872 +         */
3873 +        public int reduceKeysToInt(ObjectToInt<? super K> transformer,
3874 +                                   int basis,
3875 +                                   IntByIntToInt reducer) {
3876 +            return fjp.invoke(ForkJoinTasks.reduceKeysToInt
3877 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3878 +        }
3879 +
3880 +        /**
3881 +         * Performs the given action for each value.
3882 +         *
3883 +         * @param action the action
3884 +         */
3885 +        public void forEachValue(Action<V> action) {
3886 +            fjp.invoke(ForkJoinTasks.forEachValue
3887 +                       (ConcurrentHashMapV8.this, action));
3888 +        }
3889 +
3890 +        /**
3891 +         * Performs the given action for each non-null transformation
3892 +         * of each value.
3893 +         *
3894 +         * @param transformer a function returning the transformation
3895 +         * for an element, or null of there is no transformation (in
3896 +         * which case the action is not applied).
3897 +         */
3898 +        public <U> void forEachValue(Fun<? super V, ? extends U> transformer,
3899 +                                     Action<U> action) {
3900 +            fjp.invoke(ForkJoinTasks.forEachValue
3901 +                       (ConcurrentHashMapV8.this, transformer, action));
3902 +        }
3903 +
3904 +        /**
3905 +         * Returns a non-null result from applying the given search
3906 +         * function on each value, or null if none.  Further element
3907 +         * processing is suppressed upon success. However, this method
3908 +         * does not return until other in-progress parallel
3909 +         * invocations of the search function also complete.
3910 +         *
3911 +         * @param searchFunction a function returning a non-null
3912 +         * result on success, else null
3913 +         * @return a non-null result from applying the given search
3914 +         * function on each value, or null if none
3915 +         *
3916 +         */
3917 +        public <U> U searchValues(Fun<? super V, ? extends U> searchFunction) {
3918 +            return fjp.invoke(ForkJoinTasks.searchValues
3919 +                              (ConcurrentHashMapV8.this, searchFunction));
3920 +        }
3921 +
3922 +        /**
3923 +         * Returns the result of accumulating all values using the
3924 +         * given reducer to combine values, or null if none.
3925 +         *
3926 +         * @param reducer a commutative associative combining function
3927 +         * @return  the result of accumulating all values
3928 +         */
3929 +        public V reduceValues(BiFun<? super V, ? super V, ? extends V> reducer) {
3930 +            return fjp.invoke(ForkJoinTasks.reduceValues
3931 +                              (ConcurrentHashMapV8.this, reducer));
3932 +        }
3933 +
3934 +        /**
3935 +         * Returns the result of accumulating the given transformation
3936 +         * of all values using the given reducer to combine values, or
3937 +         * null if none.
3938 +         *
3939 +         * @param transformer a function returning the transformation
3940 +         * for an element, or null of there is no transformation (in
3941 +         * which case it is not combined).
3942 +         * @param reducer a commutative associative combining function
3943 +         * @return the result of accumulating the given transformation
3944 +         * of all values
3945 +         */
3946 +        public <U> U reduceValues(Fun<? super V, ? extends U> transformer,
3947 +                                  BiFun<? super U, ? super U, ? extends U> reducer) {
3948 +            return fjp.invoke(ForkJoinTasks.reduceValues
3949 +                              (ConcurrentHashMapV8.this, transformer, reducer));
3950 +        }
3951 +
3952 +        /**
3953 +         * Returns the result of accumulating the given transformation
3954 +         * of all values using the given reducer to combine values,
3955 +         * and the given basis as an identity value.
3956 +         *
3957 +         * @param transformer a function returning the transformation
3958 +         * for an element
3959 +         * @param basis the identity (initial default value) for the reduction
3960 +         * @param reducer a commutative associative combining function
3961 +         * @return the result of accumulating the given transformation
3962 +         * of all values
3963 +         */
3964 +        public double reduceValuesToDouble(ObjectToDouble<? super V> transformer,
3965 +                                           double basis,
3966 +                                           DoubleByDoubleToDouble reducer) {
3967 +            return fjp.invoke(ForkJoinTasks.reduceValuesToDouble
3968 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3969 +        }
3970 +
3971 +        /**
3972 +         * Returns the result of accumulating the given transformation
3973 +         * of all values using the given reducer to combine values,
3974 +         * and the given basis as an identity value.
3975 +         *
3976 +         * @param transformer a function returning the transformation
3977 +         * for an element
3978 +         * @param basis the identity (initial default value) for the reduction
3979 +         * @param reducer a commutative associative combining function
3980 +         * @return the result of accumulating the given transformation
3981 +         * of all values
3982 +         */
3983 +        public long reduceValuesToLong(ObjectToLong<? super V> transformer,
3984 +                                       long basis,
3985 +                                       LongByLongToLong reducer) {
3986 +            return fjp.invoke(ForkJoinTasks.reduceValuesToLong
3987 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
3988 +        }
3989 +
3990 +        /**
3991 +         * Returns the result of accumulating the given transformation
3992 +         * of all values using the given reducer to combine values,
3993 +         * and the given basis as an identity value.
3994 +         *
3995 +         * @param transformer a function returning the transformation
3996 +         * for an element
3997 +         * @param basis the identity (initial default value) for the reduction
3998 +         * @param reducer a commutative associative combining function
3999 +         * @return the result of accumulating the given transformation
4000 +         * of all values
4001 +         */
4002 +        public int reduceValuesToInt(ObjectToInt<? super V> transformer,
4003 +                                     int basis,
4004 +                                     IntByIntToInt reducer) {
4005 +            return fjp.invoke(ForkJoinTasks.reduceValuesToInt
4006 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4007 +        }
4008 +
4009 +        /**
4010 +         * Performs the given action for each entry.
4011 +         *
4012 +         * @param action the action
4013 +         */
4014 +        public void forEachEntry(Action<Map.Entry<K,V>> action) {
4015 +            fjp.invoke(ForkJoinTasks.forEachEntry
4016 +                       (ConcurrentHashMapV8.this, action));
4017 +        }
4018 +
4019 +        /**
4020 +         * Performs the given action for each non-null transformation
4021 +         * of each entry.
4022 +         *
4023 +         * @param transformer a function returning the transformation
4024 +         * for an element, or null of there is no transformation (in
4025 +         * which case the action is not applied).
4026 +         * @param action the action
4027 +         */
4028 +        public <U> void forEachEntry(Fun<Map.Entry<K,V>, ? extends U> transformer,
4029 +                                     Action<U> action) {
4030 +            fjp.invoke(ForkJoinTasks.forEachEntry
4031 +                       (ConcurrentHashMapV8.this, transformer, action));
4032 +        }
4033 +
4034 +        /**
4035 +         * Returns a non-null result from applying the given search
4036 +         * function on each entry, or null if none.  Further element
4037 +         * processing is suppressed upon success. However, this method
4038 +         * does not return until other in-progress parallel
4039 +         * invocations of the search function also complete.
4040 +         *
4041 +         * @param searchFunction a function returning a non-null
4042 +         * result on success, else null
4043 +         * @return a non-null result from applying the given search
4044 +         * function on each entry, or null if none
4045 +         */
4046 +        public <U> U searchEntries(Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4047 +            return fjp.invoke(ForkJoinTasks.searchEntries
4048 +                              (ConcurrentHashMapV8.this, searchFunction));
4049 +        }
4050 +
4051 +        /**
4052 +         * Returns the result of accumulating all entries using the
4053 +         * given reducer to combine values, or null if none.
4054 +         *
4055 +         * @param reducer a commutative associative combining function
4056 +         * @return the result of accumulating all entries
4057 +         */
4058 +        public Map.Entry<K,V> reduceEntries(BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4059 +            return fjp.invoke(ForkJoinTasks.reduceEntries
4060 +                              (ConcurrentHashMapV8.this, reducer));
4061 +        }
4062 +
4063 +        /**
4064 +         * Returns the result of accumulating the given transformation
4065 +         * of all entries using the given reducer to combine values,
4066 +         * or null if none.
4067 +         *
4068 +         * @param transformer a function returning the transformation
4069 +         * for an element, or null of there is no transformation (in
4070 +         * which case it is not combined).
4071 +         * @param reducer a commutative associative combining function
4072 +         * @return the result of accumulating the given transformation
4073 +         * of all entries
4074 +         */
4075 +        public <U> U reduceEntries(Fun<Map.Entry<K,V>, ? extends U> transformer,
4076 +                                   BiFun<? super U, ? super U, ? extends U> reducer) {
4077 +            return fjp.invoke(ForkJoinTasks.reduceEntries
4078 +                              (ConcurrentHashMapV8.this, transformer, reducer));
4079 +        }
4080 +
4081 +        /**
4082 +         * Returns the result of accumulating the given transformation
4083 +         * of all entries using the given reducer to combine values,
4084 +         * and the given basis as an identity value.
4085 +         *
4086 +         * @param transformer a function returning the transformation
4087 +         * for an element
4088 +         * @param basis the identity (initial default value) for the reduction
4089 +         * @param reducer a commutative associative combining function
4090 +         * @return the result of accumulating the given transformation
4091 +         * of all entries
4092 +         */
4093 +        public double reduceEntriesToDouble(ObjectToDouble<Map.Entry<K,V>> transformer,
4094 +                                            double basis,
4095 +                                            DoubleByDoubleToDouble reducer) {
4096 +            return fjp.invoke(ForkJoinTasks.reduceEntriesToDouble
4097 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4098 +        }
4099 +
4100 +        /**
4101 +         * Returns the result of accumulating the given transformation
4102 +         * of all entries using the given reducer to combine values,
4103 +         * and the given basis as an identity value.
4104 +         *
4105 +         * @param transformer a function returning the transformation
4106 +         * for an element
4107 +         * @param basis the identity (initial default value) for the reduction
4108 +         * @param reducer a commutative associative combining function
4109 +         * @return  the result of accumulating the given transformation
4110 +         * of all entries
4111 +         */
4112 +        public long reduceEntriesToLong(ObjectToLong<Map.Entry<K,V>> transformer,
4113 +                                        long basis,
4114 +                                        LongByLongToLong reducer) {
4115 +            return fjp.invoke(ForkJoinTasks.reduceEntriesToLong
4116 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4117 +        }
4118 +
4119 +        /**
4120 +         * Returns the result of accumulating the given transformation
4121 +         * of all entries using the given reducer to combine values,
4122 +         * and the given basis as an identity value.
4123 +         *
4124 +         * @param transformer a function returning the transformation
4125 +         * for an element
4126 +         * @param basis the identity (initial default value) for the reduction
4127 +         * @param reducer a commutative associative combining function
4128 +         * @return the result of accumulating the given transformation
4129 +         * of all entries
4130 +         */
4131 +        public int reduceEntriesToInt(ObjectToInt<Map.Entry<K,V>> transformer,
4132 +                                      int basis,
4133 +                                      IntByIntToInt reducer) {
4134 +            return fjp.invoke(ForkJoinTasks.reduceEntriesToInt
4135 +                              (ConcurrentHashMapV8.this, transformer, basis, reducer));
4136 +        }
4137 +    }
4138 +
4139 +    // ---------------------------------------------------------------------
4140 +
4141 +    /**
4142 +     * Predefined tasks for performing bulk parallel operations on
4143 +     * ConcurrentHashMaps. These tasks follow the forms and rules used
4144 +     * in class {@link Parallel}. Each method has the same name, but
4145 +     * returns a task rather than invoking it. These methods may be
4146 +     * useful in custom applications such as submitting a task without
4147 +     * waiting for completion, or combining with other tasks.
4148 +     */
4149 +    public static class ForkJoinTasks {
4150 +        private ForkJoinTasks() {}
4151 +
4152 +        /**
4153 +         * Returns a task that when invoked, performs the given
4154 +         * action for each (key, value)
4155 +         *
4156 +         * @param map the map
4157 +         * @param action the action
4158 +         * @return the task
4159 +         */
4160 +        public static <K,V> ForkJoinTask<Void> forEach
4161 +            (ConcurrentHashMapV8<K,V> map,
4162 +             BiAction<K,V> action) {
4163 +            if (action == null) throw new NullPointerException();
4164 +            return new ForEachMappingTask<K,V>(map, action);
4165 +        }
4166 +
4167 +        /**
4168 +         * Returns a task that when invoked, performs the given
4169 +         * action for each non-null transformation of each (key, value)
4170 +         *
4171 +         * @param map the map
4172 +         * @param transformer a function returning the transformation
4173 +         * for an element, or null of there is no transformation (in
4174 +         * which case the action is not applied).
4175 +         * @param action the action
4176 +         * @return the task
4177 +         */
4178 +        public static <K,V,U> ForkJoinTask<Void> forEach
4179 +            (ConcurrentHashMapV8<K,V> map,
4180 +             BiFun<? super K, ? super V, ? extends U> transformer,
4181 +             Action<U> action) {
4182 +            if (transformer == null || action == null)
4183 +                throw new NullPointerException();
4184 +            return new ForEachTransformedMappingTask<K,V,U>
4185 +                (map, transformer, action);
4186 +        }
4187 +
4188 +        /**
4189 +         * Returns a task that when invoked, returns a non-null
4190 +         * result from applying the given search function on each
4191 +         * (key, value), or null if none.  Further element processing
4192 +         * is suppressed upon success. However, this method does not
4193 +         * return until other in-progress parallel invocations of the
4194 +         * search function also complete.
4195 +         *
4196 +         * @param map the map
4197 +         * @param searchFunction a function returning a non-null
4198 +         * result on success, else null
4199 +         * @return the task
4200 +         */
4201 +        public static <K,V,U> ForkJoinTask<U> search
4202 +            (ConcurrentHashMapV8<K,V> map,
4203 +             BiFun<? super K, ? super V, ? extends U> searchFunction) {
4204 +            if (searchFunction == null) throw new NullPointerException();
4205 +            return new SearchMappingsTask<K,V,U>
4206 +                (map, searchFunction,
4207 +                 new AtomicReference<U>());
4208 +        }
4209 +
4210 +        /**
4211 +         * Returns a task that when invoked, returns the result of
4212 +         * accumulating the given transformation of all (key, value) pairs
4213 +         * using the given reducer to combine values, or null if none.
4214 +         *
4215 +         * @param map the map
4216 +         * @param transformer a function returning the transformation
4217 +         * for an element, or null of there is no transformation (in
4218 +         * which case it is not combined).
4219 +         * @param reducer a commutative associative combining function
4220 +         * @return the task
4221 +         */
4222 +        public static <K,V,U> ForkJoinTask<U> reduce
4223 +            (ConcurrentHashMapV8<K,V> map,
4224 +             BiFun<? super K, ? super V, ? extends U> transformer,
4225 +             BiFun<? super U, ? super U, ? extends U> reducer) {
4226 +            if (transformer == null || reducer == null)
4227 +                throw new NullPointerException();
4228 +            return new MapReduceMappingsTask<K,V,U>
4229 +                (map, transformer, reducer);
4230 +        }
4231 +
4232 +        /**
4233 +         * Returns a task that when invoked, returns the result of
4234 +         * accumulating the given transformation of all (key, value) pairs
4235 +         * using the given reducer to combine values, and the given
4236 +         * basis as an identity value.
4237 +         *
4238 +         * @param map the map
4239 +         * @param transformer a function returning the transformation
4240 +         * for an element
4241 +         * @param basis the identity (initial default value) for the reduction
4242 +         * @param reducer a commutative associative combining function
4243 +         * @return the task
4244 +         */
4245 +        public static <K,V> ForkJoinTask<Double> reduceToDouble
4246 +            (ConcurrentHashMapV8<K,V> map,
4247 +             ObjectByObjectToDouble<? super K, ? super V> transformer,
4248 +             double basis,
4249 +             DoubleByDoubleToDouble reducer) {
4250 +            if (transformer == null || reducer == null)
4251 +                throw new NullPointerException();
4252 +            return new MapReduceMappingsToDoubleTask<K,V>
4253 +                (map, transformer, basis, reducer);
4254 +        }
4255 +
4256 +        /**
4257 +         * Returns a task that when invoked, returns the result of
4258 +         * accumulating the given transformation of all (key, value) pairs
4259 +         * using the given reducer to combine values, and the given
4260 +         * basis as an identity value.
4261 +         *
4262 +         * @param map the map
4263 +         * @param transformer a function returning the transformation
4264 +         * for an element
4265 +         * @param basis the identity (initial default value) for the reduction
4266 +         * @param reducer a commutative associative combining function
4267 +         * @return the task
4268 +         */
4269 +        public static <K,V> ForkJoinTask<Long> reduceToLong
4270 +            (ConcurrentHashMapV8<K,V> map,
4271 +             ObjectByObjectToLong<? super K, ? super V> transformer,
4272 +             long basis,
4273 +             LongByLongToLong reducer) {
4274 +            if (transformer == null || reducer == null)
4275 +                throw new NullPointerException();
4276 +            return new MapReduceMappingsToLongTask<K,V>
4277 +                (map, transformer, basis, reducer);
4278 +        }
4279 +
4280 +        /**
4281 +         * Returns a task that when invoked, returns the result of
4282 +         * accumulating the given transformation of all (key, value) pairs
4283 +         * using the given reducer to combine values, and the given
4284 +         * basis as an identity value.
4285 +         *
4286 +         * @param transformer a function returning the transformation
4287 +         * for an element
4288 +         * @param basis the identity (initial default value) for the reduction
4289 +         * @param reducer a commutative associative combining function
4290 +         * @return the task
4291 +         */
4292 +        public static <K,V> ForkJoinTask<Integer> reduceToInt
4293 +            (ConcurrentHashMapV8<K,V> map,
4294 +             ObjectByObjectToInt<? super K, ? super V> transformer,
4295 +             int basis,
4296 +             IntByIntToInt reducer) {
4297 +            if (transformer == null || reducer == null)
4298 +                throw new NullPointerException();
4299 +            return new MapReduceMappingsToIntTask<K,V>
4300 +                (map, transformer, basis, reducer);
4301 +        }
4302 +
4303 +        /**
4304 +         * Returns a task that when invoked, performs the given action
4305 +         * for each key.
4306 +         *
4307 +         * @param map the map
4308 +         * @param action the action
4309 +         * @return the task
4310 +         */
4311 +        public static <K,V> ForkJoinTask<Void> forEachKey
4312 +            (ConcurrentHashMapV8<K,V> map,
4313 +             Action<K> action) {
4314 +            if (action == null) throw new NullPointerException();
4315 +            return new ForEachKeyTask<K,V>(map, action);
4316 +        }
4317 +
4318 +        /**
4319 +         * Returns a task that when invoked, performs the given action
4320 +         * for each non-null transformation of each key.
4321 +         *
4322 +         * @param map the map
4323 +         * @param transformer a function returning the transformation
4324 +         * for an element, or null of there is no transformation (in
4325 +         * which case the action is not applied).
4326 +         * @param action the action
4327 +         * @return the task
4328 +         */
4329 +        public static <K,V,U> ForkJoinTask<Void> forEachKey
4330 +            (ConcurrentHashMapV8<K,V> map,
4331 +             Fun<? super K, ? extends U> transformer,
4332 +             Action<U> action) {
4333 +            if (transformer == null || action == null)
4334 +                throw new NullPointerException();
4335 +            return new ForEachTransformedKeyTask<K,V,U>
4336 +                (map, transformer, action);
4337 +        }
4338 +
4339 +        /**
4340 +         * Returns a task that when invoked, returns a non-null result
4341 +         * from applying the given search function on each key, or
4342 +         * null if none.  Further element processing is suppressed
4343 +         * upon success. However, this method does not return until
4344 +         * other in-progress parallel invocations of the search
4345 +         * function also complete.
4346 +         *
4347 +         * @param map the map
4348 +         * @param searchFunction a function returning a non-null
4349 +         * result on success, else null
4350 +         * @return the task
4351 +         */
4352 +        public static <K,V,U> ForkJoinTask<U> searchKeys
4353 +            (ConcurrentHashMapV8<K,V> map,
4354 +             Fun<? super K, ? extends U> searchFunction) {
4355 +            if (searchFunction == null) throw new NullPointerException();
4356 +            return new SearchKeysTask<K,V,U>
4357 +                (map, searchFunction,
4358 +                 new AtomicReference<U>());
4359 +        }
4360 +
4361 +        /**
4362 +         * Returns a task that when invoked, returns the result of
4363 +         * accumulating all keys using the given reducer to combine
4364 +         * values, or null if none.
4365 +         *
4366 +         * @param map the map
4367 +         * @param reducer a commutative associative combining function
4368 +         * @return the task
4369 +         */
4370 +        public static <K,V> ForkJoinTask<K> reduceKeys
4371 +            (ConcurrentHashMapV8<K,V> map,
4372 +             BiFun<? super K, ? super K, ? extends K> reducer) {
4373 +            if (reducer == null) throw new NullPointerException();
4374 +            return new ReduceKeysTask<K,V>
4375 +                (map, reducer);
4376 +        }
4377 +        /**
4378 +         * Returns a task that when invoked, returns the result of
4379 +         * accumulating the given transformation of all keys using the given
4380 +         * reducer to combine values, or null if none.
4381 +         *
4382 +         * @param map the map
4383 +         * @param transformer a function returning the transformation
4384 +         * for an element, or null of there is no transformation (in
4385 +         * which case it is not combined).
4386 +         * @param reducer a commutative associative combining function
4387 +         * @return the task
4388 +         */
4389 +        public static <K,V,U> ForkJoinTask<U> reduceKeys
4390 +            (ConcurrentHashMapV8<K,V> map,
4391 +             Fun<? super K, ? extends U> transformer,
4392 +             BiFun<? super U, ? super U, ? extends U> reducer) {
4393 +            if (transformer == null || reducer == null)
4394 +                throw new NullPointerException();
4395 +            return new MapReduceKeysTask<K,V,U>
4396 +                (map, transformer, reducer);
4397 +        }
4398 +
4399 +        /**
4400 +         * Returns a task that when invoked, returns the result of
4401 +         * accumulating the given transformation of all keys using the given
4402 +         * reducer to combine values, and the given basis as an
4403 +         * identity value.
4404 +         *
4405 +         * @param map the map
4406 +         * @param transformer a function returning the transformation
4407 +         * for an element
4408 +         * @param basis the identity (initial default value) for the reduction
4409 +         * @param reducer a commutative associative combining function
4410 +         * @return the task
4411 +         */
4412 +        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
4413 +            (ConcurrentHashMapV8<K,V> map,
4414 +             ObjectToDouble<? super K> transformer,
4415 +             double basis,
4416 +             DoubleByDoubleToDouble reducer) {
4417 +            if (transformer == null || reducer == null)
4418 +                throw new NullPointerException();
4419 +            return new MapReduceKeysToDoubleTask<K,V>
4420 +                (map, transformer, basis, reducer);
4421 +        }
4422 +
4423 +        /**
4424 +         * Returns a task that when invoked, returns the result of
4425 +         * accumulating the given transformation of all keys using the given
4426 +         * reducer to combine values, and the given basis as an
4427 +         * identity value.
4428 +         *
4429 +         * @param map the map
4430 +         * @param transformer a function returning the transformation
4431 +         * for an element
4432 +         * @param basis the identity (initial default value) for the reduction
4433 +         * @param reducer a commutative associative combining function
4434 +         * @return the task
4435 +         */
4436 +        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
4437 +            (ConcurrentHashMapV8<K,V> map,
4438 +             ObjectToLong<? super K> transformer,
4439 +             long basis,
4440 +             LongByLongToLong reducer) {
4441 +            if (transformer == null || reducer == null)
4442 +                throw new NullPointerException();
4443 +            return new MapReduceKeysToLongTask<K,V>
4444 +                (map, transformer, basis, reducer);
4445 +        }
4446 +
4447 +        /**
4448 +         * Returns a task that when invoked, returns the result of
4449 +         * accumulating the given transformation of all keys using the given
4450 +         * reducer to combine values, and the given basis as an
4451 +         * identity value.
4452 +         *
4453 +         * @param map the map
4454 +         * @param transformer a function returning the transformation
4455 +         * for an element
4456 +         * @param basis the identity (initial default value) for the reduction
4457 +         * @param reducer a commutative associative combining function
4458 +         * @return the task
4459 +         */
4460 +        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
4461 +            (ConcurrentHashMapV8<K,V> map,
4462 +             ObjectToInt<? super K> transformer,
4463 +             int basis,
4464 +             IntByIntToInt reducer) {
4465 +            if (transformer == null || reducer == null)
4466 +                throw new NullPointerException();
4467 +            return new MapReduceKeysToIntTask<K,V>
4468 +                (map, transformer, basis, reducer);
4469 +        }
4470 +
4471 +        /**
4472 +         * Returns a task that when invoked, performs the given action
4473 +         * for each value.
4474 +         *
4475 +         * @param map the map
4476 +         * @param action the action
4477 +         */
4478 +        public static <K,V> ForkJoinTask<Void> forEachValue
4479 +            (ConcurrentHashMapV8<K,V> map,
4480 +             Action<V> action) {
4481 +            if (action == null) throw new NullPointerException();
4482 +            return new ForEachValueTask<K,V>(map, action);
4483 +        }
4484 +
4485 +        /**
4486 +         * Returns a task that when invoked, performs the given action
4487 +         * for each non-null transformation of each value.
4488 +         *
4489 +         * @param map the map
4490 +         * @param transformer a function returning the transformation
4491 +         * for an element, or null of there is no transformation (in
4492 +         * which case the action is not applied).
4493 +         * @param action the action
4494 +         */
4495 +        public static <K,V,U> ForkJoinTask<Void> forEachValue
4496 +            (ConcurrentHashMapV8<K,V> map,
4497 +             Fun<? super V, ? extends U> transformer,
4498 +             Action<U> action) {
4499 +            if (transformer == null || action == null)
4500 +                throw new NullPointerException();
4501 +            return new ForEachTransformedValueTask<K,V,U>
4502 +                (map, transformer, action);
4503 +        }
4504 +
4505 +        /**
4506 +         * Returns a task that when invoked, returns a non-null result
4507 +         * from applying the given search function on each value, or
4508 +         * null if none.  Further element processing is suppressed
4509 +         * upon success. However, this method does not return until
4510 +         * other in-progress parallel invocations of the search
4511 +         * function also complete.
4512 +         *
4513 +         * @param map the map
4514 +         * @param searchFunction a function returning a non-null
4515 +         * result on success, else null
4516 +         * @return the task
4517 +         *
4518 +         */
4519 +        public static <K,V,U> ForkJoinTask<U> searchValues
4520 +            (ConcurrentHashMapV8<K,V> map,
4521 +             Fun<? super V, ? extends U> searchFunction) {
4522 +            if (searchFunction == null) throw new NullPointerException();
4523 +            return new SearchValuesTask<K,V,U>
4524 +                (map, searchFunction,
4525 +                 new AtomicReference<U>());
4526 +        }
4527 +
4528 +        /**
4529 +         * Returns a task that when invoked, returns the result of
4530 +         * accumulating all values using the given reducer to combine
4531 +         * values, or null if none.
4532 +         *
4533 +         * @param map the map
4534 +         * @param reducer a commutative associative combining function
4535 +         * @return the task
4536 +         */
4537 +        public static <K,V> ForkJoinTask<V> reduceValues
4538 +            (ConcurrentHashMapV8<K,V> map,
4539 +             BiFun<? super V, ? super V, ? extends V> reducer) {
4540 +            if (reducer == null) throw new NullPointerException();
4541 +            return new ReduceValuesTask<K,V>
4542 +                (map, reducer);
4543 +        }
4544 +
4545 +        /**
4546 +         * Returns a task that when invoked, returns the result of
4547 +         * accumulating the given transformation of all values using the
4548 +         * given reducer to combine values, or null if none.
4549 +         *
4550 +         * @param map the map
4551 +         * @param transformer a function returning the transformation
4552 +         * for an element, or null of there is no transformation (in
4553 +         * which case it is not combined).
4554 +         * @param reducer a commutative associative combining function
4555 +         * @return the task
4556 +         */
4557 +        public static <K,V,U> ForkJoinTask<U> reduceValues
4558 +            (ConcurrentHashMapV8<K,V> map,
4559 +             Fun<? super V, ? extends U> transformer,
4560 +             BiFun<? super U, ? super U, ? extends U> reducer) {
4561 +            if (transformer == null || reducer == null)
4562 +                throw new NullPointerException();
4563 +            return new MapReduceValuesTask<K,V,U>
4564 +                (map, transformer, reducer);
4565 +        }
4566 +
4567 +        /**
4568 +         * Returns a task that when invoked, returns the result of
4569 +         * accumulating the given transformation of all values using the
4570 +         * given reducer to combine values, and the given basis as an
4571 +         * identity value.
4572 +         *
4573 +         * @param map the map
4574 +         * @param transformer a function returning the transformation
4575 +         * for an element
4576 +         * @param basis the identity (initial default value) for the reduction
4577 +         * @param reducer a commutative associative combining function
4578 +         * @return the task
4579 +         */
4580 +        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
4581 +            (ConcurrentHashMapV8<K,V> map,
4582 +             ObjectToDouble<? super V> transformer,
4583 +             double basis,
4584 +             DoubleByDoubleToDouble reducer) {
4585 +            if (transformer == null || reducer == null)
4586 +                throw new NullPointerException();
4587 +            return new MapReduceValuesToDoubleTask<K,V>
4588 +                (map, transformer, basis, reducer);
4589 +        }
4590 +
4591 +        /**
4592 +         * Returns a task that when invoked, returns the result of
4593 +         * accumulating the given transformation of all values using the
4594 +         * given reducer to combine values, and the given basis as an
4595 +         * identity value.
4596 +         *
4597 +         * @param map the map
4598 +         * @param transformer a function returning the transformation
4599 +         * for an element
4600 +         * @param basis the identity (initial default value) for the reduction
4601 +         * @param reducer a commutative associative combining function
4602 +         * @return the task
4603 +         */
4604 +        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
4605 +            (ConcurrentHashMapV8<K,V> map,
4606 +             ObjectToLong<? super V> transformer,
4607 +             long basis,
4608 +             LongByLongToLong reducer) {
4609 +            if (transformer == null || reducer == null)
4610 +                throw new NullPointerException();
4611 +            return new MapReduceValuesToLongTask<K,V>
4612 +                (map, transformer, basis, reducer);
4613 +        }
4614 +
4615 +        /**
4616 +         * Returns a task that when invoked, returns the result of
4617 +         * accumulating the given transformation of all values using the
4618 +         * given reducer to combine values, and the given basis as an
4619 +         * identity value.
4620 +         *
4621 +         * @param map the map
4622 +         * @param transformer a function returning the transformation
4623 +         * for an element
4624 +         * @param basis the identity (initial default value) for the reduction
4625 +         * @param reducer a commutative associative combining function
4626 +         * @return the task
4627 +         */
4628 +        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
4629 +            (ConcurrentHashMapV8<K,V> map,
4630 +             ObjectToInt<? super V> transformer,
4631 +             int basis,
4632 +             IntByIntToInt reducer) {
4633 +            if (transformer == null || reducer == null)
4634 +                throw new NullPointerException();
4635 +            return new MapReduceValuesToIntTask<K,V>
4636 +                (map, transformer, basis, reducer);
4637 +        }
4638 +
4639 +        /**
4640 +         * Returns a task that when invoked, perform the given action
4641 +         * for each entry.
4642 +         *
4643 +         * @param map the map
4644 +         * @param action the action
4645 +         */
4646 +        public static <K,V> ForkJoinTask<Void> forEachEntry
4647 +            (ConcurrentHashMapV8<K,V> map,
4648 +             Action<Map.Entry<K,V>> action) {
4649 +            if (action == null) throw new NullPointerException();
4650 +            return new ForEachEntryTask<K,V>(map, action);
4651 +        }
4652 +
4653 +        /**
4654 +         * Returns a task that when invoked, perform the given action
4655 +         * for each non-null transformation of each entry.
4656 +         *
4657 +         * @param map the map
4658 +         * @param transformer a function returning the transformation
4659 +         * for an element, or null of there is no transformation (in
4660 +         * which case the action is not applied).
4661 +         * @param action the action
4662 +         */
4663 +        public static <K,V,U> ForkJoinTask<Void> forEachEntry
4664 +            (ConcurrentHashMapV8<K,V> map,
4665 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
4666 +             Action<U> action) {
4667 +            if (transformer == null || action == null)
4668 +                throw new NullPointerException();
4669 +            return new ForEachTransformedEntryTask<K,V,U>
4670 +                (map, transformer, action);
4671 +        }
4672 +
4673 +        /**
4674 +         * Returns a task that when invoked, returns a non-null result
4675 +         * from applying the given search function on each entry, or
4676 +         * null if none.  Further element processing is suppressed
4677 +         * upon success. However, this method does not return until
4678 +         * other in-progress parallel invocations of the search
4679 +         * function also complete.
4680 +         *
4681 +         * @param map the map
4682 +         * @param searchFunction a function returning a non-null
4683 +         * result on success, else null
4684 +         * @return the task
4685 +         *
4686 +         */
4687 +        public static <K,V,U> ForkJoinTask<U> searchEntries
4688 +            (ConcurrentHashMapV8<K,V> map,
4689 +             Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4690 +            if (searchFunction == null) throw new NullPointerException();
4691 +            return new SearchEntriesTask<K,V,U>
4692 +                (map, searchFunction,
4693 +                 new AtomicReference<U>());
4694 +        }
4695 +
4696 +        /**
4697 +         * Returns a task that when invoked, returns the result of
4698 +         * accumulating all entries using the given reducer to combine
4699 +         * values, or null if none.
4700 +         *
4701 +         * @param map the map
4702 +         * @param reducer a commutative associative combining function
4703 +         * @return the task
4704 +         */
4705 +        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
4706 +            (ConcurrentHashMapV8<K,V> map,
4707 +             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4708 +            if (reducer == null) throw new NullPointerException();
4709 +            return new ReduceEntriesTask<K,V>
4710 +                (map, reducer);
4711 +        }
4712 +
4713 +        /**
4714 +         * Returns a task that when invoked, returns the result of
4715 +         * accumulating the given transformation of all entries using the
4716 +         * given reducer to combine values, or null if none.
4717 +         *
4718 +         * @param map the map
4719 +         * @param transformer a function returning the transformation
4720 +         * for an element, or null of there is no transformation (in
4721 +         * which case it is not combined).
4722 +         * @param reducer a commutative associative combining function
4723 +         * @return the task
4724 +         */
4725 +        public static <K,V,U> ForkJoinTask<U> reduceEntries
4726 +            (ConcurrentHashMapV8<K,V> map,
4727 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
4728 +             BiFun<? super U, ? super U, ? extends U> reducer) {
4729 +            if (transformer == null || reducer == null)
4730 +                throw new NullPointerException();
4731 +            return new MapReduceEntriesTask<K,V,U>
4732 +                (map, transformer, reducer);
4733 +        }
4734 +
4735 +        /**
4736 +         * Returns a task that when invoked, returns the result of
4737 +         * accumulating the given transformation of all entries using the
4738 +         * given reducer to combine values, and the given basis as an
4739 +         * identity value.
4740 +         *
4741 +         * @param map the map
4742 +         * @param transformer a function returning the transformation
4743 +         * for an element
4744 +         * @param basis the identity (initial default value) for the reduction
4745 +         * @param reducer a commutative associative combining function
4746 +         * @return the task
4747 +         */
4748 +        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
4749 +            (ConcurrentHashMapV8<K,V> map,
4750 +             ObjectToDouble<Map.Entry<K,V>> transformer,
4751 +             double basis,
4752 +             DoubleByDoubleToDouble reducer) {
4753 +            if (transformer == null || reducer == null)
4754 +                throw new NullPointerException();
4755 +            return new MapReduceEntriesToDoubleTask<K,V>
4756 +                (map, transformer, basis, reducer);
4757 +        }
4758 +
4759 +        /**
4760 +         * Returns a task that when invoked, returns the result of
4761 +         * accumulating the given transformation of all entries using the
4762 +         * given reducer to combine values, and the given basis as an
4763 +         * identity value.
4764 +         *
4765 +         * @param map the map
4766 +         * @param transformer a function returning the transformation
4767 +         * for an element
4768 +         * @param basis the identity (initial default value) for the reduction
4769 +         * @param reducer a commutative associative combining function
4770 +         * @return the task
4771 +         */
4772 +        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
4773 +            (ConcurrentHashMapV8<K,V> map,
4774 +             ObjectToLong<Map.Entry<K,V>> transformer,
4775 +             long basis,
4776 +             LongByLongToLong reducer) {
4777 +            if (transformer == null || reducer == null)
4778 +                throw new NullPointerException();
4779 +            return new MapReduceEntriesToLongTask<K,V>
4780 +                (map, transformer, basis, reducer);
4781 +        }
4782 +
4783 +        /**
4784 +         * Returns a task that when invoked, returns the result of
4785 +         * accumulating the given transformation of all entries using the
4786 +         * given reducer to combine values, and the given basis as an
4787 +         * identity value.
4788 +         *
4789 +         * @param map the map
4790 +         * @param transformer a function returning the transformation
4791 +         * for an element
4792 +         * @param basis the identity (initial default value) for the reduction
4793 +         * @param reducer a commutative associative combining function
4794 +         * @return the task
4795 +         */
4796 +        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
4797 +            (ConcurrentHashMapV8<K,V> map,
4798 +             ObjectToInt<Map.Entry<K,V>> transformer,
4799 +             int basis,
4800 +             IntByIntToInt reducer) {
4801 +            if (transformer == null || reducer == null)
4802 +                throw new NullPointerException();
4803 +            return new MapReduceEntriesToIntTask<K,V>
4804 +                (map, transformer, basis, reducer);
4805 +        }
4806 +    }
4807 +
4808 +    // -------------------------------------------------------
4809 +
4810 +    /**
4811 +     * Base for FJ tasks for bulk operations. This adds a variant of
4812 +     * CountedCompleters and some split and merge bookkeeping to
4813 +     * iterator functionality. The forEach and reduce methods are
4814 +     * similar to those illustrated in CountedCompleter documentation,
4815 +     * except that bottom-up reduction completions perform them within
4816 +     * their compute methods. The search methods are like forEach
4817 +     * except they continually poll for success and exit early.  Also,
4818 +     * exceptions are handled in a simpler manner, by just trying to
4819 +     * complete root task exceptionally.
4820 +     */
4821 +    static abstract class BulkTask<K,V,R> extends Traverser<K,V,R> {
4822 +        final BulkTask<K,V,?> parent;  // completion target
4823 +        int batch;                     // split control
4824 +        int pending;                   // completion control
4825 +
4826 +        /** Constructor for root tasks */
4827 +        BulkTask(ConcurrentHashMapV8<K,V> map) {
4828 +            super(map);
4829 +            this.parent = null;
4830 +            this.batch = -1; // force call to batch() on execution
4831 +        }
4832 +
4833 +        /** Constructor for subtasks */
4834 +        BulkTask(BulkTask<K,V,?> parent, int batch, boolean split) {
4835 +            super(parent, split);
4836 +            this.parent = parent;
4837 +            this.batch = batch;
4838 +        }
4839 +
4840 +        // FJ methods
4841 +
4842 +        /**
4843 +         * Propagates completion. Note that all reduce actions
4844 +         * bypass this method to combine while completing.
4845 +         */
4846 +        final void tryComplete() {
4847 +            BulkTask<K,V,?> a = this, s = a;
4848 +            for (int c;;) {
4849 +                if ((c = a.pending) == 0) {
4850 +                    if ((a = (s = a).parent) == null) {
4851 +                        s.quietlyComplete();
4852 +                        break;
4853 +                    }
4854 +                }
4855 +                else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
4856 +                    break;
4857 +            }
4858 +        }
4859 +
4860 +        /**
4861 +         * Forces root task to throw exception unless already complete.
4862 +         */
4863 +        final void tryAbortComputation(Throwable ex) {
4864 +            for (BulkTask<K,V,?> a = this;;) {
4865 +                BulkTask<K,V,?> p = a.parent;
4866 +                if (p == null) {
4867 +                    a.completeExceptionally(ex);
4868 +                    break;
4869 +                }
4870 +                a = p;
4871 +            }
4872 +        }
4873 +
4874 +        public final boolean exec() {
4875 +            try {
4876 +                compute();
4877 +            }
4878 +            catch (Throwable ex) {
4879 +                tryAbortComputation(ex);
4880 +            }
4881 +            return false;
4882 +        }
4883 +
4884 +        public abstract void compute();
4885 +
4886 +        // utilities
4887 +
4888 +        /** CompareAndSet pending count */
4889 +        final boolean casPending(int cmp, int val) {
4890 +            return U.compareAndSwapInt(this, PENDING, cmp, val);
4891 +        }
4892 +
4893 +        /**
4894 +         * Returns approx exp2 of the number of times (minus one) to
4895 +         * split task by two before executing leaf action. This value
4896 +         * is faster to compute and more convenient to use as a guide
4897 +         * to splitting than is the depth, since it is used while
4898 +         * dividing by two anyway.
4899 +         */
4900 +        final int batch() {
4901 +            int b = batch;
4902 +            if (b < 0) {
4903 +                long n = map.counter.sum();
4904 +                int sp = getPool().getParallelism() << 3; // slack of 8
4905 +                b = batch = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
4906 +            }
4907 +            return b;
4908 +        }
4909 +
4910 +        /**
4911 +         * Error message for hoisted null checks of functions
4912 +         */
4913 +        static final String NullFunctionMessage =
4914 +            "Unexpected null function";
4915 +
4916 +        /**
4917 +         * Returns exportable snapshot entry.
4918 +         */
4919 +        static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
4920 +            return new AbstractMap.SimpleEntry(k, v);
4921 +        }
4922 +
4923 +        // Unsafe mechanics
4924 +        private static final sun.misc.Unsafe U;
4925 +        private static final long PENDING;
4926 +        static {
4927 +            try {
4928 +                U = sun.misc.Unsafe.getUnsafe();
4929 +                PENDING = U.objectFieldOffset
4930 +                    (BulkTask.class.getDeclaredField("pending"));
4931 +            } catch (Exception e) {
4932 +                throw new Error(e);
4933 +            }
4934 +        }
4935 +    }
4936 +
4937 +    /*
4938 +     * Task classes. Coded in a regular but ugly format/style to
4939 +     * simplify checks that each variant differs in the right way from
4940 +     * others.
4941 +     */
4942 +
4943 +    static final class ForEachKeyTask<K,V>
4944 +        extends BulkTask<K,V,Void> {
4945 +        final Action<K> action;
4946 +        ForEachKeyTask
4947 +            (ConcurrentHashMapV8<K,V> m,
4948 +             Action<K> action) {
4949 +            super(m);
4950 +            this.action = action;
4951 +        }
4952 +        ForEachKeyTask
4953 +            (BulkTask<K,V,?> p, int b, boolean split,
4954 +             Action<K> action) {
4955 +            super(p, b, split);
4956 +            this.action = action;
4957 +        }
4958 +        public final void compute() {
4959 +            final Action<K> action = this.action;
4960 +            if (action == null)
4961 +                throw new Error(NullFunctionMessage);
4962 +            int b = batch(), c;
4963 +            while (b > 1 && baseIndex != baseLimit) {
4964 +                do {} while (!casPending(c = pending, c+1));
4965 +                new ForEachKeyTask<K,V>(this, b >>>= 1, true, action).fork();
4966 +            }
4967 +            while (advance() != null)
4968 +                action.apply((K)nextKey);
4969 +            tryComplete();
4970 +        }
4971 +    }
4972 +
4973 +    static final class ForEachValueTask<K,V>
4974 +        extends BulkTask<K,V,Void> {
4975 +        final Action<V> action;
4976 +        ForEachValueTask
4977 +            (ConcurrentHashMapV8<K,V> m,
4978 +             Action<V> action) {
4979 +            super(m);
4980 +            this.action = action;
4981 +        }
4982 +        ForEachValueTask
4983 +            (BulkTask<K,V,?> p, int b, boolean split,
4984 +             Action<V> action) {
4985 +            super(p, b, split);
4986 +            this.action = action;
4987 +        }
4988 +        public final void compute() {
4989 +            final Action<V> action = this.action;
4990 +            if (action == null)
4991 +                throw new Error(NullFunctionMessage);
4992 +            int b = batch(), c;
4993 +            while (b > 1 && baseIndex != baseLimit) {
4994 +                do {} while (!casPending(c = pending, c+1));
4995 +                new ForEachValueTask<K,V>(this, b >>>= 1, true, action).fork();
4996 +            }
4997 +            Object v;
4998 +            while ((v = advance()) != null)
4999 +                action.apply((V)v);
5000 +            tryComplete();
5001 +        }
5002 +    }
5003 +
5004 +    static final class ForEachEntryTask<K,V>
5005 +        extends BulkTask<K,V,Void> {
5006 +        final Action<Entry<K,V>> action;
5007 +        ForEachEntryTask
5008 +            (ConcurrentHashMapV8<K,V> m,
5009 +             Action<Entry<K,V>> action) {
5010 +            super(m);
5011 +            this.action = action;
5012 +        }
5013 +        ForEachEntryTask
5014 +            (BulkTask<K,V,?> p, int b, boolean split,
5015 +             Action<Entry<K,V>> action) {
5016 +            super(p, b, split);
5017 +            this.action = action;
5018 +        }
5019 +        public final void compute() {
5020 +            final Action<Entry<K,V>> action = this.action;
5021 +            if (action == null)
5022 +                throw new Error(NullFunctionMessage);
5023 +            int b = batch(), c;
5024 +            while (b > 1 && baseIndex != baseLimit) {
5025 +                do {} while (!casPending(c = pending, c+1));
5026 +                new ForEachEntryTask<K,V>(this, b >>>= 1, true, action).fork();
5027 +            }
5028 +            Object v;
5029 +            while ((v = advance()) != null)
5030 +                action.apply(entryFor((K)nextKey, (V)v));
5031 +            tryComplete();
5032 +        }
5033 +    }
5034 +
5035 +    static final class ForEachMappingTask<K,V>
5036 +        extends BulkTask<K,V,Void> {
5037 +        final BiAction<K,V> action;
5038 +        ForEachMappingTask
5039 +            (ConcurrentHashMapV8<K,V> m,
5040 +             BiAction<K,V> action) {
5041 +            super(m);
5042 +            this.action = action;
5043 +        }
5044 +        ForEachMappingTask
5045 +            (BulkTask<K,V,?> p, int b, boolean split,
5046 +             BiAction<K,V> action) {
5047 +            super(p, b, split);
5048 +            this.action = action;
5049 +        }
5050 +
5051 +        public final void compute() {
5052 +            final BiAction<K,V> action = this.action;
5053 +            if (action == null)
5054 +                throw new Error(NullFunctionMessage);
5055 +            int b = batch(), c;
5056 +            while (b > 1 && baseIndex != baseLimit) {
5057 +                do {} while (!casPending(c = pending, c+1));
5058 +                new ForEachMappingTask<K,V>(this, b >>>= 1, true,
5059 +                                            action).fork();
5060 +            }
5061 +            Object v;
5062 +            while ((v = advance()) != null)
5063 +                action.apply((K)nextKey, (V)v);
5064 +            tryComplete();
5065 +        }
5066 +    }
5067 +
5068 +    static final class ForEachTransformedKeyTask<K,V,U>
5069 +        extends BulkTask<K,V,Void> {
5070 +        final Fun<? super K, ? extends U> transformer;
5071 +        final Action<U> action;
5072 +        ForEachTransformedKeyTask
5073 +            (ConcurrentHashMapV8<K,V> m,
5074 +             Fun<? super K, ? extends U> transformer,
5075 +             Action<U> action) {
5076 +            super(m);
5077 +            this.transformer = transformer;
5078 +            this.action = action;
5079 +
5080 +        }
5081 +        ForEachTransformedKeyTask
5082 +            (BulkTask<K,V,?> p, int b, boolean split,
5083 +             Fun<? super K, ? extends U> transformer,
5084 +             Action<U> action) {
5085 +            super(p, b, split);
5086 +            this.transformer = transformer;
5087 +            this.action = action;
5088 +        }
5089 +        public final void compute() {
5090 +            final Fun<? super K, ? extends U> transformer =
5091 +                this.transformer;
5092 +            final Action<U> action = this.action;
5093 +            if (transformer == null || action == null)
5094 +                throw new Error(NullFunctionMessage);
5095 +            int b = batch(), c;
5096 +            while (b > 1 && baseIndex != baseLimit) {
5097 +                do {} while (!casPending(c = pending, c+1));
5098 +                new ForEachTransformedKeyTask<K,V,U>
5099 +                    (this, b >>>= 1, true, transformer, action).fork();
5100 +            }
5101 +            U u;
5102 +            while (advance() != null) {
5103 +                if ((u = transformer.apply((K)nextKey)) != null)
5104 +                    action.apply(u);
5105 +            }
5106 +            tryComplete();
5107 +        }
5108 +    }
5109 +
5110 +    static final class ForEachTransformedValueTask<K,V,U>
5111 +        extends BulkTask<K,V,Void> {
5112 +        final Fun<? super V, ? extends U> transformer;
5113 +        final Action<U> action;
5114 +        ForEachTransformedValueTask
5115 +            (ConcurrentHashMapV8<K,V> m,
5116 +             Fun<? super V, ? extends U> transformer,
5117 +             Action<U> action) {
5118 +            super(m);
5119 +            this.transformer = transformer;
5120 +            this.action = action;
5121 +
5122 +        }
5123 +        ForEachTransformedValueTask
5124 +            (BulkTask<K,V,?> p, int b, boolean split,
5125 +             Fun<? super V, ? extends U> transformer,
5126 +             Action<U> action) {
5127 +            super(p, b, split);
5128 +            this.transformer = transformer;
5129 +            this.action = action;
5130 +        }
5131 +        public final void compute() {
5132 +            final Fun<? super V, ? extends U> transformer =
5133 +                this.transformer;
5134 +            final Action<U> action = this.action;
5135 +            if (transformer == null || action == null)
5136 +                throw new Error(NullFunctionMessage);
5137 +            int b = batch(), c;
5138 +            while (b > 1 && baseIndex != baseLimit) {
5139 +                do {} while (!casPending(c = pending, c+1));
5140 +                new ForEachTransformedValueTask<K,V,U>
5141 +                    (this, b >>>= 1, true, transformer, action).fork();
5142 +            }
5143 +            Object v; U u;
5144 +            while ((v = advance()) != null) {
5145 +                if ((u = transformer.apply((V)v)) != null)
5146 +                    action.apply(u);
5147 +            }
5148 +            tryComplete();
5149 +        }
5150 +    }
5151 +
5152 +    static final class ForEachTransformedEntryTask<K,V,U>
5153 +        extends BulkTask<K,V,Void> {
5154 +        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5155 +        final Action<U> action;
5156 +        ForEachTransformedEntryTask
5157 +            (ConcurrentHashMapV8<K,V> m,
5158 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
5159 +             Action<U> action) {
5160 +            super(m);
5161 +            this.transformer = transformer;
5162 +            this.action = action;
5163 +
5164 +        }
5165 +        ForEachTransformedEntryTask
5166 +            (BulkTask<K,V,?> p, int b, boolean split,
5167 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
5168 +             Action<U> action) {
5169 +            super(p, b, split);
5170 +            this.transformer = transformer;
5171 +            this.action = action;
5172 +        }
5173 +        public final void compute() {
5174 +            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5175 +                this.transformer;
5176 +            final Action<U> action = this.action;
5177 +            if (transformer == null || action == null)
5178 +                throw new Error(NullFunctionMessage);
5179 +            int b = batch(), c;
5180 +            while (b > 1 && baseIndex != baseLimit) {
5181 +                do {} while (!casPending(c = pending, c+1));
5182 +                new ForEachTransformedEntryTask<K,V,U>
5183 +                    (this, b >>>= 1, true, transformer, action).fork();
5184 +            }
5185 +            Object v; U u;
5186 +            while ((v = advance()) != null) {
5187 +                if ((u = transformer.apply(entryFor((K)nextKey, (V)v))) != null)
5188 +                    action.apply(u);
5189 +            }
5190 +            tryComplete();
5191 +        }
5192 +    }
5193 +
5194 +    static final class ForEachTransformedMappingTask<K,V,U>
5195 +        extends BulkTask<K,V,Void> {
5196 +        final BiFun<? super K, ? super V, ? extends U> transformer;
5197 +        final Action<U> action;
5198 +        ForEachTransformedMappingTask
5199 +            (ConcurrentHashMapV8<K,V> m,
5200 +             BiFun<? super K, ? super V, ? extends U> transformer,
5201 +             Action<U> action) {
5202 +            super(m);
5203 +            this.transformer = transformer;
5204 +            this.action = action;
5205 +
5206 +        }
5207 +        ForEachTransformedMappingTask
5208 +            (BulkTask<K,V,?> p, int b, boolean split,
5209 +             BiFun<? super K, ? super V, ? extends U> transformer,
5210 +             Action<U> action) {
5211 +            super(p, b, split);
5212 +            this.transformer = transformer;
5213 +            this.action = action;
5214 +        }
5215 +        public final void compute() {
5216 +            final BiFun<? super K, ? super V, ? extends U> transformer =
5217 +                this.transformer;
5218 +            final Action<U> action = this.action;
5219 +            if (transformer == null || action == null)
5220 +                throw new Error(NullFunctionMessage);
5221 +            int b = batch(), c;
5222 +            while (b > 1 && baseIndex != baseLimit) {
5223 +                do {} while (!casPending(c = pending, c+1));
5224 +                new ForEachTransformedMappingTask<K,V,U>
5225 +                    (this, b >>>= 1, true, transformer, action).fork();
5226 +            }
5227 +            Object v; U u;
5228 +            while ((v = advance()) != null) {
5229 +                if ((u = transformer.apply((K)nextKey, (V)v)) != null)
5230 +                    action.apply(u);
5231 +            }
5232 +            tryComplete();
5233 +        }
5234 +    }
5235 +
5236 +    static final class SearchKeysTask<K,V,U>
5237 +        extends BulkTask<K,V,U> {
5238 +        final Fun<? super K, ? extends U> searchFunction;
5239 +        final AtomicReference<U> result;
5240 +        SearchKeysTask
5241 +            (ConcurrentHashMapV8<K,V> m,
5242 +             Fun<? super K, ? extends U> searchFunction,
5243 +             AtomicReference<U> result) {
5244 +            super(m);
5245 +            this.searchFunction = searchFunction; this.result = result;
5246 +        }
5247 +        SearchKeysTask
5248 +            (BulkTask<K,V,?> p, int b, boolean split,
5249 +             Fun<? super K, ? extends U> searchFunction,
5250 +             AtomicReference<U> result) {
5251 +            super(p, b, split);
5252 +            this.searchFunction = searchFunction; this.result = result;
5253 +        }
5254 +        public final void compute() {
5255 +            AtomicReference<U> result = this.result;
5256 +            final Fun<? super K, ? extends U> searchFunction =
5257 +                this.searchFunction;
5258 +            if (searchFunction == null || result == null)
5259 +                throw new Error(NullFunctionMessage);
5260 +            int b = batch(), c;
5261 +            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5262 +                do {} while (!casPending(c = pending, c+1));
5263 +                new SearchKeysTask<K,V,U>(this, b >>>= 1, true,
5264 +                                          searchFunction, result).fork();
5265 +            }
5266 +            U u;
5267 +            while (result.get() == null && advance() != null) {
5268 +                if ((u = searchFunction.apply((K)nextKey)) != null) {
5269 +                    result.compareAndSet(null, u);
5270 +                    break;
5271 +                }
5272 +            }
5273 +            tryComplete();
5274 +        }
5275 +        public final U getRawResult() { return result.get(); }
5276 +    }
5277 +
5278 +    static final class SearchValuesTask<K,V,U>
5279 +        extends BulkTask<K,V,U> {
5280 +        final Fun<? super V, ? extends U> searchFunction;
5281 +        final AtomicReference<U> result;
5282 +        SearchValuesTask
5283 +            (ConcurrentHashMapV8<K,V> m,
5284 +             Fun<? super V, ? extends U> searchFunction,
5285 +             AtomicReference<U> result) {
5286 +            super(m);
5287 +            this.searchFunction = searchFunction; this.result = result;
5288 +        }
5289 +        SearchValuesTask
5290 +            (BulkTask<K,V,?> p, int b, boolean split,
5291 +             Fun<? super V, ? extends U> searchFunction,
5292 +             AtomicReference<U> result) {
5293 +            super(p, b, split);
5294 +            this.searchFunction = searchFunction; this.result = result;
5295 +        }
5296 +        public final void compute() {
5297 +            AtomicReference<U> result = this.result;
5298 +            final Fun<? super V, ? extends U> searchFunction =
5299 +                this.searchFunction;
5300 +            if (searchFunction == null || result == null)
5301 +                throw new Error(NullFunctionMessage);
5302 +            int b = batch(), c;
5303 +            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5304 +                do {} while (!casPending(c = pending, c+1));
5305 +                new SearchValuesTask<K,V,U>(this, b >>>= 1, true,
5306 +                                            searchFunction, result).fork();
5307 +            }
5308 +            Object v; U u;
5309 +            while (result.get() == null && (v = advance()) != null) {
5310 +                if ((u = searchFunction.apply((V)v)) != null) {
5311 +                    result.compareAndSet(null, u);
5312 +                    break;
5313 +                }
5314 +            }
5315 +            tryComplete();
5316 +        }
5317 +        public final U getRawResult() { return result.get(); }
5318 +    }
5319 +
5320 +    static final class SearchEntriesTask<K,V,U>
5321 +        extends BulkTask<K,V,U> {
5322 +        final Fun<Entry<K,V>, ? extends U> searchFunction;
5323 +        final AtomicReference<U> result;
5324 +        SearchEntriesTask
5325 +            (ConcurrentHashMapV8<K,V> m,
5326 +             Fun<Entry<K,V>, ? extends U> searchFunction,
5327 +             AtomicReference<U> result) {
5328 +            super(m);
5329 +            this.searchFunction = searchFunction; this.result = result;
5330 +        }
5331 +        SearchEntriesTask
5332 +            (BulkTask<K,V,?> p, int b, boolean split,
5333 +             Fun<Entry<K,V>, ? extends U> searchFunction,
5334 +             AtomicReference<U> result) {
5335 +            super(p, b, split);
5336 +            this.searchFunction = searchFunction; this.result = result;
5337 +        }
5338 +        public final void compute() {
5339 +            AtomicReference<U> result = this.result;
5340 +            final Fun<Entry<K,V>, ? extends U> searchFunction =
5341 +                this.searchFunction;
5342 +            if (searchFunction == null || result == null)
5343 +                throw new Error(NullFunctionMessage);
5344 +            int b = batch(), c;
5345 +            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5346 +                do {} while (!casPending(c = pending, c+1));
5347 +                new SearchEntriesTask<K,V,U>(this, b >>>= 1, true,
5348 +                                             searchFunction, result).fork();
5349 +            }
5350 +            Object v; U u;
5351 +            while (result.get() == null && (v = advance()) != null) {
5352 +                if ((u = searchFunction.apply(entryFor((K)nextKey, (V)v))) != null) {
5353 +                    result.compareAndSet(null, u);
5354 +                    break;
5355 +                }
5356 +            }
5357 +            tryComplete();
5358 +        }
5359 +        public final U getRawResult() { return result.get(); }
5360 +    }
5361 +
5362 +    static final class SearchMappingsTask<K,V,U>
5363 +        extends BulkTask<K,V,U> {
5364 +        final BiFun<? super K, ? super V, ? extends U> searchFunction;
5365 +        final AtomicReference<U> result;
5366 +        SearchMappingsTask
5367 +            (ConcurrentHashMapV8<K,V> m,
5368 +             BiFun<? super K, ? super V, ? extends U> searchFunction,
5369 +             AtomicReference<U> result) {
5370 +            super(m);
5371 +            this.searchFunction = searchFunction; this.result = result;
5372 +        }
5373 +        SearchMappingsTask
5374 +            (BulkTask<K,V,?> p, int b, boolean split,
5375 +             BiFun<? super K, ? super V, ? extends U> searchFunction,
5376 +             AtomicReference<U> result) {
5377 +            super(p, b, split);
5378 +            this.searchFunction = searchFunction; this.result = result;
5379 +        }
5380 +        public final void compute() {
5381 +            AtomicReference<U> result = this.result;
5382 +            final BiFun<? super K, ? super V, ? extends U> searchFunction =
5383 +                this.searchFunction;
5384 +            if (searchFunction == null || result == null)
5385 +                throw new Error(NullFunctionMessage);
5386 +            int b = batch(), c;
5387 +            while (b > 1 && baseIndex != baseLimit && result.get() == null) {
5388 +                do {} while (!casPending(c = pending, c+1));
5389 +                new SearchMappingsTask<K,V,U>(this, b >>>= 1, true,
5390 +                                              searchFunction, result).fork();
5391 +            }
5392 +            Object v; U u;
5393 +            while (result.get() == null && (v = advance()) != null) {
5394 +                if ((u = searchFunction.apply((K)nextKey, (V)v)) != null) {
5395 +                    result.compareAndSet(null, u);
5396 +                    break;
5397 +                }
5398 +            }
5399 +            tryComplete();
5400 +        }
5401 +        public final U getRawResult() { return result.get(); }
5402 +    }
5403 +
5404 +    static final class ReduceKeysTask<K,V>
5405 +        extends BulkTask<K,V,K> {
5406 +        final BiFun<? super K, ? super K, ? extends K> reducer;
5407 +        K result;
5408 +        ReduceKeysTask<K,V> sibling;
5409 +        ReduceKeysTask
5410 +            (ConcurrentHashMapV8<K,V> m,
5411 +             BiFun<? super K, ? super K, ? extends K> reducer) {
5412 +            super(m);
5413 +            this.reducer = reducer;
5414 +        }
5415 +        ReduceKeysTask
5416 +            (BulkTask<K,V,?> p, int b, boolean split,
5417 +             BiFun<? super K, ? super K, ? extends K> reducer) {
5418 +            super(p, b, split);
5419 +            this.reducer = reducer;
5420 +        }
5421 +
5422 +        public final void compute() {
5423 +            ReduceKeysTask<K,V> t = this;
5424 +            final BiFun<? super K, ? super K, ? extends K> reducer =
5425 +                this.reducer;
5426 +            if (reducer == null)
5427 +                throw new Error(NullFunctionMessage);
5428 +            int b = batch();
5429 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5430 +                b >>>= 1;
5431 +                t.pending = 1;
5432 +                ReduceKeysTask<K,V> rt =
5433 +                    new ReduceKeysTask<K,V>
5434 +                    (t, b, true, reducer);
5435 +                t = new ReduceKeysTask<K,V>
5436 +                    (t, b, false, reducer);
5437 +                t.sibling = rt;
5438 +                rt.sibling = t;
5439 +                rt.fork();
5440 +            }
5441 +            K r = null;
5442 +            while (t.advance() != null) {
5443 +                K u = (K)t.nextKey;
5444 +                r = (r == null) ? u : reducer.apply(r, u);
5445 +            }
5446 +            t.result = r;
5447 +            for (;;) {
5448 +                int c; BulkTask<K,V,?> par; ReduceKeysTask<K,V> s, p; K u;
5449 +                if ((par = t.parent) == null ||
5450 +                    !(par instanceof ReduceKeysTask)) {
5451 +                    t.quietlyComplete();
5452 +                    break;
5453 +                }
5454 +                else if ((c = (p = (ReduceKeysTask<K,V>)par).pending) == 0) {
5455 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5456 +                        r = (r == null) ? u : reducer.apply(r, u);
5457 +                    (t = p).result = r;
5458 +                }
5459 +                else if (p.casPending(c, 0))
5460 +                    break;
5461 +            }
5462 +        }
5463 +        public final K getRawResult() { return result; }
5464 +    }
5465 +
5466 +    static final class ReduceValuesTask<K,V>
5467 +        extends BulkTask<K,V,V> {
5468 +        final BiFun<? super V, ? super V, ? extends V> reducer;
5469 +        V result;
5470 +        ReduceValuesTask<K,V> sibling;
5471 +        ReduceValuesTask
5472 +            (ConcurrentHashMapV8<K,V> m,
5473 +             BiFun<? super V, ? super V, ? extends V> reducer) {
5474 +            super(m);
5475 +            this.reducer = reducer;
5476 +        }
5477 +        ReduceValuesTask
5478 +            (BulkTask<K,V,?> p, int b, boolean split,
5479 +             BiFun<? super V, ? super V, ? extends V> reducer) {
5480 +            super(p, b, split);
5481 +            this.reducer = reducer;
5482 +        }
5483 +
5484 +        public final void compute() {
5485 +            ReduceValuesTask<K,V> t = this;
5486 +            final BiFun<? super V, ? super V, ? extends V> reducer =
5487 +                this.reducer;
5488 +            if (reducer == null)
5489 +                throw new Error(NullFunctionMessage);
5490 +            int b = batch();
5491 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5492 +                b >>>= 1;
5493 +                t.pending = 1;
5494 +                ReduceValuesTask<K,V> rt =
5495 +                    new ReduceValuesTask<K,V>
5496 +                    (t, b, true, reducer);
5497 +                t = new ReduceValuesTask<K,V>
5498 +                    (t, b, false, reducer);
5499 +                t.sibling = rt;
5500 +                rt.sibling = t;
5501 +                rt.fork();
5502 +            }
5503 +            V r = null;
5504 +            Object v;
5505 +            while ((v = t.advance()) != null) {
5506 +                V u = (V)v;
5507 +                r = (r == null) ? u : reducer.apply(r, u);
5508 +            }
5509 +            t.result = r;
5510 +            for (;;) {
5511 +                int c; BulkTask<K,V,?> par; ReduceValuesTask<K,V> s, p; V u;
5512 +                if ((par = t.parent) == null ||
5513 +                    !(par instanceof ReduceValuesTask)) {
5514 +                    t.quietlyComplete();
5515 +                    break;
5516 +                }
5517 +                else if ((c = (p = (ReduceValuesTask<K,V>)par).pending) == 0) {
5518 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5519 +                        r = (r == null) ? u : reducer.apply(r, u);
5520 +                    (t = p).result = r;
5521 +                }
5522 +                else if (p.casPending(c, 0))
5523 +                    break;
5524 +            }
5525 +        }
5526 +        public final V getRawResult() { return result; }
5527 +    }
5528 +
5529 +    static final class ReduceEntriesTask<K,V>
5530 +        extends BulkTask<K,V,Map.Entry<K,V>> {
5531 +        final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5532 +        Map.Entry<K,V> result;
5533 +        ReduceEntriesTask<K,V> sibling;
5534 +        ReduceEntriesTask
5535 +            (ConcurrentHashMapV8<K,V> m,
5536 +             BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5537 +            super(m);
5538 +            this.reducer = reducer;
5539 +        }
5540 +        ReduceEntriesTask
5541 +            (BulkTask<K,V,?> p, int b, boolean split,
5542 +             BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5543 +            super(p, b, split);
5544 +            this.reducer = reducer;
5545 +        }
5546 +
5547 +        public final void compute() {
5548 +            ReduceEntriesTask<K,V> t = this;
5549 +            final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer =
5550 +                this.reducer;
5551 +            if (reducer == null)
5552 +                throw new Error(NullFunctionMessage);
5553 +            int b = batch();
5554 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5555 +                b >>>= 1;
5556 +                t.pending = 1;
5557 +                ReduceEntriesTask<K,V> rt =
5558 +                    new ReduceEntriesTask<K,V>
5559 +                    (t, b, true, reducer);
5560 +                t = new ReduceEntriesTask<K,V>
5561 +                    (t, b, false, reducer);
5562 +                t.sibling = rt;
5563 +                rt.sibling = t;
5564 +                rt.fork();
5565 +            }
5566 +            Map.Entry<K,V> r = null;
5567 +            Object v;
5568 +            while ((v = t.advance()) != null) {
5569 +                Map.Entry<K,V> u = entryFor((K)t.nextKey, (V)v);
5570 +                r = (r == null) ? u : reducer.apply(r, u);
5571 +            }
5572 +            t.result = r;
5573 +            for (;;) {
5574 +                int c; BulkTask<K,V,?> par; ReduceEntriesTask<K,V> s, p;
5575 +                Map.Entry<K,V> u;
5576 +                if ((par = t.parent) == null ||
5577 +                    !(par instanceof ReduceEntriesTask)) {
5578 +                    t.quietlyComplete();
5579 +                    break;
5580 +                }
5581 +                else if ((c = (p = (ReduceEntriesTask<K,V>)par).pending) == 0) {
5582 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5583 +                        r = (r == null) ? u : reducer.apply(r, u);
5584 +                    (t = p).result = r;
5585 +                }
5586 +                else if (p.casPending(c, 0))
5587 +                    break;
5588 +            }
5589 +        }
5590 +        public final Map.Entry<K,V> getRawResult() { return result; }
5591 +    }
5592 +
5593 +    static final class MapReduceKeysTask<K,V,U>
5594 +        extends BulkTask<K,V,U> {
5595 +        final Fun<? super K, ? extends U> transformer;
5596 +        final BiFun<? super U, ? super U, ? extends U> reducer;
5597 +        U result;
5598 +        MapReduceKeysTask<K,V,U> sibling;
5599 +        MapReduceKeysTask
5600 +            (ConcurrentHashMapV8<K,V> m,
5601 +             Fun<? super K, ? extends U> transformer,
5602 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5603 +            super(m);
5604 +            this.transformer = transformer;
5605 +            this.reducer = reducer;
5606 +        }
5607 +        MapReduceKeysTask
5608 +            (BulkTask<K,V,?> p, int b, boolean split,
5609 +             Fun<? super K, ? extends U> transformer,
5610 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5611 +            super(p, b, split);
5612 +            this.transformer = transformer;
5613 +            this.reducer = reducer;
5614 +        }
5615 +        public final void compute() {
5616 +            MapReduceKeysTask<K,V,U> t = this;
5617 +            final Fun<? super K, ? extends U> transformer =
5618 +                this.transformer;
5619 +            final BiFun<? super U, ? super U, ? extends U> reducer =
5620 +                this.reducer;
5621 +            if (transformer == null || reducer == null)
5622 +                throw new Error(NullFunctionMessage);
5623 +            int b = batch();
5624 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5625 +                b >>>= 1;
5626 +                t.pending = 1;
5627 +                MapReduceKeysTask<K,V,U> rt =
5628 +                    new MapReduceKeysTask<K,V,U>
5629 +                    (t, b, true, transformer, reducer);
5630 +                t = new MapReduceKeysTask<K,V,U>
5631 +                    (t, b, false, transformer, reducer);
5632 +                t.sibling = rt;
5633 +                rt.sibling = t;
5634 +                rt.fork();
5635 +            }
5636 +            U r = null, u;
5637 +            while (t.advance() != null) {
5638 +                if ((u = transformer.apply((K)t.nextKey)) != null)
5639 +                    r = (r == null) ? u : reducer.apply(r, u);
5640 +            }
5641 +            t.result = r;
5642 +            for (;;) {
5643 +                int c; BulkTask<K,V,?> par; MapReduceKeysTask<K,V,U> s, p;
5644 +                if ((par = t.parent) == null ||
5645 +                    !(par instanceof MapReduceKeysTask)) {
5646 +                    t.quietlyComplete();
5647 +                    break;
5648 +                }
5649 +                else if ((c = (p = (MapReduceKeysTask<K,V,U>)par).pending) == 0) {
5650 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5651 +                        r = (r == null) ? u : reducer.apply(r, u);
5652 +                    (t = p).result = r;
5653 +                }
5654 +                else if (p.casPending(c, 0))
5655 +                    break;
5656 +            }
5657 +        }
5658 +        public final U getRawResult() { return result; }
5659 +    }
5660 +
5661 +    static final class MapReduceValuesTask<K,V,U>
5662 +        extends BulkTask<K,V,U> {
5663 +        final Fun<? super V, ? extends U> transformer;
5664 +        final BiFun<? super U, ? super U, ? extends U> reducer;
5665 +        U result;
5666 +        MapReduceValuesTask<K,V,U> sibling;
5667 +        MapReduceValuesTask
5668 +            (ConcurrentHashMapV8<K,V> m,
5669 +             Fun<? super V, ? extends U> transformer,
5670 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5671 +            super(m);
5672 +            this.transformer = transformer;
5673 +            this.reducer = reducer;
5674 +        }
5675 +        MapReduceValuesTask
5676 +            (BulkTask<K,V,?> p, int b, boolean split,
5677 +             Fun<? super V, ? extends U> transformer,
5678 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5679 +            super(p, b, split);
5680 +            this.transformer = transformer;
5681 +            this.reducer = reducer;
5682 +        }
5683 +        public final void compute() {
5684 +            MapReduceValuesTask<K,V,U> t = this;
5685 +            final Fun<? super V, ? extends U> transformer =
5686 +                this.transformer;
5687 +            final BiFun<? super U, ? super U, ? extends U> reducer =
5688 +                this.reducer;
5689 +            if (transformer == null || reducer == null)
5690 +                throw new Error(NullFunctionMessage);
5691 +            int b = batch();
5692 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5693 +                b >>>= 1;
5694 +                t.pending = 1;
5695 +                MapReduceValuesTask<K,V,U> rt =
5696 +                    new MapReduceValuesTask<K,V,U>
5697 +                    (t, b, true, transformer, reducer);
5698 +                t = new MapReduceValuesTask<K,V,U>
5699 +                    (t, b, false, transformer, reducer);
5700 +                t.sibling = rt;
5701 +                rt.sibling = t;
5702 +                rt.fork();
5703 +            }
5704 +            U r = null, u;
5705 +            Object v;
5706 +            while ((v = t.advance()) != null) {
5707 +                if ((u = transformer.apply((V)v)) != null)
5708 +                    r = (r == null) ? u : reducer.apply(r, u);
5709 +            }
5710 +            t.result = r;
5711 +            for (;;) {
5712 +                int c; BulkTask<K,V,?> par; MapReduceValuesTask<K,V,U> s, p;
5713 +                if ((par = t.parent) == null ||
5714 +                    !(par instanceof MapReduceValuesTask)) {
5715 +                    t.quietlyComplete();
5716 +                    break;
5717 +                }
5718 +                else if ((c = (p = (MapReduceValuesTask<K,V,U>)par).pending) == 0) {
5719 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5720 +                        r = (r == null) ? u : reducer.apply(r, u);
5721 +                    (t = p).result = r;
5722 +                }
5723 +                else if (p.casPending(c, 0))
5724 +                    break;
5725 +            }
5726 +        }
5727 +        public final U getRawResult() { return result; }
5728 +    }
5729 +
5730 +    static final class MapReduceEntriesTask<K,V,U>
5731 +        extends BulkTask<K,V,U> {
5732 +        final Fun<Map.Entry<K,V>, ? extends U> transformer;
5733 +        final BiFun<? super U, ? super U, ? extends U> reducer;
5734 +        U result;
5735 +        MapReduceEntriesTask<K,V,U> sibling;
5736 +        MapReduceEntriesTask
5737 +            (ConcurrentHashMapV8<K,V> m,
5738 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
5739 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5740 +            super(m);
5741 +            this.transformer = transformer;
5742 +            this.reducer = reducer;
5743 +        }
5744 +        MapReduceEntriesTask
5745 +            (BulkTask<K,V,?> p, int b, boolean split,
5746 +             Fun<Map.Entry<K,V>, ? extends U> transformer,
5747 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5748 +            super(p, b, split);
5749 +            this.transformer = transformer;
5750 +            this.reducer = reducer;
5751 +        }
5752 +        public final void compute() {
5753 +            MapReduceEntriesTask<K,V,U> t = this;
5754 +            final Fun<Map.Entry<K,V>, ? extends U> transformer =
5755 +                this.transformer;
5756 +            final BiFun<? super U, ? super U, ? extends U> reducer =
5757 +                this.reducer;
5758 +            if (transformer == null || reducer == null)
5759 +                throw new Error(NullFunctionMessage);
5760 +            int b = batch();
5761 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5762 +                b >>>= 1;
5763 +                t.pending = 1;
5764 +                MapReduceEntriesTask<K,V,U> rt =
5765 +                    new MapReduceEntriesTask<K,V,U>
5766 +                    (t, b, true, transformer, reducer);
5767 +                t = new MapReduceEntriesTask<K,V,U>
5768 +                    (t, b, false, transformer, reducer);
5769 +                t.sibling = rt;
5770 +                rt.sibling = t;
5771 +                rt.fork();
5772 +            }
5773 +            U r = null, u;
5774 +            Object v;
5775 +            while ((v = t.advance()) != null) {
5776 +                if ((u = transformer.apply(entryFor((K)t.nextKey, (V)v))) != null)
5777 +                    r = (r == null) ? u : reducer.apply(r, u);
5778 +            }
5779 +            t.result = r;
5780 +            for (;;) {
5781 +                int c; BulkTask<K,V,?> par; MapReduceEntriesTask<K,V,U> s, p;
5782 +                if ((par = t.parent) == null ||
5783 +                    !(par instanceof MapReduceEntriesTask)) {
5784 +                    t.quietlyComplete();
5785 +                    break;
5786 +                }
5787 +                else if ((c = (p = (MapReduceEntriesTask<K,V,U>)par).pending) == 0) {
5788 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5789 +                        r = (r == null) ? u : reducer.apply(r, u);
5790 +                    (t = p).result = r;
5791 +                }
5792 +                else if (p.casPending(c, 0))
5793 +                    break;
5794 +            }
5795 +        }
5796 +        public final U getRawResult() { return result; }
5797 +    }
5798 +
5799 +    static final class MapReduceMappingsTask<K,V,U>
5800 +        extends BulkTask<K,V,U> {
5801 +        final BiFun<? super K, ? super V, ? extends U> transformer;
5802 +        final BiFun<? super U, ? super U, ? extends U> reducer;
5803 +        U result;
5804 +        MapReduceMappingsTask<K,V,U> sibling;
5805 +        MapReduceMappingsTask
5806 +            (ConcurrentHashMapV8<K,V> m,
5807 +             BiFun<? super K, ? super V, ? extends U> transformer,
5808 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5809 +            super(m);
5810 +            this.transformer = transformer;
5811 +            this.reducer = reducer;
5812 +        }
5813 +        MapReduceMappingsTask
5814 +            (BulkTask<K,V,?> p, int b, boolean split,
5815 +             BiFun<? super K, ? super V, ? extends U> transformer,
5816 +             BiFun<? super U, ? super U, ? extends U> reducer) {
5817 +            super(p, b, split);
5818 +            this.transformer = transformer;
5819 +            this.reducer = reducer;
5820 +        }
5821 +        public final void compute() {
5822 +            MapReduceMappingsTask<K,V,U> t = this;
5823 +            final BiFun<? super K, ? super V, ? extends U> transformer =
5824 +                this.transformer;
5825 +            final BiFun<? super U, ? super U, ? extends U> reducer =
5826 +                this.reducer;
5827 +            if (transformer == null || reducer == null)
5828 +                throw new Error(NullFunctionMessage);
5829 +            int b = batch();
5830 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5831 +                b >>>= 1;
5832 +                t.pending = 1;
5833 +                MapReduceMappingsTask<K,V,U> rt =
5834 +                    new MapReduceMappingsTask<K,V,U>
5835 +                    (t, b, true, transformer, reducer);
5836 +                t = new MapReduceMappingsTask<K,V,U>
5837 +                    (t, b, false, transformer, reducer);
5838 +                t.sibling = rt;
5839 +                rt.sibling = t;
5840 +                rt.fork();
5841 +            }
5842 +            U r = null, u;
5843 +            Object v;
5844 +            while ((v = t.advance()) != null) {
5845 +                if ((u = transformer.apply((K)t.nextKey, (V)v)) != null)
5846 +                    r = (r == null) ? u : reducer.apply(r, u);
5847 +            }
5848 +            for (;;) {
5849 +                int c; BulkTask<K,V,?> par; MapReduceMappingsTask<K,V,U> s, p;
5850 +                if ((par = t.parent) == null ||
5851 +                    !(par instanceof MapReduceMappingsTask)) {
5852 +                    t.quietlyComplete();
5853 +                    break;
5854 +                }
5855 +                else if ((c = (p = (MapReduceMappingsTask<K,V,U>)par).pending) == 0) {
5856 +                    if ((s = t.sibling) != null && (u = s.result) != null)
5857 +                        r = (r == null) ? u : reducer.apply(r, u);
5858 +                    (t = p).result = r;
5859 +                }
5860 +                else if (p.casPending(c, 0))
5861 +                    break;
5862 +            }
5863 +        }
5864 +        public final U getRawResult() { return result; }
5865 +    }
5866 +
5867 +    static final class MapReduceKeysToDoubleTask<K,V>
5868 +        extends BulkTask<K,V,Double> {
5869 +        final ObjectToDouble<? super K> transformer;
5870 +        final DoubleByDoubleToDouble reducer;
5871 +        final double basis;
5872 +        double result;
5873 +        MapReduceKeysToDoubleTask<K,V> sibling;
5874 +        MapReduceKeysToDoubleTask
5875 +            (ConcurrentHashMapV8<K,V> m,
5876 +             ObjectToDouble<? super K> transformer,
5877 +             double basis,
5878 +             DoubleByDoubleToDouble reducer) {
5879 +            super(m);
5880 +            this.transformer = transformer;
5881 +            this.basis = basis; this.reducer = reducer;
5882 +        }
5883 +        MapReduceKeysToDoubleTask
5884 +            (BulkTask<K,V,?> p, int b, boolean split,
5885 +             ObjectToDouble<? super K> transformer,
5886 +             double basis,
5887 +             DoubleByDoubleToDouble reducer) {
5888 +            super(p, b, split);
5889 +            this.transformer = transformer;
5890 +            this.basis = basis; this.reducer = reducer;
5891 +        }
5892 +        public final void compute() {
5893 +            MapReduceKeysToDoubleTask<K,V> t = this;
5894 +            final ObjectToDouble<? super K> transformer =
5895 +                this.transformer;
5896 +            final DoubleByDoubleToDouble reducer = this.reducer;
5897 +            if (transformer == null || reducer == null)
5898 +                throw new Error(NullFunctionMessage);
5899 +            final double id = this.basis;
5900 +            int b = batch();
5901 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5902 +                b >>>= 1;
5903 +                t.pending = 1;
5904 +                MapReduceKeysToDoubleTask<K,V> rt =
5905 +                    new MapReduceKeysToDoubleTask<K,V>
5906 +                    (t, b, true, transformer, id, reducer);
5907 +                t = new MapReduceKeysToDoubleTask<K,V>
5908 +                    (t, b, false, transformer, id, reducer);
5909 +                t.sibling = rt;
5910 +                rt.sibling = t;
5911 +                rt.fork();
5912 +            }
5913 +            double r = id;
5914 +            while (t.advance() != null)
5915 +                r = reducer.apply(r, transformer.apply((K)t.nextKey));
5916 +            t.result = r;
5917 +            for (;;) {
5918 +                int c; BulkTask<K,V,?> par; MapReduceKeysToDoubleTask<K,V> s, p;
5919 +                if ((par = t.parent) == null ||
5920 +                    !(par instanceof MapReduceKeysToDoubleTask)) {
5921 +                    t.quietlyComplete();
5922 +                    break;
5923 +                }
5924 +                else if ((c = (p = (MapReduceKeysToDoubleTask<K,V>)par).pending) == 0) {
5925 +                    if ((s = t.sibling) != null)
5926 +                        r = reducer.apply(r, s.result);
5927 +                    (t = p).result = r;
5928 +                }
5929 +                else if (p.casPending(c, 0))
5930 +                    break;
5931 +            }
5932 +        }
5933 +        public final Double getRawResult() { return result; }
5934 +    }
5935 +
5936 +    static final class MapReduceValuesToDoubleTask<K,V>
5937 +        extends BulkTask<K,V,Double> {
5938 +        final ObjectToDouble<? super V> transformer;
5939 +        final DoubleByDoubleToDouble reducer;
5940 +        final double basis;
5941 +        double result;
5942 +        MapReduceValuesToDoubleTask<K,V> sibling;
5943 +        MapReduceValuesToDoubleTask
5944 +            (ConcurrentHashMapV8<K,V> m,
5945 +             ObjectToDouble<? super V> transformer,
5946 +             double basis,
5947 +             DoubleByDoubleToDouble reducer) {
5948 +            super(m);
5949 +            this.transformer = transformer;
5950 +            this.basis = basis; this.reducer = reducer;
5951 +        }
5952 +        MapReduceValuesToDoubleTask
5953 +            (BulkTask<K,V,?> p, int b, boolean split,
5954 +             ObjectToDouble<? super V> transformer,
5955 +             double basis,
5956 +             DoubleByDoubleToDouble reducer) {
5957 +            super(p, b, split);
5958 +            this.transformer = transformer;
5959 +            this.basis = basis; this.reducer = reducer;
5960 +        }
5961 +        public final void compute() {
5962 +            MapReduceValuesToDoubleTask<K,V> t = this;
5963 +            final ObjectToDouble<? super V> transformer =
5964 +                this.transformer;
5965 +            final DoubleByDoubleToDouble reducer = this.reducer;
5966 +            if (transformer == null || reducer == null)
5967 +                throw new Error(NullFunctionMessage);
5968 +            final double id = this.basis;
5969 +            int b = batch();
5970 +            while (b > 1 && t.baseIndex != t.baseLimit) {
5971 +                b >>>= 1;
5972 +                t.pending = 1;
5973 +                MapReduceValuesToDoubleTask<K,V> rt =
5974 +                    new MapReduceValuesToDoubleTask<K,V>
5975 +                    (t, b, true, transformer, id, reducer);
5976 +                t = new MapReduceValuesToDoubleTask<K,V>
5977 +                    (t, b, false, transformer, id, reducer);
5978 +                t.sibling = rt;
5979 +                rt.sibling = t;
5980 +                rt.fork();
5981 +            }
5982 +            double r = id;
5983 +            Object v;
5984 +            while ((v = t.advance()) != null)
5985 +                r = reducer.apply(r, transformer.apply((V)v));
5986 +            t.result = r;
5987 +            for (;;) {
5988 +                int c; BulkTask<K,V,?> par; MapReduceValuesToDoubleTask<K,V> s, p;
5989 +                if ((par = t.parent) == null ||
5990 +                    !(par instanceof MapReduceValuesToDoubleTask)) {
5991 +                    t.quietlyComplete();
5992 +                    break;
5993 +                }
5994 +                else if ((c = (p = (MapReduceValuesToDoubleTask<K,V>)par).pending) == 0) {
5995 +                    if ((s = t.sibling) != null)
5996 +                        r = reducer.apply(r, s.result);
5997 +                    (t = p).result = r;
5998 +                }
5999 +                else if (p.casPending(c, 0))
6000 +                    break;
6001 +            }
6002 +        }
6003 +        public final Double getRawResult() { return result; }
6004 +    }
6005 +
6006 +    static final class MapReduceEntriesToDoubleTask<K,V>
6007 +        extends BulkTask<K,V,Double> {
6008 +        final ObjectToDouble<Map.Entry<K,V>> transformer;
6009 +        final DoubleByDoubleToDouble reducer;
6010 +        final double basis;
6011 +        double result;
6012 +        MapReduceEntriesToDoubleTask<K,V> sibling;
6013 +        MapReduceEntriesToDoubleTask
6014 +            (ConcurrentHashMapV8<K,V> m,
6015 +             ObjectToDouble<Map.Entry<K,V>> transformer,
6016 +             double basis,
6017 +             DoubleByDoubleToDouble reducer) {
6018 +            super(m);
6019 +            this.transformer = transformer;
6020 +            this.basis = basis; this.reducer = reducer;
6021 +        }
6022 +        MapReduceEntriesToDoubleTask
6023 +            (BulkTask<K,V,?> p, int b, boolean split,
6024 +             ObjectToDouble<Map.Entry<K,V>> transformer,
6025 +             double basis,
6026 +             DoubleByDoubleToDouble reducer) {
6027 +            super(p, b, split);
6028 +            this.transformer = transformer;
6029 +            this.basis = basis; this.reducer = reducer;
6030 +        }
6031 +        public final void compute() {
6032 +            MapReduceEntriesToDoubleTask<K,V> t = this;
6033 +            final ObjectToDouble<Map.Entry<K,V>> transformer =
6034 +                this.transformer;
6035 +            final DoubleByDoubleToDouble reducer = this.reducer;
6036 +            if (transformer == null || reducer == null)
6037 +                throw new Error(NullFunctionMessage);
6038 +            final double id = this.basis;
6039 +            int b = batch();
6040 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6041 +                b >>>= 1;
6042 +                t.pending = 1;
6043 +                MapReduceEntriesToDoubleTask<K,V> rt =
6044 +                    new MapReduceEntriesToDoubleTask<K,V>
6045 +                    (t, b, true, transformer, id, reducer);
6046 +                t = new MapReduceEntriesToDoubleTask<K,V>
6047 +                    (t, b, false, transformer, id, reducer);
6048 +                t.sibling = rt;
6049 +                rt.sibling = t;
6050 +                rt.fork();
6051 +            }
6052 +            double r = id;
6053 +            Object v;
6054 +            while ((v = t.advance()) != null)
6055 +                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6056 +            t.result = r;
6057 +            for (;;) {
6058 +                int c; BulkTask<K,V,?> par; MapReduceEntriesToDoubleTask<K,V> s, p;
6059 +                if ((par = t.parent) == null ||
6060 +                    !(par instanceof MapReduceEntriesToDoubleTask)) {
6061 +                    t.quietlyComplete();
6062 +                    break;
6063 +                }
6064 +                else if ((c = (p = (MapReduceEntriesToDoubleTask<K,V>)par).pending) == 0) {
6065 +                    if ((s = t.sibling) != null)
6066 +                        r = reducer.apply(r, s.result);
6067 +                    (t = p).result = r;
6068 +                }
6069 +                else if (p.casPending(c, 0))
6070 +                    break;
6071 +            }
6072 +        }
6073 +        public final Double getRawResult() { return result; }
6074 +    }
6075 +
6076 +    static final class MapReduceMappingsToDoubleTask<K,V>
6077 +        extends BulkTask<K,V,Double> {
6078 +        final ObjectByObjectToDouble<? super K, ? super V> transformer;
6079 +        final DoubleByDoubleToDouble reducer;
6080 +        final double basis;
6081 +        double result;
6082 +        MapReduceMappingsToDoubleTask<K,V> sibling;
6083 +        MapReduceMappingsToDoubleTask
6084 +            (ConcurrentHashMapV8<K,V> m,
6085 +             ObjectByObjectToDouble<? super K, ? super V> transformer,
6086 +             double basis,
6087 +             DoubleByDoubleToDouble reducer) {
6088 +            super(m);
6089 +            this.transformer = transformer;
6090 +            this.basis = basis; this.reducer = reducer;
6091 +        }
6092 +        MapReduceMappingsToDoubleTask
6093 +            (BulkTask<K,V,?> p, int b, boolean split,
6094 +             ObjectByObjectToDouble<? super K, ? super V> transformer,
6095 +             double basis,
6096 +             DoubleByDoubleToDouble reducer) {
6097 +            super(p, b, split);
6098 +            this.transformer = transformer;
6099 +            this.basis = basis; this.reducer = reducer;
6100 +        }
6101 +        public final void compute() {
6102 +            MapReduceMappingsToDoubleTask<K,V> t = this;
6103 +            final ObjectByObjectToDouble<? super K, ? super V> transformer =
6104 +                this.transformer;
6105 +            final DoubleByDoubleToDouble reducer = this.reducer;
6106 +            if (transformer == null || reducer == null)
6107 +                throw new Error(NullFunctionMessage);
6108 +            final double id = this.basis;
6109 +            int b = batch();
6110 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6111 +                b >>>= 1;
6112 +                t.pending = 1;
6113 +                MapReduceMappingsToDoubleTask<K,V> rt =
6114 +                    new MapReduceMappingsToDoubleTask<K,V>
6115 +                    (t, b, true, transformer, id, reducer);
6116 +                t = new MapReduceMappingsToDoubleTask<K,V>
6117 +                    (t, b, false, transformer, id, reducer);
6118 +                t.sibling = rt;
6119 +                rt.sibling = t;
6120 +                rt.fork();
6121 +            }
6122 +            double r = id;
6123 +            Object v;
6124 +            while ((v = t.advance()) != null)
6125 +                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6126 +            t.result = r;
6127 +            for (;;) {
6128 +                int c; BulkTask<K,V,?> par; MapReduceMappingsToDoubleTask<K,V> s, p;
6129 +                if ((par = t.parent) == null ||
6130 +                    !(par instanceof MapReduceMappingsToDoubleTask)) {
6131 +                    t.quietlyComplete();
6132 +                    break;
6133 +                }
6134 +                else if ((c = (p = (MapReduceMappingsToDoubleTask<K,V>)par).pending) == 0) {
6135 +                    if ((s = t.sibling) != null)
6136 +                        r = reducer.apply(r, s.result);
6137 +                    (t = p).result = r;
6138 +                }
6139 +                else if (p.casPending(c, 0))
6140 +                    break;
6141 +            }
6142 +        }
6143 +        public final Double getRawResult() { return result; }
6144 +    }
6145 +
6146 +    static final class MapReduceKeysToLongTask<K,V>
6147 +        extends BulkTask<K,V,Long> {
6148 +        final ObjectToLong<? super K> transformer;
6149 +        final LongByLongToLong reducer;
6150 +        final long basis;
6151 +        long result;
6152 +        MapReduceKeysToLongTask<K,V> sibling;
6153 +        MapReduceKeysToLongTask
6154 +            (ConcurrentHashMapV8<K,V> m,
6155 +             ObjectToLong<? super K> transformer,
6156 +             long basis,
6157 +             LongByLongToLong reducer) {
6158 +            super(m);
6159 +            this.transformer = transformer;
6160 +            this.basis = basis; this.reducer = reducer;
6161 +        }
6162 +        MapReduceKeysToLongTask
6163 +            (BulkTask<K,V,?> p, int b, boolean split,
6164 +             ObjectToLong<? super K> transformer,
6165 +             long basis,
6166 +             LongByLongToLong reducer) {
6167 +            super(p, b, split);
6168 +            this.transformer = transformer;
6169 +            this.basis = basis; this.reducer = reducer;
6170 +        }
6171 +        public final void compute() {
6172 +            MapReduceKeysToLongTask<K,V> t = this;
6173 +            final ObjectToLong<? super K> transformer =
6174 +                this.transformer;
6175 +            final LongByLongToLong reducer = this.reducer;
6176 +            if (transformer == null || reducer == null)
6177 +                throw new Error(NullFunctionMessage);
6178 +            final long id = this.basis;
6179 +            int b = batch();
6180 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6181 +                b >>>= 1;
6182 +                t.pending = 1;
6183 +                MapReduceKeysToLongTask<K,V> rt =
6184 +                    new MapReduceKeysToLongTask<K,V>
6185 +                    (t, b, true, transformer, id, reducer);
6186 +                t = new MapReduceKeysToLongTask<K,V>
6187 +                    (t, b, false, transformer, id, reducer);
6188 +                t.sibling = rt;
6189 +                rt.sibling = t;
6190 +                rt.fork();
6191 +            }
6192 +            long r = id;
6193 +            while (t.advance() != null)
6194 +                r = reducer.apply(r, transformer.apply((K)t.nextKey));
6195 +            t.result = r;
6196 +            for (;;) {
6197 +                int c; BulkTask<K,V,?> par; MapReduceKeysToLongTask<K,V> s, p;
6198 +                if ((par = t.parent) == null ||
6199 +                    !(par instanceof MapReduceKeysToLongTask)) {
6200 +                    t.quietlyComplete();
6201 +                    break;
6202 +                }
6203 +                else if ((c = (p = (MapReduceKeysToLongTask<K,V>)par).pending) == 0) {
6204 +                    if ((s = t.sibling) != null)
6205 +                        r = reducer.apply(r, s.result);
6206 +                    (t = p).result = r;
6207 +                }
6208 +                else if (p.casPending(c, 0))
6209 +                    break;
6210 +            }
6211 +        }
6212 +        public final Long getRawResult() { return result; }
6213 +    }
6214 +
6215 +    static final class MapReduceValuesToLongTask<K,V>
6216 +        extends BulkTask<K,V,Long> {
6217 +        final ObjectToLong<? super V> transformer;
6218 +        final LongByLongToLong reducer;
6219 +        final long basis;
6220 +        long result;
6221 +        MapReduceValuesToLongTask<K,V> sibling;
6222 +        MapReduceValuesToLongTask
6223 +            (ConcurrentHashMapV8<K,V> m,
6224 +             ObjectToLong<? super V> transformer,
6225 +             long basis,
6226 +             LongByLongToLong reducer) {
6227 +            super(m);
6228 +            this.transformer = transformer;
6229 +            this.basis = basis; this.reducer = reducer;
6230 +        }
6231 +        MapReduceValuesToLongTask
6232 +            (BulkTask<K,V,?> p, int b, boolean split,
6233 +             ObjectToLong<? super V> transformer,
6234 +             long basis,
6235 +             LongByLongToLong reducer) {
6236 +            super(p, b, split);
6237 +            this.transformer = transformer;
6238 +            this.basis = basis; this.reducer = reducer;
6239 +        }
6240 +        public final void compute() {
6241 +            MapReduceValuesToLongTask<K,V> t = this;
6242 +            final ObjectToLong<? super V> transformer =
6243 +                this.transformer;
6244 +            final LongByLongToLong reducer = this.reducer;
6245 +            if (transformer == null || reducer == null)
6246 +                throw new Error(NullFunctionMessage);
6247 +            final long id = this.basis;
6248 +            int b = batch();
6249 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6250 +                b >>>= 1;
6251 +                t.pending = 1;
6252 +                MapReduceValuesToLongTask<K,V> rt =
6253 +                    new MapReduceValuesToLongTask<K,V>
6254 +                    (t, b, true, transformer, id, reducer);
6255 +                t = new MapReduceValuesToLongTask<K,V>
6256 +                    (t, b, false, transformer, id, reducer);
6257 +                t.sibling = rt;
6258 +                rt.sibling = t;
6259 +                rt.fork();
6260 +            }
6261 +            long r = id;
6262 +            Object v;
6263 +            while ((v = t.advance()) != null)
6264 +                r = reducer.apply(r, transformer.apply((V)v));
6265 +            t.result = r;
6266 +            for (;;) {
6267 +                int c; BulkTask<K,V,?> par; MapReduceValuesToLongTask<K,V> s, p;
6268 +                if ((par = t.parent) == null ||
6269 +                    !(par instanceof MapReduceValuesToLongTask)) {
6270 +                    t.quietlyComplete();
6271 +                    break;
6272 +                }
6273 +                else if ((c = (p = (MapReduceValuesToLongTask<K,V>)par).pending) == 0) {
6274 +                    if ((s = t.sibling) != null)
6275 +                        r = reducer.apply(r, s.result);
6276 +                    (t = p).result = r;
6277 +                }
6278 +                else if (p.casPending(c, 0))
6279 +                    break;
6280 +            }
6281 +        }
6282 +        public final Long getRawResult() { return result; }
6283 +    }
6284 +
6285 +    static final class MapReduceEntriesToLongTask<K,V>
6286 +        extends BulkTask<K,V,Long> {
6287 +        final ObjectToLong<Map.Entry<K,V>> transformer;
6288 +        final LongByLongToLong reducer;
6289 +        final long basis;
6290 +        long result;
6291 +        MapReduceEntriesToLongTask<K,V> sibling;
6292 +        MapReduceEntriesToLongTask
6293 +            (ConcurrentHashMapV8<K,V> m,
6294 +             ObjectToLong<Map.Entry<K,V>> transformer,
6295 +             long basis,
6296 +             LongByLongToLong reducer) {
6297 +            super(m);
6298 +            this.transformer = transformer;
6299 +            this.basis = basis; this.reducer = reducer;
6300 +        }
6301 +        MapReduceEntriesToLongTask
6302 +            (BulkTask<K,V,?> p, int b, boolean split,
6303 +             ObjectToLong<Map.Entry<K,V>> transformer,
6304 +             long basis,
6305 +             LongByLongToLong reducer) {
6306 +            super(p, b, split);
6307 +            this.transformer = transformer;
6308 +            this.basis = basis; this.reducer = reducer;
6309 +        }
6310 +        public final void compute() {
6311 +            MapReduceEntriesToLongTask<K,V> t = this;
6312 +            final ObjectToLong<Map.Entry<K,V>> transformer =
6313 +                this.transformer;
6314 +            final LongByLongToLong reducer = this.reducer;
6315 +            if (transformer == null || reducer == null)
6316 +                throw new Error(NullFunctionMessage);
6317 +            final long id = this.basis;
6318 +            int b = batch();
6319 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6320 +                b >>>= 1;
6321 +                t.pending = 1;
6322 +                MapReduceEntriesToLongTask<K,V> rt =
6323 +                    new MapReduceEntriesToLongTask<K,V>
6324 +                    (t, b, true, transformer, id, reducer);
6325 +                t = new MapReduceEntriesToLongTask<K,V>
6326 +                    (t, b, false, transformer, id, reducer);
6327 +                t.sibling = rt;
6328 +                rt.sibling = t;
6329 +                rt.fork();
6330 +            }
6331 +            long r = id;
6332 +            Object v;
6333 +            while ((v = t.advance()) != null)
6334 +                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6335 +            t.result = r;
6336 +            for (;;) {
6337 +                int c; BulkTask<K,V,?> par; MapReduceEntriesToLongTask<K,V> s, p;
6338 +                if ((par = t.parent) == null ||
6339 +                    !(par instanceof MapReduceEntriesToLongTask)) {
6340 +                    t.quietlyComplete();
6341 +                    break;
6342 +                }
6343 +                else if ((c = (p = (MapReduceEntriesToLongTask<K,V>)par).pending) == 0) {
6344 +                    if ((s = t.sibling) != null)
6345 +                        r = reducer.apply(r, s.result);
6346 +                    (t = p).result = r;
6347 +                }
6348 +                else if (p.casPending(c, 0))
6349 +                    break;
6350 +            }
6351 +        }
6352 +        public final Long getRawResult() { return result; }
6353 +    }
6354 +
6355 +    static final class MapReduceMappingsToLongTask<K,V>
6356 +        extends BulkTask<K,V,Long> {
6357 +        final ObjectByObjectToLong<? super K, ? super V> transformer;
6358 +        final LongByLongToLong reducer;
6359 +        final long basis;
6360 +        long result;
6361 +        MapReduceMappingsToLongTask<K,V> sibling;
6362 +        MapReduceMappingsToLongTask
6363 +            (ConcurrentHashMapV8<K,V> m,
6364 +             ObjectByObjectToLong<? super K, ? super V> transformer,
6365 +             long basis,
6366 +             LongByLongToLong reducer) {
6367 +            super(m);
6368 +            this.transformer = transformer;
6369 +            this.basis = basis; this.reducer = reducer;
6370 +        }
6371 +        MapReduceMappingsToLongTask
6372 +            (BulkTask<K,V,?> p, int b, boolean split,
6373 +             ObjectByObjectToLong<? super K, ? super V> transformer,
6374 +             long basis,
6375 +             LongByLongToLong reducer) {
6376 +            super(p, b, split);
6377 +            this.transformer = transformer;
6378 +            this.basis = basis; this.reducer = reducer;
6379 +        }
6380 +        public final void compute() {
6381 +            MapReduceMappingsToLongTask<K,V> t = this;
6382 +            final ObjectByObjectToLong<? super K, ? super V> transformer =
6383 +                this.transformer;
6384 +            final LongByLongToLong reducer = this.reducer;
6385 +            if (transformer == null || reducer == null)
6386 +                throw new Error(NullFunctionMessage);
6387 +            final long id = this.basis;
6388 +            int b = batch();
6389 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6390 +                b >>>= 1;
6391 +                t.pending = 1;
6392 +                MapReduceMappingsToLongTask<K,V> rt =
6393 +                    new MapReduceMappingsToLongTask<K,V>
6394 +                    (t, b, true, transformer, id, reducer);
6395 +                t = new MapReduceMappingsToLongTask<K,V>
6396 +                    (t, b, false, transformer, id, reducer);
6397 +                t.sibling = rt;
6398 +                rt.sibling = t;
6399 +                rt.fork();
6400 +            }
6401 +            long r = id;
6402 +            Object v;
6403 +            while ((v = t.advance()) != null)
6404 +                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6405 +            t.result = r;
6406 +            for (;;) {
6407 +                int c; BulkTask<K,V,?> par; MapReduceMappingsToLongTask<K,V> s, p;
6408 +                if ((par = t.parent) == null ||
6409 +                    !(par instanceof MapReduceMappingsToLongTask)) {
6410 +                    t.quietlyComplete();
6411 +                    break;
6412 +                }
6413 +                else if ((c = (p = (MapReduceMappingsToLongTask<K,V>)par).pending) == 0) {
6414 +                    if ((s = t.sibling) != null)
6415 +                        r = reducer.apply(r, s.result);
6416 +                    (t = p).result = r;
6417 +                }
6418 +                else if (p.casPending(c, 0))
6419 +                    break;
6420 +            }
6421 +        }
6422 +        public final Long getRawResult() { return result; }
6423 +    }
6424 +
6425 +    static final class MapReduceKeysToIntTask<K,V>
6426 +        extends BulkTask<K,V,Integer> {
6427 +        final ObjectToInt<? super K> transformer;
6428 +        final IntByIntToInt reducer;
6429 +        final int basis;
6430 +        int result;
6431 +        MapReduceKeysToIntTask<K,V> sibling;
6432 +        MapReduceKeysToIntTask
6433 +            (ConcurrentHashMapV8<K,V> m,
6434 +             ObjectToInt<? super K> transformer,
6435 +             int basis,
6436 +             IntByIntToInt reducer) {
6437 +            super(m);
6438 +            this.transformer = transformer;
6439 +            this.basis = basis; this.reducer = reducer;
6440 +        }
6441 +        MapReduceKeysToIntTask
6442 +            (BulkTask<K,V,?> p, int b, boolean split,
6443 +             ObjectToInt<? super K> transformer,
6444 +             int basis,
6445 +             IntByIntToInt reducer) {
6446 +            super(p, b, split);
6447 +            this.transformer = transformer;
6448 +            this.basis = basis; this.reducer = reducer;
6449 +        }
6450 +        public final void compute() {
6451 +            MapReduceKeysToIntTask<K,V> t = this;
6452 +            final ObjectToInt<? super K> transformer =
6453 +                this.transformer;
6454 +            final IntByIntToInt reducer = this.reducer;
6455 +            if (transformer == null || reducer == null)
6456 +                throw new Error(NullFunctionMessage);
6457 +            final int id = this.basis;
6458 +            int b = batch();
6459 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6460 +                b >>>= 1;
6461 +                t.pending = 1;
6462 +                MapReduceKeysToIntTask<K,V> rt =
6463 +                    new MapReduceKeysToIntTask<K,V>
6464 +                    (t, b, true, transformer, id, reducer);
6465 +                t = new MapReduceKeysToIntTask<K,V>
6466 +                    (t, b, false, transformer, id, reducer);
6467 +                t.sibling = rt;
6468 +                rt.sibling = t;
6469 +                rt.fork();
6470 +            }
6471 +            int r = id;
6472 +            while (t.advance() != null)
6473 +                r = reducer.apply(r, transformer.apply((K)t.nextKey));
6474 +            t.result = r;
6475 +            for (;;) {
6476 +                int c; BulkTask<K,V,?> par; MapReduceKeysToIntTask<K,V> s, p;
6477 +                if ((par = t.parent) == null ||
6478 +                    !(par instanceof MapReduceKeysToIntTask)) {
6479 +                    t.quietlyComplete();
6480 +                    break;
6481 +                }
6482 +                else if ((c = (p = (MapReduceKeysToIntTask<K,V>)par).pending) == 0) {
6483 +                    if ((s = t.sibling) != null)
6484 +                        r = reducer.apply(r, s.result);
6485 +                    (t = p).result = r;
6486 +                }
6487 +                else if (p.casPending(c, 0))
6488 +                    break;
6489 +            }
6490 +        }
6491 +        public final Integer getRawResult() { return result; }
6492 +    }
6493 +
6494 +    static final class MapReduceValuesToIntTask<K,V>
6495 +        extends BulkTask<K,V,Integer> {
6496 +        final ObjectToInt<? super V> transformer;
6497 +        final IntByIntToInt reducer;
6498 +        final int basis;
6499 +        int result;
6500 +        MapReduceValuesToIntTask<K,V> sibling;
6501 +        MapReduceValuesToIntTask
6502 +            (ConcurrentHashMapV8<K,V> m,
6503 +             ObjectToInt<? super V> transformer,
6504 +             int basis,
6505 +             IntByIntToInt reducer) {
6506 +            super(m);
6507 +            this.transformer = transformer;
6508 +            this.basis = basis; this.reducer = reducer;
6509 +        }
6510 +        MapReduceValuesToIntTask
6511 +            (BulkTask<K,V,?> p, int b, boolean split,
6512 +             ObjectToInt<? super V> transformer,
6513 +             int basis,
6514 +             IntByIntToInt reducer) {
6515 +            super(p, b, split);
6516 +            this.transformer = transformer;
6517 +            this.basis = basis; this.reducer = reducer;
6518 +        }
6519 +        public final void compute() {
6520 +            MapReduceValuesToIntTask<K,V> t = this;
6521 +            final ObjectToInt<? super V> transformer =
6522 +                this.transformer;
6523 +            final IntByIntToInt reducer = this.reducer;
6524 +            if (transformer == null || reducer == null)
6525 +                throw new Error(NullFunctionMessage);
6526 +            final int id = this.basis;
6527 +            int b = batch();
6528 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6529 +                b >>>= 1;
6530 +                t.pending = 1;
6531 +                MapReduceValuesToIntTask<K,V> rt =
6532 +                    new MapReduceValuesToIntTask<K,V>
6533 +                    (t, b, true, transformer, id, reducer);
6534 +                t = new MapReduceValuesToIntTask<K,V>
6535 +                    (t, b, false, transformer, id, reducer);
6536 +                t.sibling = rt;
6537 +                rt.sibling = t;
6538 +                rt.fork();
6539 +            }
6540 +            int r = id;
6541 +            Object v;
6542 +            while ((v = t.advance()) != null)
6543 +                r = reducer.apply(r, transformer.apply((V)v));
6544 +            t.result = r;
6545 +            for (;;) {
6546 +                int c; BulkTask<K,V,?> par; MapReduceValuesToIntTask<K,V> s, p;
6547 +                if ((par = t.parent) == null ||
6548 +                    !(par instanceof MapReduceValuesToIntTask)) {
6549 +                    t.quietlyComplete();
6550 +                    break;
6551 +                }
6552 +                else if ((c = (p = (MapReduceValuesToIntTask<K,V>)par).pending) == 0) {
6553 +                    if ((s = t.sibling) != null)
6554 +                        r = reducer.apply(r, s.result);
6555 +                    (t = p).result = r;
6556 +                }
6557 +                else if (p.casPending(c, 0))
6558 +                    break;
6559 +            }
6560 +        }
6561 +        public final Integer getRawResult() { return result; }
6562 +    }
6563 +
6564 +    static final class MapReduceEntriesToIntTask<K,V>
6565 +        extends BulkTask<K,V,Integer> {
6566 +        final ObjectToInt<Map.Entry<K,V>> transformer;
6567 +        final IntByIntToInt reducer;
6568 +        final int basis;
6569 +        int result;
6570 +        MapReduceEntriesToIntTask<K,V> sibling;
6571 +        MapReduceEntriesToIntTask
6572 +            (ConcurrentHashMapV8<K,V> m,
6573 +             ObjectToInt<Map.Entry<K,V>> transformer,
6574 +             int basis,
6575 +             IntByIntToInt reducer) {
6576 +            super(m);
6577 +            this.transformer = transformer;
6578 +            this.basis = basis; this.reducer = reducer;
6579 +        }
6580 +        MapReduceEntriesToIntTask
6581 +            (BulkTask<K,V,?> p, int b, boolean split,
6582 +             ObjectToInt<Map.Entry<K,V>> transformer,
6583 +             int basis,
6584 +             IntByIntToInt reducer) {
6585 +            super(p, b, split);
6586 +            this.transformer = transformer;
6587 +            this.basis = basis; this.reducer = reducer;
6588 +        }
6589 +        public final void compute() {
6590 +            MapReduceEntriesToIntTask<K,V> t = this;
6591 +            final ObjectToInt<Map.Entry<K,V>> transformer =
6592 +                this.transformer;
6593 +            final IntByIntToInt reducer = this.reducer;
6594 +            if (transformer == null || reducer == null)
6595 +                throw new Error(NullFunctionMessage);
6596 +            final int id = this.basis;
6597 +            int b = batch();
6598 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6599 +                b >>>= 1;
6600 +                t.pending = 1;
6601 +                MapReduceEntriesToIntTask<K,V> rt =
6602 +                    new MapReduceEntriesToIntTask<K,V>
6603 +                    (t, b, true, transformer, id, reducer);
6604 +                t = new MapReduceEntriesToIntTask<K,V>
6605 +                    (t, b, false, transformer, id, reducer);
6606 +                t.sibling = rt;
6607 +                rt.sibling = t;
6608 +                rt.fork();
6609 +            }
6610 +            int r = id;
6611 +            Object v;
6612 +            while ((v = t.advance()) != null)
6613 +                r = reducer.apply(r, transformer.apply(entryFor((K)t.nextKey, (V)v)));
6614 +            t.result = r;
6615 +            for (;;) {
6616 +                int c; BulkTask<K,V,?> par; MapReduceEntriesToIntTask<K,V> s, p;
6617 +                if ((par = t.parent) == null ||
6618 +                    !(par instanceof MapReduceEntriesToIntTask)) {
6619 +                    t.quietlyComplete();
6620 +                    break;
6621 +                }
6622 +                else if ((c = (p = (MapReduceEntriesToIntTask<K,V>)par).pending) == 0) {
6623 +                    if ((s = t.sibling) != null)
6624 +                        r = reducer.apply(r, s.result);
6625 +                    (t = p).result = r;
6626 +                }
6627 +                else if (p.casPending(c, 0))
6628 +                    break;
6629 +            }
6630 +        }
6631 +        public final Integer getRawResult() { return result; }
6632 +    }
6633 +
6634 +    static final class MapReduceMappingsToIntTask<K,V>
6635 +        extends BulkTask<K,V,Integer> {
6636 +        final ObjectByObjectToInt<? super K, ? super V> transformer;
6637 +        final IntByIntToInt reducer;
6638 +        final int basis;
6639 +        int result;
6640 +        MapReduceMappingsToIntTask<K,V> sibling;
6641 +        MapReduceMappingsToIntTask
6642 +            (ConcurrentHashMapV8<K,V> m,
6643 +             ObjectByObjectToInt<? super K, ? super V> transformer,
6644 +             int basis,
6645 +             IntByIntToInt reducer) {
6646 +            super(m);
6647 +            this.transformer = transformer;
6648 +            this.basis = basis; this.reducer = reducer;
6649 +        }
6650 +        MapReduceMappingsToIntTask
6651 +            (BulkTask<K,V,?> p, int b, boolean split,
6652 +             ObjectByObjectToInt<? super K, ? super V> transformer,
6653 +             int basis,
6654 +             IntByIntToInt reducer) {
6655 +            super(p, b, split);
6656 +            this.transformer = transformer;
6657 +            this.basis = basis; this.reducer = reducer;
6658 +        }
6659 +        public final void compute() {
6660 +            MapReduceMappingsToIntTask<K,V> t = this;
6661 +            final ObjectByObjectToInt<? super K, ? super V> transformer =
6662 +                this.transformer;
6663 +            final IntByIntToInt reducer = this.reducer;
6664 +            if (transformer == null || reducer == null)
6665 +                throw new Error(NullFunctionMessage);
6666 +            final int id = this.basis;
6667 +            int b = batch();
6668 +            while (b > 1 && t.baseIndex != t.baseLimit) {
6669 +                b >>>= 1;
6670 +                t.pending = 1;
6671 +                MapReduceMappingsToIntTask<K,V> rt =
6672 +                    new MapReduceMappingsToIntTask<K,V>
6673 +                    (t, b, true, transformer, id, reducer);
6674 +                t = new MapReduceMappingsToIntTask<K,V>
6675 +                    (t, b, false, transformer, id, reducer);
6676 +                t.sibling = rt;
6677 +                rt.sibling = t;
6678 +                rt.fork();
6679 +            }
6680 +            int r = id;
6681 +            Object v;
6682 +            while ((v = t.advance()) != null)
6683 +                r = reducer.apply(r, transformer.apply((K)t.nextKey, (V)v));
6684 +            t.result = r;
6685 +            for (;;) {
6686 +                int c; BulkTask<K,V,?> par; MapReduceMappingsToIntTask<K,V> s, p;
6687 +                if ((par = t.parent) == null ||
6688 +                    !(par instanceof MapReduceMappingsToIntTask)) {
6689 +                    t.quietlyComplete();
6690 +                    break;
6691 +                }
6692 +                else if ((c = (p = (MapReduceMappingsToIntTask<K,V>)par).pending) == 0) {
6693 +                    if ((s = t.sibling) != null)
6694 +                        r = reducer.apply(r, s.result);
6695 +                    (t = p).result = r;
6696 +                }
6697 +                else if (p.casPending(c, 0))
6698 +                    break;
6699 +            }
6700 +        }
6701 +        public final Integer getRawResult() { return result; }
6702 +    }
6703 +
6704 +
6705      // Unsafe mechanics
6706      private static final sun.misc.Unsafe UNSAFE;
6707      private static final long counterOffset;
6708 <    private static final long resizingOffset;
6708 >    private static final long sizeCtlOffset;
6709      private static final long ABASE;
6710      private static final int ASHIFT;
6711  
# Line 1695 | Line 6716 | public class ConcurrentHashMapV8<K, V>
6716              Class<?> k = ConcurrentHashMapV8.class;
6717              counterOffset = UNSAFE.objectFieldOffset
6718                  (k.getDeclaredField("counter"));
6719 <            resizingOffset = UNSAFE.objectFieldOffset
6720 <                (k.getDeclaredField("resizing"));
6719 >            sizeCtlOffset = UNSAFE.objectFieldOffset
6720 >                (k.getDeclaredField("sizeCtl"));
6721              Class<?> sc = Node[].class;
6722              ABASE = UNSAFE.arrayBaseOffset(sc);
6723              ss = UNSAFE.arrayIndexScale(sc);
# Line 1735 | Line 6756 | public class ConcurrentHashMapV8<K, V>
6756              }
6757          }
6758      }
1738
6759   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines