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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines