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.24 by dl, Fri Oct 10 23:51:28 2003 UTC vs.
Revision 1.296 by dl, Sun Jul 17 12:09:12 2016 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines