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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines