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.110 by jsr166, Wed Apr 27 14:06:30 2011 UTC vs.
Revision 1.221 by jsr166, Wed Jun 5 16:00:55 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines