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.112 by jsr166, Fri Jun 3 02:28:05 2011 UTC vs.
Revision 1.294 by dl, Wed Jun 8 19:44:32 2016 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines