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

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines