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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines