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

Comparing jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java (file contents):
Revision 1.24 by dl, Fri Oct 10 23:51:28 2003 UTC vs.
Revision 1.147 by jsr166, Sat Nov 24 03:46:28 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines