ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
(Generate patch)

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines