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.110 by jsr166, Wed Apr 27 14:06:30 2011 UTC vs.
Revision 1.235 by dl, Fri Jul 5 10:40:16 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 java.util.Map.Entry}
135 > * objects do not support method {@code setValue}.
136 > *
137 > * <ul>
138 > * <li> forEach: Perform a given action on each element.
139 > * A variant form applies a given transformation on each element
140 > * before performing the action.</li>
141 > *
142 > * <li> search: Return the first available non-null result of
143 > * applying a given function on each element; skipping further
144 > * search when a result is found.</li>
145 > *
146 > * <li> reduce: Accumulate each element.  The supplied reduction
147 > * function cannot rely on ordering (more formally, it should be
148 > * both associative and commutative).  There are five variants:
149 > *
150 > * <ul>
151 > *
152 > * <li> Plain reductions. (There is not a form of this method for
153 > * (key, value) function arguments since there is no corresponding
154 > * return type.)</li>
155 > *
156 > * <li> Mapped reductions that accumulate the results of a given
157 > * function applied to each element.</li>
158 > *
159 > * <li> Reductions to scalar doubles, longs, and ints, using a
160 > * given basis value.</li>
161 > *
162 > * </ul>
163 > * </li>
164 > * </ul>
165 > *
166 > * <p>These bulk operations accept a {@code parallelismThreshold}
167 > * argument. Methods proceed sequentially if the current map size is
168 > * estimated to be less than the given threshold. Using a value of
169 > * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
170 > * of {@code 1} results in maximal parallelism by partitioning into
171 > * enough subtasks to fully utilize the {@link
172 > * ForkJoinPool#commonPool()} that is used for all parallel
173 > * computations. Normally, you would initially choose one of these
174 > * extreme values, and then measure performance of using in-between
175 > * values that trade off overhead versus throughput.
176 > *
177 > * <p>The concurrency properties of bulk operations follow
178 > * from those of ConcurrentHashMap: Any non-null result returned
179 > * from {@code get(key)} and related access methods bears a
180 > * happens-before relation with the associated insertion or
181 > * update.  The result of any bulk operation reflects the
182 > * composition of these per-element relations (but is not
183 > * necessarily atomic with respect to the map as a whole unless it
184 > * is somehow known to be quiescent).  Conversely, because keys
185 > * and values in the map are never null, null serves as a reliable
186 > * atomic indicator of the current lack of any result.  To
187 > * maintain this property, null serves as an implicit basis for
188 > * all non-scalar reduction operations. For the double, long, and
189 > * int versions, the basis should be one that, when combined with
190 > * any other value, returns that other value (more formally, it
191 > * should be the identity element for the reduction). Most common
192 > * reductions have these properties; for example, computing a sum
193 > * with basis 0 or a minimum with basis MAX_VALUE.
194 > *
195 > * <p>Search and transformation functions provided as arguments
196 > * should similarly return null to indicate the lack of any result
197 > * (in which case it is not used). In the case of mapped
198 > * reductions, this also enables transformations to serve as
199 > * filters, returning null (or, in the case of primitive
200 > * specializations, the identity basis) if the element should not
201 > * be combined. You can create compound transformations and
202 > * filterings by composing them yourself under this "null means
203 > * there is nothing there now" rule before using them in search or
204 > * reduce operations.
205 > *
206 > * <p>Methods accepting and/or returning Entry arguments maintain
207 > * key-value associations. They may be useful for example when
208 > * finding the key for the greatest value. Note that "plain" Entry
209 > * arguments can be supplied using {@code new
210 > * AbstractMap.SimpleEntry(k,v)}.
211 > *
212 > * <p>Bulk operations may complete abruptly, throwing an
213 > * exception encountered in the application of a supplied
214 > * function. Bear in mind when handling such exceptions that other
215 > * concurrently executing functions could also have thrown
216 > * exceptions, or would have done so if the first exception had
217 > * not occurred.
218 > *
219 > * <p>Speedups for parallel compared to sequential forms are common
220 > * but not guaranteed.  Parallel operations involving brief functions
221 > * on small maps may execute more slowly than sequential forms if the
222 > * underlying work to parallelize the computation is more expensive
223 > * than the computation itself.  Similarly, parallelization may not
224 > * lead to much actual parallelism if all processors are busy
225 > * performing unrelated tasks.
226 > *
227 > * <p>All arguments to all task methods must be non-null.
228   *
229   * <p>This class is a member of the
230   * <a href="{@docRoot}/../technotes/guides/collections/index.html">
# Line 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 +     * Table of counter cells. When non-null, size is a power of 2.
754 +     */
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 <     * Sets the ith element of given table, with volatile write
225 <     * semantics. (See above about use of putOrderedObject.)
766 >     * Creates a new, empty map with the default initial table size (16).
767       */
768 <    static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
228 <                                       HashEntry<K,V> e) {
229 <        UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
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 <    // Accessing segments
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      /**
1203 <     * Gets the jth element of given segment array (if nonnull) with
1204 <     * volatile element access semantics via Unsafe. (The null check
1205 <     * can trigger harmlessly only during deserialization.) Note:
1206 <     * because each element of segments array is set only once (using
1207 <     * fully ordered writes), some performance-sensitive methods rely
1208 <     * on this method only as a recheck upon null reads.
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 <    @SuppressWarnings("unchecked")
1220 <    static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
1221 <        long u = (j << SSHIFT) + SBASE;
630 <        return ss == null ? null :
631 <            (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
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 <     * Returns the segment for the given index, creating it and
1226 <     * recording in segment table (via CAS) if not already present.
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 <     * @param k the index
639 <     * @return the segment
1229 >     * @return the hash code value for this map
1230       */
1231 <    @SuppressWarnings("unchecked")
1232 <    private Segment<K,V> ensureSegment(int k) {
1233 <        final Segment<K,V>[] ss = this.segments;
1234 <        long u = (k << SSHIFT) + SBASE; // raw offset
1235 <        Segment<K,V> seg;
1236 <        if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
1237 <            Segment<K,V> proto = ss[0]; // use segment 0 as prototype
1238 <            int cap = proto.table.length;
1239 <            float lf = proto.loadFactor;
1240 <            int threshold = (int)(cap * lf);
1241 <            HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
1242 <            if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
1243 <                == null) { // recheck
1244 <                Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
1245 <                while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
1246 <                       == null) {
1247 <                    if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
1248 <                        break;
1249 <                }
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 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 >     * @return a string representation of this map
1252 >     */
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 <        int size;
1586 <        boolean overflow; // true if size overflows 32 bits
1587 <        long sum;         // sum of modCounts
1588 <        long last = 0L;   // previous sum
1589 <        int retries = -1; // first iteration isn't retry
1590 <        try {
1591 <            for (;;) {
1592 <                if (retries++ == RETRIES_BEFORE_LOCK) {
1593 <                    for (int j = 0; j < segments.length; ++j)
1594 <                        ensureSegment(j).lock(); // force creation
1595 <                }
1596 <                sum = 0L;
1597 <                size = 0;
1598 <                overflow = false;
1599 <                for (int j = 0; j < segments.length; ++j) {
1600 <                    Segment<K,V> seg = segmentAt(segments, j);
1601 <                    if (seg != null) {
1602 <                        sum += seg.modCount;
861 <                        int c = seg.count;
862 <                        if (c < 0 || (size += c) < 0)
863 <                            overflow = true;
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 (sum == last)
1605 >                if (binCount != 0)
1606                      break;
868                last = sum;
1607              }
1608 <        } finally {
1609 <            if (retries > RETRIES_BEFORE_LOCK) {
1610 <                for (int j = 0; j < segments.length; ++j)
1611 <                    segmentAt(segments, j).unlock();
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 <        return overflow ? Integer.MAX_VALUE : size;
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()
949 <        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 <        boolean found = false;
1903 <        long last = 0L;   // previous sum
1904 <        int retries = -1;
1905 <        try {
1906 <            outer: for (;;) {
1907 <                if (retries++ == RETRIES_BEFORE_LOCK) {
1908 <                    for (int j = 0; j < segments.length; ++j)
1909 <                        ensureSegment(j).lock(); // force creation
1910 <                }
1911 <                long sum = 0L;
1912 <                for (int j = 0; j < segments.length; ++j) {
1913 <                    HashEntry<K,V>[] tab;
1914 <                    Segment<K,V> seg = segmentAt(segments, j);
1915 <                    if (seg != null && (tab = seg.table) != null) {
1916 <                        for (int i = 0 ; i < tab.length; i++) {
1917 <                            HashEntry<K,V> e;
1918 <                            for (e = entryAt(tab, i); e != null; e = e.next) {
1919 <                                V v = e.value;
1920 <                                if (v != null && value.equals(v)) {
1921 <                                    found = true;
1922 <                                    break outer;
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                          }
976                        sum += seg.modCount;
1973                      }
1974                  }
1975 <                if (retries > 0 && sum == last)
1975 >                if (binCount != 0) {
1976 >                    if (binCount >= TREEIFY_THRESHOLD)
1977 >                        treeifyBin(tab, i);
1978                      break;
1979 <                last = sum;
982 <            }
983 <        } finally {
984 <            if (retries > RETRIES_BEFORE_LOCK) {
985 <                for (int j = 0; j < segments.length; ++j)
986 <                    segmentAt(segments, j).unlock();
1979 >                }
1980              }
1981          }
1982 <        return found;
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.
1013 <     * Neither the key nor the value can be null.
1014 <     *
1015 <     * <p> The value can be retrieved by calling the <tt>get</tt> method
1016 <     * 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
1020 <     * @return the previous value associated with <tt>key</tt>, or
1021 <     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
1022 <     * @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)
1028 <            throw new NullPointerException();
1029 <        int hash = hash(key.hashCode());
1030 <        int j = (hash >>> segmentShift) & segmentMask;
1031 <        if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
1032 <             (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
1033 <            s = ensureSegment(j);
1034 <        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
1042 <     * @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)
1048 <            throw new NullPointerException();
1049 <        int hash = hash(key.hashCode());
1050 <        int j = (hash >>> segmentShift) & segmentMask;
1051 <        if ((s = (Segment<K,V>)UNSAFE.getObject
1052 <             (segments, (j << SSHIFT) + SBASE)) == null)
1053 <            s = ensureSegment(j);
1054 <        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
1075 <     *         <tt>null</tt> if there was no mapping for <tt>key</tt>
1076 <     * @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);
1081 <        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;
1092 <        return value != null && (s = segmentForHash(hash)) != null &&
1093 <            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());
1103 <        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);
1106 <        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}
1111 <     *
1112 <     * @return the previous value associated with the specified key,
1113 <     *         or <tt>null</tt> if there was no mapping for the key
1114 <     * @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 >            // loop to avoid arbitrarily deep recursion on forwarding nodes
2108 >            outer: for (Node<K,V>[] tab = nextTable;;) {
2109 >                Node<K,V> e; int n;
2110 >                if (k == null || tab == null || (n = tab.length) == 0 ||
2111 >                    (e = tabAt(tab, (n - 1) & h)) == null)
2112 >                    return null;
2113 >                for (;;) {
2114 >                    int eh; K ek;
2115 >                    if ((eh = e.hash) == h &&
2116 >                        ((ek = e.key) == k || (ek != null && k.equals(ek))))
2117 >                        return e;
2118 >                    if (eh < 0) {
2119 >                        if (e instanceof ForwardingNode) {
2120 >                            tab = ((ForwardingNode<K,V>)e).nextTable;
2121 >                            continue outer;
2122 >                        }
2123 >                        else
2124 >                            return e.find(h, k);
2125 >                    }
2126 >                    if ((e = e.next) == null)
2127 >                        return null;
2128 >                }
2129 >            }
2130 >        }
2131      }
2132  
2133      /**
2134 <     * Removes all of the mappings from this map.
2134 >     * A place-holder node used in computeIfAbsent and compute
2135       */
2136 <    public void clear() {
2137 <        final Segment<K,V>[] segments = this.segments;
2138 <        for (int j = 0; j < segments.length; ++j) {
2139 <            Segment<K,V> s = segmentAt(segments, j);
2140 <            if (s != null)
2141 <                s.clear();
2136 >    static final class ReservationNode<K,V> extends Node<K,V> {
2137 >        ReservationNode() {
2138 >            super(RESERVED, null, null, null);
2139 >        }
2140 >
2141 >        Node<K,V> find(int h, Object k) {
2142 >            return null;
2143          }
2144      }
2145  
2146 +    /* ---------------- Table Initialization and Resizing -------------- */
2147 +
2148      /**
2149 <     * Returns a {@link Set} view of the keys contained in this map.
1138 <     * The set is backed by the map, so changes to the map are
1139 <     * reflected in the set, and vice-versa.  The set supports element
1140 <     * removal, which removes the corresponding mapping from this map,
1141 <     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1142 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1143 <     * operations.  It does not support the <tt>add</tt> or
1144 <     * <tt>addAll</tt> operations.
1145 <     *
1146 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1147 <     * that will never throw {@link ConcurrentModificationException},
1148 <     * and guarantees to traverse elements as they existed upon
1149 <     * construction of the iterator, and may (but is not guaranteed to)
1150 <     * reflect any modifications subsequent to construction.
2149 >     * Initializes table, using the size recorded in sizeCtl.
2150       */
2151 <    public Set<K> keySet() {
2152 <        Set<K> ks = keySet;
2153 <        return (ks != null) ? ks : (keySet = new KeySet());
2151 >    private final Node<K,V>[] initTable() {
2152 >        Node<K,V>[] tab; int sc;
2153 >        while ((tab = table) == null || tab.length == 0) {
2154 >            if ((sc = sizeCtl) < 0)
2155 >                Thread.yield(); // lost initialization race; just spin
2156 >            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2157 >                try {
2158 >                    if ((tab = table) == null || tab.length == 0) {
2159 >                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2160 >                        @SuppressWarnings({"rawtypes","unchecked"})
2161 >                            Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2162 >                        table = tab = nt;
2163 >                        sc = n - (n >>> 2);
2164 >                    }
2165 >                } finally {
2166 >                    sizeCtl = sc;
2167 >                }
2168 >                break;
2169 >            }
2170 >        }
2171 >        return tab;
2172      }
2173  
2174      /**
2175 <     * Returns a {@link Collection} view of the values contained in this map.
2176 <     * The collection is backed by the map, so changes to the map are
2177 <     * reflected in the collection, and vice-versa.  The collection
2178 <     * supports element removal, which removes the corresponding
2179 <     * mapping from this map, via the <tt>Iterator.remove</tt>,
1163 <     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1164 <     * <tt>retainAll</tt>, and <tt>clear</tt> operations.  It does not
1165 <     * support the <tt>add</tt> or <tt>addAll</tt> operations.
2175 >     * Adds to count, and if table is too small and not already
2176 >     * resizing, initiates transfer. If already resizing, helps
2177 >     * perform transfer if work is available.  Rechecks occupancy
2178 >     * after a transfer to see if another resize is already needed
2179 >     * because resizings are lagging additions.
2180       *
2181 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2182 <     * that will never throw {@link ConcurrentModificationException},
1169 <     * and guarantees to traverse elements as they existed upon
1170 <     * construction of the iterator, and may (but is not guaranteed to)
1171 <     * reflect any modifications subsequent to construction.
2181 >     * @param x the count to add
2182 >     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2183       */
2184 <    public Collection<V> values() {
2185 <        Collection<V> vs = values;
2186 <        return (vs != null) ? vs : (values = new Values());
2184 >    private final void addCount(long x, int check) {
2185 >        CounterCell[] as; long b, s;
2186 >        if ((as = counterCells) != null ||
2187 >            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2188 >            CounterCell a; long v; int m;
2189 >            boolean uncontended = true;
2190 >            if (as == null || (m = as.length - 1) < 0 ||
2191 >                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2192 >                !(uncontended =
2193 >                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2194 >                fullAddCount(x, uncontended);
2195 >                return;
2196 >            }
2197 >            if (check <= 1)
2198 >                return;
2199 >            s = sumCount();
2200 >        }
2201 >        if (check >= 0) {
2202 >            Node<K,V>[] tab, nt; int sc;
2203 >            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2204 >                   tab.length < MAXIMUM_CAPACITY) {
2205 >                if (sc < 0) {
2206 >                    if (sc == -1 || transferIndex <= transferOrigin ||
2207 >                        (nt = nextTable) == null)
2208 >                        break;
2209 >                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2210 >                        transfer(tab, nt);
2211 >                }
2212 >                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2213 >                    transfer(tab, null);
2214 >                s = sumCount();
2215 >            }
2216 >        }
2217      }
2218  
2219      /**
2220 <     * Returns a {@link Set} view of the mappings contained in this map.
1180 <     * The set is backed by the map, so changes to the map are
1181 <     * reflected in the set, and vice-versa.  The set supports element
1182 <     * removal, which removes the corresponding mapping from the map,
1183 <     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1184 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1185 <     * operations.  It does not support the <tt>add</tt> or
1186 <     * <tt>addAll</tt> operations.
1187 <     *
1188 <     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1189 <     * that will never throw {@link ConcurrentModificationException},
1190 <     * and guarantees to traverse elements as they existed upon
1191 <     * construction of the iterator, and may (but is not guaranteed to)
1192 <     * reflect any modifications subsequent to construction.
2220 >     * Helps transfer if a resize is in progress.
2221       */
2222 <    public Set<Map.Entry<K,V>> entrySet() {
2223 <        Set<Map.Entry<K,V>> es = entrySet;
2224 <        return (es != null) ? es : (entrySet = new EntrySet());
2222 >    final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2223 >        Node<K,V>[] nextTab; int sc;
2224 >        if ((f instanceof ForwardingNode) &&
2225 >            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2226 >            if (nextTab == nextTable && tab == table &&
2227 >                transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2228 >                U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2229 >                transfer(tab, nextTab);
2230 >            return nextTab;
2231 >        }
2232 >        return table;
2233      }
2234  
2235      /**
2236 <     * Returns an enumeration of the keys in this table.
2236 >     * Tries to presize table to accommodate the given number of elements.
2237       *
2238 <     * @return an enumeration of the keys in this table
1203 <     * @see #keySet()
2238 >     * @param size number of elements (doesn't need to be perfectly accurate)
2239       */
2240 <    public Enumeration<K> keys() {
2241 <        return new KeyIterator();
2240 >    private final void tryPresize(int size) {
2241 >        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2242 >            tableSizeFor(size + (size >>> 1) + 1);
2243 >        int sc;
2244 >        while ((sc = sizeCtl) >= 0) {
2245 >            Node<K,V>[] tab = table; int n;
2246 >            if (tab == null || (n = tab.length) == 0) {
2247 >                n = (sc > c) ? sc : c;
2248 >                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2249 >                    try {
2250 >                        if (table == tab) {
2251 >                            @SuppressWarnings({"rawtypes","unchecked"})
2252 >                                Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2253 >                            table = nt;
2254 >                            sc = n - (n >>> 2);
2255 >                        }
2256 >                    } finally {
2257 >                        sizeCtl = sc;
2258 >                    }
2259 >                }
2260 >            }
2261 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
2262 >                break;
2263 >            else if (tab == table &&
2264 >                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2265 >                transfer(tab, null);
2266 >        }
2267      }
2268  
2269      /**
2270 <     * Returns an enumeration of the values in this table.
2271 <     *
1212 <     * @return an enumeration of the values in this table
1213 <     * @see #values()
2270 >     * Moves and/or copies the nodes in each bin to new table. See
2271 >     * above for explanation.
2272       */
2273 <    public Enumeration<V> elements() {
2274 <        return new ValueIterator();
2273 >    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2274 >        int n = tab.length, stride;
2275 >        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2276 >            stride = MIN_TRANSFER_STRIDE; // subdivide range
2277 >        if (nextTab == null) {            // initiating
2278 >            try {
2279 >                @SuppressWarnings({"rawtypes","unchecked"})
2280 >                    Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2281 >                nextTab = nt;
2282 >            } catch (Throwable ex) {      // try to cope with OOME
2283 >                sizeCtl = Integer.MAX_VALUE;
2284 >                return;
2285 >            }
2286 >            nextTable = nextTab;
2287 >            transferOrigin = n;
2288 >            transferIndex = n;
2289 >            ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2290 >            for (int k = n; k > 0;) {    // progressively reveal ready slots
2291 >                int nextk = (k > stride) ? k - stride : 0;
2292 >                for (int m = nextk; m < k; ++m)
2293 >                    nextTab[m] = rev;
2294 >                for (int m = n + nextk; m < n + k; ++m)
2295 >                    nextTab[m] = rev;
2296 >                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2297 >            }
2298 >        }
2299 >        int nextn = nextTab.length;
2300 >        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2301 >        boolean advance = true;
2302 >        boolean finishing = false; // to ensure sweep before committing nextTab
2303 >        for (int i = 0, bound = 0;;) {
2304 >            int nextIndex, nextBound, fh; Node<K,V> f;
2305 >            while (advance) {
2306 >                if (--i >= bound || finishing)
2307 >                    advance = false;
2308 >                else if ((nextIndex = transferIndex) <= transferOrigin) {
2309 >                    i = -1;
2310 >                    advance = false;
2311 >                }
2312 >                else if (U.compareAndSwapInt
2313 >                         (this, TRANSFERINDEX, nextIndex,
2314 >                          nextBound = (nextIndex > stride ?
2315 >                                       nextIndex - stride : 0))) {
2316 >                    bound = nextBound;
2317 >                    i = nextIndex - 1;
2318 >                    advance = false;
2319 >                }
2320 >            }
2321 >            if (i < 0 || i >= n || i + n >= nextn) {
2322 >                if (finishing) {
2323 >                    nextTable = null;
2324 >                    table = nextTab;
2325 >                    sizeCtl = (n << 1) - (n >>> 1);
2326 >                    return;
2327 >                }
2328 >                for (int sc;;) {
2329 >                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2330 >                        if (sc != -1)
2331 >                            return;
2332 >                        finishing = advance = true;
2333 >                        i = n; // recheck before commit
2334 >                        break;
2335 >                    }
2336 >                }
2337 >            }
2338 >            else if ((f = tabAt(tab, i)) == null) {
2339 >                if (casTabAt(tab, i, null, fwd)) {
2340 >                    setTabAt(nextTab, i, null);
2341 >                    setTabAt(nextTab, i + n, null);
2342 >                    advance = true;
2343 >                }
2344 >            }
2345 >            else if ((fh = f.hash) == MOVED)
2346 >                advance = true; // already processed
2347 >            else {
2348 >                synchronized (f) {
2349 >                    if (tabAt(tab, i) == f) {
2350 >                        Node<K,V> ln, hn;
2351 >                        if (fh >= 0) {
2352 >                            int runBit = fh & n;
2353 >                            Node<K,V> lastRun = f;
2354 >                            for (Node<K,V> p = f.next; p != null; p = p.next) {
2355 >                                int b = p.hash & n;
2356 >                                if (b != runBit) {
2357 >                                    runBit = b;
2358 >                                    lastRun = p;
2359 >                                }
2360 >                            }
2361 >                            if (runBit == 0) {
2362 >                                ln = lastRun;
2363 >                                hn = null;
2364 >                            }
2365 >                            else {
2366 >                                hn = lastRun;
2367 >                                ln = null;
2368 >                            }
2369 >                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
2370 >                                int ph = p.hash; K pk = p.key; V pv = p.val;
2371 >                                if ((ph & n) == 0)
2372 >                                    ln = new Node<K,V>(ph, pk, pv, ln);
2373 >                                else
2374 >                                    hn = new Node<K,V>(ph, pk, pv, hn);
2375 >                            }
2376 >                            setTabAt(nextTab, i, ln);
2377 >                            setTabAt(nextTab, i + n, hn);
2378 >                            setTabAt(tab, i, fwd);
2379 >                            advance = true;
2380 >                        }
2381 >                        else if (f instanceof TreeBin) {
2382 >                            TreeBin<K,V> t = (TreeBin<K,V>)f;
2383 >                            TreeNode<K,V> lo = null, loTail = null;
2384 >                            TreeNode<K,V> hi = null, hiTail = null;
2385 >                            int lc = 0, hc = 0;
2386 >                            for (Node<K,V> e = t.first; e != null; e = e.next) {
2387 >                                int h = e.hash;
2388 >                                TreeNode<K,V> p = new TreeNode<K,V>
2389 >                                    (h, e.key, e.val, null, null);
2390 >                                if ((h & n) == 0) {
2391 >                                    if ((p.prev = loTail) == null)
2392 >                                        lo = p;
2393 >                                    else
2394 >                                        loTail.next = p;
2395 >                                    loTail = p;
2396 >                                    ++lc;
2397 >                                }
2398 >                                else {
2399 >                                    if ((p.prev = hiTail) == null)
2400 >                                        hi = p;
2401 >                                    else
2402 >                                        hiTail.next = p;
2403 >                                    hiTail = p;
2404 >                                    ++hc;
2405 >                                }
2406 >                            }
2407 >                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2408 >                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
2409 >                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2410 >                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
2411 >                            setTabAt(nextTab, i, ln);
2412 >                            setTabAt(nextTab, i + n, hn);
2413 >                            setTabAt(tab, i, fwd);
2414 >                            advance = true;
2415 >                        }
2416 >                    }
2417 >                }
2418 >            }
2419 >        }
2420      }
2421  
2422 <    /* ---------------- Iterator Support -------------- */
2422 >    /* ---------------- Counter support -------------- */
2423  
2424 <    abstract class HashIterator {
2425 <        int nextSegmentIndex;
2426 <        int nextTableIndex;
2427 <        HashEntry<K,V>[] currentTable;
2428 <        HashEntry<K, V> nextEntry;
2429 <        HashEntry<K, V> lastReturned;
2424 >    /**
2425 >     * A padded cell for distributing counts.  Adapted from LongAdder
2426 >     * and Striped64.  See their internal docs for explanation.
2427 >     */
2428 >    @sun.misc.Contended static final class CounterCell {
2429 >        volatile long value;
2430 >        CounterCell(long x) { value = x; }
2431 >    }
2432  
2433 <        HashIterator() {
2434 <            nextSegmentIndex = segments.length - 1;
2435 <            nextTableIndex = -1;
2436 <            advance();
2433 >    final long sumCount() {
2434 >        CounterCell[] as = counterCells; CounterCell a;
2435 >        long sum = baseCount;
2436 >        if (as != null) {
2437 >            for (int i = 0; i < as.length; ++i) {
2438 >                if ((a = as[i]) != null)
2439 >                    sum += a.value;
2440 >            }
2441 >        }
2442 >        return sum;
2443 >    }
2444 >
2445 >    // See LongAdder version for explanation
2446 >    private final void fullAddCount(long x, boolean wasUncontended) {
2447 >        int h;
2448 >        if ((h = ThreadLocalRandom.getProbe()) == 0) {
2449 >            ThreadLocalRandom.localInit();      // force initialization
2450 >            h = ThreadLocalRandom.getProbe();
2451 >            wasUncontended = true;
2452 >        }
2453 >        boolean collide = false;                // True if last slot nonempty
2454 >        for (;;) {
2455 >            CounterCell[] as; CounterCell a; int n; long v;
2456 >            if ((as = counterCells) != null && (n = as.length) > 0) {
2457 >                if ((a = as[(n - 1) & h]) == null) {
2458 >                    if (cellsBusy == 0) {            // Try to attach new Cell
2459 >                        CounterCell r = new CounterCell(x); // Optimistic create
2460 >                        if (cellsBusy == 0 &&
2461 >                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2462 >                            boolean created = false;
2463 >                            try {               // Recheck under lock
2464 >                                CounterCell[] rs; int m, j;
2465 >                                if ((rs = counterCells) != null &&
2466 >                                    (m = rs.length) > 0 &&
2467 >                                    rs[j = (m - 1) & h] == null) {
2468 >                                    rs[j] = r;
2469 >                                    created = true;
2470 >                                }
2471 >                            } finally {
2472 >                                cellsBusy = 0;
2473 >                            }
2474 >                            if (created)
2475 >                                break;
2476 >                            continue;           // Slot is now non-empty
2477 >                        }
2478 >                    }
2479 >                    collide = false;
2480 >                }
2481 >                else if (!wasUncontended)       // CAS already known to fail
2482 >                    wasUncontended = true;      // Continue after rehash
2483 >                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2484 >                    break;
2485 >                else if (counterCells != as || n >= NCPU)
2486 >                    collide = false;            // At max size or stale
2487 >                else if (!collide)
2488 >                    collide = true;
2489 >                else if (cellsBusy == 0 &&
2490 >                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2491 >                    try {
2492 >                        if (counterCells == as) {// Expand table unless stale
2493 >                            CounterCell[] rs = new CounterCell[n << 1];
2494 >                            for (int i = 0; i < n; ++i)
2495 >                                rs[i] = as[i];
2496 >                            counterCells = rs;
2497 >                        }
2498 >                    } finally {
2499 >                        cellsBusy = 0;
2500 >                    }
2501 >                    collide = false;
2502 >                    continue;                   // Retry with expanded table
2503 >                }
2504 >                h = ThreadLocalRandom.advanceProbe(h);
2505 >            }
2506 >            else if (cellsBusy == 0 && counterCells == as &&
2507 >                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2508 >                boolean init = false;
2509 >                try {                           // Initialize table
2510 >                    if (counterCells == as) {
2511 >                        CounterCell[] rs = new CounterCell[2];
2512 >                        rs[h & 1] = new CounterCell(x);
2513 >                        counterCells = rs;
2514 >                        init = true;
2515 >                    }
2516 >                } finally {
2517 >                    cellsBusy = 0;
2518 >                }
2519 >                if (init)
2520 >                    break;
2521 >            }
2522 >            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2523 >                break;                          // Fall back on using base
2524 >        }
2525 >    }
2526 >
2527 >    /* ---------------- Conversion from/to TreeBins -------------- */
2528 >
2529 >    /**
2530 >     * Replaces all linked nodes in bin at given index unless table is
2531 >     * too small, in which case resizes instead.
2532 >     */
2533 >    private final void treeifyBin(Node<K,V>[] tab, int index) {
2534 >        Node<K,V> b; int n, sc;
2535 >        if (tab != null) {
2536 >            if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2537 >                if (tab == table && (sc = sizeCtl) >= 0 &&
2538 >                    U.compareAndSwapInt(this, SIZECTL, sc, -2))
2539 >                    transfer(tab, null);
2540 >            }
2541 >            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2542 >                synchronized (b) {
2543 >                    if (tabAt(tab, index) == b) {
2544 >                        TreeNode<K,V> hd = null, tl = null;
2545 >                        for (Node<K,V> e = b; e != null; e = e.next) {
2546 >                            TreeNode<K,V> p =
2547 >                                new TreeNode<K,V>(e.hash, e.key, e.val,
2548 >                                                  null, null);
2549 >                            if ((p.prev = tl) == null)
2550 >                                hd = p;
2551 >                            else
2552 >                                tl.next = p;
2553 >                            tl = p;
2554 >                        }
2555 >                        setTabAt(tab, index, new TreeBin<K,V>(hd));
2556 >                    }
2557 >                }
2558 >            }
2559 >        }
2560 >    }
2561 >
2562 >    /**
2563 >     * Returns a list on non-TreeNodes replacing those in given list.
2564 >     */
2565 >    static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2566 >        Node<K,V> hd = null, tl = null;
2567 >        for (Node<K,V> q = b; q != null; q = q.next) {
2568 >            Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2569 >            if (tl == null)
2570 >                hd = p;
2571 >            else
2572 >                tl.next = p;
2573 >            tl = p;
2574 >        }
2575 >        return hd;
2576 >    }
2577 >
2578 >    /* ---------------- TreeNodes -------------- */
2579 >
2580 >    /**
2581 >     * Nodes for use in TreeBins
2582 >     */
2583 >    static final class TreeNode<K,V> extends Node<K,V> {
2584 >        TreeNode<K,V> parent;  // red-black tree links
2585 >        TreeNode<K,V> left;
2586 >        TreeNode<K,V> right;
2587 >        TreeNode<K,V> prev;    // needed to unlink next upon deletion
2588 >        boolean red;
2589 >
2590 >        TreeNode(int hash, K key, V val, Node<K,V> next,
2591 >                 TreeNode<K,V> parent) {
2592 >            super(hash, key, val, next);
2593 >            this.parent = parent;
2594 >        }
2595 >
2596 >        Node<K,V> find(int h, Object k) {
2597 >            return findTreeNode(h, k, null);
2598          }
2599  
2600          /**
2601 <         * Sets nextEntry to first node of next non-empty table
2602 <         * (in backwards order, to simplify checks).
2601 >         * Returns the TreeNode (or null if not found) for the given key
2602 >         * starting at given root.
2603           */
2604 <        final void advance() {
2605 <            for (;;) {
2606 <                if (nextTableIndex >= 0) {
2607 <                    if ((nextEntry = entryAt(currentTable,
2608 <                                             nextTableIndex--)) != null)
2604 >        final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2605 >            if (k != null) {
2606 >                TreeNode<K,V> p = this;
2607 >                do  {
2608 >                    int ph, dir; K pk; TreeNode<K,V> q;
2609 >                    TreeNode<K,V> pl = p.left, pr = p.right;
2610 >                    if ((ph = p.hash) > h)
2611 >                        p = pl;
2612 >                    else if (ph < h)
2613 >                        p = pr;
2614 >                    else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2615 >                        return p;
2616 >                    else if (pl == null && pr == null)
2617                          break;
2618 +                    else if ((kc != null ||
2619 +                              (kc = comparableClassFor(k)) != null) &&
2620 +                             (dir = compareComparables(kc, k, pk)) != 0)
2621 +                        p = (dir < 0) ? pl : pr;
2622 +                    else if (pl == null)
2623 +                        p = pr;
2624 +                    else if (pr == null ||
2625 +                             (q = pr.findTreeNode(h, k, kc)) == null)
2626 +                        p = pl;
2627 +                    else
2628 +                        return q;
2629 +                } while (p != null);
2630 +            }
2631 +            return null;
2632 +        }
2633 +    }
2634 +
2635 +    /* ---------------- TreeBins -------------- */
2636 +
2637 +    /**
2638 +     * TreeNodes used at the heads of bins. TreeBins do not hold user
2639 +     * keys or values, but instead point to list of TreeNodes and
2640 +     * their root. They also maintain a parasitic read-write lock
2641 +     * forcing writers (who hold bin lock) to wait for readers (who do
2642 +     * not) to complete before tree restructuring operations.
2643 +     */
2644 +    static final class TreeBin<K,V> extends Node<K,V> {
2645 +        TreeNode<K,V> root;
2646 +        volatile TreeNode<K,V> first;
2647 +        volatile Thread waiter;
2648 +        volatile int lockState;
2649 +        // values for lockState
2650 +        static final int WRITER = 1; // set while holding write lock
2651 +        static final int WAITER = 2; // set when waiting for write lock
2652 +        static final int READER = 4; // increment value for setting read lock
2653 +
2654 +        /**
2655 +         * Creates bin with initial set of nodes headed by b.
2656 +         */
2657 +        TreeBin(TreeNode<K,V> b) {
2658 +            super(TREEBIN, null, null, null);
2659 +            this.first = b;
2660 +            TreeNode<K,V> r = null;
2661 +            for (TreeNode<K,V> x = b, next; x != null; x = next) {
2662 +                next = (TreeNode<K,V>)x.next;
2663 +                x.left = x.right = null;
2664 +                if (r == null) {
2665 +                    x.parent = null;
2666 +                    x.red = false;
2667 +                    r = x;
2668                  }
2669 <                else if (nextSegmentIndex >= 0) {
2670 <                    Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
2671 <                    if (seg != null && (currentTable = seg.table) != null)
2672 <                        nextTableIndex = currentTable.length - 1;
2669 >                else {
2670 >                    Object key = x.key;
2671 >                    int hash = x.hash;
2672 >                    Class<?> kc = null;
2673 >                    for (TreeNode<K,V> p = r;;) {
2674 >                        int dir, ph;
2675 >                        if ((ph = p.hash) > hash)
2676 >                            dir = -1;
2677 >                        else if (ph < hash)
2678 >                            dir = 1;
2679 >                        else if ((kc != null ||
2680 >                                  (kc = comparableClassFor(key)) != null))
2681 >                            dir = compareComparables(kc, key, p.key);
2682 >                        else
2683 >                            dir = 0;
2684 >                        TreeNode<K,V> xp = p;
2685 >                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
2686 >                            x.parent = xp;
2687 >                            if (dir <= 0)
2688 >                                xp.left = x;
2689 >                            else
2690 >                                xp.right = x;
2691 >                            r = balanceInsertion(r, x);
2692 >                            break;
2693 >                        }
2694 >                    }
2695                  }
2696 <                else
2696 >            }
2697 >            this.root = r;
2698 >        }
2699 >
2700 >        /**
2701 >         * Acquires write lock for tree restructuring.
2702 >         */
2703 >        private final void lockRoot() {
2704 >            if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2705 >                contendedLock(); // offload to separate method
2706 >        }
2707 >
2708 >        /**
2709 >         * Releases write lock for tree restructuring.
2710 >         */
2711 >        private final void unlockRoot() {
2712 >            lockState = 0;
2713 >        }
2714 >
2715 >        /**
2716 >         * Possibly blocks awaiting root lock.
2717 >         */
2718 >        private final void contendedLock() {
2719 >            boolean waiting = false;
2720 >            for (int s;;) {
2721 >                if (((s = lockState) & WRITER) == 0) {
2722 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2723 >                        if (waiting)
2724 >                            waiter = null;
2725 >                        return;
2726 >                    }
2727 >                }
2728 >                else if ((s | WAITER) == 0) {
2729 >                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2730 >                        waiting = true;
2731 >                        waiter = Thread.currentThread();
2732 >                    }
2733 >                }
2734 >                else if (waiting)
2735 >                    LockSupport.park(this);
2736 >            }
2737 >        }
2738 >
2739 >        /**
2740 >         * Returns matching node or null if none. Tries to search
2741 >         * using tree comparisons from root, but continues linear
2742 >         * search when lock not available.
2743 >         */
2744 >        final Node<K,V> find(int h, Object k) {
2745 >            if (k != null) {
2746 >                for (Node<K,V> e = first; e != null; e = e.next) {
2747 >                    int s; K ek;
2748 >                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
2749 >                        if (e.hash == h &&
2750 >                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
2751 >                            return e;
2752 >                    }
2753 >                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2754 >                                                 s + READER)) {
2755 >                        TreeNode<K,V> r, p;
2756 >                        try {
2757 >                            p = ((r = root) == null ? null :
2758 >                                 r.findTreeNode(h, k, null));
2759 >                        } finally {
2760 >                            Thread w;
2761 >                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2762 >                                (READER|WAITER) && (w = waiter) != null)
2763 >                                LockSupport.unpark(w);
2764 >                        }
2765 >                        return p;
2766 >                    }
2767 >                }
2768 >            }
2769 >            return null;
2770 >        }
2771 >
2772 >        /**
2773 >         * Finds or adds a node.
2774 >         * @return null if added
2775 >         */
2776 >        final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2777 >            Class<?> kc = null;
2778 >            for (TreeNode<K,V> p = root;;) {
2779 >                int dir, ph; K pk; TreeNode<K,V> q, pr;
2780 >                if (p == null) {
2781 >                    first = root = new TreeNode<K,V>(h, k, v, null, null);
2782                      break;
2783 +                }
2784 +                else if ((ph = p.hash) > h)
2785 +                    dir = -1;
2786 +                else if (ph < h)
2787 +                    dir = 1;
2788 +                else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2789 +                    return p;
2790 +                else if ((kc == null &&
2791 +                          (kc = comparableClassFor(k)) == null) ||
2792 +                         (dir = compareComparables(kc, k, pk)) == 0) {
2793 +                    if (p.left == null)
2794 +                        dir = 1;
2795 +                    else if ((pr = p.right) == null ||
2796 +                             (q = pr.findTreeNode(h, k, kc)) == null)
2797 +                        dir = -1;
2798 +                    else
2799 +                        return q;
2800 +                }
2801 +                TreeNode<K,V> xp = p;
2802 +                if ((p = (dir < 0) ? p.left : p.right) == null) {
2803 +                    TreeNode<K,V> x, f = first;
2804 +                    first = x = new TreeNode<K,V>(h, k, v, f, xp);
2805 +                    if (f != null)
2806 +                        f.prev = x;
2807 +                    if (dir < 0)
2808 +                        xp.left = x;
2809 +                    else
2810 +                        xp.right = x;
2811 +                    if (!xp.red)
2812 +                        x.red = true;
2813 +                    else {
2814 +                        lockRoot();
2815 +                        try {
2816 +                            root = balanceInsertion(root, x);
2817 +                        } finally {
2818 +                            unlockRoot();
2819 +                        }
2820 +                    }
2821 +                    break;
2822 +                }
2823              }
2824 +            assert checkInvariants(root);
2825 +            return null;
2826          }
2827  
2828 <        final HashEntry<K,V> nextEntry() {
2829 <            HashEntry<K,V> e = nextEntry;
2830 <            if (e == null)
2831 <                throw new NoSuchElementException();
2832 <            lastReturned = e; // cannot assign until after null check
2833 <            if ((nextEntry = e.next) == null)
2834 <                advance();
2835 <            return e;
2828 >        /**
2829 >         * Removes the given node, that must be present before this
2830 >         * call.  This is messier than typical red-black deletion code
2831 >         * because we cannot swap the contents of an interior node
2832 >         * with a leaf successor that is pinned by "next" pointers
2833 >         * that are accessible independently of lock. So instead we
2834 >         * swap the tree linkages.
2835 >         *
2836 >         * @return true if now too small, so should be untreeified
2837 >         */
2838 >        final boolean removeTreeNode(TreeNode<K,V> p) {
2839 >            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2840 >            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
2841 >            TreeNode<K,V> r, rl;
2842 >            if (pred == null)
2843 >                first = next;
2844 >            else
2845 >                pred.next = next;
2846 >            if (next != null)
2847 >                next.prev = pred;
2848 >            if (first == null) {
2849 >                root = null;
2850 >                return true;
2851 >            }
2852 >            if ((r = root) == null || r.right == null || // too small
2853 >                (rl = r.left) == null || rl.left == null)
2854 >                return true;
2855 >            lockRoot();
2856 >            try {
2857 >                TreeNode<K,V> replacement;
2858 >                TreeNode<K,V> pl = p.left;
2859 >                TreeNode<K,V> pr = p.right;
2860 >                if (pl != null && pr != null) {
2861 >                    TreeNode<K,V> s = pr, sl;
2862 >                    while ((sl = s.left) != null) // find successor
2863 >                        s = sl;
2864 >                    boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2865 >                    TreeNode<K,V> sr = s.right;
2866 >                    TreeNode<K,V> pp = p.parent;
2867 >                    if (s == pr) { // p was s's direct parent
2868 >                        p.parent = s;
2869 >                        s.right = p;
2870 >                    }
2871 >                    else {
2872 >                        TreeNode<K,V> sp = s.parent;
2873 >                        if ((p.parent = sp) != null) {
2874 >                            if (s == sp.left)
2875 >                                sp.left = p;
2876 >                            else
2877 >                                sp.right = p;
2878 >                        }
2879 >                        if ((s.right = pr) != null)
2880 >                            pr.parent = s;
2881 >                    }
2882 >                    p.left = null;
2883 >                    if ((p.right = sr) != null)
2884 >                        sr.parent = p;
2885 >                    if ((s.left = pl) != null)
2886 >                        pl.parent = s;
2887 >                    if ((s.parent = pp) == null)
2888 >                        r = s;
2889 >                    else if (p == pp.left)
2890 >                        pp.left = s;
2891 >                    else
2892 >                        pp.right = s;
2893 >                    if (sr != null)
2894 >                        replacement = sr;
2895 >                    else
2896 >                        replacement = p;
2897 >                }
2898 >                else if (pl != null)
2899 >                    replacement = pl;
2900 >                else if (pr != null)
2901 >                    replacement = pr;
2902 >                else
2903 >                    replacement = p;
2904 >                if (replacement != p) {
2905 >                    TreeNode<K,V> pp = replacement.parent = p.parent;
2906 >                    if (pp == null)
2907 >                        r = replacement;
2908 >                    else if (p == pp.left)
2909 >                        pp.left = replacement;
2910 >                    else
2911 >                        pp.right = replacement;
2912 >                    p.left = p.right = p.parent = null;
2913 >                }
2914 >
2915 >                root = (p.red) ? r : balanceDeletion(r, replacement);
2916 >
2917 >                if (p == replacement) {  // detach pointers
2918 >                    TreeNode<K,V> pp;
2919 >                    if ((pp = p.parent) != null) {
2920 >                        if (p == pp.left)
2921 >                            pp.left = null;
2922 >                        else if (p == pp.right)
2923 >                            pp.right = null;
2924 >                        p.parent = null;
2925 >                    }
2926 >                }
2927 >            } finally {
2928 >                unlockRoot();
2929 >            }
2930 >            assert checkInvariants(root);
2931 >            return false;
2932 >        }
2933 >
2934 >        /* ------------------------------------------------------------ */
2935 >        // Red-black tree methods, all adapted from CLR
2936 >
2937 >        static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2938 >                                              TreeNode<K,V> p) {
2939 >            TreeNode<K,V> r, pp, rl;
2940 >            if (p != null && (r = p.right) != null) {
2941 >                if ((rl = p.right = r.left) != null)
2942 >                    rl.parent = p;
2943 >                if ((pp = r.parent = p.parent) == null)
2944 >                    (root = r).red = false;
2945 >                else if (pp.left == p)
2946 >                    pp.left = r;
2947 >                else
2948 >                    pp.right = r;
2949 >                r.left = p;
2950 >                p.parent = r;
2951 >            }
2952 >            return root;
2953 >        }
2954 >
2955 >        static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2956 >                                               TreeNode<K,V> p) {
2957 >            TreeNode<K,V> l, pp, lr;
2958 >            if (p != null && (l = p.left) != null) {
2959 >                if ((lr = p.left = l.right) != null)
2960 >                    lr.parent = p;
2961 >                if ((pp = l.parent = p.parent) == null)
2962 >                    (root = l).red = false;
2963 >                else if (pp.right == p)
2964 >                    pp.right = l;
2965 >                else
2966 >                    pp.left = l;
2967 >                l.right = p;
2968 >                p.parent = l;
2969 >            }
2970 >            return root;
2971          }
2972  
2973 <        public final boolean hasNext() { return nextEntry != null; }
2974 <        public final boolean hasMoreElements() { return nextEntry != null; }
2973 >        static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2974 >                                                    TreeNode<K,V> x) {
2975 >            x.red = true;
2976 >            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2977 >                if ((xp = x.parent) == null) {
2978 >                    x.red = false;
2979 >                    return x;
2980 >                }
2981 >                else if (!xp.red || (xpp = xp.parent) == null)
2982 >                    return root;
2983 >                if (xp == (xppl = xpp.left)) {
2984 >                    if ((xppr = xpp.right) != null && xppr.red) {
2985 >                        xppr.red = false;
2986 >                        xp.red = false;
2987 >                        xpp.red = true;
2988 >                        x = xpp;
2989 >                    }
2990 >                    else {
2991 >                        if (x == xp.right) {
2992 >                            root = rotateLeft(root, x = xp);
2993 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
2994 >                        }
2995 >                        if (xp != null) {
2996 >                            xp.red = false;
2997 >                            if (xpp != null) {
2998 >                                xpp.red = true;
2999 >                                root = rotateRight(root, xpp);
3000 >                            }
3001 >                        }
3002 >                    }
3003 >                }
3004 >                else {
3005 >                    if (xppl != null && xppl.red) {
3006 >                        xppl.red = false;
3007 >                        xp.red = false;
3008 >                        xpp.red = true;
3009 >                        x = xpp;
3010 >                    }
3011 >                    else {
3012 >                        if (x == xp.left) {
3013 >                            root = rotateRight(root, x = xp);
3014 >                            xpp = (xp = x.parent) == null ? null : xp.parent;
3015 >                        }
3016 >                        if (xp != null) {
3017 >                            xp.red = false;
3018 >                            if (xpp != null) {
3019 >                                xpp.red = true;
3020 >                                root = rotateLeft(root, xpp);
3021 >                            }
3022 >                        }
3023 >                    }
3024 >                }
3025 >            }
3026 >        }
3027 >
3028 >        static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3029 >                                                   TreeNode<K,V> x) {
3030 >            for (TreeNode<K,V> xp, xpl, xpr;;)  {
3031 >                if (x == null || x == root)
3032 >                    return root;
3033 >                else if ((xp = x.parent) == null) {
3034 >                    x.red = false;
3035 >                    return x;
3036 >                }
3037 >                else if (x.red) {
3038 >                    x.red = false;
3039 >                    return root;
3040 >                }
3041 >                else if ((xpl = xp.left) == x) {
3042 >                    if ((xpr = xp.right) != null && xpr.red) {
3043 >                        xpr.red = false;
3044 >                        xp.red = true;
3045 >                        root = rotateLeft(root, xp);
3046 >                        xpr = (xp = x.parent) == null ? null : xp.right;
3047 >                    }
3048 >                    if (xpr == null)
3049 >                        x = xp;
3050 >                    else {
3051 >                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3052 >                        if ((sr == null || !sr.red) &&
3053 >                            (sl == null || !sl.red)) {
3054 >                            xpr.red = true;
3055 >                            x = xp;
3056 >                        }
3057 >                        else {
3058 >                            if (sr == null || !sr.red) {
3059 >                                if (sl != null)
3060 >                                    sl.red = false;
3061 >                                xpr.red = true;
3062 >                                root = rotateRight(root, xpr);
3063 >                                xpr = (xp = x.parent) == null ?
3064 >                                    null : xp.right;
3065 >                            }
3066 >                            if (xpr != null) {
3067 >                                xpr.red = (xp == null) ? false : xp.red;
3068 >                                if ((sr = xpr.right) != null)
3069 >                                    sr.red = false;
3070 >                            }
3071 >                            if (xp != null) {
3072 >                                xp.red = false;
3073 >                                root = rotateLeft(root, xp);
3074 >                            }
3075 >                            x = root;
3076 >                        }
3077 >                    }
3078 >                }
3079 >                else { // symmetric
3080 >                    if (xpl != null && xpl.red) {
3081 >                        xpl.red = false;
3082 >                        xp.red = true;
3083 >                        root = rotateRight(root, xp);
3084 >                        xpl = (xp = x.parent) == null ? null : xp.left;
3085 >                    }
3086 >                    if (xpl == null)
3087 >                        x = xp;
3088 >                    else {
3089 >                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3090 >                        if ((sl == null || !sl.red) &&
3091 >                            (sr == null || !sr.red)) {
3092 >                            xpl.red = true;
3093 >                            x = xp;
3094 >                        }
3095 >                        else {
3096 >                            if (sl == null || !sl.red) {
3097 >                                if (sr != null)
3098 >                                    sr.red = false;
3099 >                                xpl.red = true;
3100 >                                root = rotateLeft(root, xpl);
3101 >                                xpl = (xp = x.parent) == null ?
3102 >                                    null : xp.left;
3103 >                            }
3104 >                            if (xpl != null) {
3105 >                                xpl.red = (xp == null) ? false : xp.red;
3106 >                                if ((sl = xpl.left) != null)
3107 >                                    sl.red = false;
3108 >                            }
3109 >                            if (xp != null) {
3110 >                                xp.red = false;
3111 >                                root = rotateRight(root, xp);
3112 >                            }
3113 >                            x = root;
3114 >                        }
3115 >                    }
3116 >                }
3117 >            }
3118 >        }
3119 >
3120 >        /**
3121 >         * Recursive invariant check
3122 >         */
3123 >        static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3124 >            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3125 >                tb = t.prev, tn = (TreeNode<K,V>)t.next;
3126 >            if (tb != null && tb.next != t)
3127 >                return false;
3128 >            if (tn != null && tn.prev != t)
3129 >                return false;
3130 >            if (tp != null && t != tp.left && t != tp.right)
3131 >                return false;
3132 >            if (tl != null && (tl.parent != t || tl.hash > t.hash))
3133 >                return false;
3134 >            if (tr != null && (tr.parent != t || tr.hash < t.hash))
3135 >                return false;
3136 >            if (t.red && tl != null && tl.red && tr != null && tr.red)
3137 >                return false;
3138 >            if (tl != null && !checkInvariants(tl))
3139 >                return false;
3140 >            if (tr != null && !checkInvariants(tr))
3141 >                return false;
3142 >            return true;
3143 >        }
3144 >
3145 >        private static final sun.misc.Unsafe U;
3146 >        private static final long LOCKSTATE;
3147 >        static {
3148 >            try {
3149 >                U = sun.misc.Unsafe.getUnsafe();
3150 >                Class<?> k = TreeBin.class;
3151 >                LOCKSTATE = U.objectFieldOffset
3152 >                    (k.getDeclaredField("lockState"));
3153 >            } catch (Exception e) {
3154 >                throw new Error(e);
3155 >            }
3156 >        }
3157 >    }
3158 >
3159 >    /* ----------------Table Traversal -------------- */
3160 >
3161 >    /**
3162 >     * Encapsulates traversal for methods such as containsValue; also
3163 >     * serves as a base class for other iterators and spliterators.
3164 >     *
3165 >     * Method advance visits once each still-valid node that was
3166 >     * reachable upon iterator construction. It might miss some that
3167 >     * were added to a bin after the bin was visited, which is OK wrt
3168 >     * consistency guarantees. Maintaining this property in the face
3169 >     * of possible ongoing resizes requires a fair amount of
3170 >     * bookkeeping state that is difficult to optimize away amidst
3171 >     * volatile accesses.  Even so, traversal maintains reasonable
3172 >     * throughput.
3173 >     *
3174 >     * Normally, iteration proceeds bin-by-bin traversing lists.
3175 >     * However, if the table has been resized, then all future steps
3176 >     * must traverse both the bin at the current index as well as at
3177 >     * (index + baseSize); and so on for further resizings. To
3178 >     * paranoically cope with potential sharing by users of iterators
3179 >     * across threads, iteration terminates if a bounds checks fails
3180 >     * for a table read.
3181 >     */
3182 >    static class Traverser<K,V> {
3183 >        Node<K,V>[] tab;        // current table; updated if resized
3184 >        Node<K,V> next;         // the next entry to use
3185 >        int index;              // index of bin to use next
3186 >        int baseIndex;          // current index of initial table
3187 >        int baseLimit;          // index bound for initial table
3188 >        final int baseSize;     // initial table size
3189 >
3190 >        Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3191 >            this.tab = tab;
3192 >            this.baseSize = size;
3193 >            this.baseIndex = this.index = index;
3194 >            this.baseLimit = limit;
3195 >            this.next = null;
3196 >        }
3197 >
3198 >        /**
3199 >         * Advances if possible, returning next valid node, or null if none.
3200 >         */
3201 >        final Node<K,V> advance() {
3202 >            Node<K,V> e;
3203 >            if ((e = next) != null)
3204 >                e = e.next;
3205 >            for (;;) {
3206 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
3207 >                if (e != null)
3208 >                    return next = e;
3209 >                if (baseIndex >= baseLimit || (t = tab) == null ||
3210 >                    (n = t.length) <= (i = index) || i < 0)
3211 >                    return next = null;
3212 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
3213 >                    if (e instanceof ForwardingNode) {
3214 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
3215 >                        e = null;
3216 >                        continue;
3217 >                    }
3218 >                    else if (e instanceof TreeBin)
3219 >                        e = ((TreeBin<K,V>)e).first;
3220 >                    else
3221 >                        e = null;
3222 >                }
3223 >                if ((index += baseSize) >= n)
3224 >                    index = ++baseIndex;    // visit upper slots if present
3225 >            }
3226 >        }
3227 >    }
3228 >
3229 >    /**
3230 >     * Base of key, value, and entry Iterators. Adds fields to
3231 >     * Traverser to support iterator.remove.
3232 >     */
3233 >    static class BaseIterator<K,V> extends Traverser<K,V> {
3234 >        final ConcurrentHashMap<K,V> map;
3235 >        Node<K,V> lastReturned;
3236 >        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3237 >                    ConcurrentHashMap<K,V> map) {
3238 >            super(tab, size, index, limit);
3239 >            this.map = map;
3240 >            advance();
3241 >        }
3242 >
3243 >        public final boolean hasNext() { return next != null; }
3244 >        public final boolean hasMoreElements() { return next != null; }
3245  
3246          public final void remove() {
3247 <            if (lastReturned == null)
3247 >            Node<K,V> p;
3248 >            if ((p = lastReturned) == null)
3249                  throw new IllegalStateException();
1271            ConcurrentHashMap.this.remove(lastReturned.key);
3250              lastReturned = null;
3251 +            map.replaceNode(p.key, null, null);
3252          }
3253      }
3254  
3255 <    final class KeyIterator
3256 <        extends HashIterator
3257 <        implements Iterator<K>, Enumeration<K>
3258 <    {
3259 <        public final K next()        { return super.nextEntry().key; }
3260 <        public final K nextElement() { return super.nextEntry().key; }
3261 <    }
3262 <
3263 <    final class ValueIterator
3264 <        extends HashIterator
3265 <        implements Iterator<V>, Enumeration<V>
3266 <    {
3267 <        public final V next()        { return super.nextEntry().value; }
3268 <        public final V nextElement() { return super.nextEntry().value; }
3255 >    static final class KeyIterator<K,V> extends BaseIterator<K,V>
3256 >        implements Iterator<K>, Enumeration<K> {
3257 >        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3258 >                    ConcurrentHashMap<K,V> map) {
3259 >            super(tab, index, size, limit, map);
3260 >        }
3261 >
3262 >        public final K next() {
3263 >            Node<K,V> p;
3264 >            if ((p = next) == null)
3265 >                throw new NoSuchElementException();
3266 >            K k = p.key;
3267 >            lastReturned = p;
3268 >            advance();
3269 >            return k;
3270 >        }
3271 >
3272 >        public final K nextElement() { return next(); }
3273 >    }
3274 >
3275 >    static final class ValueIterator<K,V> extends BaseIterator<K,V>
3276 >        implements Iterator<V>, Enumeration<V> {
3277 >        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3278 >                      ConcurrentHashMap<K,V> map) {
3279 >            super(tab, index, size, limit, map);
3280 >        }
3281 >
3282 >        public final V next() {
3283 >            Node<K,V> p;
3284 >            if ((p = next) == null)
3285 >                throw new NoSuchElementException();
3286 >            V v = p.val;
3287 >            lastReturned = p;
3288 >            advance();
3289 >            return v;
3290 >        }
3291 >
3292 >        public final V nextElement() { return next(); }
3293 >    }
3294 >
3295 >    static final class EntryIterator<K,V> extends BaseIterator<K,V>
3296 >        implements Iterator<Map.Entry<K,V>> {
3297 >        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3298 >                      ConcurrentHashMap<K,V> map) {
3299 >            super(tab, index, size, limit, map);
3300 >        }
3301 >
3302 >        public final Map.Entry<K,V> next() {
3303 >            Node<K,V> p;
3304 >            if ((p = next) == null)
3305 >                throw new NoSuchElementException();
3306 >            K k = p.key;
3307 >            V v = p.val;
3308 >            lastReturned = p;
3309 >            advance();
3310 >            return new MapEntry<K,V>(k, v, map);
3311 >        }
3312      }
3313  
3314      /**
3315 <     * Custom Entry class used by EntryIterator.next(), that relays
3316 <     * setValue changes to the underlying map.
3317 <     */
3318 <    final class WriteThroughEntry
3319 <        extends AbstractMap.SimpleEntry<K,V>
3320 <    {
3321 <        WriteThroughEntry(K k, V v) {
3322 <            super(k,v);
3315 >     * Exported Entry for EntryIterator
3316 >     */
3317 >    static final class MapEntry<K,V> implements Map.Entry<K,V> {
3318 >        final K key; // non-null
3319 >        V val;       // non-null
3320 >        final ConcurrentHashMap<K,V> map;
3321 >        MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3322 >            this.key = key;
3323 >            this.val = val;
3324 >            this.map = map;
3325 >        }
3326 >        public K getKey()        { return key; }
3327 >        public V getValue()      { return val; }
3328 >        public int hashCode()    { return key.hashCode() ^ val.hashCode(); }
3329 >        public String toString() { return key + "=" + val; }
3330 >
3331 >        public boolean equals(Object o) {
3332 >            Object k, v; Map.Entry<?,?> e;
3333 >            return ((o instanceof Map.Entry) &&
3334 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3335 >                    (v = e.getValue()) != null &&
3336 >                    (k == key || k.equals(key)) &&
3337 >                    (v == val || v.equals(val)));
3338          }
3339  
3340          /**
3341           * Sets our entry's value and writes through to the map. The
3342 <         * value to return is somewhat arbitrary here. Since a
3343 <         * WriteThroughEntry does not necessarily track asynchronous
3344 <         * changes, the most recent "previous" value could be
3345 <         * different from what we return (or could even have been
3346 <         * removed in which case the put will re-establish). We do not
1310 <         * and cannot guarantee more.
3342 >         * value to return is somewhat arbitrary here. Since we do not
3343 >         * necessarily track asynchronous changes, the most recent
3344 >         * "previous" value could be different from what we return (or
3345 >         * could even have been removed, in which case the put will
3346 >         * re-establish). We do not and cannot guarantee more.
3347           */
3348          public V setValue(V value) {
3349              if (value == null) throw new NullPointerException();
3350 <            V v = super.setValue(value);
3351 <            ConcurrentHashMap.this.put(getKey(), value);
3350 >            V v = val;
3351 >            val = value;
3352 >            map.put(key, value);
3353              return v;
3354          }
3355      }
3356  
3357 <    final class EntryIterator
3358 <        extends HashIterator
3359 <        implements Iterator<Entry<K,V>>
3360 <    {
3361 <        public Map.Entry<K,V> next() {
3362 <            HashEntry<K,V> e = super.nextEntry();
3363 <            return new WriteThroughEntry(e.key, e.value);
3357 >    static final class KeySpliterator<K,V> extends Traverser<K,V>
3358 >        implements Spliterator<K> {
3359 >        long est;               // size estimate
3360 >        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3361 >                       long est) {
3362 >            super(tab, size, index, limit);
3363 >            this.est = est;
3364 >        }
3365 >
3366 >        public Spliterator<K> trySplit() {
3367 >            int i, f, h;
3368 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3369 >                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3370 >                                        f, est >>>= 1);
3371 >        }
3372 >
3373 >        public void forEachRemaining(Consumer<? super K> action) {
3374 >            if (action == null) throw new NullPointerException();
3375 >            for (Node<K,V> p; (p = advance()) != null;)
3376 >                action.accept(p.key);
3377 >        }
3378 >
3379 >        public boolean tryAdvance(Consumer<? super K> action) {
3380 >            if (action == null) throw new NullPointerException();
3381 >            Node<K,V> p;
3382 >            if ((p = advance()) == null)
3383 >                return false;
3384 >            action.accept(p.key);
3385 >            return true;
3386 >        }
3387 >
3388 >        public long estimateSize() { return est; }
3389 >
3390 >        public int characteristics() {
3391 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3392 >                Spliterator.NONNULL;
3393          }
3394      }
3395  
3396 <    final class KeySet extends AbstractSet<K> {
3397 <        public Iterator<K> iterator() {
3398 <            return new KeyIterator();
3396 >    static final class ValueSpliterator<K,V> extends Traverser<K,V>
3397 >        implements Spliterator<V> {
3398 >        long est;               // size estimate
3399 >        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3400 >                         long est) {
3401 >            super(tab, size, index, limit);
3402 >            this.est = est;
3403          }
3404 <        public int size() {
3405 <            return ConcurrentHashMap.this.size();
3404 >
3405 >        public Spliterator<V> trySplit() {
3406 >            int i, f, h;
3407 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3408 >                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3409 >                                          f, est >>>= 1);
3410          }
3411 <        public boolean isEmpty() {
3412 <            return ConcurrentHashMap.this.isEmpty();
3411 >
3412 >        public void forEachRemaining(Consumer<? super V> action) {
3413 >            if (action == null) throw new NullPointerException();
3414 >            for (Node<K,V> p; (p = advance()) != null;)
3415 >                action.accept(p.val);
3416          }
3417 <        public boolean contains(Object o) {
3418 <            return ConcurrentHashMap.this.containsKey(o);
3417 >
3418 >        public boolean tryAdvance(Consumer<? super V> action) {
3419 >            if (action == null) throw new NullPointerException();
3420 >            Node<K,V> p;
3421 >            if ((p = advance()) == null)
3422 >                return false;
3423 >            action.accept(p.val);
3424 >            return true;
3425          }
3426 <        public boolean remove(Object o) {
3427 <            return ConcurrentHashMap.this.remove(o) != null;
3426 >
3427 >        public long estimateSize() { return est; }
3428 >
3429 >        public int characteristics() {
3430 >            return Spliterator.CONCURRENT | Spliterator.NONNULL;
3431 >        }
3432 >    }
3433 >
3434 >    static final class EntrySpliterator<K,V> extends Traverser<K,V>
3435 >        implements Spliterator<Map.Entry<K,V>> {
3436 >        final ConcurrentHashMap<K,V> map; // To export MapEntry
3437 >        long est;               // size estimate
3438 >        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3439 >                         long est, ConcurrentHashMap<K,V> map) {
3440 >            super(tab, size, index, limit);
3441 >            this.map = map;
3442 >            this.est = est;
3443 >        }
3444 >
3445 >        public Spliterator<Map.Entry<K,V>> trySplit() {
3446 >            int i, f, h;
3447 >            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3448 >                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3449 >                                          f, est >>>= 1, map);
3450 >        }
3451 >
3452 >        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3453 >            if (action == null) throw new NullPointerException();
3454 >            for (Node<K,V> p; (p = advance()) != null; )
3455 >                action.accept(new MapEntry<K,V>(p.key, p.val, map));
3456 >        }
3457 >
3458 >        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3459 >            if (action == null) throw new NullPointerException();
3460 >            Node<K,V> p;
3461 >            if ((p = advance()) == null)
3462 >                return false;
3463 >            action.accept(new MapEntry<K,V>(p.key, p.val, map));
3464 >            return true;
3465 >        }
3466 >
3467 >        public long estimateSize() { return est; }
3468 >
3469 >        public int characteristics() {
3470 >            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3471 >                Spliterator.NONNULL;
3472 >        }
3473 >    }
3474 >
3475 >    // Parallel bulk operations
3476 >
3477 >    /**
3478 >     * Computes initial batch value for bulk tasks. The returned value
3479 >     * is approximately exp2 of the number of times (minus one) to
3480 >     * split task by two before executing leaf action. This value is
3481 >     * faster to compute and more convenient to use as a guide to
3482 >     * splitting than is the depth, since it is used while dividing by
3483 >     * two anyway.
3484 >     */
3485 >    final int batchFor(long b) {
3486 >        long n;
3487 >        if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3488 >            return 0;
3489 >        int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3490 >        return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3491 >    }
3492 >
3493 >    /**
3494 >     * Performs the given action for each (key, value).
3495 >     *
3496 >     * @param parallelismThreshold the (estimated) number of elements
3497 >     * needed for this operation to be executed in parallel
3498 >     * @param action the action
3499 >     * @since 1.8
3500 >     */
3501 >    public void forEach(long parallelismThreshold,
3502 >                        BiConsumer<? super K,? super V> action) {
3503 >        if (action == null) throw new NullPointerException();
3504 >        new ForEachMappingTask<K,V>
3505 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3506 >             action).invoke();
3507 >    }
3508 >
3509 >    /**
3510 >     * Performs the given action for each non-null transformation
3511 >     * of each (key, value).
3512 >     *
3513 >     * @param parallelismThreshold the (estimated) number of elements
3514 >     * needed for this operation to be executed in parallel
3515 >     * @param transformer a function returning the transformation
3516 >     * for an element, or null if there is no transformation (in
3517 >     * which case the action is not applied)
3518 >     * @param action the action
3519 >     * @since 1.8
3520 >     */
3521 >    public <U> void forEach(long parallelismThreshold,
3522 >                            BiFunction<? super K, ? super V, ? extends U> transformer,
3523 >                            Consumer<? super U> action) {
3524 >        if (transformer == null || action == null)
3525 >            throw new NullPointerException();
3526 >        new ForEachTransformedMappingTask<K,V,U>
3527 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3528 >             transformer, action).invoke();
3529 >    }
3530 >
3531 >    /**
3532 >     * Returns a non-null result from applying the given search
3533 >     * function on each (key, value), or null if none.  Upon
3534 >     * success, further element processing is suppressed and the
3535 >     * results of any other parallel invocations of the search
3536 >     * function are ignored.
3537 >     *
3538 >     * @param parallelismThreshold the (estimated) number of elements
3539 >     * needed for this operation to be executed in parallel
3540 >     * @param searchFunction a function returning a non-null
3541 >     * result on success, else null
3542 >     * @return a non-null result from applying the given search
3543 >     * function on each (key, value), or null if none
3544 >     * @since 1.8
3545 >     */
3546 >    public <U> U search(long parallelismThreshold,
3547 >                        BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3548 >        if (searchFunction == null) throw new NullPointerException();
3549 >        return new SearchMappingsTask<K,V,U>
3550 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3551 >             searchFunction, new AtomicReference<U>()).invoke();
3552 >    }
3553 >
3554 >    /**
3555 >     * Returns the result of accumulating the given transformation
3556 >     * of all (key, value) pairs using the given reducer to
3557 >     * combine values, or null if none.
3558 >     *
3559 >     * @param parallelismThreshold the (estimated) number of elements
3560 >     * needed for this operation to be executed in parallel
3561 >     * @param transformer a function returning the transformation
3562 >     * for an element, or null if there is no transformation (in
3563 >     * which case it is not combined)
3564 >     * @param reducer a commutative associative combining function
3565 >     * @return the result of accumulating the given transformation
3566 >     * of all (key, value) pairs
3567 >     * @since 1.8
3568 >     */
3569 >    public <U> U reduce(long parallelismThreshold,
3570 >                        BiFunction<? super K, ? super V, ? extends U> transformer,
3571 >                        BiFunction<? super U, ? super U, ? extends U> reducer) {
3572 >        if (transformer == null || reducer == null)
3573 >            throw new NullPointerException();
3574 >        return new MapReduceMappingsTask<K,V,U>
3575 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3576 >             null, transformer, reducer).invoke();
3577 >    }
3578 >
3579 >    /**
3580 >     * Returns the result of accumulating the given transformation
3581 >     * of all (key, value) pairs using the given reducer to
3582 >     * combine values, and the given basis as an identity value.
3583 >     *
3584 >     * @param parallelismThreshold the (estimated) number of elements
3585 >     * needed for this operation to be executed in parallel
3586 >     * @param transformer a function returning the transformation
3587 >     * for an element
3588 >     * @param basis the identity (initial default value) for the reduction
3589 >     * @param reducer a commutative associative combining function
3590 >     * @return the result of accumulating the given transformation
3591 >     * of all (key, value) pairs
3592 >     * @since 1.8
3593 >     */
3594 >    public double reduceToDouble(long parallelismThreshold,
3595 >                                 ToDoubleBiFunction<? super K, ? super V> transformer,
3596 >                                 double basis,
3597 >                                 DoubleBinaryOperator reducer) {
3598 >        if (transformer == null || reducer == null)
3599 >            throw new NullPointerException();
3600 >        return new MapReduceMappingsToDoubleTask<K,V>
3601 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3602 >             null, transformer, basis, reducer).invoke();
3603 >    }
3604 >
3605 >    /**
3606 >     * Returns the result of accumulating the given transformation
3607 >     * of all (key, value) pairs using the given reducer to
3608 >     * combine values, and the given basis as an identity value.
3609 >     *
3610 >     * @param parallelismThreshold the (estimated) number of elements
3611 >     * needed for this operation to be executed in parallel
3612 >     * @param transformer a function returning the transformation
3613 >     * for an element
3614 >     * @param basis the identity (initial default value) for the reduction
3615 >     * @param reducer a commutative associative combining function
3616 >     * @return the result of accumulating the given transformation
3617 >     * of all (key, value) pairs
3618 >     * @since 1.8
3619 >     */
3620 >    public long reduceToLong(long parallelismThreshold,
3621 >                             ToLongBiFunction<? super K, ? super V> transformer,
3622 >                             long basis,
3623 >                             LongBinaryOperator reducer) {
3624 >        if (transformer == null || reducer == null)
3625 >            throw new NullPointerException();
3626 >        return new MapReduceMappingsToLongTask<K,V>
3627 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3628 >             null, transformer, basis, reducer).invoke();
3629 >    }
3630 >
3631 >    /**
3632 >     * Returns the result of accumulating the given transformation
3633 >     * of all (key, value) pairs using the given reducer to
3634 >     * combine values, and the given basis as an identity value.
3635 >     *
3636 >     * @param parallelismThreshold the (estimated) number of elements
3637 >     * needed for this operation to be executed in parallel
3638 >     * @param transformer a function returning the transformation
3639 >     * for an element
3640 >     * @param basis the identity (initial default value) for the reduction
3641 >     * @param reducer a commutative associative combining function
3642 >     * @return the result of accumulating the given transformation
3643 >     * of all (key, value) pairs
3644 >     * @since 1.8
3645 >     */
3646 >    public int reduceToInt(long parallelismThreshold,
3647 >                           ToIntBiFunction<? super K, ? super V> transformer,
3648 >                           int basis,
3649 >                           IntBinaryOperator reducer) {
3650 >        if (transformer == null || reducer == null)
3651 >            throw new NullPointerException();
3652 >        return new MapReduceMappingsToIntTask<K,V>
3653 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3654 >             null, transformer, basis, reducer).invoke();
3655 >    }
3656 >
3657 >    /**
3658 >     * Performs the given action for each key.
3659 >     *
3660 >     * @param parallelismThreshold the (estimated) number of elements
3661 >     * needed for this operation to be executed in parallel
3662 >     * @param action the action
3663 >     * @since 1.8
3664 >     */
3665 >    public void forEachKey(long parallelismThreshold,
3666 >                           Consumer<? super K> action) {
3667 >        if (action == null) throw new NullPointerException();
3668 >        new ForEachKeyTask<K,V>
3669 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3670 >             action).invoke();
3671 >    }
3672 >
3673 >    /**
3674 >     * Performs the given action for each non-null transformation
3675 >     * of each key.
3676 >     *
3677 >     * @param parallelismThreshold the (estimated) number of elements
3678 >     * needed for this operation to be executed in parallel
3679 >     * @param transformer a function returning the transformation
3680 >     * for an element, or null if there is no transformation (in
3681 >     * which case the action is not applied)
3682 >     * @param action the action
3683 >     * @since 1.8
3684 >     */
3685 >    public <U> void forEachKey(long parallelismThreshold,
3686 >                               Function<? super K, ? extends U> transformer,
3687 >                               Consumer<? super U> action) {
3688 >        if (transformer == null || action == null)
3689 >            throw new NullPointerException();
3690 >        new ForEachTransformedKeyTask<K,V,U>
3691 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3692 >             transformer, action).invoke();
3693 >    }
3694 >
3695 >    /**
3696 >     * Returns a non-null result from applying the given search
3697 >     * function on each key, or null if none. Upon success,
3698 >     * further element processing is suppressed and the results of
3699 >     * any other parallel invocations of the search function are
3700 >     * ignored.
3701 >     *
3702 >     * @param parallelismThreshold the (estimated) number of elements
3703 >     * needed for this operation to be executed in parallel
3704 >     * @param searchFunction a function returning a non-null
3705 >     * result on success, else null
3706 >     * @return a non-null result from applying the given search
3707 >     * function on each key, or null if none
3708 >     * @since 1.8
3709 >     */
3710 >    public <U> U searchKeys(long parallelismThreshold,
3711 >                            Function<? super K, ? extends U> searchFunction) {
3712 >        if (searchFunction == null) throw new NullPointerException();
3713 >        return new SearchKeysTask<K,V,U>
3714 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3715 >             searchFunction, new AtomicReference<U>()).invoke();
3716 >    }
3717 >
3718 >    /**
3719 >     * Returns the result of accumulating all keys using the given
3720 >     * reducer to combine values, or null if none.
3721 >     *
3722 >     * @param parallelismThreshold the (estimated) number of elements
3723 >     * needed for this operation to be executed in parallel
3724 >     * @param reducer a commutative associative combining function
3725 >     * @return the result of accumulating all keys using the given
3726 >     * reducer to combine values, or null if none
3727 >     * @since 1.8
3728 >     */
3729 >    public K reduceKeys(long parallelismThreshold,
3730 >                        BiFunction<? super K, ? super K, ? extends K> reducer) {
3731 >        if (reducer == null) throw new NullPointerException();
3732 >        return new ReduceKeysTask<K,V>
3733 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3734 >             null, reducer).invoke();
3735 >    }
3736 >
3737 >    /**
3738 >     * Returns the result of accumulating the given transformation
3739 >     * of all keys using the given reducer to combine values, or
3740 >     * null if none.
3741 >     *
3742 >     * @param parallelismThreshold the (estimated) number of elements
3743 >     * needed for this operation to be executed in parallel
3744 >     * @param transformer a function returning the transformation
3745 >     * for an element, or null if there is no transformation (in
3746 >     * which case it is not combined)
3747 >     * @param reducer a commutative associative combining function
3748 >     * @return the result of accumulating the given transformation
3749 >     * of all keys
3750 >     * @since 1.8
3751 >     */
3752 >    public <U> U reduceKeys(long parallelismThreshold,
3753 >                            Function<? super K, ? extends U> transformer,
3754 >         BiFunction<? super U, ? super U, ? extends U> reducer) {
3755 >        if (transformer == null || reducer == null)
3756 >            throw new NullPointerException();
3757 >        return new MapReduceKeysTask<K,V,U>
3758 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3759 >             null, transformer, reducer).invoke();
3760 >    }
3761 >
3762 >    /**
3763 >     * Returns the result of accumulating the given transformation
3764 >     * of all keys using the given reducer to combine values, and
3765 >     * the given basis as an identity value.
3766 >     *
3767 >     * @param parallelismThreshold the (estimated) number of elements
3768 >     * needed for this operation to be executed in parallel
3769 >     * @param transformer a function returning the transformation
3770 >     * for an element
3771 >     * @param basis the identity (initial default value) for the reduction
3772 >     * @param reducer a commutative associative combining function
3773 >     * @return the result of accumulating the given transformation
3774 >     * of all keys
3775 >     * @since 1.8
3776 >     */
3777 >    public double reduceKeysToDouble(long parallelismThreshold,
3778 >                                     ToDoubleFunction<? super K> transformer,
3779 >                                     double basis,
3780 >                                     DoubleBinaryOperator reducer) {
3781 >        if (transformer == null || reducer == null)
3782 >            throw new NullPointerException();
3783 >        return new MapReduceKeysToDoubleTask<K,V>
3784 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3785 >             null, transformer, basis, reducer).invoke();
3786 >    }
3787 >
3788 >    /**
3789 >     * Returns the result of accumulating the given transformation
3790 >     * of all keys using the given reducer to combine values, and
3791 >     * the given basis as an identity value.
3792 >     *
3793 >     * @param parallelismThreshold the (estimated) number of elements
3794 >     * needed for this operation to be executed in parallel
3795 >     * @param transformer a function returning the transformation
3796 >     * for an element
3797 >     * @param basis the identity (initial default value) for the reduction
3798 >     * @param reducer a commutative associative combining function
3799 >     * @return the result of accumulating the given transformation
3800 >     * of all keys
3801 >     * @since 1.8
3802 >     */
3803 >    public long reduceKeysToLong(long parallelismThreshold,
3804 >                                 ToLongFunction<? super K> transformer,
3805 >                                 long basis,
3806 >                                 LongBinaryOperator reducer) {
3807 >        if (transformer == null || reducer == null)
3808 >            throw new NullPointerException();
3809 >        return new MapReduceKeysToLongTask<K,V>
3810 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3811 >             null, transformer, basis, reducer).invoke();
3812 >    }
3813 >
3814 >    /**
3815 >     * Returns the result of accumulating the given transformation
3816 >     * of all keys using the given reducer to combine values, and
3817 >     * the given basis as an identity value.
3818 >     *
3819 >     * @param parallelismThreshold the (estimated) number of elements
3820 >     * needed for this operation to be executed in parallel
3821 >     * @param transformer a function returning the transformation
3822 >     * for an element
3823 >     * @param basis the identity (initial default value) for the reduction
3824 >     * @param reducer a commutative associative combining function
3825 >     * @return the result of accumulating the given transformation
3826 >     * of all keys
3827 >     * @since 1.8
3828 >     */
3829 >    public int reduceKeysToInt(long parallelismThreshold,
3830 >                               ToIntFunction<? super K> transformer,
3831 >                               int basis,
3832 >                               IntBinaryOperator reducer) {
3833 >        if (transformer == null || reducer == null)
3834 >            throw new NullPointerException();
3835 >        return new MapReduceKeysToIntTask<K,V>
3836 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3837 >             null, transformer, basis, reducer).invoke();
3838 >    }
3839 >
3840 >    /**
3841 >     * Performs the given action for each value.
3842 >     *
3843 >     * @param parallelismThreshold the (estimated) number of elements
3844 >     * needed for this operation to be executed in parallel
3845 >     * @param action the action
3846 >     * @since 1.8
3847 >     */
3848 >    public void forEachValue(long parallelismThreshold,
3849 >                             Consumer<? super V> action) {
3850 >        if (action == null)
3851 >            throw new NullPointerException();
3852 >        new ForEachValueTask<K,V>
3853 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3854 >             action).invoke();
3855 >    }
3856 >
3857 >    /**
3858 >     * Performs the given action for each non-null transformation
3859 >     * of each value.
3860 >     *
3861 >     * @param parallelismThreshold the (estimated) number of elements
3862 >     * needed for this operation to be executed in parallel
3863 >     * @param transformer a function returning the transformation
3864 >     * for an element, or null if there is no transformation (in
3865 >     * which case the action is not applied)
3866 >     * @param action the action
3867 >     * @since 1.8
3868 >     */
3869 >    public <U> void forEachValue(long parallelismThreshold,
3870 >                                 Function<? super V, ? extends U> transformer,
3871 >                                 Consumer<? super U> action) {
3872 >        if (transformer == null || action == null)
3873 >            throw new NullPointerException();
3874 >        new ForEachTransformedValueTask<K,V,U>
3875 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3876 >             transformer, action).invoke();
3877 >    }
3878 >
3879 >    /**
3880 >     * Returns a non-null result from applying the given search
3881 >     * function on each value, or null if none.  Upon success,
3882 >     * further element processing is suppressed and the results of
3883 >     * any other parallel invocations of the search function are
3884 >     * ignored.
3885 >     *
3886 >     * @param parallelismThreshold the (estimated) number of elements
3887 >     * needed for this operation to be executed in parallel
3888 >     * @param searchFunction a function returning a non-null
3889 >     * result on success, else null
3890 >     * @return a non-null result from applying the given search
3891 >     * function on each value, or null if none
3892 >     * @since 1.8
3893 >     */
3894 >    public <U> U searchValues(long parallelismThreshold,
3895 >                              Function<? super V, ? extends U> searchFunction) {
3896 >        if (searchFunction == null) throw new NullPointerException();
3897 >        return new SearchValuesTask<K,V,U>
3898 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3899 >             searchFunction, new AtomicReference<U>()).invoke();
3900 >    }
3901 >
3902 >    /**
3903 >     * Returns the result of accumulating all values using the
3904 >     * given reducer to combine values, or null if none.
3905 >     *
3906 >     * @param parallelismThreshold the (estimated) number of elements
3907 >     * needed for this operation to be executed in parallel
3908 >     * @param reducer a commutative associative combining function
3909 >     * @return the result of accumulating all values
3910 >     * @since 1.8
3911 >     */
3912 >    public V reduceValues(long parallelismThreshold,
3913 >                          BiFunction<? super V, ? super V, ? extends V> reducer) {
3914 >        if (reducer == null) throw new NullPointerException();
3915 >        return new ReduceValuesTask<K,V>
3916 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3917 >             null, reducer).invoke();
3918 >    }
3919 >
3920 >    /**
3921 >     * Returns the result of accumulating the given transformation
3922 >     * of all values using the given reducer to combine values, or
3923 >     * null if none.
3924 >     *
3925 >     * @param parallelismThreshold the (estimated) number of elements
3926 >     * needed for this operation to be executed in parallel
3927 >     * @param transformer a function returning the transformation
3928 >     * for an element, or null if there is no transformation (in
3929 >     * which case it is not combined)
3930 >     * @param reducer a commutative associative combining function
3931 >     * @return the result of accumulating the given transformation
3932 >     * of all values
3933 >     * @since 1.8
3934 >     */
3935 >    public <U> U reduceValues(long parallelismThreshold,
3936 >                              Function<? super V, ? extends U> transformer,
3937 >                              BiFunction<? super U, ? super U, ? extends U> reducer) {
3938 >        if (transformer == null || reducer == null)
3939 >            throw new NullPointerException();
3940 >        return new MapReduceValuesTask<K,V,U>
3941 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3942 >             null, transformer, reducer).invoke();
3943 >    }
3944 >
3945 >    /**
3946 >     * Returns the result of accumulating the given transformation
3947 >     * of all values using the given reducer to combine values,
3948 >     * and the given basis as an identity value.
3949 >     *
3950 >     * @param parallelismThreshold the (estimated) number of elements
3951 >     * needed for this operation to be executed in parallel
3952 >     * @param transformer a function returning the transformation
3953 >     * for an element
3954 >     * @param basis the identity (initial default value) for the reduction
3955 >     * @param reducer a commutative associative combining function
3956 >     * @return the result of accumulating the given transformation
3957 >     * of all values
3958 >     * @since 1.8
3959 >     */
3960 >    public double reduceValuesToDouble(long parallelismThreshold,
3961 >                                       ToDoubleFunction<? super V> transformer,
3962 >                                       double basis,
3963 >                                       DoubleBinaryOperator reducer) {
3964 >        if (transformer == null || reducer == null)
3965 >            throw new NullPointerException();
3966 >        return new MapReduceValuesToDoubleTask<K,V>
3967 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3968 >             null, transformer, basis, reducer).invoke();
3969 >    }
3970 >
3971 >    /**
3972 >     * Returns the result of accumulating the given transformation
3973 >     * of all values using the given reducer to combine values,
3974 >     * and the given basis as an identity value.
3975 >     *
3976 >     * @param parallelismThreshold the (estimated) number of elements
3977 >     * needed for this operation to be executed in parallel
3978 >     * @param transformer a function returning the transformation
3979 >     * for an element
3980 >     * @param basis the identity (initial default value) for the reduction
3981 >     * @param reducer a commutative associative combining function
3982 >     * @return the result of accumulating the given transformation
3983 >     * of all values
3984 >     * @since 1.8
3985 >     */
3986 >    public long reduceValuesToLong(long parallelismThreshold,
3987 >                                   ToLongFunction<? super V> transformer,
3988 >                                   long basis,
3989 >                                   LongBinaryOperator reducer) {
3990 >        if (transformer == null || reducer == null)
3991 >            throw new NullPointerException();
3992 >        return new MapReduceValuesToLongTask<K,V>
3993 >            (null, batchFor(parallelismThreshold), 0, 0, table,
3994 >             null, transformer, basis, reducer).invoke();
3995 >    }
3996 >
3997 >    /**
3998 >     * Returns the result of accumulating the given transformation
3999 >     * of all values using the given reducer to combine values,
4000 >     * and the given basis as an identity value.
4001 >     *
4002 >     * @param parallelismThreshold the (estimated) number of elements
4003 >     * needed for this operation to be executed in parallel
4004 >     * @param transformer a function returning the transformation
4005 >     * for an element
4006 >     * @param basis the identity (initial default value) for the reduction
4007 >     * @param reducer a commutative associative combining function
4008 >     * @return the result of accumulating the given transformation
4009 >     * of all values
4010 >     * @since 1.8
4011 >     */
4012 >    public int reduceValuesToInt(long parallelismThreshold,
4013 >                                 ToIntFunction<? super V> transformer,
4014 >                                 int basis,
4015 >                                 IntBinaryOperator reducer) {
4016 >        if (transformer == null || reducer == null)
4017 >            throw new NullPointerException();
4018 >        return new MapReduceValuesToIntTask<K,V>
4019 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4020 >             null, transformer, basis, reducer).invoke();
4021 >    }
4022 >
4023 >    /**
4024 >     * Performs the given action for each entry.
4025 >     *
4026 >     * @param parallelismThreshold the (estimated) number of elements
4027 >     * needed for this operation to be executed in parallel
4028 >     * @param action the action
4029 >     * @since 1.8
4030 >     */
4031 >    public void forEachEntry(long parallelismThreshold,
4032 >                             Consumer<? super Map.Entry<K,V>> action) {
4033 >        if (action == null) throw new NullPointerException();
4034 >        new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4035 >                                  action).invoke();
4036 >    }
4037 >
4038 >    /**
4039 >     * Performs the given action for each non-null transformation
4040 >     * of each entry.
4041 >     *
4042 >     * @param parallelismThreshold the (estimated) number of elements
4043 >     * needed for this operation to be executed in parallel
4044 >     * @param transformer a function returning the transformation
4045 >     * for an element, or null if there is no transformation (in
4046 >     * which case the action is not applied)
4047 >     * @param action the action
4048 >     * @since 1.8
4049 >     */
4050 >    public <U> void forEachEntry(long parallelismThreshold,
4051 >                                 Function<Map.Entry<K,V>, ? extends U> transformer,
4052 >                                 Consumer<? super U> action) {
4053 >        if (transformer == null || action == null)
4054 >            throw new NullPointerException();
4055 >        new ForEachTransformedEntryTask<K,V,U>
4056 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4057 >             transformer, action).invoke();
4058 >    }
4059 >
4060 >    /**
4061 >     * Returns a non-null result from applying the given search
4062 >     * function on each entry, or null if none.  Upon success,
4063 >     * further element processing is suppressed and the results of
4064 >     * any other parallel invocations of the search function are
4065 >     * ignored.
4066 >     *
4067 >     * @param parallelismThreshold the (estimated) number of elements
4068 >     * needed for this operation to be executed in parallel
4069 >     * @param searchFunction a function returning a non-null
4070 >     * result on success, else null
4071 >     * @return a non-null result from applying the given search
4072 >     * function on each entry, or null if none
4073 >     * @since 1.8
4074 >     */
4075 >    public <U> U searchEntries(long parallelismThreshold,
4076 >                               Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4077 >        if (searchFunction == null) throw new NullPointerException();
4078 >        return new SearchEntriesTask<K,V,U>
4079 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4080 >             searchFunction, new AtomicReference<U>()).invoke();
4081 >    }
4082 >
4083 >    /**
4084 >     * Returns the result of accumulating all entries using the
4085 >     * given reducer to combine values, or null if none.
4086 >     *
4087 >     * @param parallelismThreshold the (estimated) number of elements
4088 >     * needed for this operation to be executed in parallel
4089 >     * @param reducer a commutative associative combining function
4090 >     * @return the result of accumulating all entries
4091 >     * @since 1.8
4092 >     */
4093 >    public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4094 >                                        BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4095 >        if (reducer == null) throw new NullPointerException();
4096 >        return new ReduceEntriesTask<K,V>
4097 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4098 >             null, reducer).invoke();
4099 >    }
4100 >
4101 >    /**
4102 >     * Returns the result of accumulating the given transformation
4103 >     * of all entries using the given reducer to combine values,
4104 >     * or null if none.
4105 >     *
4106 >     * @param parallelismThreshold the (estimated) number of elements
4107 >     * needed for this operation to be executed in parallel
4108 >     * @param transformer a function returning the transformation
4109 >     * for an element, or null if there is no transformation (in
4110 >     * which case it is not combined)
4111 >     * @param reducer a commutative associative combining function
4112 >     * @return the result of accumulating the given transformation
4113 >     * of all entries
4114 >     * @since 1.8
4115 >     */
4116 >    public <U> U reduceEntries(long parallelismThreshold,
4117 >                               Function<Map.Entry<K,V>, ? extends U> transformer,
4118 >                               BiFunction<? super U, ? super U, ? extends U> reducer) {
4119 >        if (transformer == null || reducer == null)
4120 >            throw new NullPointerException();
4121 >        return new MapReduceEntriesTask<K,V,U>
4122 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4123 >             null, transformer, reducer).invoke();
4124 >    }
4125 >
4126 >    /**
4127 >     * Returns the result of accumulating the given transformation
4128 >     * of all entries using the given reducer to combine values,
4129 >     * and the given basis as an identity value.
4130 >     *
4131 >     * @param parallelismThreshold the (estimated) number of elements
4132 >     * needed for this operation to be executed in parallel
4133 >     * @param transformer a function returning the transformation
4134 >     * for an element
4135 >     * @param basis the identity (initial default value) for the reduction
4136 >     * @param reducer a commutative associative combining function
4137 >     * @return the result of accumulating the given transformation
4138 >     * of all entries
4139 >     * @since 1.8
4140 >     */
4141 >    public double reduceEntriesToDouble(long parallelismThreshold,
4142 >                                        ToDoubleFunction<Map.Entry<K,V>> transformer,
4143 >                                        double basis,
4144 >                                        DoubleBinaryOperator reducer) {
4145 >        if (transformer == null || reducer == null)
4146 >            throw new NullPointerException();
4147 >        return new MapReduceEntriesToDoubleTask<K,V>
4148 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4149 >             null, transformer, basis, reducer).invoke();
4150 >    }
4151 >
4152 >    /**
4153 >     * Returns the result of accumulating the given transformation
4154 >     * of all entries using the given reducer to combine values,
4155 >     * and the given basis as an identity value.
4156 >     *
4157 >     * @param parallelismThreshold the (estimated) number of elements
4158 >     * needed for this operation to be executed in parallel
4159 >     * @param transformer a function returning the transformation
4160 >     * for an element
4161 >     * @param basis the identity (initial default value) for the reduction
4162 >     * @param reducer a commutative associative combining function
4163 >     * @return the result of accumulating the given transformation
4164 >     * of all entries
4165 >     * @since 1.8
4166 >     */
4167 >    public long reduceEntriesToLong(long parallelismThreshold,
4168 >                                    ToLongFunction<Map.Entry<K,V>> transformer,
4169 >                                    long basis,
4170 >                                    LongBinaryOperator reducer) {
4171 >        if (transformer == null || reducer == null)
4172 >            throw new NullPointerException();
4173 >        return new MapReduceEntriesToLongTask<K,V>
4174 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4175 >             null, transformer, basis, reducer).invoke();
4176 >    }
4177 >
4178 >    /**
4179 >     * Returns the result of accumulating the given transformation
4180 >     * of all entries using the given reducer to combine values,
4181 >     * and the given basis as an identity value.
4182 >     *
4183 >     * @param parallelismThreshold the (estimated) number of elements
4184 >     * needed for this operation to be executed in parallel
4185 >     * @param transformer a function returning the transformation
4186 >     * for an element
4187 >     * @param basis the identity (initial default value) for the reduction
4188 >     * @param reducer a commutative associative combining function
4189 >     * @return the result of accumulating the given transformation
4190 >     * of all entries
4191 >     * @since 1.8
4192 >     */
4193 >    public int reduceEntriesToInt(long parallelismThreshold,
4194 >                                  ToIntFunction<Map.Entry<K,V>> transformer,
4195 >                                  int basis,
4196 >                                  IntBinaryOperator reducer) {
4197 >        if (transformer == null || reducer == null)
4198 >            throw new NullPointerException();
4199 >        return new MapReduceEntriesToIntTask<K,V>
4200 >            (null, batchFor(parallelismThreshold), 0, 0, table,
4201 >             null, transformer, basis, reducer).invoke();
4202 >    }
4203 >
4204 >
4205 >    /* ----------------Views -------------- */
4206 >
4207 >    /**
4208 >     * Base class for views.
4209 >     */
4210 >    abstract static class CollectionView<K,V,E>
4211 >        implements Collection<E>, java.io.Serializable {
4212 >        private static final long serialVersionUID = 7249069246763182397L;
4213 >        final ConcurrentHashMap<K,V> map;
4214 >        CollectionView(ConcurrentHashMap<K,V> map)  { this.map = map; }
4215 >
4216 >        /**
4217 >         * Returns the map backing this view.
4218 >         *
4219 >         * @return the map backing this view
4220 >         */
4221 >        public ConcurrentHashMap<K,V> getMap() { return map; }
4222 >
4223 >        /**
4224 >         * Removes all of the elements from this view, by removing all
4225 >         * the mappings from the map backing this view.
4226 >         */
4227 >        public final void clear()      { map.clear(); }
4228 >        public final int size()        { return map.size(); }
4229 >        public final boolean isEmpty() { return map.isEmpty(); }
4230 >
4231 >        // implementations below rely on concrete classes supplying these
4232 >        // abstract methods
4233 >        /**
4234 >         * Returns a "weakly consistent" iterator that will never
4235 >         * throw {@link ConcurrentModificationException}, and
4236 >         * guarantees to traverse elements as they existed upon
4237 >         * construction of the iterator, and may (but is not
4238 >         * guaranteed to) reflect any modifications subsequent to
4239 >         * construction.
4240 >         */
4241 >        public abstract Iterator<E> iterator();
4242 >        public abstract boolean contains(Object o);
4243 >        public abstract boolean remove(Object o);
4244 >
4245 >        private static final String oomeMsg = "Required array size too large";
4246 >
4247 >        public final Object[] toArray() {
4248 >            long sz = map.mappingCount();
4249 >            if (sz > MAX_ARRAY_SIZE)
4250 >                throw new OutOfMemoryError(oomeMsg);
4251 >            int n = (int)sz;
4252 >            Object[] r = new Object[n];
4253 >            int i = 0;
4254 >            for (E e : this) {
4255 >                if (i == n) {
4256 >                    if (n >= MAX_ARRAY_SIZE)
4257 >                        throw new OutOfMemoryError(oomeMsg);
4258 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4259 >                        n = MAX_ARRAY_SIZE;
4260 >                    else
4261 >                        n += (n >>> 1) + 1;
4262 >                    r = Arrays.copyOf(r, n);
4263 >                }
4264 >                r[i++] = e;
4265 >            }
4266 >            return (i == n) ? r : Arrays.copyOf(r, i);
4267          }
4268 <        public void clear() {
4269 <            ConcurrentHashMap.this.clear();
4268 >
4269 >        @SuppressWarnings("unchecked")
4270 >        public final <T> T[] toArray(T[] a) {
4271 >            long sz = map.mappingCount();
4272 >            if (sz > MAX_ARRAY_SIZE)
4273 >                throw new OutOfMemoryError(oomeMsg);
4274 >            int m = (int)sz;
4275 >            T[] r = (a.length >= m) ? a :
4276 >                (T[])java.lang.reflect.Array
4277 >                .newInstance(a.getClass().getComponentType(), m);
4278 >            int n = r.length;
4279 >            int i = 0;
4280 >            for (E e : this) {
4281 >                if (i == n) {
4282 >                    if (n >= MAX_ARRAY_SIZE)
4283 >                        throw new OutOfMemoryError(oomeMsg);
4284 >                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4285 >                        n = MAX_ARRAY_SIZE;
4286 >                    else
4287 >                        n += (n >>> 1) + 1;
4288 >                    r = Arrays.copyOf(r, n);
4289 >                }
4290 >                r[i++] = (T)e;
4291 >            }
4292 >            if (a == r && i < n) {
4293 >                r[i] = null; // null-terminate
4294 >                return r;
4295 >            }
4296 >            return (i == n) ? r : Arrays.copyOf(r, i);
4297          }
4298 +
4299 +        /**
4300 +         * Returns a string representation of this collection.
4301 +         * The string representation consists of the string representations
4302 +         * of the collection's elements in the order they are returned by
4303 +         * its iterator, enclosed in square brackets ({@code "[]"}).
4304 +         * Adjacent elements are separated by the characters {@code ", "}
4305 +         * (comma and space).  Elements are converted to strings as by
4306 +         * {@link String#valueOf(Object)}.
4307 +         *
4308 +         * @return a string representation of this collection
4309 +         */
4310 +        public final String toString() {
4311 +            StringBuilder sb = new StringBuilder();
4312 +            sb.append('[');
4313 +            Iterator<E> it = iterator();
4314 +            if (it.hasNext()) {
4315 +                for (;;) {
4316 +                    Object e = it.next();
4317 +                    sb.append(e == this ? "(this Collection)" : e);
4318 +                    if (!it.hasNext())
4319 +                        break;
4320 +                    sb.append(',').append(' ');
4321 +                }
4322 +            }
4323 +            return sb.append(']').toString();
4324 +        }
4325 +
4326 +        public final boolean containsAll(Collection<?> c) {
4327 +            if (c != this) {
4328 +                for (Object e : c) {
4329 +                    if (e == null || !contains(e))
4330 +                        return false;
4331 +                }
4332 +            }
4333 +            return true;
4334 +        }
4335 +
4336 +        public final boolean removeAll(Collection<?> c) {
4337 +            boolean modified = false;
4338 +            for (Iterator<E> it = iterator(); it.hasNext();) {
4339 +                if (c.contains(it.next())) {
4340 +                    it.remove();
4341 +                    modified = true;
4342 +                }
4343 +            }
4344 +            return modified;
4345 +        }
4346 +
4347 +        public final boolean retainAll(Collection<?> c) {
4348 +            boolean modified = false;
4349 +            for (Iterator<E> it = iterator(); it.hasNext();) {
4350 +                if (!c.contains(it.next())) {
4351 +                    it.remove();
4352 +                    modified = true;
4353 +                }
4354 +            }
4355 +            return modified;
4356 +        }
4357 +
4358      }
4359  
4360 <    final class Values extends AbstractCollection<V> {
4361 <        public Iterator<V> iterator() {
4362 <            return new ValueIterator();
4360 >    /**
4361 >     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4362 >     * which additions may optionally be enabled by mapping to a
4363 >     * common value.  This class cannot be directly instantiated.
4364 >     * See {@link #keySet() keySet()},
4365 >     * {@link #keySet(Object) keySet(V)},
4366 >     * {@link #newKeySet() newKeySet()},
4367 >     * {@link #newKeySet(int) newKeySet(int)}.
4368 >     *
4369 >     * @since 1.8
4370 >     */
4371 >    public static class KeySetView<K,V> extends CollectionView<K,V,K>
4372 >        implements Set<K>, java.io.Serializable {
4373 >        private static final long serialVersionUID = 7249069246763182397L;
4374 >        private final V value;
4375 >        KeySetView(ConcurrentHashMap<K,V> map, V value) {  // non-public
4376 >            super(map);
4377 >            this.value = value;
4378          }
4379 <        public int size() {
4380 <            return ConcurrentHashMap.this.size();
4379 >
4380 >        /**
4381 >         * Returns the default mapped value for additions,
4382 >         * or {@code null} if additions are not supported.
4383 >         *
4384 >         * @return the default mapped value for additions, or {@code null}
4385 >         * if not supported
4386 >         */
4387 >        public V getMappedValue() { return value; }
4388 >
4389 >        /**
4390 >         * {@inheritDoc}
4391 >         * @throws NullPointerException if the specified key is null
4392 >         */
4393 >        public boolean contains(Object o) { return map.containsKey(o); }
4394 >
4395 >        /**
4396 >         * Removes the key from this map view, by removing the key (and its
4397 >         * corresponding value) from the backing map.  This method does
4398 >         * nothing if the key is not in the map.
4399 >         *
4400 >         * @param  o the key to be removed from the backing map
4401 >         * @return {@code true} if the backing map contained the specified key
4402 >         * @throws NullPointerException if the specified key is null
4403 >         */
4404 >        public boolean remove(Object o) { return map.remove(o) != null; }
4405 >
4406 >        /**
4407 >         * @return an iterator over the keys of the backing map
4408 >         */
4409 >        public Iterator<K> iterator() {
4410 >            Node<K,V>[] t;
4411 >            ConcurrentHashMap<K,V> m = map;
4412 >            int f = (t = m.table) == null ? 0 : t.length;
4413 >            return new KeyIterator<K,V>(t, f, 0, f, m);
4414          }
4415 <        public boolean isEmpty() {
4416 <            return ConcurrentHashMap.this.isEmpty();
4415 >
4416 >        /**
4417 >         * Adds the specified key to this set view by mapping the key to
4418 >         * the default mapped value in the backing map, if defined.
4419 >         *
4420 >         * @param e key to be added
4421 >         * @return {@code true} if this set changed as a result of the call
4422 >         * @throws NullPointerException if the specified key is null
4423 >         * @throws UnsupportedOperationException if no default mapped value
4424 >         * for additions was provided
4425 >         */
4426 >        public boolean add(K e) {
4427 >            V v;
4428 >            if ((v = value) == null)
4429 >                throw new UnsupportedOperationException();
4430 >            return map.putVal(e, v, true) == null;
4431          }
4432 <        public boolean contains(Object o) {
4433 <            return ConcurrentHashMap.this.containsValue(o);
4432 >
4433 >        /**
4434 >         * Adds all of the elements in the specified collection to this set,
4435 >         * as if by calling {@link #add} on each one.
4436 >         *
4437 >         * @param c the elements to be inserted into this set
4438 >         * @return {@code true} if this set changed as a result of the call
4439 >         * @throws NullPointerException if the collection or any of its
4440 >         * elements are {@code null}
4441 >         * @throws UnsupportedOperationException if no default mapped value
4442 >         * for additions was provided
4443 >         */
4444 >        public boolean addAll(Collection<? extends K> c) {
4445 >            boolean added = false;
4446 >            V v;
4447 >            if ((v = value) == null)
4448 >                throw new UnsupportedOperationException();
4449 >            for (K e : c) {
4450 >                if (map.putVal(e, v, true) == null)
4451 >                    added = true;
4452 >            }
4453 >            return added;
4454          }
4455 <        public void clear() {
4456 <            ConcurrentHashMap.this.clear();
4455 >
4456 >        public int hashCode() {
4457 >            int h = 0;
4458 >            for (K e : this)
4459 >                h += e.hashCode();
4460 >            return h;
4461 >        }
4462 >
4463 >        public boolean equals(Object o) {
4464 >            Set<?> c;
4465 >            return ((o instanceof Set) &&
4466 >                    ((c = (Set<?>)o) == this ||
4467 >                     (containsAll(c) && c.containsAll(this))));
4468 >        }
4469 >
4470 >        public Spliterator<K> spliterator() {
4471 >            Node<K,V>[] t;
4472 >            ConcurrentHashMap<K,V> m = map;
4473 >            long n = m.sumCount();
4474 >            int f = (t = m.table) == null ? 0 : t.length;
4475 >            return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4476 >        }
4477 >
4478 >        public void forEach(Consumer<? super K> action) {
4479 >            if (action == null) throw new NullPointerException();
4480 >            Node<K,V>[] t;
4481 >            if ((t = map.table) != null) {
4482 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4483 >                for (Node<K,V> p; (p = it.advance()) != null; )
4484 >                    action.accept(p.key);
4485 >            }
4486          }
4487      }
4488  
4489 <    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
4490 <        public Iterator<Map.Entry<K,V>> iterator() {
4491 <            return new EntryIterator();
4489 >    /**
4490 >     * A view of a ConcurrentHashMap as a {@link Collection} of
4491 >     * values, in which additions are disabled. This class cannot be
4492 >     * directly instantiated. See {@link #values()}.
4493 >     */
4494 >    static final class ValuesView<K,V> extends CollectionView<K,V,V>
4495 >        implements Collection<V>, java.io.Serializable {
4496 >        private static final long serialVersionUID = 2249069246763182397L;
4497 >        ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4498 >        public final boolean contains(Object o) {
4499 >            return map.containsValue(o);
4500 >        }
4501 >
4502 >        public final boolean remove(Object o) {
4503 >            if (o != null) {
4504 >                for (Iterator<V> it = iterator(); it.hasNext();) {
4505 >                    if (o.equals(it.next())) {
4506 >                        it.remove();
4507 >                        return true;
4508 >                    }
4509 >                }
4510 >            }
4511 >            return false;
4512 >        }
4513 >
4514 >        public final Iterator<V> iterator() {
4515 >            ConcurrentHashMap<K,V> m = map;
4516 >            Node<K,V>[] t;
4517 >            int f = (t = m.table) == null ? 0 : t.length;
4518 >            return new ValueIterator<K,V>(t, f, 0, f, m);
4519 >        }
4520 >
4521 >        public final boolean add(V e) {
4522 >            throw new UnsupportedOperationException();
4523 >        }
4524 >        public final boolean addAll(Collection<? extends V> c) {
4525 >            throw new UnsupportedOperationException();
4526 >        }
4527 >
4528 >        public Spliterator<V> spliterator() {
4529 >            Node<K,V>[] t;
4530 >            ConcurrentHashMap<K,V> m = map;
4531 >            long n = m.sumCount();
4532 >            int f = (t = m.table) == null ? 0 : t.length;
4533 >            return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4534 >        }
4535 >
4536 >        public void forEach(Consumer<? super V> action) {
4537 >            if (action == null) throw new NullPointerException();
4538 >            Node<K,V>[] t;
4539 >            if ((t = map.table) != null) {
4540 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4541 >                for (Node<K,V> p; (p = it.advance()) != null; )
4542 >                    action.accept(p.val);
4543 >            }
4544          }
4545 +    }
4546 +
4547 +    /**
4548 +     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4549 +     * entries.  This class cannot be directly instantiated. See
4550 +     * {@link #entrySet()}.
4551 +     */
4552 +    static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4553 +        implements Set<Map.Entry<K,V>>, java.io.Serializable {
4554 +        private static final long serialVersionUID = 2249069246763182397L;
4555 +        EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4556 +
4557          public boolean contains(Object o) {
4558 <            if (!(o instanceof Map.Entry))
4559 <                return false;
4560 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
4561 <            V v = ConcurrentHashMap.this.get(e.getKey());
4562 <            return v != null && v.equals(e.getValue());
4558 >            Object k, v, r; Map.Entry<?,?> e;
4559 >            return ((o instanceof Map.Entry) &&
4560 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4561 >                    (r = map.get(k)) != null &&
4562 >                    (v = e.getValue()) != null &&
4563 >                    (v == r || v.equals(r)));
4564          }
4565 +
4566          public boolean remove(Object o) {
4567 <            if (!(o instanceof Map.Entry))
4568 <                return false;
4569 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
4570 <            return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
4567 >            Object k, v; Map.Entry<?,?> e;
4568 >            return ((o instanceof Map.Entry) &&
4569 >                    (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4570 >                    (v = e.getValue()) != null &&
4571 >                    map.remove(k, v));
4572          }
4573 <        public int size() {
4574 <            return ConcurrentHashMap.this.size();
4573 >
4574 >        /**
4575 >         * @return an iterator over the entries of the backing map
4576 >         */
4577 >        public Iterator<Map.Entry<K,V>> iterator() {
4578 >            ConcurrentHashMap<K,V> m = map;
4579 >            Node<K,V>[] t;
4580 >            int f = (t = m.table) == null ? 0 : t.length;
4581 >            return new EntryIterator<K,V>(t, f, 0, f, m);
4582 >        }
4583 >
4584 >        public boolean add(Entry<K,V> e) {
4585 >            return map.putVal(e.getKey(), e.getValue(), false) == null;
4586 >        }
4587 >
4588 >        public boolean addAll(Collection<? extends Entry<K,V>> c) {
4589 >            boolean added = false;
4590 >            for (Entry<K,V> e : c) {
4591 >                if (add(e))
4592 >                    added = true;
4593 >            }
4594 >            return added;
4595          }
4596 <        public boolean isEmpty() {
4597 <            return ConcurrentHashMap.this.isEmpty();
4596 >
4597 >        public final int hashCode() {
4598 >            int h = 0;
4599 >            Node<K,V>[] t;
4600 >            if ((t = map.table) != null) {
4601 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4602 >                for (Node<K,V> p; (p = it.advance()) != null; ) {
4603 >                    h += p.hashCode();
4604 >                }
4605 >            }
4606 >            return h;
4607          }
4608 <        public void clear() {
4609 <            ConcurrentHashMap.this.clear();
4608 >
4609 >        public final boolean equals(Object o) {
4610 >            Set<?> c;
4611 >            return ((o instanceof Set) &&
4612 >                    ((c = (Set<?>)o) == this ||
4613 >                     (containsAll(c) && c.containsAll(this))));
4614 >        }
4615 >
4616 >        public Spliterator<Map.Entry<K,V>> spliterator() {
4617 >            Node<K,V>[] t;
4618 >            ConcurrentHashMap<K,V> m = map;
4619 >            long n = m.sumCount();
4620 >            int f = (t = m.table) == null ? 0 : t.length;
4621 >            return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4622 >        }
4623 >
4624 >        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4625 >            if (action == null) throw new NullPointerException();
4626 >            Node<K,V>[] t;
4627 >            if ((t = map.table) != null) {
4628 >                Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4629 >                for (Node<K,V> p; (p = it.advance()) != null; )
4630 >                    action.accept(new MapEntry<K,V>(p.key, p.val, map));
4631 >            }
4632          }
4633 +
4634      }
4635  
4636 <    /* ---------------- Serialization Support -------------- */
4636 >    // -------------------------------------------------------
4637  
4638      /**
4639 <     * Saves the state of the <tt>ConcurrentHashMap</tt> instance to a
4640 <     * stream (i.e., serializes it).
1402 <     * @param s the stream
1403 <     * @serialData
1404 <     * the key (Object) and value (Object)
1405 <     * for each key-value mapping, followed by a null pair.
1406 <     * The key-value mappings are emitted in no particular order.
4639 >     * Base class for bulk tasks. Repeats some fields and code from
4640 >     * class Traverser, because we need to subclass CountedCompleter.
4641       */
4642 <    private void writeObject(java.io.ObjectOutputStream s) throws IOException {
4643 <        // force all segments for serialization compatibility
4644 <        for (int k = 0; k < segments.length; ++k)
4645 <            ensureSegment(k);
4646 <        s.defaultWriteObject();
4647 <
4648 <        final Segment<K,V>[] segments = this.segments;
4649 <        for (int k = 0; k < segments.length; ++k) {
4650 <            Segment<K,V> seg = segmentAt(segments, k);
4651 <            seg.lock();
4652 <            try {
4653 <                HashEntry<K,V>[] tab = seg.table;
4654 <                for (int i = 0; i < tab.length; ++i) {
4655 <                    HashEntry<K,V> e;
4656 <                    for (e = entryAt(tab, i); e != null; e = e.next) {
4657 <                        s.writeObject(e.key);
4658 <                        s.writeObject(e.value);
4642 >    abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4643 >        Node<K,V>[] tab;        // same as Traverser
4644 >        Node<K,V> next;
4645 >        int index;
4646 >        int baseIndex;
4647 >        int baseLimit;
4648 >        final int baseSize;
4649 >        int batch;              // split control
4650 >
4651 >        BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4652 >            super(par);
4653 >            this.batch = b;
4654 >            this.index = this.baseIndex = i;
4655 >            if ((this.tab = t) == null)
4656 >                this.baseSize = this.baseLimit = 0;
4657 >            else if (par == null)
4658 >                this.baseSize = this.baseLimit = t.length;
4659 >            else {
4660 >                this.baseLimit = f;
4661 >                this.baseSize = par.baseSize;
4662 >            }
4663 >        }
4664 >
4665 >        /**
4666 >         * Same as Traverser version
4667 >         */
4668 >        final Node<K,V> advance() {
4669 >            Node<K,V> e;
4670 >            if ((e = next) != null)
4671 >                e = e.next;
4672 >            for (;;) {
4673 >                Node<K,V>[] t; int i, n; K ek;  // must use locals in checks
4674 >                if (e != null)
4675 >                    return next = e;
4676 >                if (baseIndex >= baseLimit || (t = tab) == null ||
4677 >                    (n = t.length) <= (i = index) || i < 0)
4678 >                    return next = null;
4679 >                if ((e = tabAt(t, index)) != null && e.hash < 0) {
4680 >                    if (e instanceof ForwardingNode) {
4681 >                        tab = ((ForwardingNode<K,V>)e).nextTable;
4682 >                        e = null;
4683 >                        continue;
4684                      }
4685 +                    else if (e instanceof TreeBin)
4686 +                        e = ((TreeBin<K,V>)e).first;
4687 +                    else
4688 +                        e = null;
4689                  }
4690 <            } finally {
4691 <                seg.unlock();
4690 >                if ((index += baseSize) >= n)
4691 >                    index = ++baseIndex;    // visit upper slots if present
4692              }
4693          }
1431        s.writeObject(null);
1432        s.writeObject(null);
4694      }
4695  
4696 <    /**
4697 <     * Reconstitutes the <tt>ConcurrentHashMap</tt> instance from a
4698 <     * stream (i.e., deserializes it).
4699 <     * @param s the stream
4700 <     */
4701 <    @SuppressWarnings("unchecked")
4702 <    private void readObject(java.io.ObjectInputStream s)
4703 <        throws IOException, ClassNotFoundException {
4704 <        s.defaultReadObject();
4696 >    /*
4697 >     * Task classes. Coded in a regular but ugly format/style to
4698 >     * simplify checks that each variant differs in the right way from
4699 >     * others. The null screenings exist because compilers cannot tell
4700 >     * that we've already null-checked task arguments, so we force
4701 >     * simplest hoisted bypass to help avoid convoluted traps.
4702 >     */
4703 >    @SuppressWarnings("serial")
4704 >    static final class ForEachKeyTask<K,V>
4705 >        extends BulkTask<K,V,Void> {
4706 >        final Consumer<? super K> action;
4707 >        ForEachKeyTask
4708 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4709 >             Consumer<? super K> action) {
4710 >            super(p, b, i, f, t);
4711 >            this.action = action;
4712 >        }
4713 >        public final void compute() {
4714 >            final Consumer<? super K> action;
4715 >            if ((action = this.action) != null) {
4716 >                for (int i = baseIndex, f, h; batch > 0 &&
4717 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4718 >                    addToPendingCount(1);
4719 >                    new ForEachKeyTask<K,V>
4720 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4721 >                         action).fork();
4722 >                }
4723 >                for (Node<K,V> p; (p = advance()) != null;)
4724 >                    action.accept(p.key);
4725 >                propagateCompletion();
4726 >            }
4727 >        }
4728 >    }
4729  
4730 <        // Re-initialize segments to be minimally sized, and let grow.
4731 <        int cap = MIN_SEGMENT_TABLE_CAPACITY;
4732 <        final Segment<K,V>[] segments = this.segments;
4733 <        for (int k = 0; k < segments.length; ++k) {
4734 <            Segment<K,V> seg = segments[k];
4735 <            if (seg != null) {
4736 <                seg.threshold = (int)(cap * seg.loadFactor);
4737 <                seg.table = (HashEntry<K,V>[]) new HashEntry[cap];
4730 >    @SuppressWarnings("serial")
4731 >    static final class ForEachValueTask<K,V>
4732 >        extends BulkTask<K,V,Void> {
4733 >        final Consumer<? super V> action;
4734 >        ForEachValueTask
4735 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4736 >             Consumer<? super V> action) {
4737 >            super(p, b, i, f, t);
4738 >            this.action = action;
4739 >        }
4740 >        public final void compute() {
4741 >            final Consumer<? super V> action;
4742 >            if ((action = this.action) != null) {
4743 >                for (int i = baseIndex, f, h; batch > 0 &&
4744 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4745 >                    addToPendingCount(1);
4746 >                    new ForEachValueTask<K,V>
4747 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4748 >                         action).fork();
4749 >                }
4750 >                for (Node<K,V> p; (p = advance()) != null;)
4751 >                    action.accept(p.val);
4752 >                propagateCompletion();
4753              }
4754          }
4755 +    }
4756  
4757 <        // Read the keys and values, and put the mappings in the table
4758 <        for (;;) {
4759 <            K key = (K) s.readObject();
4760 <            V value = (V) s.readObject();
4761 <            if (key == null)
4762 <                break;
4763 <            put(key, value);
4757 >    @SuppressWarnings("serial")
4758 >    static final class ForEachEntryTask<K,V>
4759 >        extends BulkTask<K,V,Void> {
4760 >        final Consumer<? super Entry<K,V>> action;
4761 >        ForEachEntryTask
4762 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4763 >             Consumer<? super Entry<K,V>> action) {
4764 >            super(p, b, i, f, t);
4765 >            this.action = action;
4766 >        }
4767 >        public final void compute() {
4768 >            final Consumer<? super Entry<K,V>> action;
4769 >            if ((action = this.action) != null) {
4770 >                for (int i = baseIndex, f, h; batch > 0 &&
4771 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4772 >                    addToPendingCount(1);
4773 >                    new ForEachEntryTask<K,V>
4774 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4775 >                         action).fork();
4776 >                }
4777 >                for (Node<K,V> p; (p = advance()) != null; )
4778 >                    action.accept(p);
4779 >                propagateCompletion();
4780 >            }
4781 >        }
4782 >    }
4783 >
4784 >    @SuppressWarnings("serial")
4785 >    static final class ForEachMappingTask<K,V>
4786 >        extends BulkTask<K,V,Void> {
4787 >        final BiConsumer<? super K, ? super V> action;
4788 >        ForEachMappingTask
4789 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4790 >             BiConsumer<? super K,? super V> action) {
4791 >            super(p, b, i, f, t);
4792 >            this.action = action;
4793 >        }
4794 >        public final void compute() {
4795 >            final BiConsumer<? super K, ? super V> action;
4796 >            if ((action = this.action) != null) {
4797 >                for (int i = baseIndex, f, h; batch > 0 &&
4798 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4799 >                    addToPendingCount(1);
4800 >                    new ForEachMappingTask<K,V>
4801 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4802 >                         action).fork();
4803 >                }
4804 >                for (Node<K,V> p; (p = advance()) != null; )
4805 >                    action.accept(p.key, p.val);
4806 >                propagateCompletion();
4807 >            }
4808 >        }
4809 >    }
4810 >
4811 >    @SuppressWarnings("serial")
4812 >    static final class ForEachTransformedKeyTask<K,V,U>
4813 >        extends BulkTask<K,V,Void> {
4814 >        final Function<? super K, ? extends U> transformer;
4815 >        final Consumer<? super U> action;
4816 >        ForEachTransformedKeyTask
4817 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4818 >             Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4819 >            super(p, b, i, f, t);
4820 >            this.transformer = transformer; this.action = action;
4821 >        }
4822 >        public final void compute() {
4823 >            final Function<? super K, ? extends U> transformer;
4824 >            final Consumer<? super U> action;
4825 >            if ((transformer = this.transformer) != null &&
4826 >                (action = this.action) != null) {
4827 >                for (int i = baseIndex, f, h; batch > 0 &&
4828 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4829 >                    addToPendingCount(1);
4830 >                    new ForEachTransformedKeyTask<K,V,U>
4831 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4832 >                         transformer, action).fork();
4833 >                }
4834 >                for (Node<K,V> p; (p = advance()) != null; ) {
4835 >                    U u;
4836 >                    if ((u = transformer.apply(p.key)) != null)
4837 >                        action.accept(u);
4838 >                }
4839 >                propagateCompletion();
4840 >            }
4841 >        }
4842 >    }
4843 >
4844 >    @SuppressWarnings("serial")
4845 >    static final class ForEachTransformedValueTask<K,V,U>
4846 >        extends BulkTask<K,V,Void> {
4847 >        final Function<? super V, ? extends U> transformer;
4848 >        final Consumer<? super U> action;
4849 >        ForEachTransformedValueTask
4850 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4851 >             Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4852 >            super(p, b, i, f, t);
4853 >            this.transformer = transformer; this.action = action;
4854 >        }
4855 >        public final void compute() {
4856 >            final Function<? super V, ? extends U> transformer;
4857 >            final Consumer<? super U> action;
4858 >            if ((transformer = this.transformer) != null &&
4859 >                (action = this.action) != null) {
4860 >                for (int i = baseIndex, f, h; batch > 0 &&
4861 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4862 >                    addToPendingCount(1);
4863 >                    new ForEachTransformedValueTask<K,V,U>
4864 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4865 >                         transformer, action).fork();
4866 >                }
4867 >                for (Node<K,V> p; (p = advance()) != null; ) {
4868 >                    U u;
4869 >                    if ((u = transformer.apply(p.val)) != null)
4870 >                        action.accept(u);
4871 >                }
4872 >                propagateCompletion();
4873 >            }
4874 >        }
4875 >    }
4876 >
4877 >    @SuppressWarnings("serial")
4878 >    static final class ForEachTransformedEntryTask<K,V,U>
4879 >        extends BulkTask<K,V,Void> {
4880 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
4881 >        final Consumer<? super U> action;
4882 >        ForEachTransformedEntryTask
4883 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4884 >             Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4885 >            super(p, b, i, f, t);
4886 >            this.transformer = transformer; this.action = action;
4887 >        }
4888 >        public final void compute() {
4889 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
4890 >            final Consumer<? super U> action;
4891 >            if ((transformer = this.transformer) != null &&
4892 >                (action = this.action) != null) {
4893 >                for (int i = baseIndex, f, h; batch > 0 &&
4894 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4895 >                    addToPendingCount(1);
4896 >                    new ForEachTransformedEntryTask<K,V,U>
4897 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4898 >                         transformer, action).fork();
4899 >                }
4900 >                for (Node<K,V> p; (p = advance()) != null; ) {
4901 >                    U u;
4902 >                    if ((u = transformer.apply(p)) != null)
4903 >                        action.accept(u);
4904 >                }
4905 >                propagateCompletion();
4906 >            }
4907 >        }
4908 >    }
4909 >
4910 >    @SuppressWarnings("serial")
4911 >    static final class ForEachTransformedMappingTask<K,V,U>
4912 >        extends BulkTask<K,V,Void> {
4913 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
4914 >        final Consumer<? super U> action;
4915 >        ForEachTransformedMappingTask
4916 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4917 >             BiFunction<? super K, ? super V, ? extends U> transformer,
4918 >             Consumer<? super U> action) {
4919 >            super(p, b, i, f, t);
4920 >            this.transformer = transformer; this.action = action;
4921 >        }
4922 >        public final void compute() {
4923 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
4924 >            final Consumer<? super U> action;
4925 >            if ((transformer = this.transformer) != null &&
4926 >                (action = this.action) != null) {
4927 >                for (int i = baseIndex, f, h; batch > 0 &&
4928 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4929 >                    addToPendingCount(1);
4930 >                    new ForEachTransformedMappingTask<K,V,U>
4931 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4932 >                         transformer, action).fork();
4933 >                }
4934 >                for (Node<K,V> p; (p = advance()) != null; ) {
4935 >                    U u;
4936 >                    if ((u = transformer.apply(p.key, p.val)) != null)
4937 >                        action.accept(u);
4938 >                }
4939 >                propagateCompletion();
4940 >            }
4941 >        }
4942 >    }
4943 >
4944 >    @SuppressWarnings("serial")
4945 >    static final class SearchKeysTask<K,V,U>
4946 >        extends BulkTask<K,V,U> {
4947 >        final Function<? super K, ? extends U> searchFunction;
4948 >        final AtomicReference<U> result;
4949 >        SearchKeysTask
4950 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4951 >             Function<? super K, ? extends U> searchFunction,
4952 >             AtomicReference<U> result) {
4953 >            super(p, b, i, f, t);
4954 >            this.searchFunction = searchFunction; this.result = result;
4955 >        }
4956 >        public final U getRawResult() { return result.get(); }
4957 >        public final void compute() {
4958 >            final Function<? super K, ? extends U> searchFunction;
4959 >            final AtomicReference<U> result;
4960 >            if ((searchFunction = this.searchFunction) != null &&
4961 >                (result = this.result) != null) {
4962 >                for (int i = baseIndex, f, h; batch > 0 &&
4963 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
4964 >                    if (result.get() != null)
4965 >                        return;
4966 >                    addToPendingCount(1);
4967 >                    new SearchKeysTask<K,V,U>
4968 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
4969 >                         searchFunction, result).fork();
4970 >                }
4971 >                while (result.get() == null) {
4972 >                    U u;
4973 >                    Node<K,V> p;
4974 >                    if ((p = advance()) == null) {
4975 >                        propagateCompletion();
4976 >                        break;
4977 >                    }
4978 >                    if ((u = searchFunction.apply(p.key)) != null) {
4979 >                        if (result.compareAndSet(null, u))
4980 >                            quietlyCompleteRoot();
4981 >                        break;
4982 >                    }
4983 >                }
4984 >            }
4985 >        }
4986 >    }
4987 >
4988 >    @SuppressWarnings("serial")
4989 >    static final class SearchValuesTask<K,V,U>
4990 >        extends BulkTask<K,V,U> {
4991 >        final Function<? super V, ? extends U> searchFunction;
4992 >        final AtomicReference<U> result;
4993 >        SearchValuesTask
4994 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4995 >             Function<? super V, ? extends U> searchFunction,
4996 >             AtomicReference<U> result) {
4997 >            super(p, b, i, f, t);
4998 >            this.searchFunction = searchFunction; this.result = result;
4999 >        }
5000 >        public final U getRawResult() { return result.get(); }
5001 >        public final void compute() {
5002 >            final Function<? super V, ? extends U> searchFunction;
5003 >            final AtomicReference<U> result;
5004 >            if ((searchFunction = this.searchFunction) != null &&
5005 >                (result = this.result) != null) {
5006 >                for (int i = baseIndex, f, h; batch > 0 &&
5007 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5008 >                    if (result.get() != null)
5009 >                        return;
5010 >                    addToPendingCount(1);
5011 >                    new SearchValuesTask<K,V,U>
5012 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5013 >                         searchFunction, result).fork();
5014 >                }
5015 >                while (result.get() == null) {
5016 >                    U u;
5017 >                    Node<K,V> p;
5018 >                    if ((p = advance()) == null) {
5019 >                        propagateCompletion();
5020 >                        break;
5021 >                    }
5022 >                    if ((u = searchFunction.apply(p.val)) != null) {
5023 >                        if (result.compareAndSet(null, u))
5024 >                            quietlyCompleteRoot();
5025 >                        break;
5026 >                    }
5027 >                }
5028 >            }
5029 >        }
5030 >    }
5031 >
5032 >    @SuppressWarnings("serial")
5033 >    static final class SearchEntriesTask<K,V,U>
5034 >        extends BulkTask<K,V,U> {
5035 >        final Function<Entry<K,V>, ? extends U> searchFunction;
5036 >        final AtomicReference<U> result;
5037 >        SearchEntriesTask
5038 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5039 >             Function<Entry<K,V>, ? extends U> searchFunction,
5040 >             AtomicReference<U> result) {
5041 >            super(p, b, i, f, t);
5042 >            this.searchFunction = searchFunction; this.result = result;
5043 >        }
5044 >        public final U getRawResult() { return result.get(); }
5045 >        public final void compute() {
5046 >            final Function<Entry<K,V>, ? extends U> searchFunction;
5047 >            final AtomicReference<U> result;
5048 >            if ((searchFunction = this.searchFunction) != null &&
5049 >                (result = this.result) != null) {
5050 >                for (int i = baseIndex, f, h; batch > 0 &&
5051 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5052 >                    if (result.get() != null)
5053 >                        return;
5054 >                    addToPendingCount(1);
5055 >                    new SearchEntriesTask<K,V,U>
5056 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5057 >                         searchFunction, result).fork();
5058 >                }
5059 >                while (result.get() == null) {
5060 >                    U u;
5061 >                    Node<K,V> p;
5062 >                    if ((p = advance()) == null) {
5063 >                        propagateCompletion();
5064 >                        break;
5065 >                    }
5066 >                    if ((u = searchFunction.apply(p)) != null) {
5067 >                        if (result.compareAndSet(null, u))
5068 >                            quietlyCompleteRoot();
5069 >                        return;
5070 >                    }
5071 >                }
5072 >            }
5073 >        }
5074 >    }
5075 >
5076 >    @SuppressWarnings("serial")
5077 >    static final class SearchMappingsTask<K,V,U>
5078 >        extends BulkTask<K,V,U> {
5079 >        final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5080 >        final AtomicReference<U> result;
5081 >        SearchMappingsTask
5082 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5083 >             BiFunction<? super K, ? super V, ? extends U> searchFunction,
5084 >             AtomicReference<U> result) {
5085 >            super(p, b, i, f, t);
5086 >            this.searchFunction = searchFunction; this.result = result;
5087 >        }
5088 >        public final U getRawResult() { return result.get(); }
5089 >        public final void compute() {
5090 >            final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5091 >            final AtomicReference<U> result;
5092 >            if ((searchFunction = this.searchFunction) != null &&
5093 >                (result = this.result) != null) {
5094 >                for (int i = baseIndex, f, h; batch > 0 &&
5095 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5096 >                    if (result.get() != null)
5097 >                        return;
5098 >                    addToPendingCount(1);
5099 >                    new SearchMappingsTask<K,V,U>
5100 >                        (this, batch >>>= 1, baseLimit = h, f, tab,
5101 >                         searchFunction, result).fork();
5102 >                }
5103 >                while (result.get() == null) {
5104 >                    U u;
5105 >                    Node<K,V> p;
5106 >                    if ((p = advance()) == null) {
5107 >                        propagateCompletion();
5108 >                        break;
5109 >                    }
5110 >                    if ((u = searchFunction.apply(p.key, p.val)) != null) {
5111 >                        if (result.compareAndSet(null, u))
5112 >                            quietlyCompleteRoot();
5113 >                        break;
5114 >                    }
5115 >                }
5116 >            }
5117 >        }
5118 >    }
5119 >
5120 >    @SuppressWarnings("serial")
5121 >    static final class ReduceKeysTask<K,V>
5122 >        extends BulkTask<K,V,K> {
5123 >        final BiFunction<? super K, ? super K, ? extends K> reducer;
5124 >        K result;
5125 >        ReduceKeysTask<K,V> rights, nextRight;
5126 >        ReduceKeysTask
5127 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5128 >             ReduceKeysTask<K,V> nextRight,
5129 >             BiFunction<? super K, ? super K, ? extends K> reducer) {
5130 >            super(p, b, i, f, t); this.nextRight = nextRight;
5131 >            this.reducer = reducer;
5132 >        }
5133 >        public final K getRawResult() { return result; }
5134 >        public final void compute() {
5135 >            final BiFunction<? super K, ? super K, ? extends K> reducer;
5136 >            if ((reducer = this.reducer) != null) {
5137 >                for (int i = baseIndex, f, h; batch > 0 &&
5138 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5139 >                    addToPendingCount(1);
5140 >                    (rights = new ReduceKeysTask<K,V>
5141 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5142 >                      rights, reducer)).fork();
5143 >                }
5144 >                K r = null;
5145 >                for (Node<K,V> p; (p = advance()) != null; ) {
5146 >                    K u = p.key;
5147 >                    r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5148 >                }
5149 >                result = r;
5150 >                CountedCompleter<?> c;
5151 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5152 >                    @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5153 >                        t = (ReduceKeysTask<K,V>)c,
5154 >                        s = t.rights;
5155 >                    while (s != null) {
5156 >                        K tr, sr;
5157 >                        if ((sr = s.result) != null)
5158 >                            t.result = (((tr = t.result) == null) ? sr :
5159 >                                        reducer.apply(tr, sr));
5160 >                        s = t.rights = s.nextRight;
5161 >                    }
5162 >                }
5163 >            }
5164 >        }
5165 >    }
5166 >
5167 >    @SuppressWarnings("serial")
5168 >    static final class ReduceValuesTask<K,V>
5169 >        extends BulkTask<K,V,V> {
5170 >        final BiFunction<? super V, ? super V, ? extends V> reducer;
5171 >        V result;
5172 >        ReduceValuesTask<K,V> rights, nextRight;
5173 >        ReduceValuesTask
5174 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5175 >             ReduceValuesTask<K,V> nextRight,
5176 >             BiFunction<? super V, ? super V, ? extends V> reducer) {
5177 >            super(p, b, i, f, t); this.nextRight = nextRight;
5178 >            this.reducer = reducer;
5179 >        }
5180 >        public final V getRawResult() { return result; }
5181 >        public final void compute() {
5182 >            final BiFunction<? super V, ? super V, ? extends V> reducer;
5183 >            if ((reducer = this.reducer) != null) {
5184 >                for (int i = baseIndex, f, h; batch > 0 &&
5185 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5186 >                    addToPendingCount(1);
5187 >                    (rights = new ReduceValuesTask<K,V>
5188 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5189 >                      rights, reducer)).fork();
5190 >                }
5191 >                V r = null;
5192 >                for (Node<K,V> p; (p = advance()) != null; ) {
5193 >                    V v = p.val;
5194 >                    r = (r == null) ? v : reducer.apply(r, v);
5195 >                }
5196 >                result = r;
5197 >                CountedCompleter<?> c;
5198 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5199 >                    @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5200 >                        t = (ReduceValuesTask<K,V>)c,
5201 >                        s = t.rights;
5202 >                    while (s != null) {
5203 >                        V tr, sr;
5204 >                        if ((sr = s.result) != null)
5205 >                            t.result = (((tr = t.result) == null) ? sr :
5206 >                                        reducer.apply(tr, sr));
5207 >                        s = t.rights = s.nextRight;
5208 >                    }
5209 >                }
5210 >            }
5211 >        }
5212 >    }
5213 >
5214 >    @SuppressWarnings("serial")
5215 >    static final class ReduceEntriesTask<K,V>
5216 >        extends BulkTask<K,V,Map.Entry<K,V>> {
5217 >        final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5218 >        Map.Entry<K,V> result;
5219 >        ReduceEntriesTask<K,V> rights, nextRight;
5220 >        ReduceEntriesTask
5221 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5222 >             ReduceEntriesTask<K,V> nextRight,
5223 >             BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5224 >            super(p, b, i, f, t); this.nextRight = nextRight;
5225 >            this.reducer = reducer;
5226 >        }
5227 >        public final Map.Entry<K,V> getRawResult() { return result; }
5228 >        public final void compute() {
5229 >            final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5230 >            if ((reducer = this.reducer) != null) {
5231 >                for (int i = baseIndex, f, h; batch > 0 &&
5232 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5233 >                    addToPendingCount(1);
5234 >                    (rights = new ReduceEntriesTask<K,V>
5235 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5236 >                      rights, reducer)).fork();
5237 >                }
5238 >                Map.Entry<K,V> r = null;
5239 >                for (Node<K,V> p; (p = advance()) != null; )
5240 >                    r = (r == null) ? p : reducer.apply(r, p);
5241 >                result = r;
5242 >                CountedCompleter<?> c;
5243 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5244 >                    @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5245 >                        t = (ReduceEntriesTask<K,V>)c,
5246 >                        s = t.rights;
5247 >                    while (s != null) {
5248 >                        Map.Entry<K,V> tr, sr;
5249 >                        if ((sr = s.result) != null)
5250 >                            t.result = (((tr = t.result) == null) ? sr :
5251 >                                        reducer.apply(tr, sr));
5252 >                        s = t.rights = s.nextRight;
5253 >                    }
5254 >                }
5255 >            }
5256 >        }
5257 >    }
5258 >
5259 >    @SuppressWarnings("serial")
5260 >    static final class MapReduceKeysTask<K,V,U>
5261 >        extends BulkTask<K,V,U> {
5262 >        final Function<? super K, ? extends U> transformer;
5263 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5264 >        U result;
5265 >        MapReduceKeysTask<K,V,U> rights, nextRight;
5266 >        MapReduceKeysTask
5267 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5268 >             MapReduceKeysTask<K,V,U> nextRight,
5269 >             Function<? super K, ? extends U> transformer,
5270 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5271 >            super(p, b, i, f, t); this.nextRight = nextRight;
5272 >            this.transformer = transformer;
5273 >            this.reducer = reducer;
5274 >        }
5275 >        public final U getRawResult() { return result; }
5276 >        public final void compute() {
5277 >            final Function<? super K, ? extends U> transformer;
5278 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5279 >            if ((transformer = this.transformer) != null &&
5280 >                (reducer = this.reducer) != null) {
5281 >                for (int i = baseIndex, f, h; batch > 0 &&
5282 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5283 >                    addToPendingCount(1);
5284 >                    (rights = new MapReduceKeysTask<K,V,U>
5285 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5286 >                      rights, transformer, reducer)).fork();
5287 >                }
5288 >                U r = null;
5289 >                for (Node<K,V> p; (p = advance()) != null; ) {
5290 >                    U u;
5291 >                    if ((u = transformer.apply(p.key)) != null)
5292 >                        r = (r == null) ? u : reducer.apply(r, u);
5293 >                }
5294 >                result = r;
5295 >                CountedCompleter<?> c;
5296 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5297 >                    @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5298 >                        t = (MapReduceKeysTask<K,V,U>)c,
5299 >                        s = t.rights;
5300 >                    while (s != null) {
5301 >                        U tr, sr;
5302 >                        if ((sr = s.result) != null)
5303 >                            t.result = (((tr = t.result) == null) ? sr :
5304 >                                        reducer.apply(tr, sr));
5305 >                        s = t.rights = s.nextRight;
5306 >                    }
5307 >                }
5308 >            }
5309 >        }
5310 >    }
5311 >
5312 >    @SuppressWarnings("serial")
5313 >    static final class MapReduceValuesTask<K,V,U>
5314 >        extends BulkTask<K,V,U> {
5315 >        final Function<? super V, ? extends U> transformer;
5316 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5317 >        U result;
5318 >        MapReduceValuesTask<K,V,U> rights, nextRight;
5319 >        MapReduceValuesTask
5320 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5321 >             MapReduceValuesTask<K,V,U> nextRight,
5322 >             Function<? super V, ? extends U> transformer,
5323 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5324 >            super(p, b, i, f, t); this.nextRight = nextRight;
5325 >            this.transformer = transformer;
5326 >            this.reducer = reducer;
5327 >        }
5328 >        public final U getRawResult() { return result; }
5329 >        public final void compute() {
5330 >            final Function<? super V, ? extends U> transformer;
5331 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5332 >            if ((transformer = this.transformer) != null &&
5333 >                (reducer = this.reducer) != null) {
5334 >                for (int i = baseIndex, f, h; batch > 0 &&
5335 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5336 >                    addToPendingCount(1);
5337 >                    (rights = new MapReduceValuesTask<K,V,U>
5338 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5339 >                      rights, transformer, reducer)).fork();
5340 >                }
5341 >                U r = null;
5342 >                for (Node<K,V> p; (p = advance()) != null; ) {
5343 >                    U u;
5344 >                    if ((u = transformer.apply(p.val)) != null)
5345 >                        r = (r == null) ? u : reducer.apply(r, u);
5346 >                }
5347 >                result = r;
5348 >                CountedCompleter<?> c;
5349 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5350 >                    @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5351 >                        t = (MapReduceValuesTask<K,V,U>)c,
5352 >                        s = t.rights;
5353 >                    while (s != null) {
5354 >                        U tr, sr;
5355 >                        if ((sr = s.result) != null)
5356 >                            t.result = (((tr = t.result) == null) ? sr :
5357 >                                        reducer.apply(tr, sr));
5358 >                        s = t.rights = s.nextRight;
5359 >                    }
5360 >                }
5361 >            }
5362 >        }
5363 >    }
5364 >
5365 >    @SuppressWarnings("serial")
5366 >    static final class MapReduceEntriesTask<K,V,U>
5367 >        extends BulkTask<K,V,U> {
5368 >        final Function<Map.Entry<K,V>, ? extends U> transformer;
5369 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5370 >        U result;
5371 >        MapReduceEntriesTask<K,V,U> rights, nextRight;
5372 >        MapReduceEntriesTask
5373 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5374 >             MapReduceEntriesTask<K,V,U> nextRight,
5375 >             Function<Map.Entry<K,V>, ? extends U> transformer,
5376 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5377 >            super(p, b, i, f, t); this.nextRight = nextRight;
5378 >            this.transformer = transformer;
5379 >            this.reducer = reducer;
5380 >        }
5381 >        public final U getRawResult() { return result; }
5382 >        public final void compute() {
5383 >            final Function<Map.Entry<K,V>, ? extends U> transformer;
5384 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5385 >            if ((transformer = this.transformer) != null &&
5386 >                (reducer = this.reducer) != null) {
5387 >                for (int i = baseIndex, f, h; batch > 0 &&
5388 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5389 >                    addToPendingCount(1);
5390 >                    (rights = new MapReduceEntriesTask<K,V,U>
5391 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5392 >                      rights, transformer, reducer)).fork();
5393 >                }
5394 >                U r = null;
5395 >                for (Node<K,V> p; (p = advance()) != null; ) {
5396 >                    U u;
5397 >                    if ((u = transformer.apply(p)) != null)
5398 >                        r = (r == null) ? u : reducer.apply(r, u);
5399 >                }
5400 >                result = r;
5401 >                CountedCompleter<?> c;
5402 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5403 >                    @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5404 >                        t = (MapReduceEntriesTask<K,V,U>)c,
5405 >                        s = t.rights;
5406 >                    while (s != null) {
5407 >                        U tr, sr;
5408 >                        if ((sr = s.result) != null)
5409 >                            t.result = (((tr = t.result) == null) ? sr :
5410 >                                        reducer.apply(tr, sr));
5411 >                        s = t.rights = s.nextRight;
5412 >                    }
5413 >                }
5414 >            }
5415 >        }
5416 >    }
5417 >
5418 >    @SuppressWarnings("serial")
5419 >    static final class MapReduceMappingsTask<K,V,U>
5420 >        extends BulkTask<K,V,U> {
5421 >        final BiFunction<? super K, ? super V, ? extends U> transformer;
5422 >        final BiFunction<? super U, ? super U, ? extends U> reducer;
5423 >        U result;
5424 >        MapReduceMappingsTask<K,V,U> rights, nextRight;
5425 >        MapReduceMappingsTask
5426 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5427 >             MapReduceMappingsTask<K,V,U> nextRight,
5428 >             BiFunction<? super K, ? super V, ? extends U> transformer,
5429 >             BiFunction<? super U, ? super U, ? extends U> reducer) {
5430 >            super(p, b, i, f, t); this.nextRight = nextRight;
5431 >            this.transformer = transformer;
5432 >            this.reducer = reducer;
5433 >        }
5434 >        public final U getRawResult() { return result; }
5435 >        public final void compute() {
5436 >            final BiFunction<? super K, ? super V, ? extends U> transformer;
5437 >            final BiFunction<? super U, ? super U, ? extends U> reducer;
5438 >            if ((transformer = this.transformer) != null &&
5439 >                (reducer = this.reducer) != null) {
5440 >                for (int i = baseIndex, f, h; batch > 0 &&
5441 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5442 >                    addToPendingCount(1);
5443 >                    (rights = new MapReduceMappingsTask<K,V,U>
5444 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5445 >                      rights, transformer, reducer)).fork();
5446 >                }
5447 >                U r = null;
5448 >                for (Node<K,V> p; (p = advance()) != null; ) {
5449 >                    U u;
5450 >                    if ((u = transformer.apply(p.key, p.val)) != null)
5451 >                        r = (r == null) ? u : reducer.apply(r, u);
5452 >                }
5453 >                result = r;
5454 >                CountedCompleter<?> c;
5455 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5456 >                    @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5457 >                        t = (MapReduceMappingsTask<K,V,U>)c,
5458 >                        s = t.rights;
5459 >                    while (s != null) {
5460 >                        U tr, sr;
5461 >                        if ((sr = s.result) != null)
5462 >                            t.result = (((tr = t.result) == null) ? sr :
5463 >                                        reducer.apply(tr, sr));
5464 >                        s = t.rights = s.nextRight;
5465 >                    }
5466 >                }
5467 >            }
5468 >        }
5469 >    }
5470 >
5471 >    @SuppressWarnings("serial")
5472 >    static final class MapReduceKeysToDoubleTask<K,V>
5473 >        extends BulkTask<K,V,Double> {
5474 >        final ToDoubleFunction<? super K> transformer;
5475 >        final DoubleBinaryOperator reducer;
5476 >        final double basis;
5477 >        double result;
5478 >        MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5479 >        MapReduceKeysToDoubleTask
5480 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5481 >             MapReduceKeysToDoubleTask<K,V> nextRight,
5482 >             ToDoubleFunction<? super K> transformer,
5483 >             double basis,
5484 >             DoubleBinaryOperator reducer) {
5485 >            super(p, b, i, f, t); this.nextRight = nextRight;
5486 >            this.transformer = transformer;
5487 >            this.basis = basis; this.reducer = reducer;
5488 >        }
5489 >        public final Double getRawResult() { return result; }
5490 >        public final void compute() {
5491 >            final ToDoubleFunction<? super K> transformer;
5492 >            final DoubleBinaryOperator reducer;
5493 >            if ((transformer = this.transformer) != null &&
5494 >                (reducer = this.reducer) != null) {
5495 >                double r = this.basis;
5496 >                for (int i = baseIndex, f, h; batch > 0 &&
5497 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5498 >                    addToPendingCount(1);
5499 >                    (rights = new MapReduceKeysToDoubleTask<K,V>
5500 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5501 >                      rights, transformer, r, reducer)).fork();
5502 >                }
5503 >                for (Node<K,V> p; (p = advance()) != null; )
5504 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5505 >                result = r;
5506 >                CountedCompleter<?> c;
5507 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5508 >                    @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5509 >                        t = (MapReduceKeysToDoubleTask<K,V>)c,
5510 >                        s = t.rights;
5511 >                    while (s != null) {
5512 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5513 >                        s = t.rights = s.nextRight;
5514 >                    }
5515 >                }
5516 >            }
5517 >        }
5518 >    }
5519 >
5520 >    @SuppressWarnings("serial")
5521 >    static final class MapReduceValuesToDoubleTask<K,V>
5522 >        extends BulkTask<K,V,Double> {
5523 >        final ToDoubleFunction<? super V> transformer;
5524 >        final DoubleBinaryOperator reducer;
5525 >        final double basis;
5526 >        double result;
5527 >        MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5528 >        MapReduceValuesToDoubleTask
5529 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5530 >             MapReduceValuesToDoubleTask<K,V> nextRight,
5531 >             ToDoubleFunction<? super V> transformer,
5532 >             double basis,
5533 >             DoubleBinaryOperator reducer) {
5534 >            super(p, b, i, f, t); this.nextRight = nextRight;
5535 >            this.transformer = transformer;
5536 >            this.basis = basis; this.reducer = reducer;
5537 >        }
5538 >        public final Double getRawResult() { return result; }
5539 >        public final void compute() {
5540 >            final ToDoubleFunction<? super V> transformer;
5541 >            final DoubleBinaryOperator reducer;
5542 >            if ((transformer = this.transformer) != null &&
5543 >                (reducer = this.reducer) != null) {
5544 >                double r = this.basis;
5545 >                for (int i = baseIndex, f, h; batch > 0 &&
5546 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5547 >                    addToPendingCount(1);
5548 >                    (rights = new MapReduceValuesToDoubleTask<K,V>
5549 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5550 >                      rights, transformer, r, reducer)).fork();
5551 >                }
5552 >                for (Node<K,V> p; (p = advance()) != null; )
5553 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5554 >                result = r;
5555 >                CountedCompleter<?> c;
5556 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5557 >                    @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5558 >                        t = (MapReduceValuesToDoubleTask<K,V>)c,
5559 >                        s = t.rights;
5560 >                    while (s != null) {
5561 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5562 >                        s = t.rights = s.nextRight;
5563 >                    }
5564 >                }
5565 >            }
5566 >        }
5567 >    }
5568 >
5569 >    @SuppressWarnings("serial")
5570 >    static final class MapReduceEntriesToDoubleTask<K,V>
5571 >        extends BulkTask<K,V,Double> {
5572 >        final ToDoubleFunction<Map.Entry<K,V>> transformer;
5573 >        final DoubleBinaryOperator reducer;
5574 >        final double basis;
5575 >        double result;
5576 >        MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5577 >        MapReduceEntriesToDoubleTask
5578 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5579 >             MapReduceEntriesToDoubleTask<K,V> nextRight,
5580 >             ToDoubleFunction<Map.Entry<K,V>> transformer,
5581 >             double basis,
5582 >             DoubleBinaryOperator reducer) {
5583 >            super(p, b, i, f, t); this.nextRight = nextRight;
5584 >            this.transformer = transformer;
5585 >            this.basis = basis; this.reducer = reducer;
5586 >        }
5587 >        public final Double getRawResult() { return result; }
5588 >        public final void compute() {
5589 >            final ToDoubleFunction<Map.Entry<K,V>> transformer;
5590 >            final DoubleBinaryOperator reducer;
5591 >            if ((transformer = this.transformer) != null &&
5592 >                (reducer = this.reducer) != null) {
5593 >                double r = this.basis;
5594 >                for (int i = baseIndex, f, h; batch > 0 &&
5595 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5596 >                    addToPendingCount(1);
5597 >                    (rights = new MapReduceEntriesToDoubleTask<K,V>
5598 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5599 >                      rights, transformer, r, reducer)).fork();
5600 >                }
5601 >                for (Node<K,V> p; (p = advance()) != null; )
5602 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5603 >                result = r;
5604 >                CountedCompleter<?> c;
5605 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5606 >                    @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5607 >                        t = (MapReduceEntriesToDoubleTask<K,V>)c,
5608 >                        s = t.rights;
5609 >                    while (s != null) {
5610 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5611 >                        s = t.rights = s.nextRight;
5612 >                    }
5613 >                }
5614 >            }
5615 >        }
5616 >    }
5617 >
5618 >    @SuppressWarnings("serial")
5619 >    static final class MapReduceMappingsToDoubleTask<K,V>
5620 >        extends BulkTask<K,V,Double> {
5621 >        final ToDoubleBiFunction<? super K, ? super V> transformer;
5622 >        final DoubleBinaryOperator reducer;
5623 >        final double basis;
5624 >        double result;
5625 >        MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5626 >        MapReduceMappingsToDoubleTask
5627 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5628 >             MapReduceMappingsToDoubleTask<K,V> nextRight,
5629 >             ToDoubleBiFunction<? super K, ? super V> transformer,
5630 >             double basis,
5631 >             DoubleBinaryOperator reducer) {
5632 >            super(p, b, i, f, t); this.nextRight = nextRight;
5633 >            this.transformer = transformer;
5634 >            this.basis = basis; this.reducer = reducer;
5635 >        }
5636 >        public final Double getRawResult() { return result; }
5637 >        public final void compute() {
5638 >            final ToDoubleBiFunction<? super K, ? super V> transformer;
5639 >            final DoubleBinaryOperator reducer;
5640 >            if ((transformer = this.transformer) != null &&
5641 >                (reducer = this.reducer) != null) {
5642 >                double r = this.basis;
5643 >                for (int i = baseIndex, f, h; batch > 0 &&
5644 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5645 >                    addToPendingCount(1);
5646 >                    (rights = new MapReduceMappingsToDoubleTask<K,V>
5647 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5648 >                      rights, transformer, r, reducer)).fork();
5649 >                }
5650 >                for (Node<K,V> p; (p = advance()) != null; )
5651 >                    r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5652 >                result = r;
5653 >                CountedCompleter<?> c;
5654 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5655 >                    @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5656 >                        t = (MapReduceMappingsToDoubleTask<K,V>)c,
5657 >                        s = t.rights;
5658 >                    while (s != null) {
5659 >                        t.result = reducer.applyAsDouble(t.result, s.result);
5660 >                        s = t.rights = s.nextRight;
5661 >                    }
5662 >                }
5663 >            }
5664 >        }
5665 >    }
5666 >
5667 >    @SuppressWarnings("serial")
5668 >    static final class MapReduceKeysToLongTask<K,V>
5669 >        extends BulkTask<K,V,Long> {
5670 >        final ToLongFunction<? super K> transformer;
5671 >        final LongBinaryOperator reducer;
5672 >        final long basis;
5673 >        long result;
5674 >        MapReduceKeysToLongTask<K,V> rights, nextRight;
5675 >        MapReduceKeysToLongTask
5676 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5677 >             MapReduceKeysToLongTask<K,V> nextRight,
5678 >             ToLongFunction<? super K> transformer,
5679 >             long basis,
5680 >             LongBinaryOperator reducer) {
5681 >            super(p, b, i, f, t); this.nextRight = nextRight;
5682 >            this.transformer = transformer;
5683 >            this.basis = basis; this.reducer = reducer;
5684 >        }
5685 >        public final Long getRawResult() { return result; }
5686 >        public final void compute() {
5687 >            final ToLongFunction<? super K> transformer;
5688 >            final LongBinaryOperator reducer;
5689 >            if ((transformer = this.transformer) != null &&
5690 >                (reducer = this.reducer) != null) {
5691 >                long r = this.basis;
5692 >                for (int i = baseIndex, f, h; batch > 0 &&
5693 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5694 >                    addToPendingCount(1);
5695 >                    (rights = new MapReduceKeysToLongTask<K,V>
5696 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5697 >                      rights, transformer, r, reducer)).fork();
5698 >                }
5699 >                for (Node<K,V> p; (p = advance()) != null; )
5700 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5701 >                result = r;
5702 >                CountedCompleter<?> c;
5703 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5704 >                    @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5705 >                        t = (MapReduceKeysToLongTask<K,V>)c,
5706 >                        s = t.rights;
5707 >                    while (s != null) {
5708 >                        t.result = reducer.applyAsLong(t.result, s.result);
5709 >                        s = t.rights = s.nextRight;
5710 >                    }
5711 >                }
5712 >            }
5713 >        }
5714 >    }
5715 >
5716 >    @SuppressWarnings("serial")
5717 >    static final class MapReduceValuesToLongTask<K,V>
5718 >        extends BulkTask<K,V,Long> {
5719 >        final ToLongFunction<? super V> transformer;
5720 >        final LongBinaryOperator reducer;
5721 >        final long basis;
5722 >        long result;
5723 >        MapReduceValuesToLongTask<K,V> rights, nextRight;
5724 >        MapReduceValuesToLongTask
5725 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5726 >             MapReduceValuesToLongTask<K,V> nextRight,
5727 >             ToLongFunction<? super V> transformer,
5728 >             long basis,
5729 >             LongBinaryOperator reducer) {
5730 >            super(p, b, i, f, t); this.nextRight = nextRight;
5731 >            this.transformer = transformer;
5732 >            this.basis = basis; this.reducer = reducer;
5733 >        }
5734 >        public final Long getRawResult() { return result; }
5735 >        public final void compute() {
5736 >            final ToLongFunction<? super V> transformer;
5737 >            final LongBinaryOperator reducer;
5738 >            if ((transformer = this.transformer) != null &&
5739 >                (reducer = this.reducer) != null) {
5740 >                long r = this.basis;
5741 >                for (int i = baseIndex, f, h; batch > 0 &&
5742 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5743 >                    addToPendingCount(1);
5744 >                    (rights = new MapReduceValuesToLongTask<K,V>
5745 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5746 >                      rights, transformer, r, reducer)).fork();
5747 >                }
5748 >                for (Node<K,V> p; (p = advance()) != null; )
5749 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5750 >                result = r;
5751 >                CountedCompleter<?> c;
5752 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5753 >                    @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5754 >                        t = (MapReduceValuesToLongTask<K,V>)c,
5755 >                        s = t.rights;
5756 >                    while (s != null) {
5757 >                        t.result = reducer.applyAsLong(t.result, s.result);
5758 >                        s = t.rights = s.nextRight;
5759 >                    }
5760 >                }
5761 >            }
5762 >        }
5763 >    }
5764 >
5765 >    @SuppressWarnings("serial")
5766 >    static final class MapReduceEntriesToLongTask<K,V>
5767 >        extends BulkTask<K,V,Long> {
5768 >        final ToLongFunction<Map.Entry<K,V>> transformer;
5769 >        final LongBinaryOperator reducer;
5770 >        final long basis;
5771 >        long result;
5772 >        MapReduceEntriesToLongTask<K,V> rights, nextRight;
5773 >        MapReduceEntriesToLongTask
5774 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5775 >             MapReduceEntriesToLongTask<K,V> nextRight,
5776 >             ToLongFunction<Map.Entry<K,V>> transformer,
5777 >             long basis,
5778 >             LongBinaryOperator reducer) {
5779 >            super(p, b, i, f, t); this.nextRight = nextRight;
5780 >            this.transformer = transformer;
5781 >            this.basis = basis; this.reducer = reducer;
5782 >        }
5783 >        public final Long getRawResult() { return result; }
5784 >        public final void compute() {
5785 >            final ToLongFunction<Map.Entry<K,V>> transformer;
5786 >            final LongBinaryOperator reducer;
5787 >            if ((transformer = this.transformer) != null &&
5788 >                (reducer = this.reducer) != null) {
5789 >                long r = this.basis;
5790 >                for (int i = baseIndex, f, h; batch > 0 &&
5791 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5792 >                    addToPendingCount(1);
5793 >                    (rights = new MapReduceEntriesToLongTask<K,V>
5794 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5795 >                      rights, transformer, r, reducer)).fork();
5796 >                }
5797 >                for (Node<K,V> p; (p = advance()) != null; )
5798 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5799 >                result = r;
5800 >                CountedCompleter<?> c;
5801 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5802 >                    @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5803 >                        t = (MapReduceEntriesToLongTask<K,V>)c,
5804 >                        s = t.rights;
5805 >                    while (s != null) {
5806 >                        t.result = reducer.applyAsLong(t.result, s.result);
5807 >                        s = t.rights = s.nextRight;
5808 >                    }
5809 >                }
5810 >            }
5811 >        }
5812 >    }
5813 >
5814 >    @SuppressWarnings("serial")
5815 >    static final class MapReduceMappingsToLongTask<K,V>
5816 >        extends BulkTask<K,V,Long> {
5817 >        final ToLongBiFunction<? super K, ? super V> transformer;
5818 >        final LongBinaryOperator reducer;
5819 >        final long basis;
5820 >        long result;
5821 >        MapReduceMappingsToLongTask<K,V> rights, nextRight;
5822 >        MapReduceMappingsToLongTask
5823 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5824 >             MapReduceMappingsToLongTask<K,V> nextRight,
5825 >             ToLongBiFunction<? super K, ? super V> transformer,
5826 >             long basis,
5827 >             LongBinaryOperator reducer) {
5828 >            super(p, b, i, f, t); this.nextRight = nextRight;
5829 >            this.transformer = transformer;
5830 >            this.basis = basis; this.reducer = reducer;
5831 >        }
5832 >        public final Long getRawResult() { return result; }
5833 >        public final void compute() {
5834 >            final ToLongBiFunction<? super K, ? super V> transformer;
5835 >            final LongBinaryOperator reducer;
5836 >            if ((transformer = this.transformer) != null &&
5837 >                (reducer = this.reducer) != null) {
5838 >                long r = this.basis;
5839 >                for (int i = baseIndex, f, h; batch > 0 &&
5840 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5841 >                    addToPendingCount(1);
5842 >                    (rights = new MapReduceMappingsToLongTask<K,V>
5843 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5844 >                      rights, transformer, r, reducer)).fork();
5845 >                }
5846 >                for (Node<K,V> p; (p = advance()) != null; )
5847 >                    r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
5848 >                result = r;
5849 >                CountedCompleter<?> c;
5850 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5851 >                    @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5852 >                        t = (MapReduceMappingsToLongTask<K,V>)c,
5853 >                        s = t.rights;
5854 >                    while (s != null) {
5855 >                        t.result = reducer.applyAsLong(t.result, s.result);
5856 >                        s = t.rights = s.nextRight;
5857 >                    }
5858 >                }
5859 >            }
5860 >        }
5861 >    }
5862 >
5863 >    @SuppressWarnings("serial")
5864 >    static final class MapReduceKeysToIntTask<K,V>
5865 >        extends BulkTask<K,V,Integer> {
5866 >        final ToIntFunction<? super K> transformer;
5867 >        final IntBinaryOperator reducer;
5868 >        final int basis;
5869 >        int result;
5870 >        MapReduceKeysToIntTask<K,V> rights, nextRight;
5871 >        MapReduceKeysToIntTask
5872 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5873 >             MapReduceKeysToIntTask<K,V> nextRight,
5874 >             ToIntFunction<? super K> transformer,
5875 >             int basis,
5876 >             IntBinaryOperator reducer) {
5877 >            super(p, b, i, f, t); this.nextRight = nextRight;
5878 >            this.transformer = transformer;
5879 >            this.basis = basis; this.reducer = reducer;
5880 >        }
5881 >        public final Integer getRawResult() { return result; }
5882 >        public final void compute() {
5883 >            final ToIntFunction<? super K> transformer;
5884 >            final IntBinaryOperator reducer;
5885 >            if ((transformer = this.transformer) != null &&
5886 >                (reducer = this.reducer) != null) {
5887 >                int r = this.basis;
5888 >                for (int i = baseIndex, f, h; batch > 0 &&
5889 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5890 >                    addToPendingCount(1);
5891 >                    (rights = new MapReduceKeysToIntTask<K,V>
5892 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5893 >                      rights, transformer, r, reducer)).fork();
5894 >                }
5895 >                for (Node<K,V> p; (p = advance()) != null; )
5896 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
5897 >                result = r;
5898 >                CountedCompleter<?> c;
5899 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5900 >                    @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5901 >                        t = (MapReduceKeysToIntTask<K,V>)c,
5902 >                        s = t.rights;
5903 >                    while (s != null) {
5904 >                        t.result = reducer.applyAsInt(t.result, s.result);
5905 >                        s = t.rights = s.nextRight;
5906 >                    }
5907 >                }
5908 >            }
5909 >        }
5910 >    }
5911 >
5912 >    @SuppressWarnings("serial")
5913 >    static final class MapReduceValuesToIntTask<K,V>
5914 >        extends BulkTask<K,V,Integer> {
5915 >        final ToIntFunction<? super V> transformer;
5916 >        final IntBinaryOperator reducer;
5917 >        final int basis;
5918 >        int result;
5919 >        MapReduceValuesToIntTask<K,V> rights, nextRight;
5920 >        MapReduceValuesToIntTask
5921 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5922 >             MapReduceValuesToIntTask<K,V> nextRight,
5923 >             ToIntFunction<? super V> transformer,
5924 >             int basis,
5925 >             IntBinaryOperator reducer) {
5926 >            super(p, b, i, f, t); this.nextRight = nextRight;
5927 >            this.transformer = transformer;
5928 >            this.basis = basis; this.reducer = reducer;
5929 >        }
5930 >        public final Integer getRawResult() { return result; }
5931 >        public final void compute() {
5932 >            final ToIntFunction<? super V> transformer;
5933 >            final IntBinaryOperator reducer;
5934 >            if ((transformer = this.transformer) != null &&
5935 >                (reducer = this.reducer) != null) {
5936 >                int r = this.basis;
5937 >                for (int i = baseIndex, f, h; batch > 0 &&
5938 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5939 >                    addToPendingCount(1);
5940 >                    (rights = new MapReduceValuesToIntTask<K,V>
5941 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5942 >                      rights, transformer, r, reducer)).fork();
5943 >                }
5944 >                for (Node<K,V> p; (p = advance()) != null; )
5945 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5946 >                result = r;
5947 >                CountedCompleter<?> c;
5948 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5949 >                    @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5950 >                        t = (MapReduceValuesToIntTask<K,V>)c,
5951 >                        s = t.rights;
5952 >                    while (s != null) {
5953 >                        t.result = reducer.applyAsInt(t.result, s.result);
5954 >                        s = t.rights = s.nextRight;
5955 >                    }
5956 >                }
5957 >            }
5958 >        }
5959 >    }
5960 >
5961 >    @SuppressWarnings("serial")
5962 >    static final class MapReduceEntriesToIntTask<K,V>
5963 >        extends BulkTask<K,V,Integer> {
5964 >        final ToIntFunction<Map.Entry<K,V>> transformer;
5965 >        final IntBinaryOperator reducer;
5966 >        final int basis;
5967 >        int result;
5968 >        MapReduceEntriesToIntTask<K,V> rights, nextRight;
5969 >        MapReduceEntriesToIntTask
5970 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5971 >             MapReduceEntriesToIntTask<K,V> nextRight,
5972 >             ToIntFunction<Map.Entry<K,V>> transformer,
5973 >             int basis,
5974 >             IntBinaryOperator reducer) {
5975 >            super(p, b, i, f, t); this.nextRight = nextRight;
5976 >            this.transformer = transformer;
5977 >            this.basis = basis; this.reducer = reducer;
5978 >        }
5979 >        public final Integer getRawResult() { return result; }
5980 >        public final void compute() {
5981 >            final ToIntFunction<Map.Entry<K,V>> transformer;
5982 >            final IntBinaryOperator reducer;
5983 >            if ((transformer = this.transformer) != null &&
5984 >                (reducer = this.reducer) != null) {
5985 >                int r = this.basis;
5986 >                for (int i = baseIndex, f, h; batch > 0 &&
5987 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
5988 >                    addToPendingCount(1);
5989 >                    (rights = new MapReduceEntriesToIntTask<K,V>
5990 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
5991 >                      rights, transformer, r, reducer)).fork();
5992 >                }
5993 >                for (Node<K,V> p; (p = advance()) != null; )
5994 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5995 >                result = r;
5996 >                CountedCompleter<?> c;
5997 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
5998 >                    @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5999 >                        t = (MapReduceEntriesToIntTask<K,V>)c,
6000 >                        s = t.rights;
6001 >                    while (s != null) {
6002 >                        t.result = reducer.applyAsInt(t.result, s.result);
6003 >                        s = t.rights = s.nextRight;
6004 >                    }
6005 >                }
6006 >            }
6007 >        }
6008 >    }
6009 >
6010 >    @SuppressWarnings("serial")
6011 >    static final class MapReduceMappingsToIntTask<K,V>
6012 >        extends BulkTask<K,V,Integer> {
6013 >        final ToIntBiFunction<? super K, ? super V> transformer;
6014 >        final IntBinaryOperator reducer;
6015 >        final int basis;
6016 >        int result;
6017 >        MapReduceMappingsToIntTask<K,V> rights, nextRight;
6018 >        MapReduceMappingsToIntTask
6019 >            (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6020 >             MapReduceMappingsToIntTask<K,V> nextRight,
6021 >             ToIntBiFunction<? super K, ? super V> transformer,
6022 >             int basis,
6023 >             IntBinaryOperator reducer) {
6024 >            super(p, b, i, f, t); this.nextRight = nextRight;
6025 >            this.transformer = transformer;
6026 >            this.basis = basis; this.reducer = reducer;
6027 >        }
6028 >        public final Integer getRawResult() { return result; }
6029 >        public final void compute() {
6030 >            final ToIntBiFunction<? super K, ? super V> transformer;
6031 >            final IntBinaryOperator reducer;
6032 >            if ((transformer = this.transformer) != null &&
6033 >                (reducer = this.reducer) != null) {
6034 >                int r = this.basis;
6035 >                for (int i = baseIndex, f, h; batch > 0 &&
6036 >                         (h = ((f = baseLimit) + i) >>> 1) > i;) {
6037 >                    addToPendingCount(1);
6038 >                    (rights = new MapReduceMappingsToIntTask<K,V>
6039 >                     (this, batch >>>= 1, baseLimit = h, f, tab,
6040 >                      rights, transformer, r, reducer)).fork();
6041 >                }
6042 >                for (Node<K,V> p; (p = advance()) != null; )
6043 >                    r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6044 >                result = r;
6045 >                CountedCompleter<?> c;
6046 >                for (c = firstComplete(); c != null; c = c.nextComplete()) {
6047 >                    @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6048 >                        t = (MapReduceMappingsToIntTask<K,V>)c,
6049 >                        s = t.rights;
6050 >                    while (s != null) {
6051 >                        t.result = reducer.applyAsInt(t.result, s.result);
6052 >                        s = t.rights = s.nextRight;
6053 >                    }
6054 >                }
6055 >            }
6056          }
6057      }
6058  
6059      // Unsafe mechanics
6060 <    private static final sun.misc.Unsafe UNSAFE;
6061 <    private static final long SBASE;
6062 <    private static final int SSHIFT;
6063 <    private static final long TBASE;
6064 <    private static final int TSHIFT;
6060 >    private static final sun.misc.Unsafe U;
6061 >    private static final long SIZECTL;
6062 >    private static final long TRANSFERINDEX;
6063 >    private static final long TRANSFERORIGIN;
6064 >    private static final long BASECOUNT;
6065 >    private static final long CELLSBUSY;
6066 >    private static final long CELLVALUE;
6067 >    private static final long ABASE;
6068 >    private static final int ASHIFT;
6069  
6070      static {
1474        int ss, ts;
6071          try {
6072 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
6073 <            Class tc = HashEntry[].class;
6074 <            Class sc = Segment[].class;
6075 <            TBASE = UNSAFE.arrayBaseOffset(tc);
6076 <            SBASE = UNSAFE.arrayBaseOffset(sc);
6077 <            ts = UNSAFE.arrayIndexScale(tc);
6078 <            ss = UNSAFE.arrayIndexScale(sc);
6072 >            U = sun.misc.Unsafe.getUnsafe();
6073 >            Class<?> k = ConcurrentHashMap.class;
6074 >            SIZECTL = U.objectFieldOffset
6075 >                (k.getDeclaredField("sizeCtl"));
6076 >            TRANSFERINDEX = U.objectFieldOffset
6077 >                (k.getDeclaredField("transferIndex"));
6078 >            TRANSFERORIGIN = U.objectFieldOffset
6079 >                (k.getDeclaredField("transferOrigin"));
6080 >            BASECOUNT = U.objectFieldOffset
6081 >                (k.getDeclaredField("baseCount"));
6082 >            CELLSBUSY = U.objectFieldOffset
6083 >                (k.getDeclaredField("cellsBusy"));
6084 >            Class<?> ck = CounterCell.class;
6085 >            CELLVALUE = U.objectFieldOffset
6086 >                (ck.getDeclaredField("value"));
6087 >            Class<?> ak = Node[].class;
6088 >            ABASE = U.arrayBaseOffset(ak);
6089 >            int scale = U.arrayIndexScale(ak);
6090 >            if ((scale & (scale - 1)) != 0)
6091 >                throw new Error("data type scale not a power of two");
6092 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6093          } catch (Exception e) {
6094              throw new Error(e);
6095          }
1486        if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
1487            throw new Error("data type scale not a power of two");
1488        SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1489        TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
6096      }
1491
6097   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines