ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.5
Committed: Tue Oct 9 01:42:02 2018 UTC (5 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.4: +2 -0 lines
Log Message:
fix 4jdk8-tck by backporting ConcurrentHashMap bug fix

File Contents

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