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.92 by dl, Sat Dec 2 20:55:01 2006 UTC vs.
Revision 1.267 by jsr166, Mon Feb 23 20:54:08 2015 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines