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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines