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

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines