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

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines