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.115 by jsr166, Fri Dec 2 14:28:17 2011 UTC vs.
Revision 1.251 by dl, Wed Sep 4 00:02:46 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines