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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines