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.40 by jsr166, Sat Jun 9 17:02:07 2012 UTC vs.
Revision 1.95 by jsr166, Mon Feb 11 17:35:59 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines