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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines