ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines