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.115 by jsr166, Fri Dec 2 14:28:17 2011 UTC vs.
Revision 1.160 by dl, Thu Jan 10 15:03:25 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines