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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines