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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines