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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines