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.89 by dl, Tue Jun 6 11:17:58 2006 UTC vs.
Revision 1.310 by jsr166, Wed May 23 06:11:41 2018 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines