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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines