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.110 by jsr166, Wed Apr 27 14:06:30 2011 UTC vs.
Revision 1.187 by jsr166, Fri Feb 15 22:27:11 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.Spliterator;
12 > import java.util.stream.Stream;
13 > import java.util.stream.Streams;
14 >
15 > import java.util.Comparator;
16 > import java.util.Arrays;
17 > import java.util.Map;
18 > import java.util.Set;
19 > import java.util.Collection;
20 > import java.util.AbstractMap;
21 > import java.util.AbstractSet;
22 > import java.util.AbstractCollection;
23 > import java.util.Hashtable;
24 > import java.util.HashMap;
25 > import java.util.Iterator;
26 > import java.util.Enumeration;
27 > import java.util.ConcurrentModificationException;
28 > import java.util.NoSuchElementException;
29 > import java.util.concurrent.ConcurrentMap;
30 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
31 > import java.util.concurrent.atomic.AtomicInteger;
32 > import java.util.concurrent.atomic.AtomicReference;
33   import java.io.Serializable;
11 import java.io.IOException;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
34  
35   /**
36   * A hash table supporting full concurrency of retrievals and
37 < * adjustable expected concurrency for updates. This class obeys the
37 > * high expected concurrency for updates. This class obeys the
38   * same functional specification as {@link java.util.Hashtable}, and
39   * includes versions of methods corresponding to each method of
40 < * <tt>Hashtable</tt>. However, even though all operations are
40 > * {@code Hashtable}. However, even though all operations are
41   * thread-safe, retrieval operations do <em>not</em> entail locking,
42   * and there is <em>not</em> any support for locking the entire table
43   * in a way that prevents all access.  This class is fully
44 < * interoperable with <tt>Hashtable</tt> in programs that rely on its
44 > * interoperable with {@code Hashtable} in programs that rely on its
45   * thread safety but not on its synchronization details.
46   *
47 < * <p> Retrieval operations (including <tt>get</tt>) generally do not
48 < * block, so may overlap with update operations (including
49 < * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
50 < * of the most recently <em>completed</em> update operations holding
51 < * upon their onset.  For aggregate operations such as <tt>putAll</tt>
52 < * and <tt>clear</tt>, concurrent retrievals may reflect insertion or
53 < * removal of only some entries.  Similarly, Iterators and
54 < * Enumerations return elements reflecting the state of the hash table
55 < * at some point at or since the creation of the iterator/enumeration.
56 < * They do <em>not</em> throw {@link ConcurrentModificationException}.
57 < * However, iterators are designed to be used by only one thread at a time.
58 < *
59 < * <p> The allowed concurrency among update operations is guided by
60 < * the optional <tt>concurrencyLevel</tt> constructor argument
61 < * (default <tt>16</tt>), which is used as a hint for internal sizing.  The
62 < * table is internally partitioned to try to permit the indicated
63 < * number of concurrent updates without contention. Because placement
64 < * in hash tables is essentially random, the actual concurrency will
65 < * vary.  Ideally, you should choose a value to accommodate as many
66 < * threads as will ever concurrently modify the table. Using a
67 < * significantly higher value than you need can waste space and time,
68 < * and a significantly lower value can lead to thread contention. But
69 < * overestimates and underestimates within an order of magnitude do
70 < * not usually have much noticeable impact. A value of one is
71 < * appropriate when it is known that only one thread will modify and
72 < * all others will only read. Also, resizing this or any other kind of
73 < * hash table is a relatively slow operation, so, when possible, it is
74 < * a good idea to provide estimates of expected table sizes in
75 < * constructors.
47 > * <p>Retrieval operations (including {@code get}) generally do not
48 > * block, so may overlap with update operations (including {@code put}
49 > * and {@code remove}). Retrievals reflect the results of the most
50 > * recently <em>completed</em> update operations holding upon their
51 > * onset. (More formally, an update operation for a given key bears a
52 > * <em>happens-before</em> relation with any (non-null) retrieval for
53 > * that key reporting the updated value.)  For aggregate operations
54 > * such as {@code putAll} and {@code clear}, concurrent retrievals may
55 > * reflect insertion or removal of only some entries.  Similarly,
56 > * Iterators and Enumerations return elements reflecting the state of
57 > * the hash table at some point at or since the creation of the
58 > * iterator/enumeration.  They do <em>not</em> throw {@link
59 > * ConcurrentModificationException}.  However, iterators are designed
60 > * to be used by only one thread at a time.  Bear in mind that the
61 > * results of aggregate status methods including {@code size}, {@code
62 > * isEmpty}, and {@code containsValue} are typically useful only when
63 > * a map is not undergoing concurrent updates in other threads.
64 > * Otherwise the results of these methods reflect transient states
65 > * that may be adequate for monitoring or estimation purposes, but not
66 > * for program control.
67 > *
68 > * <p>The table is dynamically expanded when there are too many
69 > * collisions (i.e., keys that have distinct hash codes but fall into
70 > * the same slot modulo the table size), with the expected average
71 > * effect of maintaining roughly two bins per mapping (corresponding
72 > * to a 0.75 load factor threshold for resizing). There may be much
73 > * variance around this average as mappings are added and removed, but
74 > * overall, this maintains a commonly accepted time/space tradeoff for
75 > * hash tables.  However, resizing this or any other kind of hash
76 > * table may be a relatively slow operation. When possible, it is a
77 > * good idea to provide a size estimate as an optional {@code
78 > * initialCapacity} constructor argument. An additional optional
79 > * {@code loadFactor} constructor argument provides a further means of
80 > * customizing initial table capacity by specifying the table density
81 > * to be used in calculating the amount of space to allocate for the
82 > * given number of elements.  Also, for compatibility with previous
83 > * versions of this class, constructors may optionally specify an
84 > * expected {@code concurrencyLevel} as an additional hint for
85 > * internal sizing.  Note that using many keys with exactly the same
86 > * {@code hashCode()} is a sure way to slow down performance of any
87 > * hash table.
88 > *
89 > * <p>A {@link Set} projection of a ConcurrentHashMap may be created
90 > * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
91 > * (using {@link #keySet(Object)} when only keys are of interest, and the
92 > * mapped values are (perhaps transiently) not used or all take the
93 > * same mapping value.
94 > *
95 > * <p>A ConcurrentHashMap can be used as scalable frequency map (a
96 > * form of histogram or multiset) by using {@link
97 > * java.util.concurrent.atomic.LongAdder} values and initializing via
98 > * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
99 > * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
100 > * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
101   *
102   * <p>This class and its views and iterators implement all of the
103   * <em>optional</em> methods of the {@link Map} and {@link Iterator}
104   * interfaces.
105   *
106 < * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
107 < * does <em>not</em> allow <tt>null</tt> to be used as a key or value.
106 > * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
107 > * does <em>not</em> allow {@code null} to be used as a key or value.
108 > *
109 > * <p>ConcurrentHashMaps support sequential and parallel operations
110 > * bulk operations. (Parallel forms use the {@link
111 > * ForkJoinPool#commonPool()}). Tasks that may be used in other
112 > * contexts are available in class {@link ForkJoinTasks}. These
113 > * operations are designed to be safely, and often sensibly, applied
114 > * even with maps that are being concurrently updated by other
115 > * threads; for example, when computing a snapshot summary of the
116 > * values in a shared registry.  There are three kinds of operation,
117 > * each with four forms, accepting functions with Keys, Values,
118 > * Entries, and (Key, Value) arguments and/or return values. Because
119 > * the elements of a ConcurrentHashMap are not ordered in any
120 > * particular way, and may be processed in different orders in
121 > * different parallel executions, the correctness of supplied
122 > * functions should not depend on any ordering, or on any other
123 > * objects or values that may transiently change while computation is
124 > * in progress; and except for forEach actions, should ideally be
125 > * side-effect-free.
126 > *
127 > * <ul>
128 > * <li> forEach: Perform a given action on each element.
129 > * A variant form applies a given transformation on each element
130 > * before performing the action.</li>
131 > *
132 > * <li> search: Return the first available non-null result of
133 > * applying a given function on each element; skipping further
134 > * search when a result is found.</li>
135 > *
136 > * <li> reduce: Accumulate each element.  The supplied reduction
137 > * function cannot rely on ordering (more formally, it should be
138 > * both associative and commutative).  There are five variants:
139 > *
140 > * <ul>
141 > *
142 > * <li> Plain reductions. (There is not a form of this method for
143 > * (key, value) function arguments since there is no corresponding
144 > * return type.)</li>
145 > *
146 > * <li> Mapped reductions that accumulate the results of a given
147 > * function applied to each element.</li>
148 > *
149 > * <li> Reductions to scalar doubles, longs, and ints, using a
150 > * given basis value.</li>
151 > *
152 > * </ul>
153 > * </li>
154 > * </ul>
155 > *
156 > * <p>The concurrency properties of bulk operations follow
157 > * from those of ConcurrentHashMap: Any non-null result returned
158 > * from {@code get(key)} and related access methods bears a
159 > * happens-before relation with the associated insertion or
160 > * update.  The result of any bulk operation reflects the
161 > * composition of these per-element relations (but is not
162 > * necessarily atomic with respect to the map as a whole unless it
163 > * is somehow known to be quiescent).  Conversely, because keys
164 > * and values in the map are never null, null serves as a reliable
165 > * atomic indicator of the current lack of any result.  To
166 > * maintain this property, null serves as an implicit basis for
167 > * all non-scalar reduction operations. For the double, long, and
168 > * int versions, the basis should be one that, when combined with
169 > * any other value, returns that other value (more formally, it
170 > * should be the identity element for the reduction). Most common
171 > * reductions have these properties; for example, computing a sum
172 > * with basis 0 or a minimum with basis MAX_VALUE.
173 > *
174 > * <p>Search and transformation functions provided as arguments
175 > * should similarly return null to indicate the lack of any result
176 > * (in which case it is not used). In the case of mapped
177 > * reductions, this also enables transformations to serve as
178 > * filters, returning null (or, in the case of primitive
179 > * specializations, the identity basis) if the element should not
180 > * be combined. You can create compound transformations and
181 > * filterings by composing them yourself under this "null means
182 > * there is nothing there now" rule before using them in search or
183 > * reduce operations.
184 > *
185 > * <p>Methods accepting and/or returning Entry arguments maintain
186 > * key-value associations. They may be useful for example when
187 > * finding the key for the greatest value. Note that "plain" Entry
188 > * arguments can be supplied using {@code new
189 > * AbstractMap.SimpleEntry(k,v)}.
190 > *
191 > * <p>Bulk operations may complete abruptly, throwing an
192 > * exception encountered in the application of a supplied
193 > * function. Bear in mind when handling such exceptions that other
194 > * concurrently executing functions could also have thrown
195 > * exceptions, or would have done so if the first exception had
196 > * not occurred.
197 > *
198 > * <p>Speedups for parallel compared to sequential forms are common
199 > * but not guaranteed.  Parallel operations involving brief functions
200 > * on small maps may execute more slowly than sequential forms if the
201 > * underlying work to parallelize the computation is more expensive
202 > * than the computation itself.  Similarly, parallelization may not
203 > * lead to much actual parallelism if all processors are busy
204 > * performing unrelated tasks.
205 > *
206 > * <p>All arguments to all task methods must be non-null.
207   *
208   * <p>This class is a member of the
209   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 70 | Line 214 | import java.io.ObjectOutputStream;
214   * @param <K> the type of keys maintained by this map
215   * @param <V> the type of mapped values
216   */
217 < public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
218 <        implements ConcurrentMap<K, V>, Serializable {
217 > public class ConcurrentHashMap<K,V>
218 >    implements ConcurrentMap<K,V>, Serializable {
219      private static final long serialVersionUID = 7249069246763182397L;
220  
221      /*
222 <     * The basic strategy is to subdivide the table among Segments,
223 <     * each of which itself is a concurrently readable hash table.  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
123 <     * be a power of two <= 1<<30 to ensure that entries are indexable
124 <     * 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 >     * The next table index (plus one) to split while resizing.
514 >     */
515 >    private transient volatile int transferIndex;
516  
517      /**
518 <     * ConcurrentHashMap list entry. Note that this is never exported
173 <     * out as a user-visible Map.Entry.
518 >     * The least available table index to split while resizing.
519       */
520 <    static final class HashEntry<K,V> {
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 <        /**
189 <         * Sets next field with volatile write semantics.  (See above
190 <         * about use of putOrderedObject.)
191 <         */
192 <        final void setNext(HashEntry<K,V> n) {
193 <            UNSAFE.putOrderedObject(this, nextOffset, n);
194 <        }
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 <     */
255 <    static final class Segment<K,V> extends ReentrantLock implements Serializable {
256 <        /*
257 <         * Segments maintain a table of entry lists that are always
258 <         * kept in a consistent state, so can be read (via volatile
259 <         * reads of segments and tables) without locking.  This
260 <         * requires replicating nodes when necessary during table
261 <         * resizing, so the old lists can be traversed by readers
262 <         * still using old version of table.
263 <         *
264 <         * This class defines only mutative methods requiring locking.
265 <         * Except as noted, the methods of this class perform the
266 <         * per-segment versions of ConcurrentHashMap methods.  (Other
267 <         * methods are integrated directly into ConcurrentHashMap
268 <         * methods.) These mutative methods use a form of controlled
269 <         * spinning on contention via methods scanAndLock and
270 <         * scanAndLockForPut. These intersperse tryLocks with
271 <         * traversals to locate nodes.  The main benefit is to absorb
272 <         * cache misses (which are very common for hash tables) while
273 <         * obtaining locks so that traversal is faster once
274 <         * acquired. We do not actually use the found nodes since they
275 <         * must be re-acquired under lock anyway to ensure sequential
276 <         * consistency of updates (and in any case may be undetectably
277 <         * stale), but they will normally be much faster to re-locate.
278 <         * Also, scanAndLockForPut speculatively creates a fresh node
279 <         * to use in put if no node is found.
280 <         */
281 <
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()
310 <         * and size() methods.  Accessed only either within locks or
311 <         * 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 *
318 <         * 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 <        Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
1085 <            this.loadFactor = lf;
1086 <            this.threshold = threshold;
1087 <            this.table = tab;
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 <        final V put(K key, int hash, V value, boolean onlyIfAbsent) {
1098 <            HashEntry<K,V> node = tryLock() ? null :
1099 <                scanAndLockForPut(key, hash, value);
1100 <            V oldValue;
1101 <            try {
1102 <                HashEntry<K,V>[] tab = table;
1103 <                int index = (tab.length - 1) & hash;
1104 <                HashEntry<K,V> first = entryAt(tab, index);
1105 <                for (HashEntry<K,V> e = first;;) {
1106 <                    if (e != null) {
1107 <                        K k;
1108 <                        if ((k = e.key) == key ||
1109 <                            (e.hash == hash && key.equals(k))) {
1110 <                            oldValue = e.value;
1111 <                            if (!onlyIfAbsent) {
1112 <                                e.value = value;
1113 <                                ++modCount;
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 >    /**
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                              }
354                            break;
1156                          }
1157 <                        e = e.next;
1157 >                    } finally {
1158 >                        t.release(0);
1159                      }
1160 <                    else {
1161 <                        if (node != null)
1162 <                            node.setNext(first);
361 <                        else
362 <                            node = new HashEntry<K,V>(hash, key, value, first);
363 <                        int c = count + 1;
364 <                        if (c > threshold && tab.length < MAXIMUM_CAPACITY)
365 <                            rehash(node);
366 <                        else
367 <                            setEntryAt(tab, index, node);
368 <                        ++modCount;
369 <                        count = c;
370 <                        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              }
377            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;
1265 <                            HashEntry<K,V> n = newTable[k];
1266 <                            newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
1267 <                        }
1268 <                    }
1269 <                }
1270 <            }
1271 <            int nodeIndex = node.hash & sizeMask; // add the new node
1272 <            node.setNext(newTable[nodeIndex]);
1273 <            newTable[nodeIndex] = node;
1274 <            table = newTable;
1275 <        }
1276 <
1277 <        /**
1278 <         * Scans for a node containing given key while trying to
1279 <         * acquire lock, creating and returning one if not found. Upon
1280 <         * return, guarantees that lock is held. Unlike in most
1281 <         * methods, calls to method equals are not screened: Since
1282 <         * traversal speed doesn't matter, we might as well help warm
1283 <         * up the associated code and accesses as well.
1284 <         *
1285 <         * @return a new node if key not found, else null
1286 <         */
1287 <        private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
1288 <            HashEntry<K,V> first = entryForHash(this, hash);
1289 <            HashEntry<K,V> e = first;
1290 <            HashEntry<K,V> node = null;
1291 <            int retries = -1; // negative while locating node
1292 <            while (!tryLock()) {
1293 <                HashEntry<K,V> f; // to recheck first below
1294 <                if (retries < 0) {
1295 <                    if (e == null) {
465 <                        if (node == null) // speculatively create node
466 <                            node = new HashEntry<K,V>(hash, key, value, null);
467 <                        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 >                    }
1266 >                }
1267 >                else
1268 >                    tab = (Node<V>[])fk;
1269 >            }
1270 >            else if (onlyIfAbsent && fh == h && (fv = f.val) != null &&
1271 >                     ((fk = f.key) == k || k.equals(fk))) // peek while nearby
1272 >                return fv;
1273 >            else {
1274 >                V oldVal = null;
1275 >                synchronized (f) {
1276 >                    if (tabAt(tab, i) == f) {
1277 >                        len = 1;
1278 >                        for (Node<V> e = f;; ++len) {
1279 >                            Object ek; V ev;
1280 >                            if (e.hash == h &&
1281 >                                (ev = e.val) != null &&
1282 >                                ((ek = e.key) == k || k.equals(ek))) {
1283 >                                oldVal = ev;
1284 >                                if (!onlyIfAbsent)
1285 >                                    e.val = v;
1286 >                                break;
1287 >                            }
1288 >                            Node<V> last = e;
1289 >                            if ((e = e.next) == null) {
1290 >                                last.next = new Node<V>(h, k, v, null);
1291 >                                if (len >= TREE_THRESHOLD)
1292 >                                    replaceWithTreeBin(tab, i, k);
1293 >                                break;
1294 >                            }
1295 >                        }
1296                      }
469                    else if (key.equals(e.key))
470                        retries = 0;
471                    else
472                        e = e.next;
1297                  }
1298 <                else if (++retries > MAX_SCAN_RETRIES) {
1299 <                    lock();
1298 >                if (len != 0) {
1299 >                    if (oldVal != null)
1300 >                        return oldVal;
1301                      break;
1302                  }
1303 <                else if ((retries & 1) == 0 &&
479 <                         (f = entryForHash(this, hash)) != first) {
480 <                    e = first = f; // re-traverse if entry changed
481 <                    retries = -1;
482 <                }
483 <            }
484 <            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) {
508 <                    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
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 <                else if ((retries & 1) == 0 &&
1400 <                         (f = entryForHash(this, hash)) != first) {
1401 <                    e = first = f;
1402 <                    retries = -1;
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                      }
548                    pred = e;
549                    e = next;
1515                  }
1516 <            } finally {
1517 <                unlock();
1516 >                if (len != 0)
1517 >                    break;
1518              }
554            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 <            } finally {
1612 <                unlock();
1611 >                if (len != 0)
1612 >                    break;
1613              }
578            return replaced;
1614          }
1615 <
1616 <        final V replace(K key, int hash, V value) {
1617 <            if (!tryLock())
1618 <                scanAndLock(key, hash);
1619 <            V oldValue = null;
1620 <            try {
1621 <                HashEntry<K,V> e;
1622 <                for (e = entryForHash(this, hash); e != null; e = e.next) {
1623 <                    K k;
1624 <                    if ((k = e.key) == key ||
1625 <                        (e.hash == hash && key.equals(k))) {
1626 <                        oldValue = e.value;
1627 <                        e.value = value;
1628 <                        ++modCount;
1629 <                        break;
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 >                                delta = 0L;
1698 >                            }
1699 >                            break;
1700 >                        }
1701                      }
1702                  }
597            } finally {
598                unlock();
1703              }
1704 <            return oldValue;
1704 >        } finally {
1705 >            if (delta != 0L)
1706 >                addCount(delta, 2);
1707          }
1708 +        if (npe)
1709 +            throw new NullPointerException();
1710 +    }
1711  
1712 <        final void clear() {
1713 <            lock();
1714 <            try {
1715 <                HashEntry<K,V>[] tab = table;
1716 <                for (int i = 0; i < tab.length ; i++)
1717 <                    setEntryAt(tab, i, null);
1718 <                ++modCount;
1719 <                count = 0;
1720 <            } finally {
1721 <                unlock();
1712 >    /**
1713 >     * Implementation for clear. Steps through each bin, removing all
1714 >     * nodes.
1715 >     */
1716 >    @SuppressWarnings("unchecked") private final void internalClear() {
1717 >        long delta = 0L; // negative number of deletions
1718 >        int i = 0;
1719 >        Node<V>[] tab = table;
1720 >        while (tab != null && i < tab.length) {
1721 >            Node<V> f = tabAt(tab, i);
1722 >            if (f == null)
1723 >                ++i;
1724 >            else if (f.hash < 0) {
1725 >                Object fk;
1726 >                if ((fk = f.key) instanceof TreeBin) {
1727 >                    TreeBin<V> t = (TreeBin<V>)fk;
1728 >                    t.acquire(0);
1729 >                    try {
1730 >                        if (tabAt(tab, i) == f) {
1731 >                            for (Node<V> p = t.first; p != null; p = p.next) {
1732 >                                if (p.val != null) { // (currently always true)
1733 >                                    p.val = null;
1734 >                                    --delta;
1735 >                                }
1736 >                            }
1737 >                            t.first = null;
1738 >                            t.root = null;
1739 >                            ++i;
1740 >                        }
1741 >                    } finally {
1742 >                        t.release(0);
1743 >                    }
1744 >                }
1745 >                else
1746 >                    tab = (Node<V>[])fk;
1747 >            }
1748 >            else {
1749 >                synchronized (f) {
1750 >                    if (tabAt(tab, i) == f) {
1751 >                        for (Node<V> e = f; e != null; e = e.next) {
1752 >                            if (e.val != null) {  // (currently always true)
1753 >                                e.val = null;
1754 >                                --delta;
1755 >                            }
1756 >                        }
1757 >                        setTabAt(tab, i, null);
1758 >                        ++i;
1759 >                    }
1760 >                }
1761              }
1762          }
1763 +        if (delta != 0L)
1764 +            addCount(delta, -1);
1765      }
1766  
1767 <    // Accessing segments
1768 <
1769 <    /**
1770 <     * Gets the jth element of given segment array (if nonnull) with
1771 <     * volatile element access semantics via Unsafe. (The null check
1772 <     * can trigger harmlessly only during deserialization.) Note:
1773 <     * because each element of segments array is set only once (using
1774 <     * fully ordered writes), some performance-sensitive methods rely
1775 <     * on this method only as a recheck upon null reads.
1776 <     */
1777 <    @SuppressWarnings("unchecked")
1778 <    static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
1779 <        long u = (j << SSHIFT) + SBASE;
1780 <        return ss == null ? null :
631 <            (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
1767 >    /* ---------------- Table Initialization and Resizing -------------- */
1768 >
1769 >    /**
1770 >     * Returns a power of two table size for the given desired capacity.
1771 >     * See Hackers Delight, sec 3.2
1772 >     */
1773 >    private static final int tableSizeFor(int c) {
1774 >        int n = c - 1;
1775 >        n |= n >>> 1;
1776 >        n |= n >>> 2;
1777 >        n |= n >>> 4;
1778 >        n |= n >>> 8;
1779 >        n |= n >>> 16;
1780 >        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1781      }
1782  
1783      /**
1784 <     * Returns the segment for the given index, creating it and
1785 <     * recording in segment table (via CAS) if not already present.
1786 <     *
1787 <     * @param k the index
1788 <     * @return the segment
1789 <     */
1790 <    @SuppressWarnings("unchecked")
1791 <    private Segment<K,V> ensureSegment(int k) {
1792 <        final Segment<K,V>[] ss = this.segments;
1793 <        long u = (k << SSHIFT) + SBASE; // raw offset
1794 <        Segment<K,V> seg;
1795 <        if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
1796 <            Segment<K,V> proto = ss[0]; // use segment 0 as prototype
1797 <            int cap = proto.table.length;
1798 <            float lf = proto.loadFactor;
1799 <            int threshold = (int)(cap * lf);
1800 <            HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
652 <            if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
653 <                == null) { // recheck
654 <                Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
655 <                while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
656 <                       == null) {
657 <                    if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
658 <                        break;
1784 >     * Initializes table, using the size recorded in sizeCtl.
1785 >     */
1786 >    @SuppressWarnings("unchecked") private final Node<V>[] initTable() {
1787 >        Node<V>[] tab; int sc;
1788 >        while ((tab = table) == null) {
1789 >            if ((sc = sizeCtl) < 0)
1790 >                Thread.yield(); // lost initialization race; just spin
1791 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1792 >                try {
1793 >                    if ((tab = table) == null) {
1794 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1795 >                        @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1796 >                        table = tab = (Node<V>[])tb;
1797 >                        sc = n - (n >>> 2);
1798 >                    }
1799 >                } finally {
1800 >                    sizeCtl = sc;
1801                  }
1802 +                break;
1803              }
1804          }
1805 <        return seg;
1805 >        return tab;
1806      }
1807  
1808 <    // Hash-based segment and entry accesses
1808 >    /**
1809 >     * Adds to count, and if table is too small and not already
1810 >     * resizing, initiates transfer. If already resizing, helps
1811 >     * perform transfer if work is available.  Rechecks occupancy
1812 >     * after a transfer to see if another resize is already needed
1813 >     * because resizings are lagging additions.
1814 >     *
1815 >     * @param x the count to add
1816 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1817 >     */
1818 >    private final void addCount(long x, int check) {
1819 >        Cell[] as; long b, s;
1820 >        if ((as = counterCells) != null ||
1821 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1822 >            Cell a; long v; int m;
1823 >            boolean uncontended = true;
1824 >            if (as == null || (m = as.length - 1) < 0 ||
1825 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
1826 >                !(uncontended =
1827 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1828 >                fullAddCount(x, uncontended);
1829 >                return;
1830 >            }
1831 >            if (check <= 1)
1832 >                return;
1833 >            s = sumCount();
1834 >        }
1835 >        if (check >= 0) {
1836 >            Node<V>[] tab, nt; int sc;
1837 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1838 >                   tab.length < MAXIMUM_CAPACITY) {
1839 >                if (sc < 0) {
1840 >                    if (sc == -1 || transferIndex <= transferOrigin ||
1841 >                        (nt = nextTable) == null)
1842 >                        break;
1843 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1844 >                        transfer(tab, nt);
1845 >                }
1846 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1847 >                    transfer(tab, null);
1848 >                s = sumCount();
1849 >            }
1850 >        }
1851 >    }
1852  
1853      /**
1854 <     * Gets the segment for the given hash code.
1854 >     * Tries to presize table to accommodate the given number of elements.
1855 >     *
1856 >     * @param size number of elements (doesn't need to be perfectly accurate)
1857       */
1858 <    @SuppressWarnings("unchecked")
1859 <    private Segment<K,V> segmentForHash(int h) {
1860 <        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
1861 <        return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
1858 >    @SuppressWarnings("unchecked") private final void tryPresize(int size) {
1859 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1860 >            tableSizeFor(size + (size >>> 1) + 1);
1861 >        int sc;
1862 >        while ((sc = sizeCtl) >= 0) {
1863 >            Node<V>[] tab = table; int n;
1864 >            if (tab == null || (n = tab.length) == 0) {
1865 >                n = (sc > c) ? sc : c;
1866 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1867 >                    try {
1868 >                        if (table == tab) {
1869 >                            @SuppressWarnings("rawtypes") Node[] tb = new Node[n];
1870 >                            table = (Node<V>[])tb;
1871 >                            sc = n - (n >>> 2);
1872 >                        }
1873 >                    } finally {
1874 >                        sizeCtl = sc;
1875 >                    }
1876 >                }
1877 >            }
1878 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1879 >                break;
1880 >            else if (tab == table &&
1881 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1882 >                transfer(tab, null);
1883 >        }
1884      }
1885  
1886      /**
1887 <     * Gets the table entry for the given segment and hash code.
1887 >     * Moves and/or copies the nodes in each bin to new table. See
1888 >     * above for explanation.
1889       */
1890 <    @SuppressWarnings("unchecked")
1891 <    static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
1892 <        HashEntry<K,V>[] tab;
1893 <        return (seg == null || (tab = seg.table) == null) ? null :
1894 <            (HashEntry<K,V>) UNSAFE.getObjectVolatile
1895 <            (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
1890 >    @SuppressWarnings("unchecked") private final void transfer
1891 >        (Node<V>[] tab, Node<V>[] nextTab) {
1892 >        int n = tab.length, stride;
1893 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1894 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
1895 >        if (nextTab == null) {            // initiating
1896 >            try {
1897 >                @SuppressWarnings("rawtypes") Node[] tb = new Node[n << 1];
1898 >                nextTab = (Node<V>[])tb;
1899 >            } catch (Throwable ex) {      // try to cope with OOME
1900 >                sizeCtl = Integer.MAX_VALUE;
1901 >                return;
1902 >            }
1903 >            nextTable = nextTab;
1904 >            transferOrigin = n;
1905 >            transferIndex = n;
1906 >            Node<V> rev = new Node<V>(MOVED, tab, null, null);
1907 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
1908 >                int nextk = (k > stride) ? k - stride : 0;
1909 >                for (int m = nextk; m < k; ++m)
1910 >                    nextTab[m] = rev;
1911 >                for (int m = n + nextk; m < n + k; ++m)
1912 >                    nextTab[m] = rev;
1913 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
1914 >            }
1915 >        }
1916 >        int nextn = nextTab.length;
1917 >        Node<V> fwd = new Node<V>(MOVED, nextTab, null, null);
1918 >        boolean advance = true;
1919 >        for (int i = 0, bound = 0;;) {
1920 >            int nextIndex, nextBound; Node<V> f; Object fk;
1921 >            while (advance) {
1922 >                if (--i >= bound)
1923 >                    advance = false;
1924 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
1925 >                    i = -1;
1926 >                    advance = false;
1927 >                }
1928 >                else if (U.compareAndSwapInt
1929 >                         (this, TRANSFERINDEX, nextIndex,
1930 >                          nextBound = (nextIndex > stride ?
1931 >                                       nextIndex - stride : 0))) {
1932 >                    bound = nextBound;
1933 >                    i = nextIndex - 1;
1934 >                    advance = false;
1935 >                }
1936 >            }
1937 >            if (i < 0 || i >= n || i + n >= nextn) {
1938 >                for (int sc;;) {
1939 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
1940 >                        if (sc == -1) {
1941 >                            nextTable = null;
1942 >                            table = nextTab;
1943 >                            sizeCtl = (n << 1) - (n >>> 1);
1944 >                        }
1945 >                        return;
1946 >                    }
1947 >                }
1948 >            }
1949 >            else if ((f = tabAt(tab, i)) == null) {
1950 >                if (casTabAt(tab, i, null, fwd)) {
1951 >                    setTabAt(nextTab, i, null);
1952 >                    setTabAt(nextTab, i + n, null);
1953 >                    advance = true;
1954 >                }
1955 >            }
1956 >            else if (f.hash >= 0) {
1957 >                synchronized (f) {
1958 >                    if (tabAt(tab, i) == f) {
1959 >                        int runBit = f.hash & n;
1960 >                        Node<V> lastRun = f, lo = null, hi = null;
1961 >                        for (Node<V> p = f.next; p != null; p = p.next) {
1962 >                            int b = p.hash & n;
1963 >                            if (b != runBit) {
1964 >                                runBit = b;
1965 >                                lastRun = p;
1966 >                            }
1967 >                        }
1968 >                        if (runBit == 0)
1969 >                            lo = lastRun;
1970 >                        else
1971 >                            hi = lastRun;
1972 >                        for (Node<V> p = f; p != lastRun; p = p.next) {
1973 >                            int ph = p.hash;
1974 >                            Object pk = p.key; V pv = p.val;
1975 >                            if ((ph & n) == 0)
1976 >                                lo = new Node<V>(ph, pk, pv, lo);
1977 >                            else
1978 >                                hi = new Node<V>(ph, pk, pv, hi);
1979 >                        }
1980 >                        setTabAt(nextTab, i, lo);
1981 >                        setTabAt(nextTab, i + n, hi);
1982 >                        setTabAt(tab, i, fwd);
1983 >                        advance = true;
1984 >                    }
1985 >                }
1986 >            }
1987 >            else if ((fk = f.key) instanceof TreeBin) {
1988 >                TreeBin<V> t = (TreeBin<V>)fk;
1989 >                t.acquire(0);
1990 >                try {
1991 >                    if (tabAt(tab, i) == f) {
1992 >                        TreeBin<V> lt = new TreeBin<V>();
1993 >                        TreeBin<V> ht = new TreeBin<V>();
1994 >                        int lc = 0, hc = 0;
1995 >                        for (Node<V> e = t.first; e != null; e = e.next) {
1996 >                            int h = e.hash;
1997 >                            Object k = e.key; V v = e.val;
1998 >                            if ((h & n) == 0) {
1999 >                                ++lc;
2000 >                                lt.putTreeNode(h, k, v);
2001 >                            }
2002 >                            else {
2003 >                                ++hc;
2004 >                                ht.putTreeNode(h, k, v);
2005 >                            }
2006 >                        }
2007 >                        Node<V> ln, hn; // throw away trees if too small
2008 >                        if (lc < TREE_THRESHOLD) {
2009 >                            ln = null;
2010 >                            for (Node<V> p = lt.first; p != null; p = p.next)
2011 >                                ln = new Node<V>(p.hash, p.key, p.val, ln);
2012 >                        }
2013 >                        else
2014 >                            ln = new Node<V>(MOVED, lt, null, null);
2015 >                        setTabAt(nextTab, i, ln);
2016 >                        if (hc < TREE_THRESHOLD) {
2017 >                            hn = null;
2018 >                            for (Node<V> p = ht.first; p != null; p = p.next)
2019 >                                hn = new Node<V>(p.hash, p.key, p.val, hn);
2020 >                        }
2021 >                        else
2022 >                            hn = new Node<V>(MOVED, ht, null, null);
2023 >                        setTabAt(nextTab, i + n, hn);
2024 >                        setTabAt(tab, i, fwd);
2025 >                        advance = true;
2026 >                    }
2027 >                } finally {
2028 >                    t.release(0);
2029 >                }
2030 >            }
2031 >            else
2032 >                advance = true; // already processed
2033 >        }
2034      }
2035  
2036 <    /* ---------------- Public operations -------------- */
2036 >    /* ---------------- Counter support -------------- */
2037 >
2038 >    final long sumCount() {
2039 >        Cell[] as = counterCells; Cell a;
2040 >        long sum = baseCount;
2041 >        if (as != null) {
2042 >            for (int i = 0; i < as.length; ++i) {
2043 >                if ((a = as[i]) != null)
2044 >                    sum += a.value;
2045 >            }
2046 >        }
2047 >        return sum;
2048 >    }
2049 >
2050 >    // See LongAdder version for explanation
2051 >    private final void fullAddCount(long x, boolean wasUncontended) {
2052 >        int h;
2053 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2054 >            ThreadLocalRandom.localInit();      // force initialization
2055 >            h = ThreadLocalRandom.getProbe();
2056 >            wasUncontended = true;
2057 >        }
2058 >        boolean collide = false;                // True if last slot nonempty
2059 >        for (;;) {
2060 >            Cell[] as; Cell a; int n; long v;
2061 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2062 >                if ((a = as[(n - 1) & h]) == null) {
2063 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2064 >                        Cell r = new Cell(x); // Optimistic create
2065 >                        if (cellsBusy == 0 &&
2066 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2067 >                            boolean created = false;
2068 >                            try {               // Recheck under lock
2069 >                                Cell[] rs; int m, j;
2070 >                                if ((rs = counterCells) != null &&
2071 >                                    (m = rs.length) > 0 &&
2072 >                                    rs[j = (m - 1) & h] == null) {
2073 >                                    rs[j] = r;
2074 >                                    created = true;
2075 >                                }
2076 >                            } finally {
2077 >                                cellsBusy = 0;
2078 >                            }
2079 >                            if (created)
2080 >                                break;
2081 >                            continue;           // Slot is now non-empty
2082 >                        }
2083 >                    }
2084 >                    collide = false;
2085 >                }
2086 >                else if (!wasUncontended)       // CAS already known to fail
2087 >                    wasUncontended = true;      // Continue after rehash
2088 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2089 >                    break;
2090 >                else if (counterCells != as || n >= NCPU)
2091 >                    collide = false;            // At max size or stale
2092 >                else if (!collide)
2093 >                    collide = true;
2094 >                else if (cellsBusy == 0 &&
2095 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2096 >                    try {
2097 >                        if (counterCells == as) {// Expand table unless stale
2098 >                            Cell[] rs = new Cell[n << 1];
2099 >                            for (int i = 0; i < n; ++i)
2100 >                                rs[i] = as[i];
2101 >                            counterCells = rs;
2102 >                        }
2103 >                    } finally {
2104 >                        cellsBusy = 0;
2105 >                    }
2106 >                    collide = false;
2107 >                    continue;                   // Retry with expanded table
2108 >                }
2109 >                h = ThreadLocalRandom.advanceProbe(h);
2110 >            }
2111 >            else if (cellsBusy == 0 && counterCells == as &&
2112 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2113 >                boolean init = false;
2114 >                try {                           // Initialize table
2115 >                    if (counterCells == as) {
2116 >                        Cell[] rs = new Cell[2];
2117 >                        rs[h & 1] = new Cell(x);
2118 >                        counterCells = rs;
2119 >                        init = true;
2120 >                    }
2121 >                } finally {
2122 >                    cellsBusy = 0;
2123 >                }
2124 >                if (init)
2125 >                    break;
2126 >            }
2127 >            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2128 >                break;                          // Fall back on using base
2129 >        }
2130 >    }
2131 >
2132 >    /* ----------------Table Traversal -------------- */
2133  
2134      /**
2135 <     * Creates a new, empty map with the specified initial
2136 <     * capacity, load factor and concurrency level.
2135 >     * Encapsulates traversal for methods such as containsValue; also
2136 >     * serves as a base class for other iterators and bulk tasks.
2137       *
2138 <     * @param initialCapacity the initial capacity. The implementation
2139 <     * performs internal sizing to accommodate this many elements.
2140 <     * @param loadFactor  the load factor threshold, used to control resizing.
2141 <     * Resizing may be performed when the average number of elements per
2142 <     * bin exceeds this threshold.
2143 <     * @param concurrencyLevel the estimated number of concurrently
2144 <     * updating threads. The implementation performs internal sizing
2145 <     * to try to accommodate this many threads.
2146 <     * @throws IllegalArgumentException if the initial capacity is
2147 <     * negative or the load factor or concurrencyLevel are
2148 <     * nonpositive.
2138 >     * At each step, the iterator snapshots the key ("nextKey") and
2139 >     * value ("nextVal") of a valid node (i.e., one that, at point of
2140 >     * snapshot, has a non-null user value). Because val fields can
2141 >     * change (including to null, indicating deletion), field nextVal
2142 >     * might not be accurate at point of use, but still maintains the
2143 >     * weak consistency property of holding a value that was once
2144 >     * valid. To support iterator.remove, the nextKey field is not
2145 >     * updated (nulled out) when the iterator cannot advance.
2146 >     *
2147 >     * Internal traversals directly access these fields, as in:
2148 >     * {@code while (it.advance() != null) { process(it.nextKey); }}
2149 >     *
2150 >     * Exported iterators must track whether the iterator has advanced
2151 >     * (in hasNext vs next) (by setting/checking/nulling field
2152 >     * nextVal), and then extract key, value, or key-value pairs as
2153 >     * return values of next().
2154 >     *
2155 >     * The iterator visits once each still-valid node that was
2156 >     * reachable upon iterator construction. It might miss some that
2157 >     * were added to a bin after the bin was visited, which is OK wrt
2158 >     * consistency guarantees. Maintaining this property in the face
2159 >     * of possible ongoing resizes requires a fair amount of
2160 >     * bookkeeping state that is difficult to optimize away amidst
2161 >     * volatile accesses.  Even so, traversal maintains reasonable
2162 >     * throughput.
2163 >     *
2164 >     * Normally, iteration proceeds bin-by-bin traversing lists.
2165 >     * However, if the table has been resized, then all future steps
2166 >     * must traverse both the bin at the current index as well as at
2167 >     * (index + baseSize); and so on for further resizings. To
2168 >     * paranoically cope with potential sharing by users of iterators
2169 >     * across threads, iteration terminates if a bounds checks fails
2170 >     * for a table read.
2171 >     *
2172 >     * This class supports both Spliterator-based traversal and
2173 >     * CountedCompleter-based bulk tasks. The same "batch" field is
2174 >     * used, but in slightly different ways, in the two cases.  For
2175 >     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2176 >     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2177 >     * size that halves down to zero for leaf tasks, that is only
2178 >     * computed upon execution of the task. (Tasks can be submitted to
2179 >     * any pool, of any size, so we don't know scale factors until
2180 >     * running.)
2181 >     *
2182 >     * This class extends CountedCompleter to streamline parallel
2183 >     * iteration in bulk operations. This adds only a few fields of
2184 >     * space overhead, which is small enough in cases where it is not
2185 >     * needed to not worry about it.  Because CountedCompleter is
2186 >     * Serializable, but iterators need not be, we need to add warning
2187 >     * suppressions.
2188 >     */
2189 >    @SuppressWarnings("serial") static class Traverser<K,V,R>
2190 >        extends CountedCompleter<R> {
2191 >        final ConcurrentHashMap<K,V> map;
2192 >        Node<V> next;        // the next entry to use
2193 >        K nextKey;           // cached key field of next
2194 >        V nextVal;           // cached val field of next
2195 >        Node<V>[] tab;       // current table; updated if resized
2196 >        int index;           // index of bin to use next
2197 >        int baseIndex;       // current index of initial table
2198 >        int baseLimit;       // index bound for initial table
2199 >        int baseSize;        // initial table size
2200 >        int batch;           // split control
2201 >        /** Creates iterator for all entries in the table. */
2202 >        Traverser(ConcurrentHashMap<K,V> map) {
2203 >            this.map = map;
2204 >            Node<V>[] t;
2205 >            if ((t = tab = map.table) != null)
2206 >                baseLimit = baseSize = t.length;
2207 >        }
2208 >
2209 >        /** Task constructor */
2210 >        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2211 >            super(it);
2212 >            this.map = map;
2213 >            this.batch = batch; // -1 if unknown
2214 >            if (it == null) {
2215 >                Node<V>[] t;
2216 >                if ((t = tab = map.table) != null)
2217 >                    baseLimit = baseSize = t.length;
2218 >            }
2219 >            else { // split parent
2220 >                this.tab = it.tab;
2221 >                this.baseSize = it.baseSize;
2222 >                int hi = this.baseLimit = it.baseLimit;
2223 >                it.baseLimit = this.index = this.baseIndex =
2224 >                    (hi + it.baseIndex + 1) >>> 1;
2225 >            }
2226 >        }
2227 >
2228 >        /** Spliterator constructor */
2229 >        Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2230 >            super(it);
2231 >            this.map = map;
2232 >            if (it == null) {
2233 >                Node<V>[] t;
2234 >                if ((t = tab = map.table) != null)
2235 >                    baseLimit = baseSize = t.length;
2236 >                long n = map.sumCount();
2237 >                batch = ((n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2238 >                         (int)n);
2239 >            }
2240 >            else {
2241 >                this.tab = it.tab;
2242 >                this.baseSize = it.baseSize;
2243 >                int hi = this.baseLimit = it.baseLimit;
2244 >                it.baseLimit = this.index = this.baseIndex =
2245 >                    (hi + it.baseIndex + 1) >>> 1;
2246 >                this.batch = it.batch >>>= 1;
2247 >            }
2248 >        }
2249 >
2250 >        /**
2251 >         * Advances next; returns nextVal or null if terminated.
2252 >         * See above for explanation.
2253 >         */
2254 >        @SuppressWarnings("unchecked") final V advance() {
2255 >            Node<V> e = next;
2256 >            V ev = null;
2257 >            outer: do {
2258 >                if (e != null)                  // advance past used/skipped node
2259 >                    e = e.next;
2260 >                while (e == null) {             // get to next non-null bin
2261 >                    ConcurrentHashMap<K,V> m;
2262 >                    Node<V>[] t; int b, i, n; Object ek; //  must use locals
2263 >                    if ((t = tab) != null)
2264 >                        n = t.length;
2265 >                    else if ((m = map) != null && (t = tab = m.table) != null)
2266 >                        n = baseLimit = baseSize = t.length;
2267 >                    else
2268 >                        break outer;
2269 >                    if ((b = baseIndex) >= baseLimit ||
2270 >                        (i = index) < 0 || i >= n)
2271 >                        break outer;
2272 >                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
2273 >                        if ((ek = e.key) instanceof TreeBin)
2274 >                            e = ((TreeBin<V>)ek).first;
2275 >                        else {
2276 >                            tab = (Node<V>[])ek;
2277 >                            continue;           // restarts due to null val
2278 >                        }
2279 >                    }                           // visit upper slots if present
2280 >                    index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2281 >                }
2282 >                nextKey = (K)e.key;
2283 >            } while ((ev = e.val) == null);    // skip deleted or special nodes
2284 >            next = e;
2285 >            return nextVal = ev;
2286 >        }
2287 >
2288 >        public final void remove() {
2289 >            K k = nextKey;
2290 >            if (k == null && (advance() == null || (k = nextKey) == null))
2291 >                throw new IllegalStateException();
2292 >            map.internalReplace(k, null, null);
2293 >        }
2294 >
2295 >        public final boolean hasNext() {
2296 >            return nextVal != null || advance() != null;
2297 >        }
2298 >
2299 >        public final boolean hasMoreElements() { return hasNext(); }
2300 >
2301 >        public void compute() { } // default no-op CountedCompleter body
2302 >
2303 >        /**
2304 >         * Returns a batch value > 0 if this task should (and must) be
2305 >         * split, if so, adding to pending count, and in any case
2306 >         * updating batch value. The initial batch value is approx
2307 >         * exp2 of the number of times (minus one) to split task by
2308 >         * two before executing leaf action. This value is faster to
2309 >         * compute and more convenient to use as a guide to splitting
2310 >         * than is the depth, since it is used while dividing by two
2311 >         * anyway.
2312 >         */
2313 >        final int preSplit() {
2314 >            int b;  ForkJoinPool pool;
2315 >            if ((b = batch) < 0) { // force initialization
2316 >                int sp = (((pool = getPool()) == null) ?
2317 >                          ForkJoinPool.getCommonPoolParallelism() :
2318 >                          pool.getParallelism()) << 3; // slack of 8
2319 >                long n = map.sumCount();
2320 >                b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2321 >            }
2322 >            b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2323 >            if ((batch = b) > 0)
2324 >                addToPendingCount(1);
2325 >            return b;
2326 >        }
2327 >
2328 >        // spliterator support
2329 >
2330 >        public boolean hasExactSize() {
2331 >            return false;
2332 >        }
2333 >
2334 >        public boolean hasExactSplits() {
2335 >            return false;
2336 >        }
2337 >
2338 >        public long estimateSize() {
2339 >            return batch;
2340 >        }
2341 >    }
2342 >
2343 >    /* ---------------- Public operations -------------- */
2344 >
2345 >    /**
2346 >     * Creates a new, empty map with the default initial table size (16).
2347       */
2348 <    @SuppressWarnings("unchecked")
706 <    public ConcurrentHashMap(int initialCapacity,
707 <                             float loadFactor, int concurrencyLevel) {
708 <        if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
709 <            throw new IllegalArgumentException();
710 <        if (concurrencyLevel > MAX_SEGMENTS)
711 <            concurrencyLevel = MAX_SEGMENTS;
712 <        // Find power-of-two sizes best matching arguments
713 <        int sshift = 0;
714 <        int ssize = 1;
715 <        while (ssize < concurrencyLevel) {
716 <            ++sshift;
717 <            ssize <<= 1;
718 <        }
719 <        this.segmentShift = 32 - sshift;
720 <        this.segmentMask = ssize - 1;
721 <        if (initialCapacity > MAXIMUM_CAPACITY)
722 <            initialCapacity = MAXIMUM_CAPACITY;
723 <        int c = initialCapacity / ssize;
724 <        if (c * ssize < initialCapacity)
725 <            ++c;
726 <        int cap = MIN_SEGMENT_TABLE_CAPACITY;
727 <        while (cap < c)
728 <            cap <<= 1;
729 <        // create segments and segments[0]
730 <        Segment<K,V> s0 =
731 <            new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
732 <                             (HashEntry<K,V>[])new HashEntry[cap]);
733 <        Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
734 <        UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
735 <        this.segments = ss;
2348 >    public ConcurrentHashMap() {
2349      }
2350  
2351      /**
2352 <     * Creates a new, empty map with the specified initial capacity
2353 <     * and load factor and with the default concurrencyLevel (16).
2352 >     * Creates a new, empty map with an initial table size
2353 >     * accommodating the specified number of elements without the need
2354 >     * to dynamically resize.
2355       *
2356       * @param initialCapacity The implementation performs internal
2357       * sizing to accommodate this many elements.
2358 <     * @param loadFactor  the load factor threshold, used to control resizing.
2359 <     * Resizing may be performed when the average number of elements per
2360 <     * bin exceeds this threshold.
2358 >     * @throws IllegalArgumentException if the initial capacity of
2359 >     * elements is negative
2360 >     */
2361 >    public ConcurrentHashMap(int initialCapacity) {
2362 >        if (initialCapacity < 0)
2363 >            throw new IllegalArgumentException();
2364 >        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2365 >                   MAXIMUM_CAPACITY :
2366 >                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2367 >        this.sizeCtl = cap;
2368 >    }
2369 >
2370 >    /**
2371 >     * Creates a new map with the same mappings as the given map.
2372 >     *
2373 >     * @param m the map
2374 >     */
2375 >    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2376 >        this.sizeCtl = DEFAULT_CAPACITY;
2377 >        internalPutAll(m);
2378 >    }
2379 >
2380 >    /**
2381 >     * Creates a new, empty map with an initial table size based on
2382 >     * the given number of elements ({@code initialCapacity}) and
2383 >     * initial table density ({@code loadFactor}).
2384 >     *
2385 >     * @param initialCapacity the initial capacity. The implementation
2386 >     * performs internal sizing to accommodate this many elements,
2387 >     * given the specified load factor.
2388 >     * @param loadFactor the load factor (table density) for
2389 >     * establishing the initial table size
2390       * @throws IllegalArgumentException if the initial capacity of
2391       * elements is negative or the load factor is nonpositive
2392       *
2393       * @since 1.6
2394       */
2395      public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2396 <        this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
2396 >        this(initialCapacity, loadFactor, 1);
2397      }
2398  
2399      /**
2400 <     * Creates a new, empty map with the specified initial capacity,
2401 <     * and with default load factor (0.75) and concurrencyLevel (16).
2400 >     * Creates a new, empty map with an initial table size based on
2401 >     * the given number of elements ({@code initialCapacity}), table
2402 >     * density ({@code loadFactor}), and number of concurrently
2403 >     * updating threads ({@code concurrencyLevel}).
2404       *
2405       * @param initialCapacity the initial capacity. The implementation
2406 <     * performs internal sizing to accommodate this many elements.
2407 <     * @throws IllegalArgumentException if the initial capacity of
2408 <     * elements is negative.
2406 >     * performs internal sizing to accommodate this many elements,
2407 >     * given the specified load factor.
2408 >     * @param loadFactor the load factor (table density) for
2409 >     * establishing the initial table size
2410 >     * @param concurrencyLevel the estimated number of concurrently
2411 >     * updating threads. The implementation may use this value as
2412 >     * a sizing hint.
2413 >     * @throws IllegalArgumentException if the initial capacity is
2414 >     * negative or the load factor or concurrencyLevel are
2415 >     * nonpositive
2416       */
2417 <    public ConcurrentHashMap(int initialCapacity) {
2418 <        this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
2417 >    public ConcurrentHashMap(int initialCapacity,
2418 >                               float loadFactor, int concurrencyLevel) {
2419 >        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2420 >            throw new IllegalArgumentException();
2421 >        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
2422 >            initialCapacity = concurrencyLevel;   // as estimated threads
2423 >        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2424 >        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2425 >            MAXIMUM_CAPACITY : tableSizeFor((int)size);
2426 >        this.sizeCtl = cap;
2427      }
2428  
2429      /**
2430 <     * Creates a new, empty map with a default initial capacity (16),
2431 <     * load factor (0.75) and concurrencyLevel (16).
2430 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2431 >     * from the given type to {@code Boolean.TRUE}.
2432 >     *
2433 >     * @return the new set
2434       */
2435 <    public ConcurrentHashMap() {
2436 <        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
2435 >    public static <K> KeySetView<K,Boolean> newKeySet() {
2436 >        return new KeySetView<K,Boolean>
2437 >            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2438      }
2439  
2440      /**
2441 <     * Creates a new map with the same mappings as the given map.
2442 <     * The map is created with a capacity of 1.5 times the number
780 <     * of mappings in the given map or 16 (whichever is greater),
781 <     * and a default load factor (0.75) and concurrencyLevel (16).
2441 >     * Creates a new {@link Set} backed by a ConcurrentHashMap
2442 >     * from the given type to {@code Boolean.TRUE}.
2443       *
2444 <     * @param m the map
2444 >     * @param initialCapacity The implementation performs internal
2445 >     * sizing to accommodate this many elements.
2446 >     * @throws IllegalArgumentException if the initial capacity of
2447 >     * elements is negative
2448 >     * @return the new set
2449       */
2450 <    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2451 <        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
2452 <                      DEFAULT_INITIAL_CAPACITY),
788 <             DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
789 <        putAll(m);
2450 >    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2451 >        return new KeySetView<K,Boolean>
2452 >            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2453      }
2454  
2455      /**
2456 <     * Returns <tt>true</tt> if this map contains no key-value mappings.
794 <     *
795 <     * @return <tt>true</tt> if this map contains no key-value mappings
2456 >     * {@inheritDoc}
2457       */
2458      public boolean isEmpty() {
2459 <        /*
799 <         * Sum per-segment modCounts to avoid mis-reporting when
800 <         * elements are concurrently added and removed in one segment
801 <         * while checking another, in which case the table was never
802 <         * actually empty at any point. (The sum ensures accuracy up
803 <         * through at least 1<<31 per-segment modifications before
804 <         * recheck.)  Methods size() and containsValue() use similar
805 <         * constructions for stability checks.
806 <         */
807 <        long sum = 0L;
808 <        final Segment<K,V>[] segments = this.segments;
809 <        for (int j = 0; j < segments.length; ++j) {
810 <            Segment<K,V> seg = segmentAt(segments, j);
811 <            if (seg != null) {
812 <                if (seg.count != 0)
813 <                    return false;
814 <                sum += seg.modCount;
815 <            }
816 <        }
817 <        if (sum != 0L) { // recheck unless no modifications
818 <            for (int j = 0; j < segments.length; ++j) {
819 <                Segment<K,V> seg = segmentAt(segments, j);
820 <                if (seg != null) {
821 <                    if (seg.count != 0)
822 <                        return false;
823 <                    sum -= seg.modCount;
824 <                }
825 <            }
826 <            if (sum != 0L)
827 <                return false;
828 <        }
829 <        return true;
2459 >        return sumCount() <= 0L; // ignore transient negative values
2460      }
2461  
2462      /**
2463 <     * Returns the number of key-value mappings in this map.  If the
834 <     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
835 <     * <tt>Integer.MAX_VALUE</tt>.
836 <     *
837 <     * @return the number of key-value mappings in this map
2463 >     * {@inheritDoc}
2464       */
2465      public int size() {
2466 <        // Try a few times to get accurate count. On failure due to
2467 <        // continuous async changes in table, resort to locking.
2468 <        final Segment<K,V>[] segments = this.segments;
2469 <        int size;
2470 <        boolean overflow; // true if size overflows 32 bits
2471 <        long sum;         // sum of modCounts
2472 <        long last = 0L;   // previous sum
2473 <        int retries = -1; // first iteration isn't retry
2474 <        try {
2475 <            for (;;) {
2476 <                if (retries++ == RETRIES_BEFORE_LOCK) {
2477 <                    for (int j = 0; j < segments.length; ++j)
2478 <                        ensureSegment(j).lock(); // force creation
2479 <                }
2480 <                sum = 0L;
2481 <                size = 0;
2482 <                overflow = false;
2483 <                for (int j = 0; j < segments.length; ++j) {
858 <                    Segment<K,V> seg = segmentAt(segments, j);
859 <                    if (seg != null) {
860 <                        sum += seg.modCount;
861 <                        int c = seg.count;
862 <                        if (c < 0 || (size += c) < 0)
863 <                            overflow = true;
864 <                    }
865 <                }
866 <                if (sum == last)
867 <                    break;
868 <                last = sum;
869 <            }
870 <        } finally {
871 <            if (retries > RETRIES_BEFORE_LOCK) {
872 <                for (int j = 0; j < segments.length; ++j)
873 <                    segmentAt(segments, j).unlock();
874 <            }
875 <        }
876 <        return overflow ? Integer.MAX_VALUE : size;
2466 >        long n = sumCount();
2467 >        return ((n < 0L) ? 0 :
2468 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2469 >                (int)n);
2470 >    }
2471 >
2472 >    /**
2473 >     * Returns the number of mappings. This method should be used
2474 >     * instead of {@link #size} because a ConcurrentHashMap may
2475 >     * contain more mappings than can be represented as an int. The
2476 >     * value returned is an estimate; the actual count may differ if
2477 >     * there are concurrent insertions or removals.
2478 >     *
2479 >     * @return the number of mappings
2480 >     */
2481 >    public long mappingCount() {
2482 >        long n = sumCount();
2483 >        return (n < 0L) ? 0L : n; // ignore transient negative values
2484      }
2485  
2486      /**
# Line 888 | Line 2495 | public class ConcurrentHashMap<K, V> ext
2495       * @throws NullPointerException if the specified key is null
2496       */
2497      public V get(Object key) {
2498 <        Segment<K,V> s; // manually integrate access methods to reduce overhead
2499 <        HashEntry<K,V>[] tab;
2500 <        int h = hash(key.hashCode());
2501 <        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
2502 <        if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
2503 <            (tab = s.table) != null) {
2504 <            for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
2505 <                     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
2506 <                 e != null; e = e.next) {
2507 <                K k;
2508 <                if ((k = e.key) == key || (e.hash == h && key.equals(k)))
2509 <                    return e.value;
2510 <            }
2511 <        }
2512 <        return null;
2498 >        return internalGet(key);
2499 >    }
2500 >
2501 >    /**
2502 >     * Returns the value to which the specified key is mapped,
2503 >     * or the given defaultValue if this map contains no mapping for the key.
2504 >     *
2505 >     * @param key the key
2506 >     * @param defaultValue the value to return if this map contains
2507 >     * no mapping for the given key
2508 >     * @return the mapping for the key, if present; else the defaultValue
2509 >     * @throws NullPointerException if the specified key is null
2510 >     */
2511 >    public V getValueOrDefault(Object key, V defaultValue) {
2512 >        V v;
2513 >        return (v = internalGet(key)) == null ? defaultValue : v;
2514      }
2515  
2516      /**
2517       * Tests if the specified object is a key in this table.
2518       *
2519       * @param  key   possible key
2520 <     * @return <tt>true</tt> if and only if the specified object
2520 >     * @return {@code true} if and only if the specified object
2521       *         is a key in this table, as determined by the
2522 <     *         <tt>equals</tt> method; <tt>false</tt> otherwise.
2522 >     *         {@code equals} method; {@code false} otherwise
2523       * @throws NullPointerException if the specified key is null
2524       */
917    @SuppressWarnings("unchecked")
2525      public boolean containsKey(Object key) {
2526 <        Segment<K,V> s; // same as get() except no need for volatile value read
920 <        HashEntry<K,V>[] tab;
921 <        int h = hash(key.hashCode());
922 <        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
923 <        if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
924 <            (tab = s.table) != null) {
925 <            for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
926 <                     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
927 <                 e != null; e = e.next) {
928 <                K k;
929 <                if ((k = e.key) == key || (e.hash == h && key.equals(k)))
930 <                    return true;
931 <            }
932 <        }
933 <        return false;
2526 >        return internalGet(key) != null;
2527      }
2528  
2529      /**
2530 <     * Returns <tt>true</tt> if this map maps one or more keys to the
2531 <     * specified value. Note: This method requires a full internal
2532 <     * traversal of the hash table, and so is much slower than
940 <     * method <tt>containsKey</tt>.
2530 >     * Returns {@code true} if this map maps one or more keys to the
2531 >     * specified value. Note: This method may require a full traversal
2532 >     * of the map, and is much slower than method {@code containsKey}.
2533       *
2534       * @param value value whose presence in this map is to be tested
2535 <     * @return <tt>true</tt> if this map maps one or more keys to the
2535 >     * @return {@code true} if this map maps one or more keys to the
2536       *         specified value
2537       * @throws NullPointerException if the specified value is null
2538       */
2539      public boolean containsValue(Object value) {
948        // Same idea as size()
2540          if (value == null)
2541              throw new NullPointerException();
2542 <        final Segment<K,V>[] segments = this.segments;
2543 <        boolean found = false;
2544 <        long last = 0L;   // previous sum
2545 <        int retries = -1;
2546 <        try {
956 <            outer: for (;;) {
957 <                if (retries++ == RETRIES_BEFORE_LOCK) {
958 <                    for (int j = 0; j < segments.length; ++j)
959 <                        ensureSegment(j).lock(); // force creation
960 <                }
961 <                long sum = 0L;
962 <                for (int j = 0; j < segments.length; ++j) {
963 <                    HashEntry<K,V>[] tab;
964 <                    Segment<K,V> seg = segmentAt(segments, j);
965 <                    if (seg != null && (tab = seg.table) != null) {
966 <                        for (int i = 0 ; i < tab.length; i++) {
967 <                            HashEntry<K,V> e;
968 <                            for (e = entryAt(tab, i); e != null; e = e.next) {
969 <                                V v = e.value;
970 <                                if (v != null && value.equals(v)) {
971 <                                    found = true;
972 <                                    break outer;
973 <                                }
974 <                            }
975 <                        }
976 <                        sum += seg.modCount;
977 <                    }
978 <                }
979 <                if (retries > 0 && sum == last)
980 <                    break;
981 <                last = sum;
982 <            }
983 <        } finally {
984 <            if (retries > RETRIES_BEFORE_LOCK) {
985 <                for (int j = 0; j < segments.length; ++j)
986 <                    segmentAt(segments, j).unlock();
987 <            }
2542 >        V v;
2543 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2544 >        while ((v = it.advance()) != null) {
2545 >            if (v == value || value.equals(v))
2546 >                return true;
2547          }
2548 <        return found;
2548 >        return false;
2549      }
2550  
2551      /**
2552       * Legacy method testing if some key maps into the specified value
2553       * in this table.  This method is identical in functionality to
2554 <     * {@link #containsValue}, and exists solely to ensure
2554 >     * {@link #containsValue(Object)}, and exists solely to ensure
2555       * full compatibility with class {@link java.util.Hashtable},
2556       * which supported this method prior to introduction of the
2557       * Java Collections framework.
2558       *
2559       * @param  value a value to search for
2560 <     * @return <tt>true</tt> if and only if some key maps to the
2561 <     *         <tt>value</tt> argument in this table as
2562 <     *         determined by the <tt>equals</tt> method;
2563 <     *         <tt>false</tt> otherwise
2560 >     * @return {@code true} if and only if some key maps to the
2561 >     *         {@code value} argument in this table as
2562 >     *         determined by the {@code equals} method;
2563 >     *         {@code false} otherwise
2564       * @throws NullPointerException if the specified value is null
2565       */
2566 <    public boolean contains(Object value) {
2566 >    @Deprecated public boolean contains(Object value) {
2567          return containsValue(value);
2568      }
2569  
# Line 1012 | Line 2571 | public class ConcurrentHashMap<K, V> ext
2571       * Maps the specified key to the specified value in this table.
2572       * Neither the key nor the value can be null.
2573       *
2574 <     * <p> The value can be retrieved by calling the <tt>get</tt> method
2574 >     * <p>The value can be retrieved by calling the {@code get} method
2575       * with a key that is equal to the original key.
2576       *
2577       * @param key key with which the specified value is to be associated
2578       * @param value value to be associated with the specified key
2579 <     * @return the previous value associated with <tt>key</tt>, or
2580 <     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
2579 >     * @return the previous value associated with {@code key}, or
2580 >     *         {@code null} if there was no mapping for {@code key}
2581       * @throws NullPointerException if the specified key or value is null
2582       */
1024    @SuppressWarnings("unchecked")
2583      public V put(K key, V value) {
2584 <        Segment<K,V> s;
1027 <        if (value == null)
1028 <            throw new NullPointerException();
1029 <        int hash = hash(key.hashCode());
1030 <        int j = (hash >>> segmentShift) & segmentMask;
1031 <        if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
1032 <             (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
1033 <            s = ensureSegment(j);
1034 <        return s.put(key, hash, value, false);
2584 >        return internalPut(key, value, false);
2585      }
2586  
2587      /**
2588       * {@inheritDoc}
2589       *
2590       * @return the previous value associated with the specified key,
2591 <     *         or <tt>null</tt> if there was no mapping for the key
2591 >     *         or {@code null} if there was no mapping for the key
2592       * @throws NullPointerException if the specified key or value is null
2593       */
1044    @SuppressWarnings("unchecked")
2594      public V putIfAbsent(K key, V value) {
2595 <        Segment<K,V> s;
1047 <        if (value == null)
1048 <            throw new NullPointerException();
1049 <        int hash = hash(key.hashCode());
1050 <        int j = (hash >>> segmentShift) & segmentMask;
1051 <        if ((s = (Segment<K,V>)UNSAFE.getObject
1052 <             (segments, (j << SSHIFT) + SBASE)) == null)
1053 <            s = ensureSegment(j);
1054 <        return s.put(key, hash, value, true);
2595 >        return internalPut(key, value, true);
2596      }
2597  
2598      /**
# Line 1062 | Line 2603 | public class ConcurrentHashMap<K, V> ext
2603       * @param m mappings to be stored in this map
2604       */
2605      public void putAll(Map<? extends K, ? extends V> m) {
2606 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
2607 <            put(e.getKey(), e.getValue());
2606 >        internalPutAll(m);
2607 >    }
2608 >
2609 >    /**
2610 >     * If the specified key is not already associated with a value (or
2611 >     * is mapped to {@code null}), attempts to compute its value using
2612 >     * the given mapping function and enters it into this map unless
2613 >     * {@code null}. The entire method invocation is performed
2614 >     * atomically, so the function is applied at most once per key.
2615 >     * Some attempted update operations on this map by other threads
2616 >     * may be blocked while computation is in progress, so the
2617 >     * computation should be short and simple, and must not attempt to
2618 >     * update any other mappings of this Map.
2619 >     *
2620 >     * @param key key with which the specified value is to be associated
2621 >     * @param mappingFunction the function to compute a value
2622 >     * @return the current (existing or computed) value associated with
2623 >     *         the specified key, or null if the computed value is null
2624 >     * @throws NullPointerException if the specified key or mappingFunction
2625 >     *         is null
2626 >     * @throws IllegalStateException if the computation detectably
2627 >     *         attempts a recursive update to this map that would
2628 >     *         otherwise never complete
2629 >     * @throws RuntimeException or Error if the mappingFunction does so,
2630 >     *         in which case the mapping is left unestablished
2631 >     */
2632 >    public V computeIfAbsent
2633 >        (K key, Function<? super K, ? extends V> mappingFunction) {
2634 >        return internalComputeIfAbsent(key, mappingFunction);
2635 >    }
2636 >
2637 >    /**
2638 >     * If the value for the specified key is present and non-null,
2639 >     * attempts to compute a new mapping given the key and its current
2640 >     * mapped value.  The entire method invocation is performed
2641 >     * atomically.  Some attempted update operations on this map by
2642 >     * other threads may be blocked while computation is in progress,
2643 >     * so the computation should be short and simple, and must not
2644 >     * attempt to update any other mappings of this Map.
2645 >     *
2646 >     * @param key key with which the specified value is to be associated
2647 >     * @param remappingFunction the function to compute a value
2648 >     * @return the new value associated with the specified key, or null if none
2649 >     * @throws NullPointerException if the specified key or remappingFunction
2650 >     *         is null
2651 >     * @throws IllegalStateException if the computation detectably
2652 >     *         attempts a recursive update to this map that would
2653 >     *         otherwise never complete
2654 >     * @throws RuntimeException or Error if the remappingFunction does so,
2655 >     *         in which case the mapping is unchanged
2656 >     */
2657 >    public V computeIfPresent
2658 >        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2659 >        return internalCompute(key, true, remappingFunction);
2660 >    }
2661 >
2662 >    /**
2663 >     * Attempts to compute a mapping for the specified key and its
2664 >     * current mapped value (or {@code null} if there is no current
2665 >     * mapping). The entire method invocation is performed atomically.
2666 >     * Some attempted update operations on this map by other threads
2667 >     * may be blocked while computation is in progress, so the
2668 >     * computation should be short and simple, and must not attempt to
2669 >     * update any other mappings of this Map.
2670 >     *
2671 >     * @param key key with which the specified value is to be associated
2672 >     * @param remappingFunction the function to compute a value
2673 >     * @return the new value associated with the specified key, or null if none
2674 >     * @throws NullPointerException if the specified key or remappingFunction
2675 >     *         is null
2676 >     * @throws IllegalStateException if the computation detectably
2677 >     *         attempts a recursive update to this map that would
2678 >     *         otherwise never complete
2679 >     * @throws RuntimeException or Error if the remappingFunction does so,
2680 >     *         in which case the mapping is unchanged
2681 >     */
2682 >    public V compute
2683 >        (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2684 >        return internalCompute(key, false, remappingFunction);
2685 >    }
2686 >
2687 >    /**
2688 >     * If the specified key is not already associated with a
2689 >     * (non-null) value, associates it with the given value.
2690 >     * Otherwise, replaces the value with the results of the given
2691 >     * remapping function, or removes if {@code null}. The entire
2692 >     * method invocation is performed atomically.  Some attempted
2693 >     * update operations on this map by other threads may be blocked
2694 >     * while computation is in progress, so the computation should be
2695 >     * short and simple, and must not attempt to update any other
2696 >     * mappings of this Map.
2697 >     *
2698 >     * @param key key with which the specified value is to be associated
2699 >     * @param value the value to use if absent
2700 >     * @param remappingFunction the function to recompute a value if present
2701 >     * @return the new value associated with the specified key, or null if none
2702 >     * @throws NullPointerException if the specified key or the
2703 >     *         remappingFunction is null
2704 >     * @throws RuntimeException or Error if the remappingFunction does so,
2705 >     *         in which case the mapping is unchanged
2706 >     */
2707 >    public V merge
2708 >        (K key, V value,
2709 >         BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2710 >        return internalMerge(key, value, remappingFunction);
2711      }
2712  
2713      /**
# Line 1071 | Line 2715 | public class ConcurrentHashMap<K, V> ext
2715       * This method does nothing if the key is not in the map.
2716       *
2717       * @param  key the key that needs to be removed
2718 <     * @return the previous value associated with <tt>key</tt>, or
2719 <     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
2718 >     * @return the previous value associated with {@code key}, or
2719 >     *         {@code null} if there was no mapping for {@code key}
2720       * @throws NullPointerException if the specified key is null
2721       */
2722      public V remove(Object key) {
2723 <        int hash = hash(key.hashCode());
1080 <        Segment<K,V> s = segmentForHash(hash);
1081 <        return s == null ? null : s.remove(key, hash, null);
2723 >        return internalReplace(key, null, null);
2724      }
2725  
2726      /**
# Line 1087 | Line 2729 | public class ConcurrentHashMap<K, V> ext
2729       * @throws NullPointerException if the specified key is null
2730       */
2731      public boolean remove(Object key, Object value) {
2732 <        int hash = hash(key.hashCode());
2733 <        Segment<K,V> s;
2734 <        return value != null && (s = segmentForHash(hash)) != null &&
1093 <            s.remove(key, hash, value) != null;
2732 >        if (key == null)
2733 >            throw new NullPointerException();
2734 >        return value != null && internalReplace(key, null, value) != null;
2735      }
2736  
2737      /**
# Line 1099 | Line 2740 | public class ConcurrentHashMap<K, V> ext
2740       * @throws NullPointerException if any of the arguments are null
2741       */
2742      public boolean replace(K key, V oldValue, V newValue) {
2743 <        int hash = hash(key.hashCode());
1103 <        if (oldValue == null || newValue == null)
2743 >        if (key == null || oldValue == null || newValue == null)
2744              throw new NullPointerException();
2745 <        Segment<K,V> s = segmentForHash(hash);
1106 <        return s != null && s.replace(key, hash, oldValue, newValue);
2745 >        return internalReplace(key, newValue, oldValue) != null;
2746      }
2747  
2748      /**
2749       * {@inheritDoc}
2750       *
2751       * @return the previous value associated with the specified key,
2752 <     *         or <tt>null</tt> if there was no mapping for the key
2752 >     *         or {@code null} if there was no mapping for the key
2753       * @throws NullPointerException if the specified key or value is null
2754       */
2755      public V replace(K key, V value) {
2756 <        int hash = hash(key.hashCode());
1118 <        if (value == null)
2756 >        if (key == null || value == null)
2757              throw new NullPointerException();
2758 <        Segment<K,V> s = segmentForHash(hash);
1121 <        return s == null ? null : s.replace(key, hash, value);
2758 >        return internalReplace(key, value, null);
2759      }
2760  
2761      /**
2762       * Removes all of the mappings from this map.
2763       */
2764      public void clear() {
2765 <        final Segment<K,V>[] segments = this.segments;
1129 <        for (int j = 0; j < segments.length; ++j) {
1130 <            Segment<K,V> s = segmentAt(segments, j);
1131 <            if (s != null)
1132 <                s.clear();
1133 <        }
2765 >        internalClear();
2766      }
2767  
2768      /**
2769       * Returns a {@link Set} view of the keys contained in this map.
2770       * The set is backed by the map, so changes to the map are
2771 <     * reflected in the set, and vice-versa.  The set supports element
1140 <     * removal, which removes the corresponding mapping from this map,
1141 <     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1142 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1143 <     * operations.  It does not support the <tt>add</tt> or
1144 <     * <tt>addAll</tt> operations.
2771 >     * reflected in the set, and vice-versa.
2772       *
2773 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2774 <     * that will never throw {@link ConcurrentModificationException},
2775 <     * and guarantees to traverse elements as they existed upon
2776 <     * construction of the iterator, and may (but is not guaranteed to)
2777 <     * reflect any modifications subsequent to construction.
2773 >     * @return the set view
2774 >     */
2775 >    public KeySetView<K,V> keySet() {
2776 >        KeySetView<K,V> ks = keySet;
2777 >        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2778 >    }
2779 >
2780 >    /**
2781 >     * Returns a {@link Set} view of the keys in this map, using the
2782 >     * given common mapped value for any additions (i.e., {@link
2783 >     * Collection#add} and {@link Collection#addAll(Collection)}).
2784 >     * This is of course only appropriate if it is acceptable to use
2785 >     * the same value for all additions from this view.
2786 >     *
2787 >     * @param mappedValue the mapped value to use for any additions
2788 >     * @return the set view
2789 >     * @throws NullPointerException if the mappedValue is null
2790       */
2791 <    public Set<K> keySet() {
2792 <        Set<K> ks = keySet;
2793 <        return (ks != null) ? ks : (keySet = new KeySet());
2791 >    public KeySetView<K,V> keySet(V mappedValue) {
2792 >        if (mappedValue == null)
2793 >            throw new NullPointerException();
2794 >        return new KeySetView<K,V>(this, mappedValue);
2795      }
2796  
2797      /**
2798       * Returns a {@link Collection} view of the values contained in this map.
2799       * The collection is backed by the map, so changes to the map are
2800 <     * reflected in the collection, and vice-versa.  The collection
1161 <     * supports element removal, which removes the corresponding
1162 <     * mapping from this map, via the <tt>Iterator.remove</tt>,
1163 <     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1164 <     * <tt>retainAll</tt>, and <tt>clear</tt> operations.  It does not
1165 <     * support the <tt>add</tt> or <tt>addAll</tt> operations.
2800 >     * reflected in the collection, and vice-versa.
2801       *
2802 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1168 <     * that will never throw {@link ConcurrentModificationException},
1169 <     * and guarantees to traverse elements as they existed upon
1170 <     * construction of the iterator, and may (but is not guaranteed to)
1171 <     * reflect any modifications subsequent to construction.
2802 >     * @return the collection view
2803       */
2804 <    public Collection<V> values() {
2805 <        Collection<V> vs = values;
2806 <        return (vs != null) ? vs : (values = new Values());
2804 >    public ValuesView<K,V> values() {
2805 >        ValuesView<K,V> vs = values;
2806 >        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2807      }
2808  
2809      /**
# Line 1180 | Line 2811 | public class ConcurrentHashMap<K, V> ext
2811       * The set is backed by the map, so changes to the map are
2812       * reflected in the set, and vice-versa.  The set supports element
2813       * removal, which removes the corresponding mapping from the map,
2814 <     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
2815 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
2816 <     * operations.  It does not support the <tt>add</tt> or
2817 <     * <tt>addAll</tt> operations.
2814 >     * via the {@code Iterator.remove}, {@code Set.remove},
2815 >     * {@code removeAll}, {@code retainAll}, and {@code clear}
2816 >     * operations.  It does not support the {@code add} or
2817 >     * {@code addAll} operations.
2818       *
2819 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2819 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2820       * that will never throw {@link ConcurrentModificationException},
2821       * and guarantees to traverse elements as they existed upon
2822       * construction of the iterator, and may (but is not guaranteed to)
2823       * reflect any modifications subsequent to construction.
2824 +     *
2825 +     * @return the set view
2826       */
2827      public Set<Map.Entry<K,V>> entrySet() {
2828 <        Set<Map.Entry<K,V>> es = entrySet;
2829 <        return (es != null) ? es : (entrySet = new EntrySet());
2828 >        EntrySetView<K,V> es = entrySet;
2829 >        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2830      }
2831  
2832      /**
# Line 1203 | Line 2836 | public class ConcurrentHashMap<K, V> ext
2836       * @see #keySet()
2837       */
2838      public Enumeration<K> keys() {
2839 <        return new KeyIterator();
2839 >        return new KeyIterator<K,V>(this);
2840      }
2841  
2842      /**
# Line 1213 | Line 2846 | public class ConcurrentHashMap<K, V> ext
2846       * @see #values()
2847       */
2848      public Enumeration<V> elements() {
2849 <        return new ValueIterator();
2849 >        return new ValueIterator<K,V>(this);
2850      }
2851  
2852 <    /* ---------------- Iterator Support -------------- */
2853 <
2854 <    abstract class HashIterator {
2855 <        int nextSegmentIndex;
2856 <        int nextTableIndex;
2857 <        HashEntry<K,V>[] currentTable;
2858 <        HashEntry<K, V> nextEntry;
2859 <        HashEntry<K, V> lastReturned;
2860 <
2861 <        HashIterator() {
2862 <            nextSegmentIndex = segments.length - 1;
2863 <            nextTableIndex = -1;
2864 <            advance();
2865 <        }
2852 >    /**
2853 >     * Returns the hash code value for this {@link Map}, i.e.,
2854 >     * the sum of, for each key-value pair in the map,
2855 >     * {@code key.hashCode() ^ value.hashCode()}.
2856 >     *
2857 >     * @return the hash code value for this map
2858 >     */
2859 >    public int hashCode() {
2860 >        int h = 0;
2861 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2862 >        V v;
2863 >        while ((v = it.advance()) != null) {
2864 >            h += it.nextKey.hashCode() ^ v.hashCode();
2865 >        }
2866 >        return h;
2867 >    }
2868  
2869 <        /**
2870 <         * Sets nextEntry to first node of next non-empty table
2871 <         * (in backwards order, to simplify checks).
2872 <         */
2873 <        final void advance() {
2869 >    /**
2870 >     * Returns a string representation of this map.  The string
2871 >     * representation consists of a list of key-value mappings (in no
2872 >     * particular order) enclosed in braces ("{@code {}}").  Adjacent
2873 >     * mappings are separated by the characters {@code ", "} (comma
2874 >     * and space).  Each key-value mapping is rendered as the key
2875 >     * followed by an equals sign ("{@code =}") followed by the
2876 >     * associated value.
2877 >     *
2878 >     * @return a string representation of this map
2879 >     */
2880 >    public String toString() {
2881 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2882 >        StringBuilder sb = new StringBuilder();
2883 >        sb.append('{');
2884 >        V v;
2885 >        if ((v = it.advance()) != null) {
2886              for (;;) {
2887 <                if (nextTableIndex >= 0) {
2888 <                    if ((nextEntry = entryAt(currentTable,
2889 <                                             nextTableIndex--)) != null)
2890 <                        break;
2891 <                }
1245 <                else if (nextSegmentIndex >= 0) {
1246 <                    Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
1247 <                    if (seg != null && (currentTable = seg.table) != null)
1248 <                        nextTableIndex = currentTable.length - 1;
1249 <                }
1250 <                else
2887 >                K k = it.nextKey;
2888 >                sb.append(k == this ? "(this Map)" : k);
2889 >                sb.append('=');
2890 >                sb.append(v == this ? "(this Map)" : v);
2891 >                if ((v = it.advance()) == null)
2892                      break;
2893 +                sb.append(',').append(' ');
2894              }
2895          }
2896 +        return sb.append('}').toString();
2897 +    }
2898  
2899 <        final HashEntry<K,V> nextEntry() {
2900 <            HashEntry<K,V> e = nextEntry;
2901 <            if (e == null)
2899 >    /**
2900 >     * Compares the specified object with this map for equality.
2901 >     * Returns {@code true} if the given object is a map with the same
2902 >     * mappings as this map.  This operation may return misleading
2903 >     * results if either map is concurrently modified during execution
2904 >     * of this method.
2905 >     *
2906 >     * @param o object to be compared for equality with this map
2907 >     * @return {@code true} if the specified object is equal to this map
2908 >     */
2909 >    public boolean equals(Object o) {
2910 >        if (o != this) {
2911 >            if (!(o instanceof Map))
2912 >                return false;
2913 >            Map<?,?> m = (Map<?,?>) o;
2914 >            Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2915 >            V val;
2916 >            while ((val = it.advance()) != null) {
2917 >                Object v = m.get(it.nextKey);
2918 >                if (v == null || (v != val && !v.equals(val)))
2919 >                    return false;
2920 >            }
2921 >            for (Map.Entry<?,?> e : m.entrySet()) {
2922 >                Object mk, mv, v;
2923 >                if ((mk = e.getKey()) == null ||
2924 >                    (mv = e.getValue()) == null ||
2925 >                    (v = internalGet(mk)) == null ||
2926 >                    (mv != v && !mv.equals(v)))
2927 >                    return false;
2928 >            }
2929 >        }
2930 >        return true;
2931 >    }
2932 >
2933 >    /* ----------------Iterators -------------- */
2934 >
2935 >    @SuppressWarnings("serial") static final class KeyIterator<K,V>
2936 >        extends Traverser<K,V,Object>
2937 >        implements Spliterator<K>, Iterator<K>, Enumeration<K> {
2938 >        KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
2939 >        KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2940 >            super(map, it);
2941 >        }
2942 >        public KeyIterator<K,V> trySplit() {
2943 >            if (tab != null && baseIndex == baseLimit)
2944 >                return null;
2945 >            return new KeyIterator<K,V>(map, this);
2946 >        }
2947 >        public final K next() {
2948 >            if (nextVal == null && advance() == null)
2949                  throw new NoSuchElementException();
2950 <            lastReturned = e; // cannot assign until after null check
2951 <            if ((nextEntry = e.next) == null)
2952 <                advance();
1262 <            return e;
2950 >            K k = nextKey;
2951 >            nextVal = null;
2952 >            return k;
2953          }
2954  
2955 <        public final boolean hasNext() { return nextEntry != null; }
1266 <        public final boolean hasMoreElements() { return nextEntry != null; }
2955 >        public final K nextElement() { return next(); }
2956  
2957 <        public final void remove() {
2958 <            if (lastReturned == null)
2959 <                throw new IllegalStateException();
2960 <            ConcurrentHashMap.this.remove(lastReturned.key);
2961 <            lastReturned = null;
2957 >        public Iterator<K> iterator() { return this; }
2958 >
2959 >        public void forEach(Consumer<? super K> action) {
2960 >            if (action == null) throw new NullPointerException();
2961 >            while (advance() != null)
2962 >                action.accept(nextKey);
2963 >        }
2964 >
2965 >        public boolean tryAdvance(Consumer<? super K> block) {
2966 >            if (block == null) throw new NullPointerException();
2967 >            if (advance() == null)
2968 >                return false;
2969 >            block.accept(nextKey);
2970 >            return true;
2971          }
2972      }
2973  
2974 <    final class KeyIterator
2975 <        extends HashIterator
2976 <        implements Iterator<K>, Enumeration<K>
2977 <    {
2978 <        public final K next()        { return super.nextEntry().key; }
2979 <        public final K nextElement() { return super.nextEntry().key; }
2974 >    @SuppressWarnings("serial") static final class ValueIterator<K,V>
2975 >        extends Traverser<K,V,Object>
2976 >        implements Spliterator<V>, Iterator<V>, Enumeration<V> {
2977 >        ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
2978 >        ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2979 >            super(map, it);
2980 >        }
2981 >        public ValueIterator<K,V> trySplit() {
2982 >            if (tab != null && baseIndex == baseLimit)
2983 >                return null;
2984 >            return new ValueIterator<K,V>(map, this);
2985 >        }
2986 >
2987 >        public final V next() {
2988 >            V v;
2989 >            if ((v = nextVal) == null && (v = advance()) == null)
2990 >                throw new NoSuchElementException();
2991 >            nextVal = null;
2992 >            return v;
2993 >        }
2994 >
2995 >        public final V nextElement() { return next(); }
2996 >
2997 >        public Iterator<V> iterator() { return this; }
2998 >
2999 >        public void forEach(Consumer<? super V> action) {
3000 >            if (action == null) throw new NullPointerException();
3001 >            V v;
3002 >            while ((v = advance()) != null)
3003 >                action.accept(v);
3004 >        }
3005 >
3006 >        public boolean tryAdvance(Consumer<? super V> block) {
3007 >            V v;
3008 >            if (block == null) throw new NullPointerException();
3009 >            if ((v = advance()) == null)
3010 >                return false;
3011 >            block.accept(v);
3012 >            return true;
3013 >        }
3014 >
3015      }
3016  
3017 <    final class ValueIterator
3018 <        extends HashIterator
3019 <        implements Iterator<V>, Enumeration<V>
3020 <    {
3021 <        public final V next()        { return super.nextEntry().value; }
3022 <        public final V nextElement() { return super.nextEntry().value; }
3017 >    @SuppressWarnings("serial") static final class EntryIterator<K,V>
3018 >        extends Traverser<K,V,Object>
3019 >        implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3020 >        EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3021 >        EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3022 >            super(map, it);
3023 >        }
3024 >        public EntryIterator<K,V> trySplit() {
3025 >            if (tab != null && baseIndex == baseLimit)
3026 >                return null;
3027 >            return new EntryIterator<K,V>(map, this);
3028 >        }
3029 >
3030 >        public final Map.Entry<K,V> next() {
3031 >            V v;
3032 >            if ((v = nextVal) == null && (v = advance()) == null)
3033 >                throw new NoSuchElementException();
3034 >            K k = nextKey;
3035 >            nextVal = null;
3036 >            return new MapEntry<K,V>(k, v, map);
3037 >        }
3038 >
3039 >        public Iterator<Map.Entry<K,V>> iterator() { return this; }
3040 >
3041 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
3042 >            if (action == null) throw new NullPointerException();
3043 >            V v;
3044 >            while ((v = advance()) != null)
3045 >                action.accept(entryFor(nextKey, v));
3046 >        }
3047 >
3048 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3049 >            V v;
3050 >            if (block == null) throw new NullPointerException();
3051 >            if ((v = advance()) == null)
3052 >                return false;
3053 >            block.accept(entryFor(nextKey, v));
3054 >            return true;
3055 >        }
3056 >
3057      }
3058  
3059      /**
3060 <     * Custom Entry class used by EntryIterator.next(), that relays
1294 <     * setValue changes to the underlying map.
3060 >     * Exported Entry for iterators
3061       */
3062 <    final class WriteThroughEntry
3063 <        extends AbstractMap.SimpleEntry<K,V>
3064 <    {
3065 <        WriteThroughEntry(K k, V v) {
3066 <            super(k,v);
3062 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3063 >        final K key; // non-null
3064 >        V val;       // non-null
3065 >        final ConcurrentHashMap<K,V> map;
3066 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3067 >            this.key = key;
3068 >            this.val = val;
3069 >            this.map = map;
3070 >        }
3071 >        public final K getKey()       { return key; }
3072 >        public final V getValue()     { return val; }
3073 >        public final int hashCode()   { return key.hashCode() ^ val.hashCode(); }
3074 >        public final String toString(){ return key + "=" + val; }
3075 >
3076 >        public final boolean equals(Object o) {
3077 >            Object k, v; Map.Entry<?,?> e;
3078 >            return ((o instanceof Map.Entry) &&
3079 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3080 >                    (v = e.getValue()) != null &&
3081 >                    (k == key || k.equals(key)) &&
3082 >                    (v == val || v.equals(val)));
3083          }
3084  
3085          /**
3086           * Sets our entry's value and writes through to the map. The
3087 <         * value to return is somewhat arbitrary here. Since a
3088 <         * WriteThroughEntry does not necessarily track asynchronous
3089 <         * changes, the most recent "previous" value could be
3090 <         * different from what we return (or could even have been
3091 <         * removed in which case the put will re-establish). We do not
1310 <         * and cannot guarantee more.
3087 >         * value to return is somewhat arbitrary here. Since we do not
3088 >         * necessarily track asynchronous changes, the most recent
3089 >         * "previous" value could be different from what we return (or
3090 >         * could even have been removed in which case the put will
3091 >         * re-establish). We do not and cannot guarantee more.
3092           */
3093 <        public V setValue(V value) {
3093 >        public final V setValue(V value) {
3094              if (value == null) throw new NullPointerException();
3095 <            V v = super.setValue(value);
3096 <            ConcurrentHashMap.this.put(getKey(), value);
3095 >            V v = val;
3096 >            val = value;
3097 >            map.put(key, value);
3098              return v;
3099          }
3100      }
3101  
3102 <    final class EntryIterator
3103 <        extends HashIterator
3104 <        implements Iterator<Entry<K,V>>
3105 <    {
3106 <        public Map.Entry<K,V> next() {
3107 <            HashEntry<K,V> e = super.nextEntry();
3108 <            return new WriteThroughEntry(e.key, e.value);
3109 <        }
3102 >    /**
3103 >     * Returns exportable snapshot entry for the given key and value
3104 >     * when write-through can't or shouldn't be used.
3105 >     */
3106 >    static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3107 >        return new AbstractMap.SimpleEntry<K,V>(k, v);
3108 >    }
3109 >
3110 >    /* ---------------- Serialization Support -------------- */
3111 >
3112 >    /**
3113 >     * Stripped-down version of helper class used in previous version,
3114 >     * declared for the sake of serialization compatibility
3115 >     */
3116 >    static class Segment<K,V> implements Serializable {
3117 >        private static final long serialVersionUID = 2249069246763182397L;
3118 >        final float loadFactor;
3119 >        Segment(float lf) { this.loadFactor = lf; }
3120      }
3121  
3122 <    final class KeySet extends AbstractSet<K> {
3123 <        public Iterator<K> iterator() {
3124 <            return new KeyIterator();
3122 >    /**
3123 >     * Saves the state of the {@code ConcurrentHashMap} instance to a
3124 >     * stream (i.e., serializes it).
3125 >     * @param s the stream
3126 >     * @serialData
3127 >     * the key (Object) and value (Object)
3128 >     * for each key-value mapping, followed by a null pair.
3129 >     * The key-value mappings are emitted in no particular order.
3130 >     */
3131 >    @SuppressWarnings("unchecked") private void writeObject
3132 >        (java.io.ObjectOutputStream s)
3133 >        throws java.io.IOException {
3134 >        if (segments == null) { // for serialization compatibility
3135 >            segments = (Segment<K,V>[])
3136 >                new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3137 >            for (int i = 0; i < segments.length; ++i)
3138 >                segments[i] = new Segment<K,V>(LOAD_FACTOR);
3139          }
3140 <        public int size() {
3141 <            return ConcurrentHashMap.this.size();
3140 >        s.defaultWriteObject();
3141 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3142 >        V v;
3143 >        while ((v = it.advance()) != null) {
3144 >            s.writeObject(it.nextKey);
3145 >            s.writeObject(v);
3146          }
3147 <        public boolean isEmpty() {
3148 <            return ConcurrentHashMap.this.isEmpty();
3147 >        s.writeObject(null);
3148 >        s.writeObject(null);
3149 >        segments = null; // throw away
3150 >    }
3151 >
3152 >    /**
3153 >     * Reconstitutes the instance from a stream (that is, deserializes it).
3154 >     * @param s the stream
3155 >     */
3156 >    @SuppressWarnings("unchecked") private void readObject
3157 >        (java.io.ObjectInputStream s)
3158 >        throws java.io.IOException, ClassNotFoundException {
3159 >        s.defaultReadObject();
3160 >        this.segments = null; // unneeded
3161 >
3162 >        // Create all nodes, then place in table once size is known
3163 >        long size = 0L;
3164 >        Node<V> p = null;
3165 >        for (;;) {
3166 >            K k = (K) s.readObject();
3167 >            V v = (V) s.readObject();
3168 >            if (k != null && v != null) {
3169 >                int h = spread(k.hashCode());
3170 >                p = new Node<V>(h, k, v, p);
3171 >                ++size;
3172 >            }
3173 >            else
3174 >                break;
3175          }
3176 <        public boolean contains(Object o) {
3177 <            return ConcurrentHashMap.this.containsKey(o);
3176 >        if (p != null) {
3177 >            boolean init = false;
3178 >            int n;
3179 >            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3180 >                n = MAXIMUM_CAPACITY;
3181 >            else {
3182 >                int sz = (int)size;
3183 >                n = tableSizeFor(sz + (sz >>> 1) + 1);
3184 >            }
3185 >            int sc = sizeCtl;
3186 >            boolean collide = false;
3187 >            if (n > sc &&
3188 >                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3189 >                try {
3190 >                    if (table == null) {
3191 >                        init = true;
3192 >                        @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3193 >                        Node<V>[] tab = (Node<V>[])rt;
3194 >                        int mask = n - 1;
3195 >                        while (p != null) {
3196 >                            int j = p.hash & mask;
3197 >                            Node<V> next = p.next;
3198 >                            Node<V> q = p.next = tabAt(tab, j);
3199 >                            setTabAt(tab, j, p);
3200 >                            if (!collide && q != null && q.hash == p.hash)
3201 >                                collide = true;
3202 >                            p = next;
3203 >                        }
3204 >                        table = tab;
3205 >                        addCount(size, -1);
3206 >                        sc = n - (n >>> 2);
3207 >                    }
3208 >                } finally {
3209 >                    sizeCtl = sc;
3210 >                }
3211 >                if (collide) { // rescan and convert to TreeBins
3212 >                    Node<V>[] tab = table;
3213 >                    for (int i = 0; i < tab.length; ++i) {
3214 >                        int c = 0;
3215 >                        for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3216 >                            if (++c > TREE_THRESHOLD &&
3217 >                                (e.key instanceof Comparable)) {
3218 >                                replaceWithTreeBin(tab, i, e.key);
3219 >                                break;
3220 >                            }
3221 >                        }
3222 >                    }
3223 >                }
3224 >            }
3225 >            if (!init) { // Can only happen if unsafely published.
3226 >                while (p != null) {
3227 >                    internalPut((K)p.key, p.val, false);
3228 >                    p = p.next;
3229 >                }
3230 >            }
3231          }
3232 <        public boolean remove(Object o) {
3233 <            return ConcurrentHashMap.this.remove(o) != null;
3232 >    }
3233 >
3234 >    // -------------------------------------------------------
3235 >
3236 >    // Sequential bulk operations
3237 >
3238 >    /**
3239 >     * Performs the given action for each (key, value).
3240 >     *
3241 >     * @param action the action
3242 >     */
3243 >    public void forEachSequentially
3244 >        (BiConsumer<? super K, ? super V> action) {
3245 >        if (action == null) throw new NullPointerException();
3246 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3247 >        V v;
3248 >        while ((v = it.advance()) != null)
3249 >            action.accept(it.nextKey, v);
3250 >    }
3251 >
3252 >    /**
3253 >     * Performs the given action for each non-null transformation
3254 >     * of each (key, value).
3255 >     *
3256 >     * @param transformer a function returning the transformation
3257 >     * for an element, or null if there is no transformation (in
3258 >     * which case the action is not applied)
3259 >     * @param action the action
3260 >     */
3261 >    public <U> void forEachSequentially
3262 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3263 >         Consumer<? super U> action) {
3264 >        if (transformer == null || action == null)
3265 >            throw new NullPointerException();
3266 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3267 >        V v; U u;
3268 >        while ((v = it.advance()) != null) {
3269 >            if ((u = transformer.apply(it.nextKey, v)) != null)
3270 >                action.accept(u);
3271          }
3272 <        public void clear() {
3273 <            ConcurrentHashMap.this.clear();
3272 >    }
3273 >
3274 >    /**
3275 >     * Returns a non-null result from applying the given search
3276 >     * function on each (key, value), or null if none.
3277 >     *
3278 >     * @param searchFunction a function returning a non-null
3279 >     * result on success, else null
3280 >     * @return a non-null result from applying the given search
3281 >     * function on each (key, value), or null if none
3282 >     */
3283 >    public <U> U searchSequentially
3284 >        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3285 >        if (searchFunction == null) throw new NullPointerException();
3286 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3287 >        V v; U u;
3288 >        while ((v = it.advance()) != null) {
3289 >            if ((u = searchFunction.apply(it.nextKey, v)) != null)
3290 >                return u;
3291          }
3292 +        return null;
3293      }
3294  
3295 <    final class Values extends AbstractCollection<V> {
3296 <        public Iterator<V> iterator() {
3297 <            return new ValueIterator();
3295 >    /**
3296 >     * Returns the result of accumulating the given transformation
3297 >     * of all (key, value) pairs using the given reducer to
3298 >     * combine values, or null if none.
3299 >     *
3300 >     * @param transformer a function returning the transformation
3301 >     * for an element, or null if there is no transformation (in
3302 >     * which case it is not combined)
3303 >     * @param reducer a commutative associative combining function
3304 >     * @return the result of accumulating the given transformation
3305 >     * of all (key, value) pairs
3306 >     */
3307 >    public <U> U reduceSequentially
3308 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3309 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3310 >        if (transformer == null || reducer == null)
3311 >            throw new NullPointerException();
3312 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3313 >        U r = null, u; V v;
3314 >        while ((v = it.advance()) != null) {
3315 >            if ((u = transformer.apply(it.nextKey, v)) != null)
3316 >                r = (r == null) ? u : reducer.apply(r, u);
3317          }
3318 <        public int size() {
3319 <            return ConcurrentHashMap.this.size();
3318 >        return r;
3319 >    }
3320 >
3321 >    /**
3322 >     * Returns the result of accumulating the given transformation
3323 >     * of all (key, value) pairs using the given reducer to
3324 >     * combine values, and the given basis as an identity value.
3325 >     *
3326 >     * @param transformer a function returning the transformation
3327 >     * for an element
3328 >     * @param basis the identity (initial default value) for the reduction
3329 >     * @param reducer a commutative associative combining function
3330 >     * @return the result of accumulating the given transformation
3331 >     * of all (key, value) pairs
3332 >     */
3333 >    public double reduceToDoubleSequentially
3334 >        (ToDoubleBiFunction<? super K, ? super V> transformer,
3335 >         double basis,
3336 >         DoubleBinaryOperator reducer) {
3337 >        if (transformer == null || reducer == null)
3338 >            throw new NullPointerException();
3339 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3340 >        double r = basis; V v;
3341 >        while ((v = it.advance()) != null)
3342 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3343 >        return r;
3344 >    }
3345 >
3346 >    /**
3347 >     * Returns the result of accumulating the given transformation
3348 >     * of all (key, value) pairs using the given reducer to
3349 >     * combine values, and the given basis as an identity value.
3350 >     *
3351 >     * @param transformer a function returning the transformation
3352 >     * for an element
3353 >     * @param basis the identity (initial default value) for the reduction
3354 >     * @param reducer a commutative associative combining function
3355 >     * @return the result of accumulating the given transformation
3356 >     * of all (key, value) pairs
3357 >     */
3358 >    public long reduceToLongSequentially
3359 >        (ToLongBiFunction<? super K, ? super V> transformer,
3360 >         long basis,
3361 >         LongBinaryOperator reducer) {
3362 >        if (transformer == null || reducer == null)
3363 >            throw new NullPointerException();
3364 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3365 >        long r = basis; V v;
3366 >        while ((v = it.advance()) != null)
3367 >            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3368 >        return r;
3369 >    }
3370 >
3371 >    /**
3372 >     * Returns the result of accumulating the given transformation
3373 >     * of all (key, value) pairs using the given reducer to
3374 >     * combine values, and the given basis as an identity value.
3375 >     *
3376 >     * @param transformer a function returning the transformation
3377 >     * for an element
3378 >     * @param basis the identity (initial default value) for the reduction
3379 >     * @param reducer a commutative associative combining function
3380 >     * @return the result of accumulating the given transformation
3381 >     * of all (key, value) pairs
3382 >     */
3383 >    public int reduceToIntSequentially
3384 >        (ToIntBiFunction<? super K, ? super V> transformer,
3385 >         int basis,
3386 >         IntBinaryOperator reducer) {
3387 >        if (transformer == null || reducer == null)
3388 >            throw new NullPointerException();
3389 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3390 >        int r = basis; V v;
3391 >        while ((v = it.advance()) != null)
3392 >            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3393 >        return r;
3394 >    }
3395 >
3396 >    /**
3397 >     * Performs the given action for each key.
3398 >     *
3399 >     * @param action the action
3400 >     */
3401 >    public void forEachKeySequentially
3402 >        (Consumer<? super K> action) {
3403 >        if (action == null) throw new NullPointerException();
3404 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3405 >        while (it.advance() != null)
3406 >            action.accept(it.nextKey);
3407 >    }
3408 >
3409 >    /**
3410 >     * Performs the given action for each non-null transformation
3411 >     * of each key.
3412 >     *
3413 >     * @param transformer a function returning the transformation
3414 >     * for an element, or null if there is no transformation (in
3415 >     * which case the action is not applied)
3416 >     * @param action the action
3417 >     */
3418 >    public <U> void forEachKeySequentially
3419 >        (Function<? super K, ? extends U> transformer,
3420 >         Consumer<? super U> action) {
3421 >        if (transformer == null || action == null)
3422 >            throw new NullPointerException();
3423 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3424 >        U u;
3425 >        while (it.advance() != null) {
3426 >            if ((u = transformer.apply(it.nextKey)) != null)
3427 >                action.accept(u);
3428          }
3429 <        public boolean isEmpty() {
3430 <            return ConcurrentHashMap.this.isEmpty();
3429 >        ForkJoinTasks.forEachKey
3430 >            (this, transformer, action).invoke();
3431 >    }
3432 >
3433 >    /**
3434 >     * Returns a non-null result from applying the given search
3435 >     * function on each key, or null if none.
3436 >     *
3437 >     * @param searchFunction a function returning a non-null
3438 >     * result on success, else null
3439 >     * @return a non-null result from applying the given search
3440 >     * function on each key, or null if none
3441 >     */
3442 >    public <U> U searchKeysSequentially
3443 >        (Function<? super K, ? extends U> searchFunction) {
3444 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3445 >        U u;
3446 >        while (it.advance() != null) {
3447 >            if ((u = searchFunction.apply(it.nextKey)) != null)
3448 >                return u;
3449          }
3450 <        public boolean contains(Object o) {
3451 <            return ConcurrentHashMap.this.containsValue(o);
3450 >        return null;
3451 >    }
3452 >
3453 >    /**
3454 >     * Returns the result of accumulating all keys using the given
3455 >     * reducer to combine values, or null if none.
3456 >     *
3457 >     * @param reducer a commutative associative combining function
3458 >     * @return the result of accumulating all keys using the given
3459 >     * reducer to combine values, or null if none
3460 >     */
3461 >    public K reduceKeysSequentially
3462 >        (BiFunction<? super K, ? super K, ? extends K> reducer) {
3463 >        if (reducer == null) throw new NullPointerException();
3464 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3465 >        K r = null;
3466 >        while (it.advance() != null) {
3467 >            K u = it.nextKey;
3468 >            r = (r == null) ? u : reducer.apply(r, u);
3469 >        }
3470 >        return r;
3471 >    }
3472 >
3473 >    /**
3474 >     * Returns the result of accumulating the given transformation
3475 >     * of all keys using the given reducer to combine values, or
3476 >     * null if none.
3477 >     *
3478 >     * @param transformer a function returning the transformation
3479 >     * for an element, or null if there is no transformation (in
3480 >     * which case it is not combined)
3481 >     * @param reducer a commutative associative combining function
3482 >     * @return the result of accumulating the given transformation
3483 >     * of all keys
3484 >     */
3485 >    public <U> U reduceKeysSequentially
3486 >        (Function<? super K, ? extends U> transformer,
3487 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3488 >        if (transformer == null || reducer == null)
3489 >            throw new NullPointerException();
3490 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3491 >        U r = null, u;
3492 >        while (it.advance() != null) {
3493 >            if ((u = transformer.apply(it.nextKey)) != null)
3494 >                r = (r == null) ? u : reducer.apply(r, u);
3495          }
3496 <        public void clear() {
3497 <            ConcurrentHashMap.this.clear();
3496 >        return r;
3497 >    }
3498 >
3499 >    /**
3500 >     * Returns the result of accumulating the given transformation
3501 >     * of all keys using the given reducer to combine values, and
3502 >     * the given basis as an identity value.
3503 >     *
3504 >     * @param transformer a function returning the transformation
3505 >     * for an element
3506 >     * @param basis the identity (initial default value) for the reduction
3507 >     * @param reducer a commutative associative combining function
3508 >     * @return the result of accumulating the given transformation
3509 >     * of all keys
3510 >     */
3511 >    public double reduceKeysToDoubleSequentially
3512 >        (ToDoubleFunction<? super K> transformer,
3513 >         double basis,
3514 >         DoubleBinaryOperator reducer) {
3515 >        if (transformer == null || reducer == null)
3516 >            throw new NullPointerException();
3517 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3518 >        double r = basis;
3519 >        while (it.advance() != null)
3520 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey));
3521 >        return r;
3522 >    }
3523 >
3524 >    /**
3525 >     * Returns the result of accumulating the given transformation
3526 >     * of all keys using the given reducer to combine values, and
3527 >     * the given basis as an identity value.
3528 >     *
3529 >     * @param transformer a function returning the transformation
3530 >     * for an element
3531 >     * @param basis the identity (initial default value) for the reduction
3532 >     * @param reducer a commutative associative combining function
3533 >     * @return the result of accumulating the given transformation
3534 >     * of all keys
3535 >     */
3536 >    public long reduceKeysToLongSequentially
3537 >        (ToLongFunction<? super K> transformer,
3538 >         long basis,
3539 >         LongBinaryOperator reducer) {
3540 >        if (transformer == null || reducer == null)
3541 >            throw new NullPointerException();
3542 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3543 >        long r = basis;
3544 >        while (it.advance() != null)
3545 >            r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey));
3546 >        return r;
3547 >    }
3548 >
3549 >    /**
3550 >     * Returns the result of accumulating the given transformation
3551 >     * of all keys using the given reducer to combine values, and
3552 >     * the given basis as an identity value.
3553 >     *
3554 >     * @param transformer a function returning the transformation
3555 >     * for an element
3556 >     * @param basis the identity (initial default value) for the reduction
3557 >     * @param reducer a commutative associative combining function
3558 >     * @return the result of accumulating the given transformation
3559 >     * of all keys
3560 >     */
3561 >    public int reduceKeysToIntSequentially
3562 >        (ToIntFunction<? super K> transformer,
3563 >         int basis,
3564 >         IntBinaryOperator reducer) {
3565 >        if (transformer == null || reducer == null)
3566 >            throw new NullPointerException();
3567 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3568 >        int r = basis;
3569 >        while (it.advance() != null)
3570 >            r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey));
3571 >        return r;
3572 >    }
3573 >
3574 >    /**
3575 >     * Performs the given action for each value.
3576 >     *
3577 >     * @param action the action
3578 >     */
3579 >    public void forEachValueSequentially(Consumer<? super V> action) {
3580 >        if (action == null) throw new NullPointerException();
3581 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3582 >        V v;
3583 >        while ((v = it.advance()) != null)
3584 >            action.accept(v);
3585 >    }
3586 >
3587 >    /**
3588 >     * Performs the given action for each non-null transformation
3589 >     * of each value.
3590 >     *
3591 >     * @param transformer a function returning the transformation
3592 >     * for an element, or null if there is no transformation (in
3593 >     * which case the action is not applied)
3594 >     * @param action the action
3595 >     */
3596 >    public <U> void forEachValueSequentially
3597 >        (Function<? super V, ? extends U> transformer,
3598 >         Consumer<? super U> action) {
3599 >        if (transformer == null || action == null)
3600 >            throw new NullPointerException();
3601 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3602 >        V v; U u;
3603 >        while ((v = it.advance()) != null) {
3604 >            if ((u = transformer.apply(v)) != null)
3605 >                action.accept(u);
3606          }
3607      }
3608  
3609 <    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
3610 <        public Iterator<Map.Entry<K,V>> iterator() {
3611 <            return new EntryIterator();
3609 >    /**
3610 >     * Returns a non-null result from applying the given search
3611 >     * function on each value, or null if none.
3612 >     *
3613 >     * @param searchFunction a function returning a non-null
3614 >     * result on success, else null
3615 >     * @return a non-null result from applying the given search
3616 >     * function on each value, or null if none
3617 >     */
3618 >    public <U> U searchValuesSequentially
3619 >        (Function<? super V, ? extends U> searchFunction) {
3620 >        if (searchFunction == null) throw new NullPointerException();
3621 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3622 >        V v; U u;
3623 >        while ((v = it.advance()) != null) {
3624 >            if ((u = searchFunction.apply(v)) != null)
3625 >                return u;
3626          }
3627 <        public boolean contains(Object o) {
3628 <            if (!(o instanceof Map.Entry))
3629 <                return false;
3630 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
3631 <            V v = ConcurrentHashMap.this.get(e.getKey());
3632 <            return v != null && v.equals(e.getValue());
3627 >        return null;
3628 >    }
3629 >
3630 >    /**
3631 >     * Returns the result of accumulating all values using the
3632 >     * given reducer to combine values, or null if none.
3633 >     *
3634 >     * @param reducer a commutative associative combining function
3635 >     * @return the result of accumulating all values
3636 >     */
3637 >    public V reduceValuesSequentially
3638 >        (BiFunction<? super V, ? super V, ? extends V> reducer) {
3639 >        if (reducer == null) throw new NullPointerException();
3640 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3641 >        V r = null; V v;
3642 >        while ((v = it.advance()) != null)
3643 >            r = (r == null) ? v : reducer.apply(r, v);
3644 >        return r;
3645 >    }
3646 >
3647 >    /**
3648 >     * Returns the result of accumulating the given transformation
3649 >     * of all values using the given reducer to combine values, or
3650 >     * null if none.
3651 >     *
3652 >     * @param transformer a function returning the transformation
3653 >     * for an element, or null if there is no transformation (in
3654 >     * which case it is not combined)
3655 >     * @param reducer a commutative associative combining function
3656 >     * @return the result of accumulating the given transformation
3657 >     * of all values
3658 >     */
3659 >    public <U> U reduceValuesSequentially
3660 >        (Function<? super V, ? extends U> transformer,
3661 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3662 >        if (transformer == null || reducer == null)
3663 >            throw new NullPointerException();
3664 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3665 >        U r = null, u; V v;
3666 >        while ((v = it.advance()) != null) {
3667 >            if ((u = transformer.apply(v)) != null)
3668 >                r = (r == null) ? u : reducer.apply(r, u);
3669          }
3670 <        public boolean remove(Object o) {
3671 <            if (!(o instanceof Map.Entry))
3672 <                return false;
3673 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
3674 <            return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
3670 >        return r;
3671 >    }
3672 >
3673 >    /**
3674 >     * Returns the result of accumulating the given transformation
3675 >     * of all values using the given reducer to combine values,
3676 >     * and the given basis as an identity value.
3677 >     *
3678 >     * @param transformer a function returning the transformation
3679 >     * for an element
3680 >     * @param basis the identity (initial default value) for the reduction
3681 >     * @param reducer a commutative associative combining function
3682 >     * @return the result of accumulating the given transformation
3683 >     * of all values
3684 >     */
3685 >    public double reduceValuesToDoubleSequentially
3686 >        (ToDoubleFunction<? super V> transformer,
3687 >         double basis,
3688 >         DoubleBinaryOperator reducer) {
3689 >        if (transformer == null || reducer == null)
3690 >            throw new NullPointerException();
3691 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3692 >        double r = basis; V v;
3693 >        while ((v = it.advance()) != null)
3694 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3695 >        return r;
3696 >    }
3697 >
3698 >    /**
3699 >     * Returns the result of accumulating the given transformation
3700 >     * of all values using the given reducer to combine values,
3701 >     * and the given basis as an identity value.
3702 >     *
3703 >     * @param transformer a function returning the transformation
3704 >     * for an element
3705 >     * @param basis the identity (initial default value) for the reduction
3706 >     * @param reducer a commutative associative combining function
3707 >     * @return the result of accumulating the given transformation
3708 >     * of all values
3709 >     */
3710 >    public long reduceValuesToLongSequentially
3711 >        (ToLongFunction<? super V> transformer,
3712 >         long basis,
3713 >         LongBinaryOperator reducer) {
3714 >        if (transformer == null || reducer == null)
3715 >            throw new NullPointerException();
3716 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3717 >        long r = basis; V v;
3718 >        while ((v = it.advance()) != null)
3719 >            r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3720 >        return r;
3721 >    }
3722 >
3723 >    /**
3724 >     * Returns the result of accumulating the given transformation
3725 >     * of all values using the given reducer to combine values,
3726 >     * and the given basis as an identity value.
3727 >     *
3728 >     * @param transformer a function returning the transformation
3729 >     * for an element
3730 >     * @param basis the identity (initial default value) for the reduction
3731 >     * @param reducer a commutative associative combining function
3732 >     * @return the result of accumulating the given transformation
3733 >     * of all values
3734 >     */
3735 >    public int reduceValuesToIntSequentially
3736 >        (ToIntFunction<? super V> transformer,
3737 >         int basis,
3738 >         IntBinaryOperator reducer) {
3739 >        if (transformer == null || reducer == null)
3740 >            throw new NullPointerException();
3741 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3742 >        int r = basis; V v;
3743 >        while ((v = it.advance()) != null)
3744 >            r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3745 >        return r;
3746 >    }
3747 >
3748 >    /**
3749 >     * Performs the given action for each entry.
3750 >     *
3751 >     * @param action the action
3752 >     */
3753 >    public void forEachEntrySequentially
3754 >        (Consumer<? super Map.Entry<K,V>> action) {
3755 >        if (action == null) throw new NullPointerException();
3756 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3757 >        V v;
3758 >        while ((v = it.advance()) != null)
3759 >            action.accept(entryFor(it.nextKey, v));
3760 >    }
3761 >
3762 >    /**
3763 >     * Performs the given action for each non-null transformation
3764 >     * of each entry.
3765 >     *
3766 >     * @param transformer a function returning the transformation
3767 >     * for an element, or null if there is no transformation (in
3768 >     * which case the action is not applied)
3769 >     * @param action the action
3770 >     */
3771 >    public <U> void forEachEntrySequentially
3772 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
3773 >         Consumer<? super U> action) {
3774 >        if (transformer == null || action == null)
3775 >            throw new NullPointerException();
3776 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3777 >        V v; U u;
3778 >        while ((v = it.advance()) != null) {
3779 >            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3780 >                action.accept(u);
3781          }
3782 <        public int size() {
3783 <            return ConcurrentHashMap.this.size();
3782 >    }
3783 >
3784 >    /**
3785 >     * Returns a non-null result from applying the given search
3786 >     * function on each entry, or null if none.
3787 >     *
3788 >     * @param searchFunction a function returning a non-null
3789 >     * result on success, else null
3790 >     * @return a non-null result from applying the given search
3791 >     * function on each entry, or null if none
3792 >     */
3793 >    public <U> U searchEntriesSequentially
3794 >        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3795 >        if (searchFunction == null) throw new NullPointerException();
3796 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3797 >        V v; U u;
3798 >        while ((v = it.advance()) != null) {
3799 >            if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3800 >                return u;
3801          }
3802 <        public boolean isEmpty() {
3803 <            return ConcurrentHashMap.this.isEmpty();
3802 >        return null;
3803 >    }
3804 >
3805 >    /**
3806 >     * Returns the result of accumulating all entries using the
3807 >     * given reducer to combine values, or null if none.
3808 >     *
3809 >     * @param reducer a commutative associative combining function
3810 >     * @return the result of accumulating all entries
3811 >     */
3812 >    public Map.Entry<K,V> reduceEntriesSequentially
3813 >        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3814 >        if (reducer == null) throw new NullPointerException();
3815 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3816 >        Map.Entry<K,V> r = null; V v;
3817 >        while ((v = it.advance()) != null) {
3818 >            Map.Entry<K,V> u = entryFor(it.nextKey, v);
3819 >            r = (r == null) ? u : reducer.apply(r, u);
3820          }
3821 <        public void clear() {
3822 <            ConcurrentHashMap.this.clear();
3821 >        return r;
3822 >    }
3823 >
3824 >    /**
3825 >     * Returns the result of accumulating the given transformation
3826 >     * of all entries using the given reducer to combine values,
3827 >     * or null if none.
3828 >     *
3829 >     * @param transformer a function returning the transformation
3830 >     * for an element, or null if there is no transformation (in
3831 >     * which case it is not combined)
3832 >     * @param reducer a commutative associative combining function
3833 >     * @return the result of accumulating the given transformation
3834 >     * of all entries
3835 >     */
3836 >    public <U> U reduceEntriesSequentially
3837 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
3838 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3839 >        if (transformer == null || reducer == null)
3840 >            throw new NullPointerException();
3841 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3842 >        U r = null, u; V v;
3843 >        while ((v = it.advance()) != null) {
3844 >            if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3845 >                r = (r == null) ? u : reducer.apply(r, u);
3846          }
3847 +        return r;
3848      }
3849  
3850 <    /* ---------------- Serialization Support -------------- */
3850 >    /**
3851 >     * Returns the result of accumulating the given transformation
3852 >     * of all entries using the given reducer to combine values,
3853 >     * and the given basis as an identity value.
3854 >     *
3855 >     * @param transformer a function returning the transformation
3856 >     * for an element
3857 >     * @param basis the identity (initial default value) for the reduction
3858 >     * @param reducer a commutative associative combining function
3859 >     * @return the result of accumulating the given transformation
3860 >     * of all entries
3861 >     */
3862 >    public double reduceEntriesToDoubleSequentially
3863 >        (ToDoubleFunction<Map.Entry<K,V>> transformer,
3864 >         double basis,
3865 >         DoubleBinaryOperator reducer) {
3866 >        if (transformer == null || reducer == null)
3867 >            throw new NullPointerException();
3868 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3869 >        double r = basis; V v;
3870 >        while ((v = it.advance()) != null)
3871 >            r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
3872 >        return r;
3873 >    }
3874  
3875      /**
3876 <     * Saves the state of the <tt>ConcurrentHashMap</tt> instance to a
3877 <     * stream (i.e., serializes it).
3878 <     * @param s the stream
3879 <     * @serialData
3880 <     * the key (Object) and value (Object)
3881 <     * for each key-value mapping, followed by a null pair.
3882 <     * The key-value mappings are emitted in no particular order.
3876 >     * Returns the result of accumulating the given transformation
3877 >     * of all entries using the given reducer to combine values,
3878 >     * and the given basis as an identity value.
3879 >     *
3880 >     * @param transformer a function returning the transformation
3881 >     * for an element
3882 >     * @param basis the identity (initial default value) for the reduction
3883 >     * @param reducer a commutative associative combining function
3884 >     * @return the result of accumulating the given transformation
3885 >     * of all entries
3886 >     */
3887 >    public long reduceEntriesToLongSequentially
3888 >        (ToLongFunction<Map.Entry<K,V>> transformer,
3889 >         long basis,
3890 >         LongBinaryOperator reducer) {
3891 >        if (transformer == null || reducer == null)
3892 >            throw new NullPointerException();
3893 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3894 >        long r = basis; V v;
3895 >        while ((v = it.advance()) != null)
3896 >            r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
3897 >        return r;
3898 >    }
3899 >
3900 >    /**
3901 >     * Returns the result of accumulating the given transformation
3902 >     * of all entries using the given reducer to combine values,
3903 >     * and the given basis as an identity value.
3904 >     *
3905 >     * @param transformer a function returning the transformation
3906 >     * for an element
3907 >     * @param basis the identity (initial default value) for the reduction
3908 >     * @param reducer a commutative associative combining function
3909 >     * @return the result of accumulating the given transformation
3910 >     * of all entries
3911 >     */
3912 >    public int reduceEntriesToIntSequentially
3913 >        (ToIntFunction<Map.Entry<K,V>> transformer,
3914 >         int basis,
3915 >         IntBinaryOperator reducer) {
3916 >        if (transformer == null || reducer == null)
3917 >            throw new NullPointerException();
3918 >        Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3919 >        int r = basis; V v;
3920 >        while ((v = it.advance()) != null)
3921 >            r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
3922 >        return r;
3923 >    }
3924 >
3925 >    // Parallel bulk operations
3926 >
3927 >    /**
3928 >     * Performs the given action for each (key, value).
3929 >     *
3930 >     * @param action the action
3931       */
3932 <    private void writeObject(java.io.ObjectOutputStream s) throws IOException {
3933 <        // force all segments for serialization compatibility
3934 <        for (int k = 0; k < segments.length; ++k)
3935 <            ensureSegment(k);
1412 <        s.defaultWriteObject();
3932 >    public void forEachInParallel(BiConsumer<? super K,? super V> action) {
3933 >        ForkJoinTasks.forEach
3934 >            (this, action).invoke();
3935 >    }
3936  
3937 <        final Segment<K,V>[] segments = this.segments;
3938 <        for (int k = 0; k < segments.length; ++k) {
3939 <            Segment<K,V> seg = segmentAt(segments, k);
3940 <            seg.lock();
3941 <            try {
3942 <                HashEntry<K,V>[] tab = seg.table;
3943 <                for (int i = 0; i < tab.length; ++i) {
3944 <                    HashEntry<K,V> e;
3945 <                    for (e = entryAt(tab, i); e != null; e = e.next) {
3946 <                        s.writeObject(e.key);
3947 <                        s.writeObject(e.value);
3937 >    /**
3938 >     * Performs the given action for each non-null transformation
3939 >     * of each (key, value).
3940 >     *
3941 >     * @param transformer a function returning the transformation
3942 >     * for an element, or null if there is no transformation (in
3943 >     * which case the action is not applied)
3944 >     * @param action the action
3945 >     */
3946 >    public <U> void forEachInParallel
3947 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3948 >                            Consumer<? super U> action) {
3949 >        ForkJoinTasks.forEach
3950 >            (this, transformer, action).invoke();
3951 >    }
3952 >
3953 >    /**
3954 >     * Returns a non-null result from applying the given search
3955 >     * function on each (key, value), or null if none.  Upon
3956 >     * success, further element processing is suppressed and the
3957 >     * results of any other parallel invocations of the search
3958 >     * function are ignored.
3959 >     *
3960 >     * @param searchFunction a function returning a non-null
3961 >     * result on success, else null
3962 >     * @return a non-null result from applying the given search
3963 >     * function on each (key, value), or null if none
3964 >     */
3965 >    public <U> U searchInParallel
3966 >        (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3967 >        return ForkJoinTasks.search
3968 >            (this, searchFunction).invoke();
3969 >    }
3970 >
3971 >    /**
3972 >     * Returns the result of accumulating the given transformation
3973 >     * of all (key, value) pairs using the given reducer to
3974 >     * combine values, or null if none.
3975 >     *
3976 >     * @param transformer a function returning the transformation
3977 >     * for an element, or null if there is no transformation (in
3978 >     * which case it is not combined)
3979 >     * @param reducer a commutative associative combining function
3980 >     * @return the result of accumulating the given transformation
3981 >     * of all (key, value) pairs
3982 >     */
3983 >    public <U> U reduceInParallel
3984 >        (BiFunction<? super K, ? super V, ? extends U> transformer,
3985 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3986 >        return ForkJoinTasks.reduce
3987 >            (this, transformer, reducer).invoke();
3988 >    }
3989 >
3990 >    /**
3991 >     * Returns the result of accumulating the given transformation
3992 >     * of all (key, value) pairs using the given reducer to
3993 >     * combine values, and the given basis as an identity value.
3994 >     *
3995 >     * @param transformer a function returning the transformation
3996 >     * for an element
3997 >     * @param basis the identity (initial default value) for the reduction
3998 >     * @param reducer a commutative associative combining function
3999 >     * @return the result of accumulating the given transformation
4000 >     * of all (key, value) pairs
4001 >     */
4002 >    public double reduceToDoubleInParallel
4003 >        (ToDoubleBiFunction<? super K, ? super V> transformer,
4004 >         double basis,
4005 >         DoubleBinaryOperator reducer) {
4006 >        return ForkJoinTasks.reduceToDouble
4007 >            (this, transformer, basis, reducer).invoke();
4008 >    }
4009 >
4010 >    /**
4011 >     * Returns the result of accumulating the given transformation
4012 >     * of all (key, value) pairs using the given reducer to
4013 >     * combine values, and the given basis as an identity value.
4014 >     *
4015 >     * @param transformer a function returning the transformation
4016 >     * for an element
4017 >     * @param basis the identity (initial default value) for the reduction
4018 >     * @param reducer a commutative associative combining function
4019 >     * @return the result of accumulating the given transformation
4020 >     * of all (key, value) pairs
4021 >     */
4022 >    public long reduceToLongInParallel
4023 >        (ToLongBiFunction<? super K, ? super V> transformer,
4024 >         long basis,
4025 >         LongBinaryOperator reducer) {
4026 >        return ForkJoinTasks.reduceToLong
4027 >            (this, transformer, basis, reducer).invoke();
4028 >    }
4029 >
4030 >    /**
4031 >     * Returns the result of accumulating the given transformation
4032 >     * of all (key, value) pairs using the given reducer to
4033 >     * combine values, and the given basis as an identity value.
4034 >     *
4035 >     * @param transformer a function returning the transformation
4036 >     * for an element
4037 >     * @param basis the identity (initial default value) for the reduction
4038 >     * @param reducer a commutative associative combining function
4039 >     * @return the result of accumulating the given transformation
4040 >     * of all (key, value) pairs
4041 >     */
4042 >    public int reduceToIntInParallel
4043 >        (ToIntBiFunction<? super K, ? super V> transformer,
4044 >         int basis,
4045 >         IntBinaryOperator reducer) {
4046 >        return ForkJoinTasks.reduceToInt
4047 >            (this, transformer, basis, reducer).invoke();
4048 >    }
4049 >
4050 >    /**
4051 >     * Performs the given action for each key.
4052 >     *
4053 >     * @param action the action
4054 >     */
4055 >    public void forEachKeyInParallel(Consumer<? super K> action) {
4056 >        ForkJoinTasks.forEachKey
4057 >            (this, action).invoke();
4058 >    }
4059 >
4060 >    /**
4061 >     * Performs the given action for each non-null transformation
4062 >     * of each key.
4063 >     *
4064 >     * @param transformer a function returning the transformation
4065 >     * for an element, or null if there is no transformation (in
4066 >     * which case the action is not applied)
4067 >     * @param action the action
4068 >     */
4069 >    public <U> void forEachKeyInParallel
4070 >        (Function<? super K, ? extends U> transformer,
4071 >         Consumer<? super U> action) {
4072 >        ForkJoinTasks.forEachKey
4073 >            (this, transformer, action).invoke();
4074 >    }
4075 >
4076 >    /**
4077 >     * Returns a non-null result from applying the given search
4078 >     * function on each key, or null if none. Upon success,
4079 >     * further element processing is suppressed and the results of
4080 >     * any other parallel invocations of the search function are
4081 >     * ignored.
4082 >     *
4083 >     * @param searchFunction a function returning a non-null
4084 >     * result on success, else null
4085 >     * @return a non-null result from applying the given search
4086 >     * function on each key, or null if none
4087 >     */
4088 >    public <U> U searchKeysInParallel
4089 >        (Function<? super K, ? extends U> searchFunction) {
4090 >        return ForkJoinTasks.searchKeys
4091 >            (this, searchFunction).invoke();
4092 >    }
4093 >
4094 >    /**
4095 >     * Returns the result of accumulating all keys using the given
4096 >     * reducer to combine values, or null if none.
4097 >     *
4098 >     * @param reducer a commutative associative combining function
4099 >     * @return the result of accumulating all keys using the given
4100 >     * reducer to combine values, or null if none
4101 >     */
4102 >    public K reduceKeysInParallel
4103 >        (BiFunction<? super K, ? super K, ? extends K> reducer) {
4104 >        return ForkJoinTasks.reduceKeys
4105 >            (this, reducer).invoke();
4106 >    }
4107 >
4108 >    /**
4109 >     * Returns the result of accumulating the given transformation
4110 >     * of all keys using the given reducer to combine values, or
4111 >     * null if none.
4112 >     *
4113 >     * @param transformer a function returning the transformation
4114 >     * for an element, or null if there is no transformation (in
4115 >     * which case it is not combined)
4116 >     * @param reducer a commutative associative combining function
4117 >     * @return the result of accumulating the given transformation
4118 >     * of all keys
4119 >     */
4120 >    public <U> U reduceKeysInParallel
4121 >        (Function<? super K, ? extends U> transformer,
4122 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4123 >        return ForkJoinTasks.reduceKeys
4124 >            (this, transformer, reducer).invoke();
4125 >    }
4126 >
4127 >    /**
4128 >     * Returns the result of accumulating the given transformation
4129 >     * of all keys using the given reducer to combine values, and
4130 >     * the given basis as an identity value.
4131 >     *
4132 >     * @param transformer a function returning the transformation
4133 >     * for an element
4134 >     * @param basis the identity (initial default value) for the reduction
4135 >     * @param reducer a commutative associative combining function
4136 >     * @return the result of accumulating the given transformation
4137 >     * of all keys
4138 >     */
4139 >    public double reduceKeysToDoubleInParallel
4140 >        (ToDoubleFunction<? super K> transformer,
4141 >         double basis,
4142 >         DoubleBinaryOperator reducer) {
4143 >        return ForkJoinTasks.reduceKeysToDouble
4144 >            (this, transformer, basis, reducer).invoke();
4145 >    }
4146 >
4147 >    /**
4148 >     * Returns the result of accumulating the given transformation
4149 >     * of all keys using the given reducer to combine values, and
4150 >     * the given basis as an identity value.
4151 >     *
4152 >     * @param transformer a function returning the transformation
4153 >     * for an element
4154 >     * @param basis the identity (initial default value) for the reduction
4155 >     * @param reducer a commutative associative combining function
4156 >     * @return the result of accumulating the given transformation
4157 >     * of all keys
4158 >     */
4159 >    public long reduceKeysToLongInParallel
4160 >        (ToLongFunction<? super K> transformer,
4161 >         long basis,
4162 >         LongBinaryOperator reducer) {
4163 >        return ForkJoinTasks.reduceKeysToLong
4164 >            (this, transformer, basis, reducer).invoke();
4165 >    }
4166 >
4167 >    /**
4168 >     * Returns the result of accumulating the given transformation
4169 >     * of all keys using the given reducer to combine values, and
4170 >     * the given basis as an identity value.
4171 >     *
4172 >     * @param transformer a function returning the transformation
4173 >     * for an element
4174 >     * @param basis the identity (initial default value) for the reduction
4175 >     * @param reducer a commutative associative combining function
4176 >     * @return the result of accumulating the given transformation
4177 >     * of all keys
4178 >     */
4179 >    public int reduceKeysToIntInParallel
4180 >        (ToIntFunction<? super K> transformer,
4181 >         int basis,
4182 >         IntBinaryOperator reducer) {
4183 >        return ForkJoinTasks.reduceKeysToInt
4184 >            (this, transformer, basis, reducer).invoke();
4185 >    }
4186 >
4187 >    /**
4188 >     * Performs the given action for each value.
4189 >     *
4190 >     * @param action the action
4191 >     */
4192 >    public void forEachValueInParallel(Consumer<? super V> action) {
4193 >        ForkJoinTasks.forEachValue
4194 >            (this, action).invoke();
4195 >    }
4196 >
4197 >    /**
4198 >     * Performs the given action for each non-null transformation
4199 >     * of each value.
4200 >     *
4201 >     * @param transformer a function returning the transformation
4202 >     * for an element, or null if there is no transformation (in
4203 >     * which case the action is not applied)
4204 >     * @param action the action
4205 >     */
4206 >    public <U> void forEachValueInParallel
4207 >        (Function<? super V, ? extends U> transformer,
4208 >         Consumer<? super U> action) {
4209 >        ForkJoinTasks.forEachValue
4210 >            (this, transformer, action).invoke();
4211 >    }
4212 >
4213 >    /**
4214 >     * Returns a non-null result from applying the given search
4215 >     * function on each value, or null if none.  Upon success,
4216 >     * further element processing is suppressed and the results of
4217 >     * any other parallel invocations of the search function are
4218 >     * ignored.
4219 >     *
4220 >     * @param searchFunction a function returning a non-null
4221 >     * result on success, else null
4222 >     * @return a non-null result from applying the given search
4223 >     * function on each value, or null if none
4224 >     */
4225 >    public <U> U searchValuesInParallel
4226 >        (Function<? super V, ? extends U> searchFunction) {
4227 >        return ForkJoinTasks.searchValues
4228 >            (this, searchFunction).invoke();
4229 >    }
4230 >
4231 >    /**
4232 >     * Returns the result of accumulating all values using the
4233 >     * given reducer to combine values, or null if none.
4234 >     *
4235 >     * @param reducer a commutative associative combining function
4236 >     * @return the result of accumulating all values
4237 >     */
4238 >    public V reduceValuesInParallel
4239 >        (BiFunction<? super V, ? super V, ? extends V> reducer) {
4240 >        return ForkJoinTasks.reduceValues
4241 >            (this, reducer).invoke();
4242 >    }
4243 >
4244 >    /**
4245 >     * Returns the result of accumulating the given transformation
4246 >     * of all values using the given reducer to combine values, or
4247 >     * null if none.
4248 >     *
4249 >     * @param transformer a function returning the transformation
4250 >     * for an element, or null if there is no transformation (in
4251 >     * which case it is not combined)
4252 >     * @param reducer a commutative associative combining function
4253 >     * @return the result of accumulating the given transformation
4254 >     * of all values
4255 >     */
4256 >    public <U> U reduceValuesInParallel
4257 >        (Function<? super V, ? extends U> transformer,
4258 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4259 >        return ForkJoinTasks.reduceValues
4260 >            (this, transformer, reducer).invoke();
4261 >    }
4262 >
4263 >    /**
4264 >     * Returns the result of accumulating the given transformation
4265 >     * of all values using the given reducer to combine values,
4266 >     * and the given basis as an identity value.
4267 >     *
4268 >     * @param transformer a function returning the transformation
4269 >     * for an element
4270 >     * @param basis the identity (initial default value) for the reduction
4271 >     * @param reducer a commutative associative combining function
4272 >     * @return the result of accumulating the given transformation
4273 >     * of all values
4274 >     */
4275 >    public double reduceValuesToDoubleInParallel
4276 >        (ToDoubleFunction<? super V> transformer,
4277 >         double basis,
4278 >         DoubleBinaryOperator reducer) {
4279 >        return ForkJoinTasks.reduceValuesToDouble
4280 >            (this, transformer, basis, reducer).invoke();
4281 >    }
4282 >
4283 >    /**
4284 >     * Returns the result of accumulating the given transformation
4285 >     * of all values using the given reducer to combine values,
4286 >     * and the given basis as an identity value.
4287 >     *
4288 >     * @param transformer a function returning the transformation
4289 >     * for an element
4290 >     * @param basis the identity (initial default value) for the reduction
4291 >     * @param reducer a commutative associative combining function
4292 >     * @return the result of accumulating the given transformation
4293 >     * of all values
4294 >     */
4295 >    public long reduceValuesToLongInParallel
4296 >        (ToLongFunction<? super V> transformer,
4297 >         long basis,
4298 >         LongBinaryOperator reducer) {
4299 >        return ForkJoinTasks.reduceValuesToLong
4300 >            (this, transformer, basis, reducer).invoke();
4301 >    }
4302 >
4303 >    /**
4304 >     * Returns the result of accumulating the given transformation
4305 >     * of all values using the given reducer to combine values,
4306 >     * and the given basis as an identity value.
4307 >     *
4308 >     * @param transformer a function returning the transformation
4309 >     * for an element
4310 >     * @param basis the identity (initial default value) for the reduction
4311 >     * @param reducer a commutative associative combining function
4312 >     * @return the result of accumulating the given transformation
4313 >     * of all values
4314 >     */
4315 >    public int reduceValuesToIntInParallel
4316 >        (ToIntFunction<? super V> transformer,
4317 >         int basis,
4318 >         IntBinaryOperator reducer) {
4319 >        return ForkJoinTasks.reduceValuesToInt
4320 >            (this, transformer, basis, reducer).invoke();
4321 >    }
4322 >
4323 >    /**
4324 >     * Performs the given action for each entry.
4325 >     *
4326 >     * @param action the action
4327 >     */
4328 >    public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4329 >        ForkJoinTasks.forEachEntry
4330 >            (this, action).invoke();
4331 >    }
4332 >
4333 >    /**
4334 >     * Performs the given action for each non-null transformation
4335 >     * of each entry.
4336 >     *
4337 >     * @param transformer a function returning the transformation
4338 >     * for an element, or null if there is no transformation (in
4339 >     * which case the action is not applied)
4340 >     * @param action the action
4341 >     */
4342 >    public <U> void forEachEntryInParallel
4343 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
4344 >         Consumer<? super U> action) {
4345 >        ForkJoinTasks.forEachEntry
4346 >            (this, transformer, action).invoke();
4347 >    }
4348 >
4349 >    /**
4350 >     * Returns a non-null result from applying the given search
4351 >     * function on each entry, or null if none.  Upon success,
4352 >     * further element processing is suppressed and the results of
4353 >     * any other parallel invocations of the search function are
4354 >     * ignored.
4355 >     *
4356 >     * @param searchFunction a function returning a non-null
4357 >     * result on success, else null
4358 >     * @return a non-null result from applying the given search
4359 >     * function on each entry, or null if none
4360 >     */
4361 >    public <U> U searchEntriesInParallel
4362 >        (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4363 >        return ForkJoinTasks.searchEntries
4364 >            (this, searchFunction).invoke();
4365 >    }
4366 >
4367 >    /**
4368 >     * Returns the result of accumulating all entries using the
4369 >     * given reducer to combine values, or null if none.
4370 >     *
4371 >     * @param reducer a commutative associative combining function
4372 >     * @return the result of accumulating all entries
4373 >     */
4374 >    public Map.Entry<K,V> reduceEntriesInParallel
4375 >        (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4376 >        return ForkJoinTasks.reduceEntries
4377 >            (this, reducer).invoke();
4378 >    }
4379 >
4380 >    /**
4381 >     * Returns the result of accumulating the given transformation
4382 >     * of all entries using the given reducer to combine values,
4383 >     * or null if none.
4384 >     *
4385 >     * @param transformer a function returning the transformation
4386 >     * for an element, or null if there is no transformation (in
4387 >     * which case it is not combined)
4388 >     * @param reducer a commutative associative combining function
4389 >     * @return the result of accumulating the given transformation
4390 >     * of all entries
4391 >     */
4392 >    public <U> U reduceEntriesInParallel
4393 >        (Function<Map.Entry<K,V>, ? extends U> transformer,
4394 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
4395 >        return ForkJoinTasks.reduceEntries
4396 >            (this, transformer, reducer).invoke();
4397 >    }
4398 >
4399 >    /**
4400 >     * Returns the result of accumulating the given transformation
4401 >     * of all entries using the given reducer to combine values,
4402 >     * and the given basis as an identity value.
4403 >     *
4404 >     * @param transformer a function returning the transformation
4405 >     * for an element
4406 >     * @param basis the identity (initial default value) for the reduction
4407 >     * @param reducer a commutative associative combining function
4408 >     * @return the result of accumulating the given transformation
4409 >     * of all entries
4410 >     */
4411 >    public double reduceEntriesToDoubleInParallel
4412 >        (ToDoubleFunction<Map.Entry<K,V>> transformer,
4413 >         double basis,
4414 >         DoubleBinaryOperator reducer) {
4415 >        return ForkJoinTasks.reduceEntriesToDouble
4416 >            (this, transformer, basis, reducer).invoke();
4417 >    }
4418 >
4419 >    /**
4420 >     * Returns the result of accumulating the given transformation
4421 >     * of all entries using the given reducer to combine values,
4422 >     * and the given basis as an identity value.
4423 >     *
4424 >     * @param transformer a function returning the transformation
4425 >     * for an element
4426 >     * @param basis the identity (initial default value) for the reduction
4427 >     * @param reducer a commutative associative combining function
4428 >     * @return the result of accumulating the given transformation
4429 >     * of all entries
4430 >     */
4431 >    public long reduceEntriesToLongInParallel
4432 >        (ToLongFunction<Map.Entry<K,V>> transformer,
4433 >         long basis,
4434 >         LongBinaryOperator reducer) {
4435 >        return ForkJoinTasks.reduceEntriesToLong
4436 >            (this, transformer, basis, reducer).invoke();
4437 >    }
4438 >
4439 >    /**
4440 >     * Returns the result of accumulating the given transformation
4441 >     * of all entries using the given reducer to combine values,
4442 >     * and the given basis as an identity value.
4443 >     *
4444 >     * @param transformer a function returning the transformation
4445 >     * for an element
4446 >     * @param basis the identity (initial default value) for the reduction
4447 >     * @param reducer a commutative associative combining function
4448 >     * @return the result of accumulating the given transformation
4449 >     * of all entries
4450 >     */
4451 >    public int reduceEntriesToIntInParallel
4452 >        (ToIntFunction<Map.Entry<K,V>> transformer,
4453 >         int basis,
4454 >         IntBinaryOperator reducer) {
4455 >        return ForkJoinTasks.reduceEntriesToInt
4456 >            (this, transformer, basis, reducer).invoke();
4457 >    }
4458 >
4459 >
4460 >    /* ----------------Views -------------- */
4461 >
4462 >    /**
4463 >     * Base class for views.
4464 >     */
4465 >    abstract static class CHMCollectionView<K,V,E>
4466 >            implements Collection<E>, java.io.Serializable {
4467 >        private static final long serialVersionUID = 7249069246763182397L;
4468 >        final ConcurrentHashMap<K,V> map;
4469 >        CHMCollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4470 >
4471 >        /**
4472 >         * Returns the map backing this view.
4473 >         *
4474 >         * @return the map backing this view
4475 >         */
4476 >        public ConcurrentHashMap<K,V> getMap() { return map; }
4477 >
4478 >        /**
4479 >         * Removes all of the elements from this view, by removing all
4480 >         * the mappings from the map backing this view.
4481 >         */
4482 >        public final void clear()      { map.clear(); }
4483 >        public final int size()        { return map.size(); }
4484 >        public final boolean isEmpty() { return map.isEmpty(); }
4485 >
4486 >        // implementations below rely on concrete classes supplying these
4487 >        // abstract methods
4488 >        /**
4489 >         * Returns a "weakly consistent" iterator that will never
4490 >         * throw {@link ConcurrentModificationException}, and
4491 >         * guarantees to traverse elements as they existed upon
4492 >         * construction of the iterator, and may (but is not
4493 >         * guaranteed to) reflect any modifications subsequent to
4494 >         * construction.
4495 >         */
4496 >        public abstract Iterator<E> iterator();
4497 >        public abstract boolean contains(Object o);
4498 >        public abstract boolean remove(Object o);
4499 >
4500 >        private static final String oomeMsg = "Required array size too large";
4501 >
4502 >        public final Object[] toArray() {
4503 >            long sz = map.mappingCount();
4504 >            if (sz > MAX_ARRAY_SIZE)
4505 >                throw new OutOfMemoryError(oomeMsg);
4506 >            int n = (int)sz;
4507 >            Object[] r = new Object[n];
4508 >            int i = 0;
4509 >            for (E e : this) {
4510 >                if (i == n) {
4511 >                    if (n >= MAX_ARRAY_SIZE)
4512 >                        throw new OutOfMemoryError(oomeMsg);
4513 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4514 >                        n = MAX_ARRAY_SIZE;
4515 >                    else
4516 >                        n += (n >>> 1) + 1;
4517 >                    r = Arrays.copyOf(r, n);
4518 >                }
4519 >                r[i++] = e;
4520 >            }
4521 >            return (i == n) ? r : Arrays.copyOf(r, i);
4522 >        }
4523 >
4524 >        @SuppressWarnings("unchecked")
4525 >        public final <T> T[] toArray(T[] a) {
4526 >            long sz = map.mappingCount();
4527 >            if (sz > MAX_ARRAY_SIZE)
4528 >                throw new OutOfMemoryError(oomeMsg);
4529 >            int m = (int)sz;
4530 >            T[] r = (a.length >= m) ? a :
4531 >                (T[])java.lang.reflect.Array
4532 >                .newInstance(a.getClass().getComponentType(), m);
4533 >            int n = r.length;
4534 >            int i = 0;
4535 >            for (E e : this) {
4536 >                if (i == n) {
4537 >                    if (n >= MAX_ARRAY_SIZE)
4538 >                        throw new OutOfMemoryError(oomeMsg);
4539 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4540 >                        n = MAX_ARRAY_SIZE;
4541 >                    else
4542 >                        n += (n >>> 1) + 1;
4543 >                    r = Arrays.copyOf(r, n);
4544 >                }
4545 >                r[i++] = (T)e;
4546 >            }
4547 >            if (a == r && i < n) {
4548 >                r[i] = null; // null-terminate
4549 >                return r;
4550 >            }
4551 >            return (i == n) ? r : Arrays.copyOf(r, i);
4552 >        }
4553 >
4554 >        /**
4555 >         * Returns a string representation of this collection.
4556 >         * The string representation consists of the string representations
4557 >         * of the collection's elements in the order they are returned by
4558 >         * its iterator, enclosed in square brackets ({@code "[]"}).
4559 >         * Adjacent elements are separated by the characters {@code ", "}
4560 >         * (comma and space).  Elements are converted to strings as by
4561 >         * {@link String#valueOf(Object)}.
4562 >         *
4563 >         * @return a string representation of this collection
4564 >         */
4565 >        public final String toString() {
4566 >            StringBuilder sb = new StringBuilder();
4567 >            sb.append('[');
4568 >            Iterator<E> it = iterator();
4569 >            if (it.hasNext()) {
4570 >                for (;;) {
4571 >                    Object e = it.next();
4572 >                    sb.append(e == this ? "(this Collection)" : e);
4573 >                    if (!it.hasNext())
4574 >                        break;
4575 >                    sb.append(',').append(' ');
4576 >                }
4577 >            }
4578 >            return sb.append(']').toString();
4579 >        }
4580 >
4581 >        public final boolean containsAll(Collection<?> c) {
4582 >            if (c != this) {
4583 >                for (Object e : c) {
4584 >                    if (e == null || !contains(e))
4585 >                        return false;
4586 >                }
4587 >            }
4588 >            return true;
4589 >        }
4590 >
4591 >        public final boolean removeAll(Collection<?> c) {
4592 >            boolean modified = false;
4593 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4594 >                if (c.contains(it.next())) {
4595 >                    it.remove();
4596 >                    modified = true;
4597 >                }
4598 >            }
4599 >            return modified;
4600 >        }
4601 >
4602 >        public final boolean retainAll(Collection<?> c) {
4603 >            boolean modified = false;
4604 >            for (Iterator<E> it = iterator(); it.hasNext();) {
4605 >                if (!c.contains(it.next())) {
4606 >                    it.remove();
4607 >                    modified = true;
4608 >                }
4609 >            }
4610 >            return modified;
4611 >        }
4612 >
4613 >    }
4614 >
4615 >    abstract static class CHMSetView<K,V,E>
4616 >            extends CHMCollectionView<K,V,E>
4617 >            implements Set<E>, java.io.Serializable {
4618 >        private static final long serialVersionUID = 7249069246763182397L;
4619 >        CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4620 >
4621 >        // Implement Set API
4622 >
4623 >        /**
4624 >         * Implements {@link Set#hashCode()}.
4625 >         * @return the hash code value for this set
4626 >         */
4627 >        public final int hashCode() {
4628 >            int h = 0;
4629 >            for (E e : this)
4630 >                h += e.hashCode();
4631 >            return h;
4632 >        }
4633 >
4634 >        /**
4635 >         * Implements {@link Set#equals(Object)}.
4636 >         * @param o object to be compared for equality with this set
4637 >         * @return {@code true} if the specified object is equal to this set
4638 >        */
4639 >        public final boolean equals(Object o) {
4640 >            Set<?> c;
4641 >            return ((o instanceof Set) &&
4642 >                    ((c = (Set<?>)o) == this ||
4643 >                     (containsAll(c) && c.containsAll(this))));
4644 >        }
4645 >    }
4646 >
4647 >    /**
4648 >     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4649 >     * which additions may optionally be enabled by mapping to a
4650 >     * common value.  This class cannot be directly instantiated.
4651 >     * See {@link #keySet() keySet()},
4652 >     * {@link #keySet(Object) keySet(V)},
4653 >     * {@link #newKeySet() newKeySet()},
4654 >     * {@link #newKeySet(int) newKeySet(int)}.
4655 >     */
4656 >    public static class KeySetView<K,V>
4657 >            extends CHMSetView<K,V,K>
4658 >            implements Set<K>, java.io.Serializable {
4659 >        private static final long serialVersionUID = 7249069246763182397L;
4660 >        private final V value;
4661 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4662 >            super(map);
4663 >            this.value = value;
4664 >        }
4665 >
4666 >        /**
4667 >         * Returns the default mapped value for additions,
4668 >         * or {@code null} if additions are not supported.
4669 >         *
4670 >         * @return the default mapped value for additions, or {@code null}
4671 >         * if not supported
4672 >         */
4673 >        public V getMappedValue() { return value; }
4674 >
4675 >        /**
4676 >         * {@inheritDoc}
4677 >         * @throws NullPointerException if the specified key is null
4678 >         */
4679 >        public boolean contains(Object o) { return map.containsKey(o); }
4680 >
4681 >        /**
4682 >         * Removes the key from this map view, by removing the key (and its
4683 >         * corresponding value) from the backing map.  This method does
4684 >         * nothing if the key is not in the map.
4685 >         *
4686 >         * @param  o the key to be removed from the backing map
4687 >         * @return {@code true} if the backing map contained the specified key
4688 >         * @throws NullPointerException if the specified key is null
4689 >         */
4690 >        public boolean remove(Object o) { return map.remove(o) != null; }
4691 >
4692 >        /**
4693 >         * @return an iterator over the keys of the backing map
4694 >         */
4695 >        public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4696 >
4697 >        /**
4698 >         * Adds the specified key to this set view by mapping the key to
4699 >         * the default mapped value in the backing map, if defined.
4700 >         *
4701 >         * @param e key to be added
4702 >         * @return {@code true} if this set changed as a result of the call
4703 >         * @throws NullPointerException if the specified key is null
4704 >         * @throws UnsupportedOperationException if no default mapped value
4705 >         * for additions was provided
4706 >         */
4707 >        public boolean add(K e) {
4708 >            V v;
4709 >            if ((v = value) == null)
4710 >                throw new UnsupportedOperationException();
4711 >            return map.internalPut(e, v, true) == null;
4712 >        }
4713 >
4714 >        /**
4715 >         * Adds all of the elements in the specified collection to this set,
4716 >         * as if by calling {@link #add} on each one.
4717 >         *
4718 >         * @param c the elements to be inserted into this set
4719 >         * @return {@code true} if this set changed as a result of the call
4720 >         * @throws NullPointerException if the collection or any of its
4721 >         * elements are {@code null}
4722 >         * @throws UnsupportedOperationException if no default mapped value
4723 >         * for additions was provided
4724 >         */
4725 >        public boolean addAll(Collection<? extends K> c) {
4726 >            boolean added = false;
4727 >            V v;
4728 >            if ((v = value) == null)
4729 >                throw new UnsupportedOperationException();
4730 >            for (K e : c) {
4731 >                if (map.internalPut(e, v, true) == null)
4732 >                    added = true;
4733 >            }
4734 >            return added;
4735 >        }
4736 >
4737 >        public Stream<K> stream() {
4738 >            return Streams.stream(() -> new KeyIterator<K,V>(map), 0);
4739 >        }
4740 >        public Stream<K> parallelStream() {
4741 >            return Streams.parallelStream(() -> new KeyIterator<K,V>(map, null),
4742 >                                          0);
4743 >        }
4744 >    }
4745 >
4746 >    /**
4747 >     * A view of a ConcurrentHashMap as a {@link Collection} of
4748 >     * values, in which additions are disabled. This class cannot be
4749 >     * directly instantiated. See {@link #values()}.
4750 >     *
4751 >     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4752 >     * that will never throw {@link ConcurrentModificationException},
4753 >     * and guarantees to traverse elements as they existed upon
4754 >     * construction of the iterator, and may (but is not guaranteed to)
4755 >     * reflect any modifications subsequent to construction.
4756 >     */
4757 >    public static final class ValuesView<K,V>
4758 >            extends CHMCollectionView<K,V,V>
4759 >            implements Collection<V>, java.io.Serializable {
4760 >        private static final long serialVersionUID = 2249069246763182397L;
4761 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4762 >        public final boolean contains(Object o) {
4763 >            return map.containsValue(o);
4764 >        }
4765 >        public final boolean remove(Object o) {
4766 >            if (o != null) {
4767 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4768 >                    if (o.equals(it.next())) {
4769 >                        it.remove();
4770 >                        return true;
4771                      }
4772                  }
1427            } finally {
1428                seg.unlock();
4773              }
4774 +            return false;
4775          }
4776 <        s.writeObject(null);
4777 <        s.writeObject(null);
4776 >
4777 >        /**
4778 >         * @return an iterator over the values of the backing map
4779 >         */
4780 >        public final Iterator<V> iterator() {
4781 >            return new ValueIterator<K,V>(map);
4782 >        }
4783 >
4784 >        /** Always throws {@link UnsupportedOperationException}. */
4785 >        public final boolean add(V e) {
4786 >            throw new UnsupportedOperationException();
4787 >        }
4788 >        /** Always throws {@link UnsupportedOperationException}. */
4789 >        public final boolean addAll(Collection<? extends V> c) {
4790 >            throw new UnsupportedOperationException();
4791 >        }
4792 >
4793 >        public Stream<V> stream() {
4794 >            return Streams.stream(() -> new ValueIterator<K,V>(map), 0);
4795 >        }
4796 >
4797 >        public Stream<V> parallelStream() {
4798 >            return Streams.parallelStream(() -> new ValueIterator<K,V>(map, null),
4799 >                                          0);
4800 >        }
4801 >
4802      }
4803  
4804      /**
4805 <     * Reconstitutes the <tt>ConcurrentHashMap</tt> instance from a
4806 <     * stream (i.e., deserializes it).
4807 <     * @param s the stream
4805 >     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4806 >     * entries.  This class cannot be directly instantiated. See
4807 >     * {@link #entrySet()}.
4808       */
4809 <    @SuppressWarnings("unchecked")
4810 <    private void readObject(java.io.ObjectInputStream s)
4811 <        throws IOException, ClassNotFoundException {
4812 <        s.defaultReadObject();
4809 >    public static final class EntrySetView<K,V>
4810 >            extends CHMSetView<K,V,Map.Entry<K,V>>
4811 >            implements Set<Map.Entry<K,V>>, java.io.Serializable {
4812 >        private static final long serialVersionUID = 2249069246763182397L;
4813 >        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4814 >
4815 >        public final boolean contains(Object o) {
4816 >            Object k, v, r; Map.Entry<?,?> e;
4817 >            return ((o instanceof Map.Entry) &&
4818 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4819 >                    (r = map.get(k)) != null &&
4820 >                    (v = e.getValue()) != null &&
4821 >                    (v == r || v.equals(r)));
4822 >        }
4823 >        public final boolean remove(Object o) {
4824 >            Object k, v; Map.Entry<?,?> e;
4825 >            return ((o instanceof Map.Entry) &&
4826 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4827 >                    (v = e.getValue()) != null &&
4828 >                    map.remove(k, v));
4829 >        }
4830 >
4831 >        /**
4832 >         * @return an iterator over the entries of the backing map
4833 >         */
4834 >        public final Iterator<Map.Entry<K,V>> iterator() {
4835 >            return new EntryIterator<K,V>(map);
4836 >        }
4837 >
4838 >        /**
4839 >         * Adds the specified mapping to this view.
4840 >         *
4841 >         * @param e mapping to be added
4842 >         * @return {@code true} if this set changed as a result of the call
4843 >         * @throws NullPointerException if the entry, its key, or its
4844 >         * value is null
4845 >         */
4846 >        public final boolean add(Entry<K,V> e) {
4847 >            return map.internalPut(e.getKey(), e.getValue(), false) == null;
4848 >        }
4849 >        /**
4850 >         * Adds all of the mappings in the specified collection to this
4851 >         * set, as if by calling {@link #add(Map.Entry)} on each one.
4852 >         * @param c the mappings to be inserted into this set
4853 >         * @return {@code true} if this set changed as a result of the call
4854 >         * @throws NullPointerException if the collection or any of its
4855 >         * entries, keys, or values are null
4856 >         */
4857 >        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4858 >            boolean added = false;
4859 >            for (Entry<K,V> e : c) {
4860 >                if (add(e))
4861 >                    added = true;
4862 >            }
4863 >            return added;
4864 >        }
4865 >
4866 >        public Stream<Map.Entry<K,V>> stream() {
4867 >            return Streams.stream(() -> new EntryIterator<K,V>(map), 0);
4868 >        }
4869 >
4870 >        public Stream<Map.Entry<K,V>> parallelStream() {
4871 >            return Streams.parallelStream(() -> new EntryIterator<K,V>(map, null),
4872 >                                          0);
4873 >        }
4874 >    }
4875 >
4876 >    // ---------------------------------------------------------------------
4877 >
4878 >    /**
4879 >     * Predefined tasks for performing bulk parallel operations on
4880 >     * ConcurrentHashMaps. These tasks follow the forms and rules used
4881 >     * for bulk operations. Each method has the same name, but returns
4882 >     * a task rather than invoking it. These methods may be useful in
4883 >     * custom applications such as submitting a task without waiting
4884 >     * for completion, using a custom pool, or combining with other
4885 >     * tasks.
4886 >     */
4887 >    public static class ForkJoinTasks {
4888 >        private ForkJoinTasks() {}
4889 >
4890 >        /**
4891 >         * Returns a task that when invoked, performs the given
4892 >         * action for each (key, value)
4893 >         *
4894 >         * @param map the map
4895 >         * @param action the action
4896 >         * @return the task
4897 >         */
4898 >        public static <K,V> ForkJoinTask<Void> forEach
4899 >            (ConcurrentHashMap<K,V> map,
4900 >             BiConsumer<? super K, ? super V> action) {
4901 >            if (action == null) throw new NullPointerException();
4902 >            return new ForEachMappingTask<K,V>(map, null, -1, action);
4903 >        }
4904 >
4905 >        /**
4906 >         * Returns a task that when invoked, performs the given
4907 >         * action for each non-null transformation of each (key, value)
4908 >         *
4909 >         * @param map the map
4910 >         * @param transformer a function returning the transformation
4911 >         * for an element, or null if there is no transformation (in
4912 >         * which case the action is not applied)
4913 >         * @param action the action
4914 >         * @return the task
4915 >         */
4916 >        public static <K,V,U> ForkJoinTask<Void> forEach
4917 >            (ConcurrentHashMap<K,V> map,
4918 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4919 >             Consumer<? super U> action) {
4920 >            if (transformer == null || action == null)
4921 >                throw new NullPointerException();
4922 >            return new ForEachTransformedMappingTask<K,V,U>
4923 >                (map, null, -1, transformer, action);
4924 >        }
4925 >
4926 >        /**
4927 >         * Returns a task that when invoked, returns a non-null result
4928 >         * from applying the given search function on each (key,
4929 >         * value), or null if none. Upon success, further element
4930 >         * processing is suppressed and the results of any other
4931 >         * parallel invocations of the search function are ignored.
4932 >         *
4933 >         * @param map the map
4934 >         * @param searchFunction a function returning a non-null
4935 >         * result on success, else null
4936 >         * @return the task
4937 >         */
4938 >        public static <K,V,U> ForkJoinTask<U> search
4939 >            (ConcurrentHashMap<K,V> map,
4940 >             BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4941 >            if (searchFunction == null) throw new NullPointerException();
4942 >            return new SearchMappingsTask<K,V,U>
4943 >                (map, null, -1, searchFunction,
4944 >                 new AtomicReference<U>());
4945 >        }
4946 >
4947 >        /**
4948 >         * Returns a task that when invoked, returns the result of
4949 >         * accumulating the given transformation of all (key, value) pairs
4950 >         * using the given reducer to combine values, or null if none.
4951 >         *
4952 >         * @param map the map
4953 >         * @param transformer a function returning the transformation
4954 >         * for an element, or null if there is no transformation (in
4955 >         * which case it is not combined)
4956 >         * @param reducer a commutative associative combining function
4957 >         * @return the task
4958 >         */
4959 >        public static <K,V,U> ForkJoinTask<U> reduce
4960 >            (ConcurrentHashMap<K,V> map,
4961 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4962 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
4963 >            if (transformer == null || reducer == null)
4964 >                throw new NullPointerException();
4965 >            return new MapReduceMappingsTask<K,V,U>
4966 >                (map, null, -1, null, transformer, reducer);
4967 >        }
4968 >
4969 >        /**
4970 >         * Returns a task that when invoked, returns the result of
4971 >         * accumulating the given transformation of all (key, value) pairs
4972 >         * using the given reducer to combine values, and the given
4973 >         * basis as an identity value.
4974 >         *
4975 >         * @param map the map
4976 >         * @param transformer a function returning the transformation
4977 >         * for an element
4978 >         * @param basis the identity (initial default value) for the reduction
4979 >         * @param reducer a commutative associative combining function
4980 >         * @return the task
4981 >         */
4982 >        public static <K,V> ForkJoinTask<Double> reduceToDouble
4983 >            (ConcurrentHashMap<K,V> map,
4984 >             ToDoubleBiFunction<? super K, ? super V> transformer,
4985 >             double basis,
4986 >             DoubleBinaryOperator reducer) {
4987 >            if (transformer == null || reducer == null)
4988 >                throw new NullPointerException();
4989 >            return new MapReduceMappingsToDoubleTask<K,V>
4990 >                (map, null, -1, null, transformer, basis, reducer);
4991 >        }
4992 >
4993 >        /**
4994 >         * Returns a task that when invoked, returns the result of
4995 >         * accumulating the given transformation of all (key, value) pairs
4996 >         * using the given reducer to combine values, and the given
4997 >         * basis as an identity value.
4998 >         *
4999 >         * @param map the map
5000 >         * @param transformer a function returning the transformation
5001 >         * for an element
5002 >         * @param basis the identity (initial default value) for the reduction
5003 >         * @param reducer a commutative associative combining function
5004 >         * @return the task
5005 >         */
5006 >        public static <K,V> ForkJoinTask<Long> reduceToLong
5007 >            (ConcurrentHashMap<K,V> map,
5008 >             ToLongBiFunction<? super K, ? super V> transformer,
5009 >             long basis,
5010 >             LongBinaryOperator reducer) {
5011 >            if (transformer == null || reducer == null)
5012 >                throw new NullPointerException();
5013 >            return new MapReduceMappingsToLongTask<K,V>
5014 >                (map, null, -1, null, transformer, basis, reducer);
5015 >        }
5016  
5017 <        // Re-initialize segments to be minimally sized, and let grow.
5018 <        int cap = MIN_SEGMENT_TABLE_CAPACITY;
5019 <        final Segment<K,V>[] segments = this.segments;
5020 <        for (int k = 0; k < segments.length; ++k) {
5021 <            Segment<K,V> seg = segments[k];
5022 <            if (seg != null) {
5023 <                seg.threshold = (int)(cap * seg.loadFactor);
5024 <                seg.table = (HashEntry<K,V>[]) new HashEntry[cap];
5017 >        /**
5018 >         * Returns a task that when invoked, returns the result of
5019 >         * accumulating the given transformation of all (key, value) pairs
5020 >         * using the given reducer to combine values, and the given
5021 >         * basis as an identity value.
5022 >         *
5023 >         * @param map the map
5024 >         * @param transformer a function returning the transformation
5025 >         * for an element
5026 >         * @param basis the identity (initial default value) for the reduction
5027 >         * @param reducer a commutative associative combining function
5028 >         * @return the task
5029 >         */
5030 >        public static <K,V> ForkJoinTask<Integer> reduceToInt
5031 >            (ConcurrentHashMap<K,V> map,
5032 >             ToIntBiFunction<? super K, ? super V> transformer,
5033 >             int basis,
5034 >             IntBinaryOperator reducer) {
5035 >            if (transformer == null || reducer == null)
5036 >                throw new NullPointerException();
5037 >            return new MapReduceMappingsToIntTask<K,V>
5038 >                (map, null, -1, null, transformer, basis, reducer);
5039 >        }
5040 >
5041 >        /**
5042 >         * Returns a task that when invoked, performs the given action
5043 >         * for each key.
5044 >         *
5045 >         * @param map the map
5046 >         * @param action the action
5047 >         * @return the task
5048 >         */
5049 >        public static <K,V> ForkJoinTask<Void> forEachKey
5050 >            (ConcurrentHashMap<K,V> map,
5051 >             Consumer<? super K> action) {
5052 >            if (action == null) throw new NullPointerException();
5053 >            return new ForEachKeyTask<K,V>(map, null, -1, action);
5054 >        }
5055 >
5056 >        /**
5057 >         * Returns a task that when invoked, performs the given action
5058 >         * for each non-null transformation of each key.
5059 >         *
5060 >         * @param map the map
5061 >         * @param transformer a function returning the transformation
5062 >         * for an element, or null if there is no transformation (in
5063 >         * which case the action is not applied)
5064 >         * @param action the action
5065 >         * @return the task
5066 >         */
5067 >        public static <K,V,U> ForkJoinTask<Void> forEachKey
5068 >            (ConcurrentHashMap<K,V> map,
5069 >             Function<? super K, ? extends U> transformer,
5070 >             Consumer<? super U> action) {
5071 >            if (transformer == null || action == null)
5072 >                throw new NullPointerException();
5073 >            return new ForEachTransformedKeyTask<K,V,U>
5074 >                (map, null, -1, transformer, action);
5075 >        }
5076 >
5077 >        /**
5078 >         * Returns a task that when invoked, returns a non-null result
5079 >         * from applying the given search function on each key, or
5080 >         * null if none.  Upon success, further element processing is
5081 >         * suppressed and the results of any other parallel
5082 >         * invocations of the search function are ignored.
5083 >         *
5084 >         * @param map the map
5085 >         * @param searchFunction a function returning a non-null
5086 >         * result on success, else null
5087 >         * @return the task
5088 >         */
5089 >        public static <K,V,U> ForkJoinTask<U> searchKeys
5090 >            (ConcurrentHashMap<K,V> map,
5091 >             Function<? super K, ? extends U> searchFunction) {
5092 >            if (searchFunction == null) throw new NullPointerException();
5093 >            return new SearchKeysTask<K,V,U>
5094 >                (map, null, -1, searchFunction,
5095 >                 new AtomicReference<U>());
5096 >        }
5097 >
5098 >        /**
5099 >         * Returns a task that when invoked, returns the result of
5100 >         * accumulating all keys using the given reducer to combine
5101 >         * values, or null if none.
5102 >         *
5103 >         * @param map the map
5104 >         * @param reducer a commutative associative combining function
5105 >         * @return the task
5106 >         */
5107 >        public static <K,V> ForkJoinTask<K> reduceKeys
5108 >            (ConcurrentHashMap<K,V> map,
5109 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5110 >            if (reducer == null) throw new NullPointerException();
5111 >            return new ReduceKeysTask<K,V>
5112 >                (map, null, -1, null, reducer);
5113 >        }
5114 >
5115 >        /**
5116 >         * Returns a task that when invoked, returns the result of
5117 >         * accumulating the given transformation of all keys using the given
5118 >         * reducer to combine values, or null if none.
5119 >         *
5120 >         * @param map the map
5121 >         * @param transformer a function returning the transformation
5122 >         * for an element, or null if there is no transformation (in
5123 >         * which case it is not combined)
5124 >         * @param reducer a commutative associative combining function
5125 >         * @return the task
5126 >         */
5127 >        public static <K,V,U> ForkJoinTask<U> reduceKeys
5128 >            (ConcurrentHashMap<K,V> map,
5129 >             Function<? super K, ? extends U> transformer,
5130 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5131 >            if (transformer == null || reducer == null)
5132 >                throw new NullPointerException();
5133 >            return new MapReduceKeysTask<K,V,U>
5134 >                (map, null, -1, null, transformer, reducer);
5135 >        }
5136 >
5137 >        /**
5138 >         * Returns a task that when invoked, returns the result of
5139 >         * accumulating the given transformation of all keys using the given
5140 >         * reducer to combine values, and the given basis as an
5141 >         * identity value.
5142 >         *
5143 >         * @param map the map
5144 >         * @param transformer a function returning the transformation
5145 >         * for an element
5146 >         * @param basis the identity (initial default value) for the reduction
5147 >         * @param reducer a commutative associative combining function
5148 >         * @return the task
5149 >         */
5150 >        public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5151 >            (ConcurrentHashMap<K,V> map,
5152 >             ToDoubleFunction<? super K> transformer,
5153 >             double basis,
5154 >             DoubleBinaryOperator reducer) {
5155 >            if (transformer == null || reducer == null)
5156 >                throw new NullPointerException();
5157 >            return new MapReduceKeysToDoubleTask<K,V>
5158 >                (map, null, -1, null, transformer, basis, reducer);
5159 >        }
5160 >
5161 >        /**
5162 >         * Returns a task that when invoked, returns the result of
5163 >         * accumulating the given transformation of all keys using the given
5164 >         * reducer to combine values, and the given basis as an
5165 >         * identity value.
5166 >         *
5167 >         * @param map the map
5168 >         * @param transformer a function returning the transformation
5169 >         * for an element
5170 >         * @param basis the identity (initial default value) for the reduction
5171 >         * @param reducer a commutative associative combining function
5172 >         * @return the task
5173 >         */
5174 >        public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5175 >            (ConcurrentHashMap<K,V> map,
5176 >             ToLongFunction<? super K> transformer,
5177 >             long basis,
5178 >             LongBinaryOperator reducer) {
5179 >            if (transformer == null || reducer == null)
5180 >                throw new NullPointerException();
5181 >            return new MapReduceKeysToLongTask<K,V>
5182 >                (map, null, -1, null, transformer, basis, reducer);
5183 >        }
5184 >
5185 >        /**
5186 >         * Returns a task that when invoked, returns the result of
5187 >         * accumulating the given transformation of all keys using the given
5188 >         * reducer to combine values, and the given basis as an
5189 >         * identity value.
5190 >         *
5191 >         * @param map the map
5192 >         * @param transformer a function returning the transformation
5193 >         * for an element
5194 >         * @param basis the identity (initial default value) for the reduction
5195 >         * @param reducer a commutative associative combining function
5196 >         * @return the task
5197 >         */
5198 >        public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5199 >            (ConcurrentHashMap<K,V> map,
5200 >             ToIntFunction<? super K> transformer,
5201 >             int basis,
5202 >             IntBinaryOperator reducer) {
5203 >            if (transformer == null || reducer == null)
5204 >                throw new NullPointerException();
5205 >            return new MapReduceKeysToIntTask<K,V>
5206 >                (map, null, -1, null, transformer, basis, reducer);
5207 >        }
5208 >
5209 >        /**
5210 >         * Returns a task that when invoked, performs the given action
5211 >         * for each value.
5212 >         *
5213 >         * @param map the map
5214 >         * @param action the action
5215 >         * @return the task
5216 >         */
5217 >        public static <K,V> ForkJoinTask<Void> forEachValue
5218 >            (ConcurrentHashMap<K,V> map,
5219 >             Consumer<? super V> action) {
5220 >            if (action == null) throw new NullPointerException();
5221 >            return new ForEachValueTask<K,V>(map, null, -1, action);
5222 >        }
5223 >
5224 >        /**
5225 >         * Returns a task that when invoked, performs the given action
5226 >         * for each non-null transformation of each value.
5227 >         *
5228 >         * @param map the map
5229 >         * @param transformer a function returning the transformation
5230 >         * for an element, or null if there is no transformation (in
5231 >         * which case the action is not applied)
5232 >         * @param action the action
5233 >         * @return the task
5234 >         */
5235 >        public static <K,V,U> ForkJoinTask<Void> forEachValue
5236 >            (ConcurrentHashMap<K,V> map,
5237 >             Function<? super V, ? extends U> transformer,
5238 >             Consumer<? super U> action) {
5239 >            if (transformer == null || action == null)
5240 >                throw new NullPointerException();
5241 >            return new ForEachTransformedValueTask<K,V,U>
5242 >                (map, null, -1, transformer, action);
5243 >        }
5244 >
5245 >        /**
5246 >         * Returns a task that when invoked, returns a non-null result
5247 >         * from applying the given search function on each value, or
5248 >         * null if none.  Upon success, further element processing is
5249 >         * suppressed and the results of any other parallel
5250 >         * invocations of the search function are ignored.
5251 >         *
5252 >         * @param map the map
5253 >         * @param searchFunction a function returning a non-null
5254 >         * result on success, else null
5255 >         * @return the task
5256 >         */
5257 >        public static <K,V,U> ForkJoinTask<U> searchValues
5258 >            (ConcurrentHashMap<K,V> map,
5259 >             Function<? super V, ? extends U> searchFunction) {
5260 >            if (searchFunction == null) throw new NullPointerException();
5261 >            return new SearchValuesTask<K,V,U>
5262 >                (map, null, -1, searchFunction,
5263 >                 new AtomicReference<U>());
5264 >        }
5265 >
5266 >        /**
5267 >         * Returns a task that when invoked, returns the result of
5268 >         * accumulating all values using the given reducer to combine
5269 >         * values, or null if none.
5270 >         *
5271 >         * @param map the map
5272 >         * @param reducer a commutative associative combining function
5273 >         * @return the task
5274 >         */
5275 >        public static <K,V> ForkJoinTask<V> reduceValues
5276 >            (ConcurrentHashMap<K,V> map,
5277 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5278 >            if (reducer == null) throw new NullPointerException();
5279 >            return new ReduceValuesTask<K,V>
5280 >                (map, null, -1, null, reducer);
5281 >        }
5282 >
5283 >        /**
5284 >         * Returns a task that when invoked, returns the result of
5285 >         * accumulating the given transformation of all values using the
5286 >         * given reducer to combine values, or null if none.
5287 >         *
5288 >         * @param map the map
5289 >         * @param transformer a function returning the transformation
5290 >         * for an element, or null if there is no transformation (in
5291 >         * which case it is not combined)
5292 >         * @param reducer a commutative associative combining function
5293 >         * @return the task
5294 >         */
5295 >        public static <K,V,U> ForkJoinTask<U> reduceValues
5296 >            (ConcurrentHashMap<K,V> map,
5297 >             Function<? super V, ? extends U> transformer,
5298 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5299 >            if (transformer == null || reducer == null)
5300 >                throw new NullPointerException();
5301 >            return new MapReduceValuesTask<K,V,U>
5302 >                (map, null, -1, null, transformer, reducer);
5303 >        }
5304 >
5305 >        /**
5306 >         * Returns a task that when invoked, returns the result of
5307 >         * accumulating the given transformation of all values using the
5308 >         * given reducer to combine values, and the given basis as an
5309 >         * identity value.
5310 >         *
5311 >         * @param map the map
5312 >         * @param transformer a function returning the transformation
5313 >         * for an element
5314 >         * @param basis the identity (initial default value) for the reduction
5315 >         * @param reducer a commutative associative combining function
5316 >         * @return the task
5317 >         */
5318 >        public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5319 >            (ConcurrentHashMap<K,V> map,
5320 >             ToDoubleFunction<? super V> transformer,
5321 >             double basis,
5322 >             DoubleBinaryOperator reducer) {
5323 >            if (transformer == null || reducer == null)
5324 >                throw new NullPointerException();
5325 >            return new MapReduceValuesToDoubleTask<K,V>
5326 >                (map, null, -1, null, transformer, basis, reducer);
5327 >        }
5328 >
5329 >        /**
5330 >         * Returns a task that when invoked, returns the result of
5331 >         * accumulating the given transformation of all values using the
5332 >         * given reducer to combine values, and the given basis as an
5333 >         * identity value.
5334 >         *
5335 >         * @param map the map
5336 >         * @param transformer a function returning the transformation
5337 >         * for an element
5338 >         * @param basis the identity (initial default value) for the reduction
5339 >         * @param reducer a commutative associative combining function
5340 >         * @return the task
5341 >         */
5342 >        public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5343 >            (ConcurrentHashMap<K,V> map,
5344 >             ToLongFunction<? super V> transformer,
5345 >             long basis,
5346 >             LongBinaryOperator reducer) {
5347 >            if (transformer == null || reducer == null)
5348 >                throw new NullPointerException();
5349 >            return new MapReduceValuesToLongTask<K,V>
5350 >                (map, null, -1, null, transformer, basis, reducer);
5351 >        }
5352 >
5353 >        /**
5354 >         * Returns a task that when invoked, returns the result of
5355 >         * accumulating the given transformation of all values using the
5356 >         * given reducer to combine values, and the given basis as an
5357 >         * identity value.
5358 >         *
5359 >         * @param map the map
5360 >         * @param transformer a function returning the transformation
5361 >         * for an element
5362 >         * @param basis the identity (initial default value) for the reduction
5363 >         * @param reducer a commutative associative combining function
5364 >         * @return the task
5365 >         */
5366 >        public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5367 >            (ConcurrentHashMap<K,V> map,
5368 >             ToIntFunction<? super V> transformer,
5369 >             int basis,
5370 >             IntBinaryOperator reducer) {
5371 >            if (transformer == null || reducer == null)
5372 >                throw new NullPointerException();
5373 >            return new MapReduceValuesToIntTask<K,V>
5374 >                (map, null, -1, null, transformer, basis, reducer);
5375 >        }
5376 >
5377 >        /**
5378 >         * Returns a task that when invoked, perform the given action
5379 >         * for each entry.
5380 >         *
5381 >         * @param map the map
5382 >         * @param action the action
5383 >         * @return the task
5384 >         */
5385 >        public static <K,V> ForkJoinTask<Void> forEachEntry
5386 >            (ConcurrentHashMap<K,V> map,
5387 >             Consumer<? super Map.Entry<K,V>> action) {
5388 >            if (action == null) throw new NullPointerException();
5389 >            return new ForEachEntryTask<K,V>(map, null, -1, action);
5390 >        }
5391 >
5392 >        /**
5393 >         * Returns a task that when invoked, perform the given action
5394 >         * for each non-null transformation of each entry.
5395 >         *
5396 >         * @param map the map
5397 >         * @param transformer a function returning the transformation
5398 >         * for an element, or null if there is no transformation (in
5399 >         * which case the action is not applied)
5400 >         * @param action the action
5401 >         * @return the task
5402 >         */
5403 >        public static <K,V,U> ForkJoinTask<Void> forEachEntry
5404 >            (ConcurrentHashMap<K,V> map,
5405 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5406 >             Consumer<? super U> action) {
5407 >            if (transformer == null || action == null)
5408 >                throw new NullPointerException();
5409 >            return new ForEachTransformedEntryTask<K,V,U>
5410 >                (map, null, -1, transformer, action);
5411 >        }
5412 >
5413 >        /**
5414 >         * Returns a task that when invoked, returns a non-null result
5415 >         * from applying the given search function on each entry, or
5416 >         * null if none.  Upon success, further element processing is
5417 >         * suppressed and the results of any other parallel
5418 >         * invocations of the search function are ignored.
5419 >         *
5420 >         * @param map the map
5421 >         * @param searchFunction a function returning a non-null
5422 >         * result on success, else null
5423 >         * @return the task
5424 >         */
5425 >        public static <K,V,U> ForkJoinTask<U> searchEntries
5426 >            (ConcurrentHashMap<K,V> map,
5427 >             Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5428 >            if (searchFunction == null) throw new NullPointerException();
5429 >            return new SearchEntriesTask<K,V,U>
5430 >                (map, null, -1, searchFunction,
5431 >                 new AtomicReference<U>());
5432 >        }
5433 >
5434 >        /**
5435 >         * Returns a task that when invoked, returns the result of
5436 >         * accumulating all entries using the given reducer to combine
5437 >         * values, or null if none.
5438 >         *
5439 >         * @param map the map
5440 >         * @param reducer a commutative associative combining function
5441 >         * @return the task
5442 >         */
5443 >        public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5444 >            (ConcurrentHashMap<K,V> map,
5445 >             BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5446 >            if (reducer == null) throw new NullPointerException();
5447 >            return new ReduceEntriesTask<K,V>
5448 >                (map, null, -1, null, reducer);
5449 >        }
5450 >
5451 >        /**
5452 >         * Returns a task that when invoked, returns the result of
5453 >         * accumulating the given transformation of all entries using the
5454 >         * given reducer to combine values, or null if none.
5455 >         *
5456 >         * @param map the map
5457 >         * @param transformer a function returning the transformation
5458 >         * for an element, or null if there is no transformation (in
5459 >         * which case it is not combined)
5460 >         * @param reducer a commutative associative combining function
5461 >         * @return the task
5462 >         */
5463 >        public static <K,V,U> ForkJoinTask<U> reduceEntries
5464 >            (ConcurrentHashMap<K,V> map,
5465 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5466 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5467 >            if (transformer == null || reducer == null)
5468 >                throw new NullPointerException();
5469 >            return new MapReduceEntriesTask<K,V,U>
5470 >                (map, null, -1, null, transformer, reducer);
5471 >        }
5472 >
5473 >        /**
5474 >         * Returns a task that when invoked, returns the result of
5475 >         * accumulating the given transformation of all entries using the
5476 >         * given reducer to combine values, and the given basis as an
5477 >         * identity value.
5478 >         *
5479 >         * @param map the map
5480 >         * @param transformer a function returning the transformation
5481 >         * for an element
5482 >         * @param basis the identity (initial default value) for the reduction
5483 >         * @param reducer a commutative associative combining function
5484 >         * @return the task
5485 >         */
5486 >        public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5487 >            (ConcurrentHashMap<K,V> map,
5488 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5489 >             double basis,
5490 >             DoubleBinaryOperator reducer) {
5491 >            if (transformer == null || reducer == null)
5492 >                throw new NullPointerException();
5493 >            return new MapReduceEntriesToDoubleTask<K,V>
5494 >                (map, null, -1, null, transformer, basis, reducer);
5495 >        }
5496 >
5497 >        /**
5498 >         * Returns a task that when invoked, returns the result of
5499 >         * accumulating the given transformation of all entries using the
5500 >         * given reducer to combine values, and the given basis as an
5501 >         * identity value.
5502 >         *
5503 >         * @param map the map
5504 >         * @param transformer a function returning the transformation
5505 >         * for an element
5506 >         * @param basis the identity (initial default value) for the reduction
5507 >         * @param reducer a commutative associative combining function
5508 >         * @return the task
5509 >         */
5510 >        public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5511 >            (ConcurrentHashMap<K,V> map,
5512 >             ToLongFunction<Map.Entry<K,V>> transformer,
5513 >             long basis,
5514 >             LongBinaryOperator reducer) {
5515 >            if (transformer == null || reducer == null)
5516 >                throw new NullPointerException();
5517 >            return new MapReduceEntriesToLongTask<K,V>
5518 >                (map, null, -1, null, transformer, basis, reducer);
5519 >        }
5520 >
5521 >        /**
5522 >         * Returns a task that when invoked, returns the result of
5523 >         * accumulating the given transformation of all entries using the
5524 >         * given reducer to combine values, and the given basis as an
5525 >         * identity value.
5526 >         *
5527 >         * @param map the map
5528 >         * @param transformer a function returning the transformation
5529 >         * for an element
5530 >         * @param basis the identity (initial default value) for the reduction
5531 >         * @param reducer a commutative associative combining function
5532 >         * @return the task
5533 >         */
5534 >        public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5535 >            (ConcurrentHashMap<K,V> map,
5536 >             ToIntFunction<Map.Entry<K,V>> transformer,
5537 >             int basis,
5538 >             IntBinaryOperator reducer) {
5539 >            if (transformer == null || reducer == null)
5540 >                throw new NullPointerException();
5541 >            return new MapReduceEntriesToIntTask<K,V>
5542 >                (map, null, -1, null, transformer, basis, reducer);
5543 >        }
5544 >    }
5545 >
5546 >    // -------------------------------------------------------
5547 >
5548 >    /*
5549 >     * Task classes. Coded in a regular but ugly format/style to
5550 >     * simplify checks that each variant differs in the right way from
5551 >     * others. The null screenings exist because compilers cannot tell
5552 >     * that we've already null-checked task arguments, so we force
5553 >     * simplest hoisted bypass to help avoid convoluted traps.
5554 >     */
5555 >
5556 >    @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5557 >        extends Traverser<K,V,Void> {
5558 >        final Consumer<? super K> action;
5559 >        ForEachKeyTask
5560 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5561 >             Consumer<? super K> action) {
5562 >            super(m, p, b);
5563 >            this.action = action;
5564 >        }
5565 >        public final void compute() {
5566 >            final Consumer<? super K> action;
5567 >            if ((action = this.action) != null) {
5568 >                for (int b; (b = preSplit()) > 0;)
5569 >                    new ForEachKeyTask<K,V>(map, this, b, action).fork();
5570 >                while (advance() != null)
5571 >                    action.accept(nextKey);
5572 >                propagateCompletion();
5573              }
5574          }
5575 +    }
5576  
5577 <        // Read the keys and values, and put the mappings in the table
5578 <        for (;;) {
5579 <            K key = (K) s.readObject();
5580 <            V value = (V) s.readObject();
5581 <            if (key == null)
5582 <                break;
5583 <            put(key, value);
5577 >    @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5578 >        extends Traverser<K,V,Void> {
5579 >        final Consumer<? super V> action;
5580 >        ForEachValueTask
5581 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5582 >             Consumer<? super V> action) {
5583 >            super(m, p, b);
5584 >            this.action = action;
5585 >        }
5586 >        public final void compute() {
5587 >            final Consumer<? super V> action;
5588 >            if ((action = this.action) != null) {
5589 >                for (int b; (b = preSplit()) > 0;)
5590 >                    new ForEachValueTask<K,V>(map, this, b, action).fork();
5591 >                V v;
5592 >                while ((v = advance()) != null)
5593 >                    action.accept(v);
5594 >                propagateCompletion();
5595 >            }
5596 >        }
5597 >    }
5598 >
5599 >    @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5600 >        extends Traverser<K,V,Void> {
5601 >        final Consumer<? super Entry<K,V>> action;
5602 >        ForEachEntryTask
5603 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5604 >             Consumer<? super Entry<K,V>> action) {
5605 >            super(m, p, b);
5606 >            this.action = action;
5607 >        }
5608 >        public final void compute() {
5609 >            final Consumer<? super Entry<K,V>> action;
5610 >            if ((action = this.action) != null) {
5611 >                for (int b; (b = preSplit()) > 0;)
5612 >                    new ForEachEntryTask<K,V>(map, this, b, action).fork();
5613 >                V v;
5614 >                while ((v = advance()) != null)
5615 >                    action.accept(entryFor(nextKey, v));
5616 >                propagateCompletion();
5617 >            }
5618 >        }
5619 >    }
5620 >
5621 >    @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5622 >        extends Traverser<K,V,Void> {
5623 >        final BiConsumer<? super K, ? super V> action;
5624 >        ForEachMappingTask
5625 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5626 >             BiConsumer<? super K,? super V> action) {
5627 >            super(m, p, b);
5628 >            this.action = action;
5629 >        }
5630 >        public final void compute() {
5631 >            final BiConsumer<? super K, ? super V> action;
5632 >            if ((action = this.action) != null) {
5633 >                for (int b; (b = preSplit()) > 0;)
5634 >                    new ForEachMappingTask<K,V>(map, this, b, action).fork();
5635 >                V v;
5636 >                while ((v = advance()) != null)
5637 >                    action.accept(nextKey, v);
5638 >                propagateCompletion();
5639 >            }
5640 >        }
5641 >    }
5642 >
5643 >    @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5644 >        extends Traverser<K,V,Void> {
5645 >        final Function<? super K, ? extends U> transformer;
5646 >        final Consumer<? super U> action;
5647 >        ForEachTransformedKeyTask
5648 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5649 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5650 >            super(m, p, b);
5651 >            this.transformer = transformer; this.action = action;
5652 >        }
5653 >        public final void compute() {
5654 >            final Function<? super K, ? extends U> transformer;
5655 >            final Consumer<? super U> action;
5656 >            if ((transformer = this.transformer) != null &&
5657 >                (action = this.action) != null) {
5658 >                for (int b; (b = preSplit()) > 0;)
5659 >                    new ForEachTransformedKeyTask<K,V,U>
5660 >                        (map, this, b, transformer, action).fork();
5661 >                U u;
5662 >                while (advance() != null) {
5663 >                    if ((u = transformer.apply(nextKey)) != null)
5664 >                        action.accept(u);
5665 >                }
5666 >                propagateCompletion();
5667 >            }
5668 >        }
5669 >    }
5670 >
5671 >    @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5672 >        extends Traverser<K,V,Void> {
5673 >        final Function<? super V, ? extends U> transformer;
5674 >        final Consumer<? super U> action;
5675 >        ForEachTransformedValueTask
5676 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5677 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5678 >            super(m, p, b);
5679 >            this.transformer = transformer; this.action = action;
5680 >        }
5681 >        public final void compute() {
5682 >            final Function<? super V, ? extends U> transformer;
5683 >            final Consumer<? super U> action;
5684 >            if ((transformer = this.transformer) != null &&
5685 >                (action = this.action) != null) {
5686 >                for (int b; (b = preSplit()) > 0;)
5687 >                    new ForEachTransformedValueTask<K,V,U>
5688 >                        (map, this, b, transformer, action).fork();
5689 >                V v; U u;
5690 >                while ((v = advance()) != null) {
5691 >                    if ((u = transformer.apply(v)) != null)
5692 >                        action.accept(u);
5693 >                }
5694 >                propagateCompletion();
5695 >            }
5696 >        }
5697 >    }
5698 >
5699 >    @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5700 >        extends Traverser<K,V,Void> {
5701 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5702 >        final Consumer<? super U> action;
5703 >        ForEachTransformedEntryTask
5704 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5705 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5706 >            super(m, p, b);
5707 >            this.transformer = transformer; this.action = action;
5708 >        }
5709 >        public final void compute() {
5710 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5711 >            final Consumer<? super U> action;
5712 >            if ((transformer = this.transformer) != null &&
5713 >                (action = this.action) != null) {
5714 >                for (int b; (b = preSplit()) > 0;)
5715 >                    new ForEachTransformedEntryTask<K,V,U>
5716 >                        (map, this, b, transformer, action).fork();
5717 >                V v; U u;
5718 >                while ((v = advance()) != null) {
5719 >                    if ((u = transformer.apply(entryFor(nextKey,
5720 >                                                        v))) != null)
5721 >                        action.accept(u);
5722 >                }
5723 >                propagateCompletion();
5724 >            }
5725 >        }
5726 >    }
5727 >
5728 >    @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5729 >        extends Traverser<K,V,Void> {
5730 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5731 >        final Consumer<? super U> action;
5732 >        ForEachTransformedMappingTask
5733 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5734 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5735 >             Consumer<? super U> action) {
5736 >            super(m, p, b);
5737 >            this.transformer = transformer; this.action = action;
5738 >        }
5739 >        public final void compute() {
5740 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5741 >            final Consumer<? super U> action;
5742 >            if ((transformer = this.transformer) != null &&
5743 >                (action = this.action) != null) {
5744 >                for (int b; (b = preSplit()) > 0;)
5745 >                    new ForEachTransformedMappingTask<K,V,U>
5746 >                        (map, this, b, transformer, action).fork();
5747 >                V v; U u;
5748 >                while ((v = advance()) != null) {
5749 >                    if ((u = transformer.apply(nextKey, v)) != null)
5750 >                        action.accept(u);
5751 >                }
5752 >                propagateCompletion();
5753 >            }
5754 >        }
5755 >    }
5756 >
5757 >    @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5758 >        extends Traverser<K,V,U> {
5759 >        final Function<? super K, ? extends U> searchFunction;
5760 >        final AtomicReference<U> result;
5761 >        SearchKeysTask
5762 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5763 >             Function<? super K, ? extends U> searchFunction,
5764 >             AtomicReference<U> result) {
5765 >            super(m, p, b);
5766 >            this.searchFunction = searchFunction; this.result = result;
5767 >        }
5768 >        public final U getRawResult() { return result.get(); }
5769 >        public final void compute() {
5770 >            final Function<? super K, ? extends U> searchFunction;
5771 >            final AtomicReference<U> result;
5772 >            if ((searchFunction = this.searchFunction) != null &&
5773 >                (result = this.result) != null) {
5774 >                for (int b;;) {
5775 >                    if (result.get() != null)
5776 >                        return;
5777 >                    if ((b = preSplit()) <= 0)
5778 >                        break;
5779 >                    new SearchKeysTask<K,V,U>
5780 >                        (map, this, b, searchFunction, result).fork();
5781 >                }
5782 >                while (result.get() == null) {
5783 >                    U u;
5784 >                    if (advance() == null) {
5785 >                        propagateCompletion();
5786 >                        break;
5787 >                    }
5788 >                    if ((u = searchFunction.apply(nextKey)) != null) {
5789 >                        if (result.compareAndSet(null, u))
5790 >                            quietlyCompleteRoot();
5791 >                        break;
5792 >                    }
5793 >                }
5794 >            }
5795 >        }
5796 >    }
5797 >
5798 >    @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5799 >        extends Traverser<K,V,U> {
5800 >        final Function<? super V, ? extends U> searchFunction;
5801 >        final AtomicReference<U> result;
5802 >        SearchValuesTask
5803 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5804 >             Function<? super V, ? extends U> searchFunction,
5805 >             AtomicReference<U> result) {
5806 >            super(m, p, b);
5807 >            this.searchFunction = searchFunction; this.result = result;
5808 >        }
5809 >        public final U getRawResult() { return result.get(); }
5810 >        public final void compute() {
5811 >            final Function<? super V, ? extends U> searchFunction;
5812 >            final AtomicReference<U> result;
5813 >            if ((searchFunction = this.searchFunction) != null &&
5814 >                (result = this.result) != null) {
5815 >                for (int b;;) {
5816 >                    if (result.get() != null)
5817 >                        return;
5818 >                    if ((b = preSplit()) <= 0)
5819 >                        break;
5820 >                    new SearchValuesTask<K,V,U>
5821 >                        (map, this, b, searchFunction, result).fork();
5822 >                }
5823 >                while (result.get() == null) {
5824 >                    V v; U u;
5825 >                    if ((v = advance()) == null) {
5826 >                        propagateCompletion();
5827 >                        break;
5828 >                    }
5829 >                    if ((u = searchFunction.apply(v)) != null) {
5830 >                        if (result.compareAndSet(null, u))
5831 >                            quietlyCompleteRoot();
5832 >                        break;
5833 >                    }
5834 >                }
5835 >            }
5836 >        }
5837 >    }
5838 >
5839 >    @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5840 >        extends Traverser<K,V,U> {
5841 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5842 >        final AtomicReference<U> result;
5843 >        SearchEntriesTask
5844 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5845 >             Function<Entry<K,V>, ? extends U> searchFunction,
5846 >             AtomicReference<U> result) {
5847 >            super(m, p, b);
5848 >            this.searchFunction = searchFunction; this.result = result;
5849 >        }
5850 >        public final U getRawResult() { return result.get(); }
5851 >        public final void compute() {
5852 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5853 >            final AtomicReference<U> result;
5854 >            if ((searchFunction = this.searchFunction) != null &&
5855 >                (result = this.result) != null) {
5856 >                for (int b;;) {
5857 >                    if (result.get() != null)
5858 >                        return;
5859 >                    if ((b = preSplit()) <= 0)
5860 >                        break;
5861 >                    new SearchEntriesTask<K,V,U>
5862 >                        (map, this, b, searchFunction, result).fork();
5863 >                }
5864 >                while (result.get() == null) {
5865 >                    V v; U u;
5866 >                    if ((v = advance()) == null) {
5867 >                        propagateCompletion();
5868 >                        break;
5869 >                    }
5870 >                    if ((u = searchFunction.apply(entryFor(nextKey,
5871 >                                                           v))) != null) {
5872 >                        if (result.compareAndSet(null, u))
5873 >                            quietlyCompleteRoot();
5874 >                        return;
5875 >                    }
5876 >                }
5877 >            }
5878 >        }
5879 >    }
5880 >
5881 >    @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5882 >        extends Traverser<K,V,U> {
5883 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5884 >        final AtomicReference<U> result;
5885 >        SearchMappingsTask
5886 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5887 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5888 >             AtomicReference<U> result) {
5889 >            super(m, p, b);
5890 >            this.searchFunction = searchFunction; this.result = result;
5891 >        }
5892 >        public final U getRawResult() { return result.get(); }
5893 >        public final void compute() {
5894 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5895 >            final AtomicReference<U> result;
5896 >            if ((searchFunction = this.searchFunction) != null &&
5897 >                (result = this.result) != null) {
5898 >                for (int b;;) {
5899 >                    if (result.get() != null)
5900 >                        return;
5901 >                    if ((b = preSplit()) <= 0)
5902 >                        break;
5903 >                    new SearchMappingsTask<K,V,U>
5904 >                        (map, this, b, searchFunction, result).fork();
5905 >                }
5906 >                while (result.get() == null) {
5907 >                    V v; U u;
5908 >                    if ((v = advance()) == null) {
5909 >                        propagateCompletion();
5910 >                        break;
5911 >                    }
5912 >                    if ((u = searchFunction.apply(nextKey, v)) != null) {
5913 >                        if (result.compareAndSet(null, u))
5914 >                            quietlyCompleteRoot();
5915 >                        break;
5916 >                    }
5917 >                }
5918 >            }
5919 >        }
5920 >    }
5921 >
5922 >    @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5923 >        extends Traverser<K,V,K> {
5924 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5925 >        K result;
5926 >        ReduceKeysTask<K,V> rights, nextRight;
5927 >        ReduceKeysTask
5928 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5929 >             ReduceKeysTask<K,V> nextRight,
5930 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5931 >            super(m, p, b); this.nextRight = nextRight;
5932 >            this.reducer = reducer;
5933 >        }
5934 >        public final K getRawResult() { return result; }
5935 >        @SuppressWarnings("unchecked") public final void compute() {
5936 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5937 >            if ((reducer = this.reducer) != null) {
5938 >                for (int b; (b = preSplit()) > 0;)
5939 >                    (rights = new ReduceKeysTask<K,V>
5940 >                     (map, this, b, rights, reducer)).fork();
5941 >                K r = null;
5942 >                while (advance() != null) {
5943 >                    K u = nextKey;
5944 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5945 >                }
5946 >                result = r;
5947 >                CountedCompleter<?> c;
5948 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5949 >                    ReduceKeysTask<K,V>
5950 >                        t = (ReduceKeysTask<K,V>)c,
5951 >                        s = t.rights;
5952 >                    while (s != null) {
5953 >                        K tr, sr;
5954 >                        if ((sr = s.result) != null)
5955 >                            t.result = (((tr = t.result) == null) ? sr :
5956 >                                        reducer.apply(tr, sr));
5957 >                        s = t.rights = s.nextRight;
5958 >                    }
5959 >                }
5960 >            }
5961 >        }
5962 >    }
5963 >
5964 >    @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5965 >        extends Traverser<K,V,V> {
5966 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5967 >        V result;
5968 >        ReduceValuesTask<K,V> rights, nextRight;
5969 >        ReduceValuesTask
5970 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5971 >             ReduceValuesTask<K,V> nextRight,
5972 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5973 >            super(m, p, b); this.nextRight = nextRight;
5974 >            this.reducer = reducer;
5975 >        }
5976 >        public final V getRawResult() { return result; }
5977 >        @SuppressWarnings("unchecked") public final void compute() {
5978 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5979 >            if ((reducer = this.reducer) != null) {
5980 >                for (int b; (b = preSplit()) > 0;)
5981 >                    (rights = new ReduceValuesTask<K,V>
5982 >                     (map, this, b, rights, reducer)).fork();
5983 >                V r = null, v;
5984 >                while ((v = advance()) != null)
5985 >                    r = (r == null) ? v : reducer.apply(r, v);
5986 >                result = r;
5987 >                CountedCompleter<?> c;
5988 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5989 >                    ReduceValuesTask<K,V>
5990 >                        t = (ReduceValuesTask<K,V>)c,
5991 >                        s = t.rights;
5992 >                    while (s != null) {
5993 >                        V tr, sr;
5994 >                        if ((sr = s.result) != null)
5995 >                            t.result = (((tr = t.result) == null) ? sr :
5996 >                                        reducer.apply(tr, sr));
5997 >                        s = t.rights = s.nextRight;
5998 >                    }
5999 >                }
6000 >            }
6001 >        }
6002 >    }
6003 >
6004 >    @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6005 >        extends Traverser<K,V,Map.Entry<K,V>> {
6006 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6007 >        Map.Entry<K,V> result;
6008 >        ReduceEntriesTask<K,V> rights, nextRight;
6009 >        ReduceEntriesTask
6010 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6011 >             ReduceEntriesTask<K,V> nextRight,
6012 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6013 >            super(m, p, b); this.nextRight = nextRight;
6014 >            this.reducer = reducer;
6015 >        }
6016 >        public final Map.Entry<K,V> getRawResult() { return result; }
6017 >        @SuppressWarnings("unchecked") public final void compute() {
6018 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6019 >            if ((reducer = this.reducer) != null) {
6020 >                for (int b; (b = preSplit()) > 0;)
6021 >                    (rights = new ReduceEntriesTask<K,V>
6022 >                     (map, this, b, rights, reducer)).fork();
6023 >                Map.Entry<K,V> r = null;
6024 >                V v;
6025 >                while ((v = advance()) != null) {
6026 >                    Map.Entry<K,V> u = entryFor(nextKey, v);
6027 >                    r = (r == null) ? u : reducer.apply(r, u);
6028 >                }
6029 >                result = r;
6030 >                CountedCompleter<?> c;
6031 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6032 >                    ReduceEntriesTask<K,V>
6033 >                        t = (ReduceEntriesTask<K,V>)c,
6034 >                        s = t.rights;
6035 >                    while (s != null) {
6036 >                        Map.Entry<K,V> tr, sr;
6037 >                        if ((sr = s.result) != null)
6038 >                            t.result = (((tr = t.result) == null) ? sr :
6039 >                                        reducer.apply(tr, sr));
6040 >                        s = t.rights = s.nextRight;
6041 >                    }
6042 >                }
6043 >            }
6044 >        }
6045 >    }
6046 >
6047 >    @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6048 >        extends Traverser<K,V,U> {
6049 >        final Function<? super K, ? extends U> transformer;
6050 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6051 >        U result;
6052 >        MapReduceKeysTask<K,V,U> rights, nextRight;
6053 >        MapReduceKeysTask
6054 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6055 >             MapReduceKeysTask<K,V,U> nextRight,
6056 >             Function<? super K, ? extends U> transformer,
6057 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6058 >            super(m, p, b); this.nextRight = nextRight;
6059 >            this.transformer = transformer;
6060 >            this.reducer = reducer;
6061 >        }
6062 >        public final U getRawResult() { return result; }
6063 >        @SuppressWarnings("unchecked") public final void compute() {
6064 >            final Function<? super K, ? extends U> transformer;
6065 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6066 >            if ((transformer = this.transformer) != null &&
6067 >                (reducer = this.reducer) != null) {
6068 >                for (int b; (b = preSplit()) > 0;)
6069 >                    (rights = new MapReduceKeysTask<K,V,U>
6070 >                     (map, this, b, rights, transformer, reducer)).fork();
6071 >                U r = null, u;
6072 >                while (advance() != null) {
6073 >                    if ((u = transformer.apply(nextKey)) != null)
6074 >                        r = (r == null) ? u : reducer.apply(r, u);
6075 >                }
6076 >                result = r;
6077 >                CountedCompleter<?> c;
6078 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6079 >                    MapReduceKeysTask<K,V,U>
6080 >                        t = (MapReduceKeysTask<K,V,U>)c,
6081 >                        s = t.rights;
6082 >                    while (s != null) {
6083 >                        U tr, sr;
6084 >                        if ((sr = s.result) != null)
6085 >                            t.result = (((tr = t.result) == null) ? sr :
6086 >                                        reducer.apply(tr, sr));
6087 >                        s = t.rights = s.nextRight;
6088 >                    }
6089 >                }
6090 >            }
6091 >        }
6092 >    }
6093 >
6094 >    @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6095 >        extends Traverser<K,V,U> {
6096 >        final Function<? super V, ? extends U> transformer;
6097 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6098 >        U result;
6099 >        MapReduceValuesTask<K,V,U> rights, nextRight;
6100 >        MapReduceValuesTask
6101 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6102 >             MapReduceValuesTask<K,V,U> nextRight,
6103 >             Function<? super V, ? extends U> transformer,
6104 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6105 >            super(m, p, b); this.nextRight = nextRight;
6106 >            this.transformer = transformer;
6107 >            this.reducer = reducer;
6108 >        }
6109 >        public final U getRawResult() { return result; }
6110 >        @SuppressWarnings("unchecked") public final void compute() {
6111 >            final Function<? super V, ? extends U> transformer;
6112 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6113 >            if ((transformer = this.transformer) != null &&
6114 >                (reducer = this.reducer) != null) {
6115 >                for (int b; (b = preSplit()) > 0;)
6116 >                    (rights = new MapReduceValuesTask<K,V,U>
6117 >                     (map, this, b, rights, transformer, reducer)).fork();
6118 >                U r = null, u;
6119 >                V v;
6120 >                while ((v = advance()) != null) {
6121 >                    if ((u = transformer.apply(v)) != null)
6122 >                        r = (r == null) ? u : reducer.apply(r, u);
6123 >                }
6124 >                result = r;
6125 >                CountedCompleter<?> c;
6126 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6127 >                    MapReduceValuesTask<K,V,U>
6128 >                        t = (MapReduceValuesTask<K,V,U>)c,
6129 >                        s = t.rights;
6130 >                    while (s != null) {
6131 >                        U tr, sr;
6132 >                        if ((sr = s.result) != null)
6133 >                            t.result = (((tr = t.result) == null) ? sr :
6134 >                                        reducer.apply(tr, sr));
6135 >                        s = t.rights = s.nextRight;
6136 >                    }
6137 >                }
6138 >            }
6139 >        }
6140 >    }
6141 >
6142 >    @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6143 >        extends Traverser<K,V,U> {
6144 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
6145 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6146 >        U result;
6147 >        MapReduceEntriesTask<K,V,U> rights, nextRight;
6148 >        MapReduceEntriesTask
6149 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6150 >             MapReduceEntriesTask<K,V,U> nextRight,
6151 >             Function<Map.Entry<K,V>, ? extends U> transformer,
6152 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6153 >            super(m, p, b); this.nextRight = nextRight;
6154 >            this.transformer = transformer;
6155 >            this.reducer = reducer;
6156 >        }
6157 >        public final U getRawResult() { return result; }
6158 >        @SuppressWarnings("unchecked") public final void compute() {
6159 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
6160 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6161 >            if ((transformer = this.transformer) != null &&
6162 >                (reducer = this.reducer) != null) {
6163 >                for (int b; (b = preSplit()) > 0;)
6164 >                    (rights = new MapReduceEntriesTask<K,V,U>
6165 >                     (map, this, b, rights, transformer, reducer)).fork();
6166 >                U r = null, u;
6167 >                V v;
6168 >                while ((v = advance()) != null) {
6169 >                    if ((u = transformer.apply(entryFor(nextKey,
6170 >                                                        v))) != null)
6171 >                        r = (r == null) ? u : reducer.apply(r, u);
6172 >                }
6173 >                result = r;
6174 >                CountedCompleter<?> c;
6175 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6176 >                    MapReduceEntriesTask<K,V,U>
6177 >                        t = (MapReduceEntriesTask<K,V,U>)c,
6178 >                        s = t.rights;
6179 >                    while (s != null) {
6180 >                        U tr, sr;
6181 >                        if ((sr = s.result) != null)
6182 >                            t.result = (((tr = t.result) == null) ? sr :
6183 >                                        reducer.apply(tr, sr));
6184 >                        s = t.rights = s.nextRight;
6185 >                    }
6186 >                }
6187 >            }
6188 >        }
6189 >    }
6190 >
6191 >    @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6192 >        extends Traverser<K,V,U> {
6193 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
6194 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
6195 >        U result;
6196 >        MapReduceMappingsTask<K,V,U> rights, nextRight;
6197 >        MapReduceMappingsTask
6198 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6199 >             MapReduceMappingsTask<K,V,U> nextRight,
6200 >             BiFunction<? super K, ? super V, ? extends U> transformer,
6201 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
6202 >            super(m, p, b); this.nextRight = nextRight;
6203 >            this.transformer = transformer;
6204 >            this.reducer = reducer;
6205 >        }
6206 >        public final U getRawResult() { return result; }
6207 >        @SuppressWarnings("unchecked") public final void compute() {
6208 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
6209 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
6210 >            if ((transformer = this.transformer) != null &&
6211 >                (reducer = this.reducer) != null) {
6212 >                for (int b; (b = preSplit()) > 0;)
6213 >                    (rights = new MapReduceMappingsTask<K,V,U>
6214 >                     (map, this, b, rights, transformer, reducer)).fork();
6215 >                U r = null, u;
6216 >                V v;
6217 >                while ((v = advance()) != null) {
6218 >                    if ((u = transformer.apply(nextKey, v)) != null)
6219 >                        r = (r == null) ? u : reducer.apply(r, u);
6220 >                }
6221 >                result = r;
6222 >                CountedCompleter<?> c;
6223 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6224 >                    MapReduceMappingsTask<K,V,U>
6225 >                        t = (MapReduceMappingsTask<K,V,U>)c,
6226 >                        s = t.rights;
6227 >                    while (s != null) {
6228 >                        U tr, sr;
6229 >                        if ((sr = s.result) != null)
6230 >                            t.result = (((tr = t.result) == null) ? sr :
6231 >                                        reducer.apply(tr, sr));
6232 >                        s = t.rights = s.nextRight;
6233 >                    }
6234 >                }
6235 >            }
6236 >        }
6237 >    }
6238 >
6239 >    @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6240 >        extends Traverser<K,V,Double> {
6241 >        final ToDoubleFunction<? super K> transformer;
6242 >        final DoubleBinaryOperator reducer;
6243 >        final double basis;
6244 >        double result;
6245 >        MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6246 >        MapReduceKeysToDoubleTask
6247 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6248 >             MapReduceKeysToDoubleTask<K,V> nextRight,
6249 >             ToDoubleFunction<? super K> transformer,
6250 >             double basis,
6251 >             DoubleBinaryOperator reducer) {
6252 >            super(m, p, b); this.nextRight = nextRight;
6253 >            this.transformer = transformer;
6254 >            this.basis = basis; this.reducer = reducer;
6255 >        }
6256 >        public final Double getRawResult() { return result; }
6257 >        @SuppressWarnings("unchecked") public final void compute() {
6258 >            final ToDoubleFunction<? super K> transformer;
6259 >            final DoubleBinaryOperator reducer;
6260 >            if ((transformer = this.transformer) != null &&
6261 >                (reducer = this.reducer) != null) {
6262 >                double r = this.basis;
6263 >                for (int b; (b = preSplit()) > 0;)
6264 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
6265 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6266 >                while (advance() != null)
6267 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey));
6268 >                result = r;
6269 >                CountedCompleter<?> c;
6270 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6271 >                    MapReduceKeysToDoubleTask<K,V>
6272 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
6273 >                        s = t.rights;
6274 >                    while (s != null) {
6275 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6276 >                        s = t.rights = s.nextRight;
6277 >                    }
6278 >                }
6279 >            }
6280 >        }
6281 >    }
6282 >
6283 >    @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6284 >        extends Traverser<K,V,Double> {
6285 >        final ToDoubleFunction<? super V> transformer;
6286 >        final DoubleBinaryOperator reducer;
6287 >        final double basis;
6288 >        double result;
6289 >        MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6290 >        MapReduceValuesToDoubleTask
6291 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6292 >             MapReduceValuesToDoubleTask<K,V> nextRight,
6293 >             ToDoubleFunction<? super V> transformer,
6294 >             double basis,
6295 >             DoubleBinaryOperator reducer) {
6296 >            super(m, p, b); this.nextRight = nextRight;
6297 >            this.transformer = transformer;
6298 >            this.basis = basis; this.reducer = reducer;
6299 >        }
6300 >        public final Double getRawResult() { return result; }
6301 >        @SuppressWarnings("unchecked") public final void compute() {
6302 >            final ToDoubleFunction<? super V> transformer;
6303 >            final DoubleBinaryOperator reducer;
6304 >            if ((transformer = this.transformer) != null &&
6305 >                (reducer = this.reducer) != null) {
6306 >                double r = this.basis;
6307 >                for (int b; (b = preSplit()) > 0;)
6308 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
6309 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6310 >                V v;
6311 >                while ((v = advance()) != null)
6312 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
6313 >                result = r;
6314 >                CountedCompleter<?> c;
6315 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6316 >                    MapReduceValuesToDoubleTask<K,V>
6317 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
6318 >                        s = t.rights;
6319 >                    while (s != null) {
6320 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6321 >                        s = t.rights = s.nextRight;
6322 >                    }
6323 >                }
6324 >            }
6325 >        }
6326 >    }
6327 >
6328 >    @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6329 >        extends Traverser<K,V,Double> {
6330 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
6331 >        final DoubleBinaryOperator reducer;
6332 >        final double basis;
6333 >        double result;
6334 >        MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6335 >        MapReduceEntriesToDoubleTask
6336 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6337 >             MapReduceEntriesToDoubleTask<K,V> nextRight,
6338 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
6339 >             double basis,
6340 >             DoubleBinaryOperator reducer) {
6341 >            super(m, p, b); this.nextRight = nextRight;
6342 >            this.transformer = transformer;
6343 >            this.basis = basis; this.reducer = reducer;
6344 >        }
6345 >        public final Double getRawResult() { return result; }
6346 >        @SuppressWarnings("unchecked") public final void compute() {
6347 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
6348 >            final DoubleBinaryOperator reducer;
6349 >            if ((transformer = this.transformer) != null &&
6350 >                (reducer = this.reducer) != null) {
6351 >                double r = this.basis;
6352 >                for (int b; (b = preSplit()) > 0;)
6353 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
6354 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6355 >                V v;
6356 >                while ((v = advance()) != null)
6357 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
6358 >                                                                    v)));
6359 >                result = r;
6360 >                CountedCompleter<?> c;
6361 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6362 >                    MapReduceEntriesToDoubleTask<K,V>
6363 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
6364 >                        s = t.rights;
6365 >                    while (s != null) {
6366 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6367 >                        s = t.rights = s.nextRight;
6368 >                    }
6369 >                }
6370 >            }
6371 >        }
6372 >    }
6373 >
6374 >    @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6375 >        extends Traverser<K,V,Double> {
6376 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
6377 >        final DoubleBinaryOperator reducer;
6378 >        final double basis;
6379 >        double result;
6380 >        MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6381 >        MapReduceMappingsToDoubleTask
6382 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6383 >             MapReduceMappingsToDoubleTask<K,V> nextRight,
6384 >             ToDoubleBiFunction<? super K, ? super V> transformer,
6385 >             double basis,
6386 >             DoubleBinaryOperator reducer) {
6387 >            super(m, p, b); this.nextRight = nextRight;
6388 >            this.transformer = transformer;
6389 >            this.basis = basis; this.reducer = reducer;
6390 >        }
6391 >        public final Double getRawResult() { return result; }
6392 >        @SuppressWarnings("unchecked") public final void compute() {
6393 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
6394 >            final DoubleBinaryOperator reducer;
6395 >            if ((transformer = this.transformer) != null &&
6396 >                (reducer = this.reducer) != null) {
6397 >                double r = this.basis;
6398 >                for (int b; (b = preSplit()) > 0;)
6399 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
6400 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6401 >                V v;
6402 >                while ((v = advance()) != null)
6403 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
6404 >                result = r;
6405 >                CountedCompleter<?> c;
6406 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6407 >                    MapReduceMappingsToDoubleTask<K,V>
6408 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
6409 >                        s = t.rights;
6410 >                    while (s != null) {
6411 >                        t.result = reducer.applyAsDouble(t.result, s.result);
6412 >                        s = t.rights = s.nextRight;
6413 >                    }
6414 >                }
6415 >            }
6416 >        }
6417 >    }
6418 >
6419 >    @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6420 >        extends Traverser<K,V,Long> {
6421 >        final ToLongFunction<? super K> transformer;
6422 >        final LongBinaryOperator reducer;
6423 >        final long basis;
6424 >        long result;
6425 >        MapReduceKeysToLongTask<K,V> rights, nextRight;
6426 >        MapReduceKeysToLongTask
6427 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6428 >             MapReduceKeysToLongTask<K,V> nextRight,
6429 >             ToLongFunction<? super K> transformer,
6430 >             long basis,
6431 >             LongBinaryOperator reducer) {
6432 >            super(m, p, b); this.nextRight = nextRight;
6433 >            this.transformer = transformer;
6434 >            this.basis = basis; this.reducer = reducer;
6435 >        }
6436 >        public final Long getRawResult() { return result; }
6437 >        @SuppressWarnings("unchecked") public final void compute() {
6438 >            final ToLongFunction<? super K> transformer;
6439 >            final LongBinaryOperator reducer;
6440 >            if ((transformer = this.transformer) != null &&
6441 >                (reducer = this.reducer) != null) {
6442 >                long r = this.basis;
6443 >                for (int b; (b = preSplit()) > 0;)
6444 >                    (rights = new MapReduceKeysToLongTask<K,V>
6445 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6446 >                while (advance() != null)
6447 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey));
6448 >                result = r;
6449 >                CountedCompleter<?> c;
6450 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6451 >                    MapReduceKeysToLongTask<K,V>
6452 >                        t = (MapReduceKeysToLongTask<K,V>)c,
6453 >                        s = t.rights;
6454 >                    while (s != null) {
6455 >                        t.result = reducer.applyAsLong(t.result, s.result);
6456 >                        s = t.rights = s.nextRight;
6457 >                    }
6458 >                }
6459 >            }
6460 >        }
6461 >    }
6462 >
6463 >    @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6464 >        extends Traverser<K,V,Long> {
6465 >        final ToLongFunction<? super V> transformer;
6466 >        final LongBinaryOperator reducer;
6467 >        final long basis;
6468 >        long result;
6469 >        MapReduceValuesToLongTask<K,V> rights, nextRight;
6470 >        MapReduceValuesToLongTask
6471 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6472 >             MapReduceValuesToLongTask<K,V> nextRight,
6473 >             ToLongFunction<? super V> transformer,
6474 >             long basis,
6475 >             LongBinaryOperator reducer) {
6476 >            super(m, p, b); this.nextRight = nextRight;
6477 >            this.transformer = transformer;
6478 >            this.basis = basis; this.reducer = reducer;
6479 >        }
6480 >        public final Long getRawResult() { return result; }
6481 >        @SuppressWarnings("unchecked") public final void compute() {
6482 >            final ToLongFunction<? super V> transformer;
6483 >            final LongBinaryOperator reducer;
6484 >            if ((transformer = this.transformer) != null &&
6485 >                (reducer = this.reducer) != null) {
6486 >                long r = this.basis;
6487 >                for (int b; (b = preSplit()) > 0;)
6488 >                    (rights = new MapReduceValuesToLongTask<K,V>
6489 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6490 >                V v;
6491 >                while ((v = advance()) != null)
6492 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6493 >                result = r;
6494 >                CountedCompleter<?> c;
6495 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6496 >                    MapReduceValuesToLongTask<K,V>
6497 >                        t = (MapReduceValuesToLongTask<K,V>)c,
6498 >                        s = t.rights;
6499 >                    while (s != null) {
6500 >                        t.result = reducer.applyAsLong(t.result, s.result);
6501 >                        s = t.rights = s.nextRight;
6502 >                    }
6503 >                }
6504 >            }
6505 >        }
6506 >    }
6507 >
6508 >    @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6509 >        extends Traverser<K,V,Long> {
6510 >        final ToLongFunction<Map.Entry<K,V>> transformer;
6511 >        final LongBinaryOperator reducer;
6512 >        final long basis;
6513 >        long result;
6514 >        MapReduceEntriesToLongTask<K,V> rights, nextRight;
6515 >        MapReduceEntriesToLongTask
6516 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6517 >             MapReduceEntriesToLongTask<K,V> nextRight,
6518 >             ToLongFunction<Map.Entry<K,V>> transformer,
6519 >             long basis,
6520 >             LongBinaryOperator reducer) {
6521 >            super(m, p, b); this.nextRight = nextRight;
6522 >            this.transformer = transformer;
6523 >            this.basis = basis; this.reducer = reducer;
6524 >        }
6525 >        public final Long getRawResult() { return result; }
6526 >        @SuppressWarnings("unchecked") public final void compute() {
6527 >            final ToLongFunction<Map.Entry<K,V>> transformer;
6528 >            final LongBinaryOperator reducer;
6529 >            if ((transformer = this.transformer) != null &&
6530 >                (reducer = this.reducer) != null) {
6531 >                long r = this.basis;
6532 >                for (int b; (b = preSplit()) > 0;)
6533 >                    (rights = new MapReduceEntriesToLongTask<K,V>
6534 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6535 >                V v;
6536 >                while ((v = advance()) != null)
6537 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6538 >                result = r;
6539 >                CountedCompleter<?> c;
6540 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6541 >                    MapReduceEntriesToLongTask<K,V>
6542 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
6543 >                        s = t.rights;
6544 >                    while (s != null) {
6545 >                        t.result = reducer.applyAsLong(t.result, s.result);
6546 >                        s = t.rights = s.nextRight;
6547 >                    }
6548 >                }
6549 >            }
6550 >        }
6551 >    }
6552 >
6553 >    @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6554 >        extends Traverser<K,V,Long> {
6555 >        final ToLongBiFunction<? super K, ? super V> transformer;
6556 >        final LongBinaryOperator reducer;
6557 >        final long basis;
6558 >        long result;
6559 >        MapReduceMappingsToLongTask<K,V> rights, nextRight;
6560 >        MapReduceMappingsToLongTask
6561 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6562 >             MapReduceMappingsToLongTask<K,V> nextRight,
6563 >             ToLongBiFunction<? super K, ? super V> transformer,
6564 >             long basis,
6565 >             LongBinaryOperator reducer) {
6566 >            super(m, p, b); this.nextRight = nextRight;
6567 >            this.transformer = transformer;
6568 >            this.basis = basis; this.reducer = reducer;
6569 >        }
6570 >        public final Long getRawResult() { return result; }
6571 >        @SuppressWarnings("unchecked") public final void compute() {
6572 >            final ToLongBiFunction<? super K, ? super V> transformer;
6573 >            final LongBinaryOperator reducer;
6574 >            if ((transformer = this.transformer) != null &&
6575 >                (reducer = this.reducer) != null) {
6576 >                long r = this.basis;
6577 >                for (int b; (b = preSplit()) > 0;)
6578 >                    (rights = new MapReduceMappingsToLongTask<K,V>
6579 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6580 >                V v;
6581 >                while ((v = advance()) != null)
6582 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6583 >                result = r;
6584 >                CountedCompleter<?> c;
6585 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6586 >                    MapReduceMappingsToLongTask<K,V>
6587 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
6588 >                        s = t.rights;
6589 >                    while (s != null) {
6590 >                        t.result = reducer.applyAsLong(t.result, s.result);
6591 >                        s = t.rights = s.nextRight;
6592 >                    }
6593 >                }
6594 >            }
6595 >        }
6596 >    }
6597 >
6598 >    @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6599 >        extends Traverser<K,V,Integer> {
6600 >        final ToIntFunction<? super K> transformer;
6601 >        final IntBinaryOperator reducer;
6602 >        final int basis;
6603 >        int result;
6604 >        MapReduceKeysToIntTask<K,V> rights, nextRight;
6605 >        MapReduceKeysToIntTask
6606 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6607 >             MapReduceKeysToIntTask<K,V> nextRight,
6608 >             ToIntFunction<? super K> transformer,
6609 >             int basis,
6610 >             IntBinaryOperator reducer) {
6611 >            super(m, p, b); this.nextRight = nextRight;
6612 >            this.transformer = transformer;
6613 >            this.basis = basis; this.reducer = reducer;
6614 >        }
6615 >        public final Integer getRawResult() { return result; }
6616 >        @SuppressWarnings("unchecked") public final void compute() {
6617 >            final ToIntFunction<? super K> transformer;
6618 >            final IntBinaryOperator reducer;
6619 >            if ((transformer = this.transformer) != null &&
6620 >                (reducer = this.reducer) != null) {
6621 >                int r = this.basis;
6622 >                for (int b; (b = preSplit()) > 0;)
6623 >                    (rights = new MapReduceKeysToIntTask<K,V>
6624 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6625 >                while (advance() != null)
6626 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey));
6627 >                result = r;
6628 >                CountedCompleter<?> c;
6629 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6630 >                    MapReduceKeysToIntTask<K,V>
6631 >                        t = (MapReduceKeysToIntTask<K,V>)c,
6632 >                        s = t.rights;
6633 >                    while (s != null) {
6634 >                        t.result = reducer.applyAsInt(t.result, s.result);
6635 >                        s = t.rights = s.nextRight;
6636 >                    }
6637 >                }
6638 >            }
6639 >        }
6640 >    }
6641 >
6642 >    @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6643 >        extends Traverser<K,V,Integer> {
6644 >        final ToIntFunction<? super V> transformer;
6645 >        final IntBinaryOperator reducer;
6646 >        final int basis;
6647 >        int result;
6648 >        MapReduceValuesToIntTask<K,V> rights, nextRight;
6649 >        MapReduceValuesToIntTask
6650 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6651 >             MapReduceValuesToIntTask<K,V> nextRight,
6652 >             ToIntFunction<? super V> transformer,
6653 >             int basis,
6654 >             IntBinaryOperator reducer) {
6655 >            super(m, p, b); this.nextRight = nextRight;
6656 >            this.transformer = transformer;
6657 >            this.basis = basis; this.reducer = reducer;
6658 >        }
6659 >        public final Integer getRawResult() { return result; }
6660 >        @SuppressWarnings("unchecked") public final void compute() {
6661 >            final ToIntFunction<? super V> transformer;
6662 >            final IntBinaryOperator reducer;
6663 >            if ((transformer = this.transformer) != null &&
6664 >                (reducer = this.reducer) != null) {
6665 >                int r = this.basis;
6666 >                for (int b; (b = preSplit()) > 0;)
6667 >                    (rights = new MapReduceValuesToIntTask<K,V>
6668 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6669 >                V v;
6670 >                while ((v = advance()) != null)
6671 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6672 >                result = r;
6673 >                CountedCompleter<?> c;
6674 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6675 >                    MapReduceValuesToIntTask<K,V>
6676 >                        t = (MapReduceValuesToIntTask<K,V>)c,
6677 >                        s = t.rights;
6678 >                    while (s != null) {
6679 >                        t.result = reducer.applyAsInt(t.result, s.result);
6680 >                        s = t.rights = s.nextRight;
6681 >                    }
6682 >                }
6683 >            }
6684 >        }
6685 >    }
6686 >
6687 >    @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6688 >        extends Traverser<K,V,Integer> {
6689 >        final ToIntFunction<Map.Entry<K,V>> transformer;
6690 >        final IntBinaryOperator reducer;
6691 >        final int basis;
6692 >        int result;
6693 >        MapReduceEntriesToIntTask<K,V> rights, nextRight;
6694 >        MapReduceEntriesToIntTask
6695 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6696 >             MapReduceEntriesToIntTask<K,V> nextRight,
6697 >             ToIntFunction<Map.Entry<K,V>> transformer,
6698 >             int basis,
6699 >             IntBinaryOperator reducer) {
6700 >            super(m, p, b); this.nextRight = nextRight;
6701 >            this.transformer = transformer;
6702 >            this.basis = basis; this.reducer = reducer;
6703 >        }
6704 >        public final Integer getRawResult() { return result; }
6705 >        @SuppressWarnings("unchecked") public final void compute() {
6706 >            final ToIntFunction<Map.Entry<K,V>> transformer;
6707 >            final IntBinaryOperator reducer;
6708 >            if ((transformer = this.transformer) != null &&
6709 >                (reducer = this.reducer) != null) {
6710 >                int r = this.basis;
6711 >                for (int b; (b = preSplit()) > 0;)
6712 >                    (rights = new MapReduceEntriesToIntTask<K,V>
6713 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6714 >                V v;
6715 >                while ((v = advance()) != null)
6716 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6717 >                                                                    v)));
6718 >                result = r;
6719 >                CountedCompleter<?> c;
6720 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6721 >                    MapReduceEntriesToIntTask<K,V>
6722 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6723 >                        s = t.rights;
6724 >                    while (s != null) {
6725 >                        t.result = reducer.applyAsInt(t.result, s.result);
6726 >                        s = t.rights = s.nextRight;
6727 >                    }
6728 >                }
6729 >            }
6730 >        }
6731 >    }
6732 >
6733 >    @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6734 >        extends Traverser<K,V,Integer> {
6735 >        final ToIntBiFunction<? super K, ? super V> transformer;
6736 >        final IntBinaryOperator reducer;
6737 >        final int basis;
6738 >        int result;
6739 >        MapReduceMappingsToIntTask<K,V> rights, nextRight;
6740 >        MapReduceMappingsToIntTask
6741 >            (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6742 >             MapReduceMappingsToIntTask<K,V> nextRight,
6743 >             ToIntBiFunction<? super K, ? super V> transformer,
6744 >             int basis,
6745 >             IntBinaryOperator reducer) {
6746 >            super(m, p, b); this.nextRight = nextRight;
6747 >            this.transformer = transformer;
6748 >            this.basis = basis; this.reducer = reducer;
6749 >        }
6750 >        public final Integer getRawResult() { return result; }
6751 >        @SuppressWarnings("unchecked") public final void compute() {
6752 >            final ToIntBiFunction<? super K, ? super V> transformer;
6753 >            final IntBinaryOperator reducer;
6754 >            if ((transformer = this.transformer) != null &&
6755 >                (reducer = this.reducer) != null) {
6756 >                int r = this.basis;
6757 >                for (int b; (b = preSplit()) > 0;)
6758 >                    (rights = new MapReduceMappingsToIntTask<K,V>
6759 >                     (map, this, b, rights, transformer, r, reducer)).fork();
6760 >                V v;
6761 >                while ((v = advance()) != null)
6762 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6763 >                result = r;
6764 >                CountedCompleter<?> c;
6765 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6766 >                    MapReduceMappingsToIntTask<K,V>
6767 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6768 >                        s = t.rights;
6769 >                    while (s != null) {
6770 >                        t.result = reducer.applyAsInt(t.result, s.result);
6771 >                        s = t.rights = s.nextRight;
6772 >                    }
6773 >                }
6774 >            }
6775          }
6776      }
6777  
6778      // Unsafe mechanics
6779 <    private static final sun.misc.Unsafe UNSAFE;
6780 <    private static final long SBASE;
6781 <    private static final int SSHIFT;
6782 <    private static final long TBASE;
6783 <    private static final int TSHIFT;
6779 >    private static final sun.misc.Unsafe U;
6780 >    private static final long SIZECTL;
6781 >    private static final long TRANSFERINDEX;
6782 >    private static final long TRANSFERORIGIN;
6783 >    private static final long BASECOUNT;
6784 >    private static final long CELLSBUSY;
6785 >    private static final long CELLVALUE;
6786 >    private static final long ABASE;
6787 >    private static final int ASHIFT;
6788  
6789      static {
1474        int ss, ts;
6790          try {
6791 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6792 <            Class tc = HashEntry[].class;
6793 <            Class sc = Segment[].class;
6794 <            TBASE = UNSAFE.arrayBaseOffset(tc);
6795 <            SBASE = UNSAFE.arrayBaseOffset(sc);
6796 <            ts = UNSAFE.arrayIndexScale(tc);
6797 <            ss = UNSAFE.arrayIndexScale(sc);
6791 >            U = sun.misc.Unsafe.getUnsafe();
6792 >            Class<?> k = ConcurrentHashMap.class;
6793 >            SIZECTL = U.objectFieldOffset
6794 >                (k.getDeclaredField("sizeCtl"));
6795 >            TRANSFERINDEX = U.objectFieldOffset
6796 >                (k.getDeclaredField("transferIndex"));
6797 >            TRANSFERORIGIN = U.objectFieldOffset
6798 >                (k.getDeclaredField("transferOrigin"));
6799 >            BASECOUNT = U.objectFieldOffset
6800 >                (k.getDeclaredField("baseCount"));
6801 >            CELLSBUSY = U.objectFieldOffset
6802 >                (k.getDeclaredField("cellsBusy"));
6803 >            Class<?> ck = Cell.class;
6804 >            CELLVALUE = U.objectFieldOffset
6805 >                (ck.getDeclaredField("value"));
6806 >            Class<?> sc = Node[].class;
6807 >            ABASE = U.arrayBaseOffset(sc);
6808 >            int scale = U.arrayIndexScale(sc);
6809 >            if ((scale & (scale - 1)) != 0)
6810 >                throw new Error("data type scale not a power of two");
6811 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6812          } catch (Exception e) {
6813              throw new Error(e);
6814          }
1486        if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
1487            throw new Error("data type scale not a power of two");
1488        SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1489        TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
6815      }
6816  
6817   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines