ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.83 by jsr166, Mon Aug 22 03:42:10 2005 UTC vs.
Revision 1.194 by dl, Wed Mar 13 12:39:01 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines