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

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.110 by jsr166, Wed Apr 27 14:06:30 2011 UTC vs.
Revision 1.205 by dl, Thu Apr 11 20:13:38 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines