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.195 by dl, Sat Mar 16 16:03:08 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines