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.33 by dl, Sat Dec 6 00:16:20 2003 UTC vs.
Revision 1.163 by dl, Thu Jan 17 14:13:00 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines