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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines