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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines