ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.1
Committed: Sat Mar 26 06:22:49 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Log Message:
fork jdk8 maintenance branch for source and jtreg tests

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     return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1217     }
1218    
1219     /**
1220     * Returns a {@link Collection} view of the values contained in this map.
1221     * The collection is backed by the map, so changes to the map are
1222     * reflected in the collection, and vice-versa. The collection
1223     * supports element removal, which removes the corresponding
1224     * mapping from this map, via the {@code Iterator.remove},
1225     * {@code Collection.remove}, {@code removeAll},
1226     * {@code retainAll}, and {@code clear} operations. It does not
1227     * support the {@code add} or {@code addAll} operations.
1228     *
1229     * <p>The view's iterators and spliterators are
1230     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1231     *
1232     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT}
1233     * and {@link Spliterator#NONNULL}.
1234     *
1235     * @return the collection view
1236     */
1237     public Collection<V> values() {
1238     ValuesView<K,V> vs;
1239     return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1240     }
1241    
1242     /**
1243     * Returns a {@link Set} view of the mappings contained in this map.
1244     * The set is backed by the map, so changes to the map are
1245     * reflected in the set, and vice-versa. The set supports element
1246     * removal, which removes the corresponding mapping from the map,
1247     * via the {@code Iterator.remove}, {@code Set.remove},
1248     * {@code removeAll}, {@code retainAll}, and {@code clear}
1249     * operations.
1250     *
1251     * <p>The view's iterators and spliterators are
1252     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1253     *
1254     * <p>The view's {@code spliterator} reports {@link Spliterator#CONCURRENT},
1255     * {@link Spliterator#DISTINCT}, and {@link Spliterator#NONNULL}.
1256     *
1257     * @return the set view
1258     */
1259     public Set<Map.Entry<K,V>> entrySet() {
1260     EntrySetView<K,V> es;
1261     return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1262     }
1263    
1264     /**
1265     * Returns the hash code value for this {@link Map}, i.e.,
1266     * the sum of, for each key-value pair in the map,
1267     * {@code key.hashCode() ^ value.hashCode()}.
1268     *
1269     * @return the hash code value for this map
1270     */
1271     public int hashCode() {
1272     int h = 0;
1273     Node<K,V>[] t;
1274     if ((t = table) != null) {
1275     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1276     for (Node<K,V> p; (p = it.advance()) != null; )
1277     h += p.key.hashCode() ^ p.val.hashCode();
1278     }
1279     return h;
1280     }
1281    
1282     /**
1283     * Returns a string representation of this map. The string
1284     * representation consists of a list of key-value mappings (in no
1285     * particular order) enclosed in braces ("{@code {}}"). Adjacent
1286     * mappings are separated by the characters {@code ", "} (comma
1287     * and space). Each key-value mapping is rendered as the key
1288     * followed by an equals sign ("{@code =}") followed by the
1289     * associated value.
1290     *
1291     * @return a string representation of this map
1292     */
1293     public String toString() {
1294     Node<K,V>[] t;
1295     int f = (t = table) == null ? 0 : t.length;
1296     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1297     StringBuilder sb = new StringBuilder();
1298     sb.append('{');
1299     Node<K,V> p;
1300     if ((p = it.advance()) != null) {
1301     for (;;) {
1302     K k = p.key;
1303     V v = p.val;
1304     sb.append(k == this ? "(this Map)" : k);
1305     sb.append('=');
1306     sb.append(v == this ? "(this Map)" : v);
1307     if ((p = it.advance()) == null)
1308     break;
1309     sb.append(',').append(' ');
1310     }
1311     }
1312     return sb.append('}').toString();
1313     }
1314    
1315     /**
1316     * Compares the specified object with this map for equality.
1317     * Returns {@code true} if the given object is a map with the same
1318     * mappings as this map. This operation may return misleading
1319     * results if either map is concurrently modified during execution
1320     * of this method.
1321     *
1322     * @param o object to be compared for equality with this map
1323     * @return {@code true} if the specified object is equal to this map
1324     */
1325     public boolean equals(Object o) {
1326     if (o != this) {
1327     if (!(o instanceof Map))
1328     return false;
1329     Map<?,?> m = (Map<?,?>) o;
1330     Node<K,V>[] t;
1331     int f = (t = table) == null ? 0 : t.length;
1332     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1333     for (Node<K,V> p; (p = it.advance()) != null; ) {
1334     V val = p.val;
1335     Object v = m.get(p.key);
1336     if (v == null || (v != val && !v.equals(val)))
1337     return false;
1338     }
1339     for (Map.Entry<?,?> e : m.entrySet()) {
1340     Object mk, mv, v;
1341     if ((mk = e.getKey()) == null ||
1342     (mv = e.getValue()) == null ||
1343     (v = get(mk)) == null ||
1344     (mv != v && !mv.equals(v)))
1345     return false;
1346     }
1347     }
1348     return true;
1349     }
1350    
1351     /**
1352     * Stripped-down version of helper class used in previous version,
1353     * declared for the sake of serialization compatibility.
1354     */
1355     static class Segment<K,V> extends ReentrantLock implements Serializable {
1356     private static final long serialVersionUID = 2249069246763182397L;
1357     final float loadFactor;
1358     Segment(float lf) { this.loadFactor = lf; }
1359     }
1360    
1361     /**
1362     * Saves the state of the {@code ConcurrentHashMap} instance to a
1363     * stream (i.e., serializes it).
1364     * @param s the stream
1365     * @throws java.io.IOException if an I/O error occurs
1366     * @serialData
1367     * the serialized fields, followed by the key (Object) and value
1368     * (Object) for each key-value mapping, followed by a null pair.
1369     * The key-value mappings are emitted in no particular order.
1370     */
1371     private void writeObject(java.io.ObjectOutputStream s)
1372     throws java.io.IOException {
1373     // For serialization compatibility
1374     // Emulate segment calculation from previous version of this class
1375     int sshift = 0;
1376     int ssize = 1;
1377     while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1378     ++sshift;
1379     ssize <<= 1;
1380     }
1381     int segmentShift = 32 - sshift;
1382     int segmentMask = ssize - 1;
1383     @SuppressWarnings("unchecked")
1384     Segment<K,V>[] segments = (Segment<K,V>[])
1385     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1386     for (int i = 0; i < segments.length; ++i)
1387     segments[i] = new Segment<K,V>(LOAD_FACTOR);
1388     java.io.ObjectOutputStream.PutField streamFields = s.putFields();
1389     streamFields.put("segments", segments);
1390     streamFields.put("segmentShift", segmentShift);
1391     streamFields.put("segmentMask", segmentMask);
1392     s.writeFields();
1393    
1394     Node<K,V>[] t;
1395     if ((t = table) != null) {
1396     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1397     for (Node<K,V> p; (p = it.advance()) != null; ) {
1398     s.writeObject(p.key);
1399     s.writeObject(p.val);
1400     }
1401     }
1402     s.writeObject(null);
1403     s.writeObject(null);
1404     }
1405    
1406     /**
1407     * Reconstitutes the instance from a stream (that is, deserializes it).
1408     * @param s the stream
1409     * @throws ClassNotFoundException if the class of a serialized object
1410     * could not be found
1411     * @throws java.io.IOException if an I/O error occurs
1412     */
1413     private void readObject(java.io.ObjectInputStream s)
1414     throws java.io.IOException, ClassNotFoundException {
1415     /*
1416     * To improve performance in typical cases, we create nodes
1417     * while reading, then place in table once size is known.
1418     * However, we must also validate uniqueness and deal with
1419     * overpopulated bins while doing so, which requires
1420     * specialized versions of putVal mechanics.
1421     */
1422     sizeCtl = -1; // force exclusion for table construction
1423     s.defaultReadObject();
1424     long size = 0L;
1425     Node<K,V> p = null;
1426     for (;;) {
1427     @SuppressWarnings("unchecked")
1428     K k = (K) s.readObject();
1429     @SuppressWarnings("unchecked")
1430     V v = (V) s.readObject();
1431     if (k != null && v != null) {
1432     p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1433     ++size;
1434     }
1435     else
1436     break;
1437     }
1438     if (size == 0L)
1439     sizeCtl = 0;
1440     else {
1441     int n;
1442     if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1443     n = MAXIMUM_CAPACITY;
1444     else {
1445     int sz = (int)size;
1446     n = tableSizeFor(sz + (sz >>> 1) + 1);
1447     }
1448     @SuppressWarnings("unchecked")
1449     Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1450     int mask = n - 1;
1451     long added = 0L;
1452     while (p != null) {
1453     boolean insertAtFront;
1454     Node<K,V> next = p.next, first;
1455     int h = p.hash, j = h & mask;
1456     if ((first = tabAt(tab, j)) == null)
1457     insertAtFront = true;
1458     else {
1459     K k = p.key;
1460     if (first.hash < 0) {
1461     TreeBin<K,V> t = (TreeBin<K,V>)first;
1462     if (t.putTreeVal(h, k, p.val) == null)
1463     ++added;
1464     insertAtFront = false;
1465     }
1466     else {
1467     int binCount = 0;
1468     insertAtFront = true;
1469     Node<K,V> q; K qk;
1470     for (q = first; q != null; q = q.next) {
1471     if (q.hash == h &&
1472     ((qk = q.key) == k ||
1473     (qk != null && k.equals(qk)))) {
1474     insertAtFront = false;
1475     break;
1476     }
1477     ++binCount;
1478     }
1479     if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1480     insertAtFront = false;
1481     ++added;
1482     p.next = first;
1483     TreeNode<K,V> hd = null, tl = null;
1484     for (q = p; q != null; q = q.next) {
1485     TreeNode<K,V> t = new TreeNode<K,V>
1486     (q.hash, q.key, q.val, null, null);
1487     if ((t.prev = tl) == null)
1488     hd = t;
1489     else
1490     tl.next = t;
1491     tl = t;
1492     }
1493     setTabAt(tab, j, new TreeBin<K,V>(hd));
1494     }
1495     }
1496     }
1497     if (insertAtFront) {
1498     ++added;
1499     p.next = first;
1500     setTabAt(tab, j, p);
1501     }
1502     p = next;
1503     }
1504     table = tab;
1505     sizeCtl = n - (n >>> 2);
1506     baseCount = added;
1507     }
1508     }
1509    
1510     // ConcurrentMap methods
1511    
1512     /**
1513     * {@inheritDoc}
1514     *
1515     * @return the previous value associated with the specified key,
1516     * or {@code null} if there was no mapping for the key
1517     * @throws NullPointerException if the specified key or value is null
1518     */
1519     public V putIfAbsent(K key, V value) {
1520     return putVal(key, value, true);
1521     }
1522    
1523     /**
1524     * {@inheritDoc}
1525     *
1526     * @throws NullPointerException if the specified key is null
1527     */
1528     public boolean remove(Object key, Object value) {
1529     if (key == null)
1530     throw new NullPointerException();
1531     return value != null && replaceNode(key, null, value) != null;
1532     }
1533    
1534     /**
1535     * {@inheritDoc}
1536     *
1537     * @throws NullPointerException if any of the arguments are null
1538     */
1539     public boolean replace(K key, V oldValue, V newValue) {
1540     if (key == null || oldValue == null || newValue == null)
1541     throw new NullPointerException();
1542     return replaceNode(key, newValue, oldValue) != null;
1543     }
1544    
1545     /**
1546     * {@inheritDoc}
1547     *
1548     * @return the previous value associated with the specified key,
1549     * or {@code null} if there was no mapping for the key
1550     * @throws NullPointerException if the specified key or value is null
1551     */
1552     public V replace(K key, V value) {
1553     if (key == null || value == null)
1554     throw new NullPointerException();
1555     return replaceNode(key, value, null);
1556     }
1557    
1558     // Overrides of JDK8+ Map extension method defaults
1559    
1560     /**
1561     * Returns the value to which the specified key is mapped, or the
1562     * given default value if this map contains no mapping for the
1563     * key.
1564     *
1565     * @param key the key whose associated value is to be returned
1566     * @param defaultValue the value to return if this map contains
1567     * no mapping for the given key
1568     * @return the mapping for the key, if present; else the default value
1569     * @throws NullPointerException if the specified key is null
1570     */
1571     public V getOrDefault(Object key, V defaultValue) {
1572     V v;
1573     return (v = get(key)) == null ? defaultValue : v;
1574     }
1575    
1576     public void forEach(BiConsumer<? super K, ? super V> action) {
1577     if (action == null) throw new NullPointerException();
1578     Node<K,V>[] t;
1579     if ((t = table) != null) {
1580     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1581     for (Node<K,V> p; (p = it.advance()) != null; ) {
1582     action.accept(p.key, p.val);
1583     }
1584     }
1585     }
1586    
1587     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1588     if (function == null) throw new NullPointerException();
1589     Node<K,V>[] t;
1590     if ((t = table) != null) {
1591     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1592     for (Node<K,V> p; (p = it.advance()) != null; ) {
1593     V oldValue = p.val;
1594     for (K key = p.key;;) {
1595     V newValue = function.apply(key, oldValue);
1596     if (newValue == null)
1597     throw new NullPointerException();
1598     if (replaceNode(key, newValue, oldValue) != null ||
1599     (oldValue = get(key)) == null)
1600     break;
1601     }
1602     }
1603     }
1604     }
1605    
1606     /**
1607     * Helper method for EntrySetView.removeIf.
1608     */
1609     boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
1610     if (function == null) throw new NullPointerException();
1611     Node<K,V>[] t;
1612     boolean removed = false;
1613     if ((t = table) != null) {
1614     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1615     for (Node<K,V> p; (p = it.advance()) != null; ) {
1616     K k = p.key;
1617     V v = p.val;
1618     Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
1619     if (function.test(e) && replaceNode(k, null, v) != null)
1620     removed = true;
1621     }
1622     }
1623     return removed;
1624     }
1625    
1626     /**
1627     * Helper method for ValuesView.removeIf.
1628     */
1629     boolean removeValueIf(Predicate<? super V> function) {
1630     if (function == null) throw new NullPointerException();
1631     Node<K,V>[] t;
1632     boolean removed = false;
1633     if ((t = table) != null) {
1634     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1635     for (Node<K,V> p; (p = it.advance()) != null; ) {
1636     K k = p.key;
1637     V v = p.val;
1638     if (function.test(v) && replaceNode(k, null, v) != null)
1639     removed = true;
1640     }
1641     }
1642     return removed;
1643     }
1644    
1645     /**
1646     * If the specified key is not already associated with a value,
1647     * attempts to compute its value using the given mapping function
1648     * and enters it into this map unless {@code null}. The entire
1649     * method invocation is performed atomically, so the function is
1650     * applied at most once per key. Some attempted update operations
1651     * on this map by other threads may be blocked while computation
1652     * is in progress, so the computation should be short and simple,
1653     * and must not attempt to update any other mappings of this map.
1654     *
1655     * @param key key with which the specified value is to be associated
1656     * @param mappingFunction the function to compute a value
1657     * @return the current (existing or computed) value associated with
1658     * the specified key, or null if the computed value is null
1659     * @throws NullPointerException if the specified key or mappingFunction
1660     * is null
1661     * @throws IllegalStateException if the computation detectably
1662     * attempts a recursive update to this map that would
1663     * otherwise never complete
1664     * @throws RuntimeException or Error if the mappingFunction does so,
1665     * in which case the mapping is left unestablished
1666     */
1667     public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1668     if (key == null || mappingFunction == null)
1669     throw new NullPointerException();
1670     int h = spread(key.hashCode());
1671     V val = null;
1672     int binCount = 0;
1673     for (Node<K,V>[] tab = table;;) {
1674     Node<K,V> f; int n, i, fh;
1675     if (tab == null || (n = tab.length) == 0)
1676     tab = initTable();
1677     else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1678     Node<K,V> r = new ReservationNode<K,V>();
1679     synchronized (r) {
1680     if (casTabAt(tab, i, null, r)) {
1681     binCount = 1;
1682     Node<K,V> node = null;
1683     try {
1684     if ((val = mappingFunction.apply(key)) != null)
1685     node = new Node<K,V>(h, key, val);
1686     } finally {
1687     setTabAt(tab, i, node);
1688     }
1689     }
1690     }
1691     if (binCount != 0)
1692     break;
1693     }
1694     else if ((fh = f.hash) == MOVED)
1695     tab = helpTransfer(tab, f);
1696     else {
1697     boolean added = false;
1698     synchronized (f) {
1699     if (tabAt(tab, i) == f) {
1700     if (fh >= 0) {
1701     binCount = 1;
1702     for (Node<K,V> e = f;; ++binCount) {
1703     K ek;
1704     if (e.hash == h &&
1705     ((ek = e.key) == key ||
1706     (ek != null && key.equals(ek)))) {
1707     val = e.val;
1708     break;
1709     }
1710     Node<K,V> pred = e;
1711     if ((e = e.next) == null) {
1712     if ((val = mappingFunction.apply(key)) != null) {
1713     if (pred.next != null)
1714     throw new IllegalStateException("Recursive update");
1715     added = true;
1716     pred.next = new Node<K,V>(h, key, val);
1717     }
1718     break;
1719     }
1720     }
1721     }
1722     else if (f instanceof TreeBin) {
1723     binCount = 2;
1724     TreeBin<K,V> t = (TreeBin<K,V>)f;
1725     TreeNode<K,V> r, p;
1726     if ((r = t.root) != null &&
1727     (p = r.findTreeNode(h, key, null)) != null)
1728     val = p.val;
1729     else if ((val = mappingFunction.apply(key)) != null) {
1730     added = true;
1731     t.putTreeVal(h, key, val);
1732     }
1733     }
1734     else if (f instanceof ReservationNode)
1735     throw new IllegalStateException("Recursive update");
1736     }
1737     }
1738     if (binCount != 0) {
1739     if (binCount >= TREEIFY_THRESHOLD)
1740     treeifyBin(tab, i);
1741     if (!added)
1742     return val;
1743     break;
1744     }
1745     }
1746     }
1747     if (val != null)
1748     addCount(1L, binCount);
1749     return val;
1750     }
1751    
1752     /**
1753     * If the value for the specified key is present, attempts to
1754     * compute a new mapping given the key and its current mapped
1755     * value. The entire method invocation is performed atomically.
1756     * Some attempted update operations on this map by other threads
1757     * may be blocked while computation is in progress, so the
1758     * computation should be short and simple, and must not attempt to
1759     * update any other mappings of this map.
1760     *
1761     * @param key key with which a value may be associated
1762     * @param remappingFunction the function to compute a value
1763     * @return the new value associated with the specified key, or null if none
1764     * @throws NullPointerException if the specified key or remappingFunction
1765     * is null
1766     * @throws IllegalStateException if the computation detectably
1767     * attempts a recursive update to this map that would
1768     * otherwise never complete
1769     * @throws RuntimeException or Error if the remappingFunction does so,
1770     * in which case the mapping is unchanged
1771     */
1772     public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1773     if (key == null || remappingFunction == null)
1774     throw new NullPointerException();
1775     int h = spread(key.hashCode());
1776     V val = null;
1777     int delta = 0;
1778     int binCount = 0;
1779     for (Node<K,V>[] tab = table;;) {
1780     Node<K,V> f; int n, i, fh;
1781     if (tab == null || (n = tab.length) == 0)
1782     tab = initTable();
1783     else if ((f = tabAt(tab, i = (n - 1) & h)) == null)
1784     break;
1785     else if ((fh = f.hash) == MOVED)
1786     tab = helpTransfer(tab, f);
1787     else {
1788     synchronized (f) {
1789     if (tabAt(tab, i) == f) {
1790     if (fh >= 0) {
1791     binCount = 1;
1792     for (Node<K,V> e = f, pred = null;; ++binCount) {
1793     K ek;
1794     if (e.hash == h &&
1795     ((ek = e.key) == key ||
1796     (ek != null && key.equals(ek)))) {
1797     val = remappingFunction.apply(key, e.val);
1798     if (val != null)
1799     e.val = val;
1800     else {
1801     delta = -1;
1802     Node<K,V> en = e.next;
1803     if (pred != null)
1804     pred.next = en;
1805     else
1806     setTabAt(tab, i, en);
1807     }
1808     break;
1809     }
1810     pred = e;
1811     if ((e = e.next) == null)
1812     break;
1813     }
1814     }
1815     else if (f instanceof TreeBin) {
1816     binCount = 2;
1817     TreeBin<K,V> t = (TreeBin<K,V>)f;
1818     TreeNode<K,V> r, p;
1819     if ((r = t.root) != null &&
1820     (p = r.findTreeNode(h, key, null)) != null) {
1821     val = remappingFunction.apply(key, p.val);
1822     if (val != null)
1823     p.val = val;
1824     else {
1825     delta = -1;
1826     if (t.removeTreeNode(p))
1827     setTabAt(tab, i, untreeify(t.first));
1828     }
1829     }
1830     }
1831     else if (f instanceof ReservationNode)
1832     throw new IllegalStateException("Recursive update");
1833     }
1834     }
1835     if (binCount != 0)
1836     break;
1837     }
1838     }
1839     if (delta != 0)
1840     addCount((long)delta, binCount);
1841     return val;
1842     }
1843    
1844     /**
1845     * Attempts to compute a mapping for the specified key and its
1846     * current mapped value (or {@code null} if there is no current
1847     * mapping). The entire method invocation is performed atomically.
1848     * Some attempted update operations on this map by other threads
1849     * may be blocked while computation is in progress, so the
1850     * computation should be short and simple, and must not attempt to
1851     * update any other mappings of this Map.
1852     *
1853     * @param key key with which the specified value is to be associated
1854     * @param remappingFunction the function to compute a value
1855     * @return the new value associated with the specified key, or null if none
1856     * @throws NullPointerException if the specified key or remappingFunction
1857     * is null
1858     * @throws IllegalStateException if the computation detectably
1859     * attempts a recursive update to this map that would
1860     * otherwise never complete
1861     * @throws RuntimeException or Error if the remappingFunction does so,
1862     * in which case the mapping is unchanged
1863     */
1864     public V compute(K key,
1865     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1866     if (key == null || remappingFunction == null)
1867     throw new NullPointerException();
1868     int h = spread(key.hashCode());
1869     V val = null;
1870     int delta = 0;
1871     int binCount = 0;
1872     for (Node<K,V>[] tab = table;;) {
1873     Node<K,V> f; int n, i, fh;
1874     if (tab == null || (n = tab.length) == 0)
1875     tab = initTable();
1876     else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
1877     Node<K,V> r = new ReservationNode<K,V>();
1878     synchronized (r) {
1879     if (casTabAt(tab, i, null, r)) {
1880     binCount = 1;
1881     Node<K,V> node = null;
1882     try {
1883     if ((val = remappingFunction.apply(key, null)) != null) {
1884     delta = 1;
1885     node = new Node<K,V>(h, key, val);
1886     }
1887     } finally {
1888     setTabAt(tab, i, node);
1889     }
1890     }
1891     }
1892     if (binCount != 0)
1893     break;
1894     }
1895     else if ((fh = f.hash) == MOVED)
1896     tab = helpTransfer(tab, f);
1897     else {
1898     synchronized (f) {
1899     if (tabAt(tab, i) == f) {
1900     if (fh >= 0) {
1901     binCount = 1;
1902     for (Node<K,V> e = f, pred = null;; ++binCount) {
1903     K ek;
1904     if (e.hash == h &&
1905     ((ek = e.key) == key ||
1906     (ek != null && key.equals(ek)))) {
1907     val = remappingFunction.apply(key, e.val);
1908     if (val != null)
1909     e.val = val;
1910     else {
1911     delta = -1;
1912     Node<K,V> en = e.next;
1913     if (pred != null)
1914     pred.next = en;
1915     else
1916     setTabAt(tab, i, en);
1917     }
1918     break;
1919     }
1920     pred = e;
1921     if ((e = e.next) == null) {
1922     val = remappingFunction.apply(key, null);
1923     if (val != null) {
1924     if (pred.next != null)
1925     throw new IllegalStateException("Recursive update");
1926     delta = 1;
1927     pred.next = new Node<K,V>(h, key, val);
1928     }
1929     break;
1930     }
1931     }
1932     }
1933     else if (f instanceof TreeBin) {
1934     binCount = 1;
1935     TreeBin<K,V> t = (TreeBin<K,V>)f;
1936     TreeNode<K,V> r, p;
1937     if ((r = t.root) != null)
1938     p = r.findTreeNode(h, key, null);
1939     else
1940     p = null;
1941     V pv = (p == null) ? null : p.val;
1942     val = remappingFunction.apply(key, pv);
1943     if (val != null) {
1944     if (p != null)
1945     p.val = val;
1946     else {
1947     delta = 1;
1948     t.putTreeVal(h, key, val);
1949     }
1950     }
1951     else if (p != null) {
1952     delta = -1;
1953     if (t.removeTreeNode(p))
1954     setTabAt(tab, i, untreeify(t.first));
1955     }
1956     }
1957     else if (f instanceof ReservationNode)
1958     throw new IllegalStateException("Recursive update");
1959     }
1960     }
1961     if (binCount != 0) {
1962     if (binCount >= TREEIFY_THRESHOLD)
1963     treeifyBin(tab, i);
1964     break;
1965     }
1966     }
1967     }
1968     if (delta != 0)
1969     addCount((long)delta, binCount);
1970     return val;
1971     }
1972    
1973     /**
1974     * If the specified key is not already associated with a
1975     * (non-null) value, associates it with the given value.
1976     * Otherwise, replaces the value with the results of the given
1977     * remapping function, or removes if {@code null}. The entire
1978     * method invocation is performed atomically. Some attempted
1979     * update operations on this map by other threads may be blocked
1980     * while computation is in progress, so the computation should be
1981     * short and simple, and must not attempt to update any other
1982     * mappings of this Map.
1983     *
1984     * @param key key with which the specified value is to be associated
1985     * @param value the value to use if absent
1986     * @param remappingFunction the function to recompute a value if present
1987     * @return the new value associated with the specified key, or null if none
1988     * @throws NullPointerException if the specified key or the
1989     * remappingFunction is null
1990     * @throws RuntimeException or Error if the remappingFunction does so,
1991     * in which case the mapping is unchanged
1992     */
1993     public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1994     if (key == null || value == null || remappingFunction == null)
1995     throw new NullPointerException();
1996     int h = spread(key.hashCode());
1997     V val = null;
1998     int delta = 0;
1999     int binCount = 0;
2000     for (Node<K,V>[] tab = table;;) {
2001     Node<K,V> f; int n, i, fh;
2002     if (tab == null || (n = tab.length) == 0)
2003     tab = initTable();
2004     else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
2005     if (casTabAt(tab, i, null, new Node<K,V>(h, key, value))) {
2006     delta = 1;
2007     val = value;
2008     break;
2009     }
2010     }
2011     else if ((fh = f.hash) == MOVED)
2012     tab = helpTransfer(tab, f);
2013     else {
2014     synchronized (f) {
2015     if (tabAt(tab, i) == f) {
2016     if (fh >= 0) {
2017     binCount = 1;
2018     for (Node<K,V> e = f, pred = null;; ++binCount) {
2019     K ek;
2020     if (e.hash == h &&
2021     ((ek = e.key) == key ||
2022     (ek != null && key.equals(ek)))) {
2023     val = remappingFunction.apply(e.val, value);
2024     if (val != null)
2025     e.val = val;
2026     else {
2027     delta = -1;
2028     Node<K,V> en = e.next;
2029     if (pred != null)
2030     pred.next = en;
2031     else
2032     setTabAt(tab, i, en);
2033     }
2034     break;
2035     }
2036     pred = e;
2037     if ((e = e.next) == null) {
2038     delta = 1;
2039     val = value;
2040     pred.next = new Node<K,V>(h, key, val);
2041     break;
2042     }
2043     }
2044     }
2045     else if (f instanceof TreeBin) {
2046     binCount = 2;
2047     TreeBin<K,V> t = (TreeBin<K,V>)f;
2048     TreeNode<K,V> r = t.root;
2049     TreeNode<K,V> p = (r == null) ? null :
2050     r.findTreeNode(h, key, null);
2051     val = (p == null) ? value :
2052     remappingFunction.apply(p.val, value);
2053     if (val != null) {
2054     if (p != null)
2055     p.val = val;
2056     else {
2057     delta = 1;
2058     t.putTreeVal(h, key, val);
2059     }
2060     }
2061     else if (p != null) {
2062     delta = -1;
2063     if (t.removeTreeNode(p))
2064     setTabAt(tab, i, untreeify(t.first));
2065     }
2066     }
2067     else if (f instanceof ReservationNode)
2068     throw new IllegalStateException("Recursive update");
2069     }
2070     }
2071     if (binCount != 0) {
2072     if (binCount >= TREEIFY_THRESHOLD)
2073     treeifyBin(tab, i);
2074     break;
2075     }
2076     }
2077     }
2078     if (delta != 0)
2079     addCount((long)delta, binCount);
2080     return val;
2081     }
2082    
2083     // Hashtable legacy methods
2084    
2085     /**
2086     * Tests if some key maps into the specified value in this table.
2087     *
2088     * <p>Note that this method is identical in functionality to
2089     * {@link #containsValue(Object)}, and exists solely to ensure
2090     * full compatibility with class {@link java.util.Hashtable},
2091     * which supported this method prior to introduction of the
2092     * Java Collections Framework.
2093     *
2094     * @param value a value to search for
2095     * @return {@code true} if and only if some key maps to the
2096     * {@code value} argument in this table as
2097     * determined by the {@code equals} method;
2098     * {@code false} otherwise
2099     * @throws NullPointerException if the specified value is null
2100     */
2101     public boolean contains(Object value) {
2102     return containsValue(value);
2103     }
2104    
2105     /**
2106     * Returns an enumeration of the keys in this table.
2107     *
2108     * @return an enumeration of the keys in this table
2109     * @see #keySet()
2110     */
2111     public Enumeration<K> keys() {
2112     Node<K,V>[] t;
2113     int f = (t = table) == null ? 0 : t.length;
2114     return new KeyIterator<K,V>(t, f, 0, f, this);
2115     }
2116    
2117     /**
2118     * Returns an enumeration of the values in this table.
2119     *
2120     * @return an enumeration of the values in this table
2121     * @see #values()
2122     */
2123     public Enumeration<V> elements() {
2124     Node<K,V>[] t;
2125     int f = (t = table) == null ? 0 : t.length;
2126     return new ValueIterator<K,V>(t, f, 0, f, this);
2127     }
2128    
2129     // ConcurrentHashMap-only methods
2130    
2131     /**
2132     * Returns the number of mappings. This method should be used
2133     * instead of {@link #size} because a ConcurrentHashMap may
2134     * contain more mappings than can be represented as an int. The
2135     * value returned is an estimate; the actual count may differ if
2136     * there are concurrent insertions or removals.
2137     *
2138     * @return the number of mappings
2139     * @since 1.8
2140     */
2141     public long mappingCount() {
2142     long n = sumCount();
2143     return (n < 0L) ? 0L : n; // ignore transient negative values
2144     }
2145    
2146     /**
2147     * Creates a new {@link Set} backed by a ConcurrentHashMap
2148     * from the given type to {@code Boolean.TRUE}.
2149     *
2150     * @param <K> the element type of the returned set
2151     * @return the new set
2152     * @since 1.8
2153     */
2154     public static <K> KeySetView<K,Boolean> newKeySet() {
2155     return new KeySetView<K,Boolean>
2156     (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2157     }
2158    
2159     /**
2160     * Creates a new {@link Set} backed by a ConcurrentHashMap
2161     * from the given type to {@code Boolean.TRUE}.
2162     *
2163     * @param initialCapacity The implementation performs internal
2164     * sizing to accommodate this many elements.
2165     * @param <K> the element type of the returned set
2166     * @return the new set
2167     * @throws IllegalArgumentException if the initial capacity of
2168     * elements is negative
2169     * @since 1.8
2170     */
2171     public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2172     return new KeySetView<K,Boolean>
2173     (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2174     }
2175    
2176     /**
2177     * Returns a {@link Set} view of the keys in this map, using the
2178     * given common mapped value for any additions (i.e., {@link
2179     * Collection#add} and {@link Collection#addAll(Collection)}).
2180     * This is of course only appropriate if it is acceptable to use
2181     * the same value for all additions from this view.
2182     *
2183     * @param mappedValue the mapped value to use for any additions
2184     * @return the set view
2185     * @throws NullPointerException if the mappedValue is null
2186     */
2187     public KeySetView<K,V> keySet(V mappedValue) {
2188     if (mappedValue == null)
2189     throw new NullPointerException();
2190     return new KeySetView<K,V>(this, mappedValue);
2191     }
2192    
2193     /* ---------------- Special Nodes -------------- */
2194    
2195     /**
2196     * A node inserted at head of bins during transfer operations.
2197     */
2198     static final class ForwardingNode<K,V> extends Node<K,V> {
2199     final Node<K,V>[] nextTable;
2200     ForwardingNode(Node<K,V>[] tab) {
2201     super(MOVED, null, null);
2202     this.nextTable = tab;
2203     }
2204    
2205     Node<K,V> find(int h, Object k) {
2206     // loop to avoid arbitrarily deep recursion on forwarding nodes
2207     outer: for (Node<K,V>[] tab = nextTable;;) {
2208     Node<K,V> e; int n;
2209     if (k == null || tab == null || (n = tab.length) == 0 ||
2210     (e = tabAt(tab, (n - 1) & h)) == null)
2211     return null;
2212     for (;;) {
2213     int eh; K ek;
2214     if ((eh = e.hash) == h &&
2215     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2216     return e;
2217     if (eh < 0) {
2218     if (e instanceof ForwardingNode) {
2219     tab = ((ForwardingNode<K,V>)e).nextTable;
2220     continue outer;
2221     }
2222     else
2223     return e.find(h, k);
2224     }
2225     if ((e = e.next) == null)
2226     return null;
2227     }
2228     }
2229     }
2230     }
2231    
2232     /**
2233     * A place-holder node used in computeIfAbsent and compute.
2234     */
2235     static final class ReservationNode<K,V> extends Node<K,V> {
2236     ReservationNode() {
2237     super(RESERVED, null, null);
2238     }
2239    
2240     Node<K,V> find(int h, Object k) {
2241     return null;
2242     }
2243     }
2244    
2245     /* ---------------- Table Initialization and Resizing -------------- */
2246    
2247     /**
2248     * Returns the stamp bits for resizing a table of size n.
2249     * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
2250     */
2251     static final int resizeStamp(int n) {
2252     return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2253     }
2254    
2255     /**
2256     * Initializes table, using the size recorded in sizeCtl.
2257     */
2258     private final Node<K,V>[] initTable() {
2259     Node<K,V>[] tab; int sc;
2260     while ((tab = table) == null || tab.length == 0) {
2261     if ((sc = sizeCtl) < 0)
2262     Thread.yield(); // lost initialization race; just spin
2263     else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2264     try {
2265     if ((tab = table) == null || tab.length == 0) {
2266     int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2267     @SuppressWarnings("unchecked")
2268     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2269     table = tab = nt;
2270     sc = n - (n >>> 2);
2271     }
2272     } finally {
2273     sizeCtl = sc;
2274     }
2275     break;
2276     }
2277     }
2278     return tab;
2279     }
2280    
2281     /**
2282     * Adds to count, and if table is too small and not already
2283     * resizing, initiates transfer. If already resizing, helps
2284     * perform transfer if work is available. Rechecks occupancy
2285     * after a transfer to see if another resize is already needed
2286     * because resizings are lagging additions.
2287     *
2288     * @param x the count to add
2289     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2290     */
2291     private final void addCount(long x, int check) {
2292     CounterCell[] as; long b, s;
2293     if ((as = counterCells) != null ||
2294     !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2295     CounterCell a; long v; int m;
2296     boolean uncontended = true;
2297     if (as == null || (m = as.length - 1) < 0 ||
2298     (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2299     !(uncontended =
2300     U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2301     fullAddCount(x, uncontended);
2302     return;
2303     }
2304     if (check <= 1)
2305     return;
2306     s = sumCount();
2307     }
2308     if (check >= 0) {
2309     Node<K,V>[] tab, nt; int n, sc;
2310     while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2311     (n = tab.length) < MAXIMUM_CAPACITY) {
2312     int rs = resizeStamp(n);
2313     if (sc < 0) {
2314     if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2315     sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
2316     transferIndex <= 0)
2317     break;
2318     if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
2319     transfer(tab, nt);
2320     }
2321     else if (U.compareAndSwapInt(this, SIZECTL, sc,
2322     (rs << RESIZE_STAMP_SHIFT) + 2))
2323     transfer(tab, null);
2324     s = sumCount();
2325     }
2326     }
2327     }
2328    
2329     /**
2330     * Helps transfer if a resize is in progress.
2331     */
2332     final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2333     Node<K,V>[] nextTab; int sc;
2334     if (tab != null && (f instanceof ForwardingNode) &&
2335     (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2336     int rs = resizeStamp(tab.length);
2337     while (nextTab == nextTable && table == tab &&
2338     (sc = sizeCtl) < 0) {
2339     if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2340     sc == rs + MAX_RESIZERS || transferIndex <= 0)
2341     break;
2342     if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
2343     transfer(tab, nextTab);
2344     break;
2345     }
2346     }
2347     return nextTab;
2348     }
2349     return table;
2350     }
2351    
2352     /**
2353     * Tries to presize table to accommodate the given number of elements.
2354     *
2355     * @param size number of elements (doesn't need to be perfectly accurate)
2356     */
2357     private final void tryPresize(int size) {
2358     int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2359     tableSizeFor(size + (size >>> 1) + 1);
2360     int sc;
2361     while ((sc = sizeCtl) >= 0) {
2362     Node<K,V>[] tab = table; int n;
2363     if (tab == null || (n = tab.length) == 0) {
2364     n = (sc > c) ? sc : c;
2365     if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2366     try {
2367     if (table == tab) {
2368     @SuppressWarnings("unchecked")
2369     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
2370     table = nt;
2371     sc = n - (n >>> 2);
2372     }
2373     } finally {
2374     sizeCtl = sc;
2375     }
2376     }
2377     }
2378     else if (c <= sc || n >= MAXIMUM_CAPACITY)
2379     break;
2380     else if (tab == table) {
2381     int rs = resizeStamp(n);
2382     if (U.compareAndSwapInt(this, SIZECTL, sc,
2383     (rs << RESIZE_STAMP_SHIFT) + 2))
2384     transfer(tab, null);
2385     }
2386     }
2387     }
2388    
2389     /**
2390     * Moves and/or copies the nodes in each bin to new table. See
2391     * above for explanation.
2392     */
2393     private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2394     int n = tab.length, stride;
2395     if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2396     stride = MIN_TRANSFER_STRIDE; // subdivide range
2397     if (nextTab == null) { // initiating
2398     try {
2399     @SuppressWarnings("unchecked")
2400     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
2401     nextTab = nt;
2402     } catch (Throwable ex) { // try to cope with OOME
2403     sizeCtl = Integer.MAX_VALUE;
2404     return;
2405     }
2406     nextTable = nextTab;
2407     transferIndex = n;
2408     }
2409     int nextn = nextTab.length;
2410     ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2411     boolean advance = true;
2412     boolean finishing = false; // to ensure sweep before committing nextTab
2413     for (int i = 0, bound = 0;;) {
2414     Node<K,V> f; int fh;
2415     while (advance) {
2416     int nextIndex, nextBound;
2417     if (--i >= bound || finishing)
2418     advance = false;
2419     else if ((nextIndex = transferIndex) <= 0) {
2420     i = -1;
2421     advance = false;
2422     }
2423     else if (U.compareAndSwapInt
2424     (this, TRANSFERINDEX, nextIndex,
2425     nextBound = (nextIndex > stride ?
2426     nextIndex - stride : 0))) {
2427     bound = nextBound;
2428     i = nextIndex - 1;
2429     advance = false;
2430     }
2431     }
2432     if (i < 0 || i >= n || i + n >= nextn) {
2433     int sc;
2434     if (finishing) {
2435     nextTable = null;
2436     table = nextTab;
2437     sizeCtl = (n << 1) - (n >>> 1);
2438     return;
2439     }
2440     if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
2441     if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
2442     return;
2443     finishing = advance = true;
2444     i = n; // recheck before commit
2445     }
2446     }
2447     else if ((f = tabAt(tab, i)) == null)
2448     advance = casTabAt(tab, i, null, fwd);
2449     else if ((fh = f.hash) == MOVED)
2450     advance = true; // already processed
2451     else {
2452     synchronized (f) {
2453     if (tabAt(tab, i) == f) {
2454     Node<K,V> ln, hn;
2455     if (fh >= 0) {
2456     int runBit = fh & n;
2457     Node<K,V> lastRun = f;
2458     for (Node<K,V> p = f.next; p != null; p = p.next) {
2459     int b = p.hash & n;
2460     if (b != runBit) {
2461     runBit = b;
2462     lastRun = p;
2463     }
2464     }
2465     if (runBit == 0) {
2466     ln = lastRun;
2467     hn = null;
2468     }
2469     else {
2470     hn = lastRun;
2471     ln = null;
2472     }
2473     for (Node<K,V> p = f; p != lastRun; p = p.next) {
2474     int ph = p.hash; K pk = p.key; V pv = p.val;
2475     if ((ph & n) == 0)
2476     ln = new Node<K,V>(ph, pk, pv, ln);
2477     else
2478     hn = new Node<K,V>(ph, pk, pv, hn);
2479     }
2480     setTabAt(nextTab, i, ln);
2481     setTabAt(nextTab, i + n, hn);
2482     setTabAt(tab, i, fwd);
2483     advance = true;
2484     }
2485     else if (f instanceof TreeBin) {
2486     TreeBin<K,V> t = (TreeBin<K,V>)f;
2487     TreeNode<K,V> lo = null, loTail = null;
2488     TreeNode<K,V> hi = null, hiTail = null;
2489     int lc = 0, hc = 0;
2490     for (Node<K,V> e = t.first; e != null; e = e.next) {
2491     int h = e.hash;
2492     TreeNode<K,V> p = new TreeNode<K,V>
2493     (h, e.key, e.val, null, null);
2494     if ((h & n) == 0) {
2495     if ((p.prev = loTail) == null)
2496     lo = p;
2497     else
2498     loTail.next = p;
2499     loTail = p;
2500     ++lc;
2501     }
2502     else {
2503     if ((p.prev = hiTail) == null)
2504     hi = p;
2505     else
2506     hiTail.next = p;
2507     hiTail = p;
2508     ++hc;
2509     }
2510     }
2511     ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2512     (hc != 0) ? new TreeBin<K,V>(lo) : t;
2513     hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2514     (lc != 0) ? new TreeBin<K,V>(hi) : t;
2515     setTabAt(nextTab, i, ln);
2516     setTabAt(nextTab, i + n, hn);
2517     setTabAt(tab, i, fwd);
2518     advance = true;
2519     }
2520     }
2521     }
2522     }
2523     }
2524     }
2525    
2526     /* ---------------- Counter support -------------- */
2527    
2528     /**
2529     * A padded cell for distributing counts. Adapted from LongAdder
2530     * and Striped64. See their internal docs for explanation.
2531     */
2532     @jdk.internal.vm.annotation.Contended static final class CounterCell {
2533     volatile long value;
2534     CounterCell(long x) { value = x; }
2535     }
2536    
2537     final long sumCount() {
2538     CounterCell[] as = counterCells; CounterCell a;
2539     long sum = baseCount;
2540     if (as != null) {
2541     for (int i = 0; i < as.length; ++i) {
2542     if ((a = as[i]) != null)
2543     sum += a.value;
2544     }
2545     }
2546     return sum;
2547     }
2548    
2549     // See LongAdder version for explanation
2550     private final void fullAddCount(long x, boolean wasUncontended) {
2551     int h;
2552     if ((h = ThreadLocalRandom.getProbe()) == 0) {
2553     ThreadLocalRandom.localInit(); // force initialization
2554     h = ThreadLocalRandom.getProbe();
2555     wasUncontended = true;
2556     }
2557     boolean collide = false; // True if last slot nonempty
2558     for (;;) {
2559     CounterCell[] as; CounterCell a; int n; long v;
2560     if ((as = counterCells) != null && (n = as.length) > 0) {
2561     if ((a = as[(n - 1) & h]) == null) {
2562     if (cellsBusy == 0) { // Try to attach new Cell
2563     CounterCell r = new CounterCell(x); // Optimistic create
2564     if (cellsBusy == 0 &&
2565     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2566     boolean created = false;
2567     try { // Recheck under lock
2568     CounterCell[] rs; int m, j;
2569     if ((rs = counterCells) != null &&
2570     (m = rs.length) > 0 &&
2571     rs[j = (m - 1) & h] == null) {
2572     rs[j] = r;
2573     created = true;
2574     }
2575     } finally {
2576     cellsBusy = 0;
2577     }
2578     if (created)
2579     break;
2580     continue; // Slot is now non-empty
2581     }
2582     }
2583     collide = false;
2584     }
2585     else if (!wasUncontended) // CAS already known to fail
2586     wasUncontended = true; // Continue after rehash
2587     else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2588     break;
2589     else if (counterCells != as || n >= NCPU)
2590     collide = false; // At max size or stale
2591     else if (!collide)
2592     collide = true;
2593     else if (cellsBusy == 0 &&
2594     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2595     try {
2596     if (counterCells == as) {// Expand table unless stale
2597     CounterCell[] rs = new CounterCell[n << 1];
2598     for (int i = 0; i < n; ++i)
2599     rs[i] = as[i];
2600     counterCells = rs;
2601     }
2602     } finally {
2603     cellsBusy = 0;
2604     }
2605     collide = false;
2606     continue; // Retry with expanded table
2607     }
2608     h = ThreadLocalRandom.advanceProbe(h);
2609     }
2610     else if (cellsBusy == 0 && counterCells == as &&
2611     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2612     boolean init = false;
2613     try { // Initialize table
2614     if (counterCells == as) {
2615     CounterCell[] rs = new CounterCell[2];
2616     rs[h & 1] = new CounterCell(x);
2617     counterCells = rs;
2618     init = true;
2619     }
2620     } finally {
2621     cellsBusy = 0;
2622     }
2623     if (init)
2624     break;
2625     }
2626     else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2627     break; // Fall back on using base
2628     }
2629     }
2630    
2631     /* ---------------- Conversion from/to TreeBins -------------- */
2632    
2633     /**
2634     * Replaces all linked nodes in bin at given index unless table is
2635     * too small, in which case resizes instead.
2636     */
2637     private final void treeifyBin(Node<K,V>[] tab, int index) {
2638     Node<K,V> b; int n;
2639     if (tab != null) {
2640     if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2641     tryPresize(n << 1);
2642     else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2643     synchronized (b) {
2644     if (tabAt(tab, index) == b) {
2645     TreeNode<K,V> hd = null, tl = null;
2646     for (Node<K,V> e = b; e != null; e = e.next) {
2647     TreeNode<K,V> p =
2648     new TreeNode<K,V>(e.hash, e.key, e.val,
2649     null, null);
2650     if ((p.prev = tl) == null)
2651     hd = p;
2652     else
2653     tl.next = p;
2654     tl = p;
2655     }
2656     setTabAt(tab, index, new TreeBin<K,V>(hd));
2657     }
2658     }
2659     }
2660     }
2661     }
2662    
2663     /**
2664     * Returns a list of non-TreeNodes replacing those in given list.
2665     */
2666     static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2667     Node<K,V> hd = null, tl = null;
2668     for (Node<K,V> q = b; q != null; q = q.next) {
2669     Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val);
2670     if (tl == null)
2671     hd = p;
2672     else
2673     tl.next = p;
2674     tl = p;
2675     }
2676     return hd;
2677     }
2678    
2679     /* ---------------- TreeNodes -------------- */
2680    
2681     /**
2682     * Nodes for use in TreeBins.
2683     */
2684     static final class TreeNode<K,V> extends Node<K,V> {
2685     TreeNode<K,V> parent; // red-black tree links
2686     TreeNode<K,V> left;
2687     TreeNode<K,V> right;
2688     TreeNode<K,V> prev; // needed to unlink next upon deletion
2689     boolean red;
2690    
2691     TreeNode(int hash, K key, V val, Node<K,V> next,
2692     TreeNode<K,V> parent) {
2693     super(hash, key, val, next);
2694     this.parent = parent;
2695     }
2696    
2697     Node<K,V> find(int h, Object k) {
2698     return findTreeNode(h, k, null);
2699     }
2700    
2701     /**
2702     * Returns the TreeNode (or null if not found) for the given key
2703     * starting at given root.
2704     */
2705     final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2706     if (k != null) {
2707     TreeNode<K,V> p = this;
2708     do {
2709     int ph, dir; K pk; TreeNode<K,V> q;
2710     TreeNode<K,V> pl = p.left, pr = p.right;
2711     if ((ph = p.hash) > h)
2712     p = pl;
2713     else if (ph < h)
2714     p = pr;
2715     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2716     return p;
2717     else if (pl == null)
2718     p = pr;
2719     else if (pr == null)
2720     p = pl;
2721     else if ((kc != null ||
2722     (kc = comparableClassFor(k)) != null) &&
2723     (dir = compareComparables(kc, k, pk)) != 0)
2724     p = (dir < 0) ? pl : pr;
2725     else if ((q = pr.findTreeNode(h, k, kc)) != null)
2726     return q;
2727     else
2728     p = pl;
2729     } while (p != null);
2730     }
2731     return null;
2732     }
2733     }
2734    
2735     /* ---------------- TreeBins -------------- */
2736    
2737     /**
2738     * TreeNodes used at the heads of bins. TreeBins do not hold user
2739     * keys or values, but instead point to list of TreeNodes and
2740     * their root. They also maintain a parasitic read-write lock
2741     * forcing writers (who hold bin lock) to wait for readers (who do
2742     * not) to complete before tree restructuring operations.
2743     */
2744     static final class TreeBin<K,V> extends Node<K,V> {
2745     TreeNode<K,V> root;
2746     volatile TreeNode<K,V> first;
2747     volatile Thread waiter;
2748     volatile int lockState;
2749     // values for lockState
2750     static final int WRITER = 1; // set while holding write lock
2751     static final int WAITER = 2; // set when waiting for write lock
2752     static final int READER = 4; // increment value for setting read lock
2753    
2754     /**
2755     * Tie-breaking utility for ordering insertions when equal
2756     * hashCodes and non-comparable. We don't require a total
2757     * order, just a consistent insertion rule to maintain
2758     * equivalence across rebalancings. Tie-breaking further than
2759     * necessary simplifies testing a bit.
2760     */
2761     static int tieBreakOrder(Object a, Object b) {
2762     int d;
2763     if (a == null || b == null ||
2764     (d = a.getClass().getName().
2765     compareTo(b.getClass().getName())) == 0)
2766     d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2767     -1 : 1);
2768     return d;
2769     }
2770    
2771     /**
2772     * Creates bin with initial set of nodes headed by b.
2773     */
2774     TreeBin(TreeNode<K,V> b) {
2775     super(TREEBIN, null, null);
2776     this.first = b;
2777     TreeNode<K,V> r = null;
2778     for (TreeNode<K,V> x = b, next; x != null; x = next) {
2779     next = (TreeNode<K,V>)x.next;
2780     x.left = x.right = null;
2781     if (r == null) {
2782     x.parent = null;
2783     x.red = false;
2784     r = x;
2785     }
2786     else {
2787     K k = x.key;
2788     int h = x.hash;
2789     Class<?> kc = null;
2790     for (TreeNode<K,V> p = r;;) {
2791     int dir, ph;
2792     K pk = p.key;
2793     if ((ph = p.hash) > h)
2794     dir = -1;
2795     else if (ph < h)
2796     dir = 1;
2797     else if ((kc == null &&
2798     (kc = comparableClassFor(k)) == null) ||
2799     (dir = compareComparables(kc, k, pk)) == 0)
2800     dir = tieBreakOrder(k, pk);
2801     TreeNode<K,V> xp = p;
2802     if ((p = (dir <= 0) ? p.left : p.right) == null) {
2803     x.parent = xp;
2804     if (dir <= 0)
2805     xp.left = x;
2806     else
2807     xp.right = x;
2808     r = balanceInsertion(r, x);
2809     break;
2810     }
2811     }
2812     }
2813     }
2814     this.root = r;
2815     assert checkInvariants(root);
2816     }
2817    
2818     /**
2819     * Acquires write lock for tree restructuring.
2820     */
2821     private final void lockRoot() {
2822     if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2823     contendedLock(); // offload to separate method
2824     }
2825    
2826     /**
2827     * Releases write lock for tree restructuring.
2828     */
2829     private final void unlockRoot() {
2830     lockState = 0;
2831     }
2832    
2833     /**
2834     * Possibly blocks awaiting root lock.
2835     */
2836     private final void contendedLock() {
2837     boolean waiting = false;
2838     for (int s;;) {
2839     if (((s = lockState) & ~WAITER) == 0) {
2840     if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2841     if (waiting)
2842     waiter = null;
2843     return;
2844     }
2845     }
2846     else if ((s & WAITER) == 0) {
2847     if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2848     waiting = true;
2849     waiter = Thread.currentThread();
2850     }
2851     }
2852     else if (waiting)
2853     LockSupport.park(this);
2854     }
2855     }
2856    
2857     /**
2858     * Returns matching node or null if none. Tries to search
2859     * using tree comparisons from root, but continues linear
2860     * search when lock not available.
2861     */
2862     final Node<K,V> find(int h, Object k) {
2863     if (k != null) {
2864     for (Node<K,V> e = first; e != null; ) {
2865     int s; K ek;
2866     if (((s = lockState) & (WAITER|WRITER)) != 0) {
2867     if (e.hash == h &&
2868     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2869     return e;
2870     e = e.next;
2871     }
2872     else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2873     s + READER)) {
2874     TreeNode<K,V> r, p;
2875     try {
2876     p = ((r = root) == null ? null :
2877     r.findTreeNode(h, k, null));
2878     } finally {
2879     Thread w;
2880     if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2881     (READER|WAITER) && (w = waiter) != null)
2882     LockSupport.unpark(w);
2883     }
2884     return p;
2885     }
2886     }
2887     }
2888     return null;
2889     }
2890    
2891     /**
2892     * Finds or adds a node.
2893     * @return null if added
2894     */
2895     final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2896     Class<?> kc = null;
2897     boolean searched = false;
2898     for (TreeNode<K,V> p = root;;) {
2899     int dir, ph; K pk;
2900     if (p == null) {
2901     first = root = new TreeNode<K,V>(h, k, v, null, null);
2902     break;
2903     }
2904     else if ((ph = p.hash) > h)
2905     dir = -1;
2906     else if (ph < h)
2907     dir = 1;
2908     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2909     return p;
2910     else if ((kc == null &&
2911     (kc = comparableClassFor(k)) == null) ||
2912     (dir = compareComparables(kc, k, pk)) == 0) {
2913     if (!searched) {
2914     TreeNode<K,V> q, ch;
2915     searched = true;
2916     if (((ch = p.left) != null &&
2917     (q = ch.findTreeNode(h, k, kc)) != null) ||
2918     ((ch = p.right) != null &&
2919     (q = ch.findTreeNode(h, k, kc)) != null))
2920     return q;
2921     }
2922     dir = tieBreakOrder(k, pk);
2923     }
2924    
2925     TreeNode<K,V> xp = p;
2926     if ((p = (dir <= 0) ? p.left : p.right) == null) {
2927     TreeNode<K,V> x, f = first;
2928     first = x = new TreeNode<K,V>(h, k, v, f, xp);
2929     if (f != null)
2930     f.prev = x;
2931     if (dir <= 0)
2932     xp.left = x;
2933     else
2934     xp.right = x;
2935     if (!xp.red)
2936     x.red = true;
2937     else {
2938     lockRoot();
2939     try {
2940     root = balanceInsertion(root, x);
2941     } finally {
2942     unlockRoot();
2943     }
2944     }
2945     break;
2946     }
2947     }
2948     assert checkInvariants(root);
2949     return null;
2950     }
2951    
2952     /**
2953     * Removes the given node, that must be present before this
2954     * call. This is messier than typical red-black deletion code
2955     * because we cannot swap the contents of an interior node
2956     * with a leaf successor that is pinned by "next" pointers
2957     * that are accessible independently of lock. So instead we
2958     * swap the tree linkages.
2959     *
2960     * @return true if now too small, so should be untreeified
2961     */
2962     final boolean removeTreeNode(TreeNode<K,V> p) {
2963     TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2964     TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2965     TreeNode<K,V> r, rl;
2966     if (pred == null)
2967     first = next;
2968     else
2969     pred.next = next;
2970     if (next != null)
2971     next.prev = pred;
2972     if (first == null) {
2973     root = null;
2974     return true;
2975     }
2976     if ((r = root) == null || r.right == null || // too small
2977     (rl = r.left) == null || rl.left == null)
2978     return true;
2979     lockRoot();
2980     try {
2981     TreeNode<K,V> replacement;
2982     TreeNode<K,V> pl = p.left;
2983     TreeNode<K,V> pr = p.right;
2984     if (pl != null && pr != null) {
2985     TreeNode<K,V> s = pr, sl;
2986     while ((sl = s.left) != null) // find successor
2987     s = sl;
2988     boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2989     TreeNode<K,V> sr = s.right;
2990     TreeNode<K,V> pp = p.parent;
2991     if (s == pr) { // p was s's direct parent
2992     p.parent = s;
2993     s.right = p;
2994     }
2995     else {
2996     TreeNode<K,V> sp = s.parent;
2997     if ((p.parent = sp) != null) {
2998     if (s == sp.left)
2999     sp.left = p;
3000     else
3001     sp.right = p;
3002     }
3003     if ((s.right = pr) != null)
3004     pr.parent = s;
3005     }
3006     p.left = null;
3007     if ((p.right = sr) != null)
3008     sr.parent = p;
3009     if ((s.left = pl) != null)
3010     pl.parent = s;
3011     if ((s.parent = pp) == null)
3012     r = s;
3013     else if (p == pp.left)
3014     pp.left = s;
3015     else
3016     pp.right = s;
3017     if (sr != null)
3018     replacement = sr;
3019     else
3020     replacement = p;
3021     }
3022     else if (pl != null)
3023     replacement = pl;
3024     else if (pr != null)
3025     replacement = pr;
3026     else
3027     replacement = p;
3028     if (replacement != p) {
3029     TreeNode<K,V> pp = replacement.parent = p.parent;
3030     if (pp == null)
3031     r = replacement;
3032     else if (p == pp.left)
3033     pp.left = replacement;
3034     else
3035     pp.right = replacement;
3036     p.left = p.right = p.parent = null;
3037     }
3038    
3039     root = (p.red) ? r : balanceDeletion(r, replacement);
3040    
3041     if (p == replacement) { // detach pointers
3042     TreeNode<K,V> pp;
3043     if ((pp = p.parent) != null) {
3044     if (p == pp.left)
3045     pp.left = null;
3046     else if (p == pp.right)
3047     pp.right = null;
3048     p.parent = null;
3049     }
3050     }
3051     } finally {
3052     unlockRoot();
3053     }
3054     assert checkInvariants(root);
3055     return false;
3056     }
3057    
3058     /* ------------------------------------------------------------ */
3059     // Red-black tree methods, all adapted from CLR
3060    
3061     static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3062     TreeNode<K,V> p) {
3063     TreeNode<K,V> r, pp, rl;
3064     if (p != null && (r = p.right) != null) {
3065     if ((rl = p.right = r.left) != null)
3066     rl.parent = p;
3067     if ((pp = r.parent = p.parent) == null)
3068     (root = r).red = false;
3069     else if (pp.left == p)
3070     pp.left = r;
3071     else
3072     pp.right = r;
3073     r.left = p;
3074     p.parent = r;
3075     }
3076     return root;
3077     }
3078    
3079     static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3080     TreeNode<K,V> p) {
3081     TreeNode<K,V> l, pp, lr;
3082     if (p != null && (l = p.left) != null) {
3083     if ((lr = p.left = l.right) != null)
3084     lr.parent = p;
3085     if ((pp = l.parent = p.parent) == null)
3086     (root = l).red = false;
3087     else if (pp.right == p)
3088     pp.right = l;
3089     else
3090     pp.left = l;
3091     l.right = p;
3092     p.parent = l;
3093     }
3094     return root;
3095     }
3096    
3097     static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3098     TreeNode<K,V> x) {
3099     x.red = true;
3100     for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3101     if ((xp = x.parent) == null) {
3102     x.red = false;
3103     return x;
3104     }
3105     else if (!xp.red || (xpp = xp.parent) == null)
3106     return root;
3107     if (xp == (xppl = xpp.left)) {
3108     if ((xppr = xpp.right) != null && xppr.red) {
3109     xppr.red = false;
3110     xp.red = false;
3111     xpp.red = true;
3112     x = xpp;
3113     }
3114     else {
3115     if (x == xp.right) {
3116     root = rotateLeft(root, x = xp);
3117     xpp = (xp = x.parent) == null ? null : xp.parent;
3118     }
3119     if (xp != null) {
3120     xp.red = false;
3121     if (xpp != null) {
3122     xpp.red = true;
3123     root = rotateRight(root, xpp);
3124     }
3125     }
3126     }
3127     }
3128     else {
3129     if (xppl != null && xppl.red) {
3130     xppl.red = false;
3131     xp.red = false;
3132     xpp.red = true;
3133     x = xpp;
3134     }
3135     else {
3136     if (x == xp.left) {
3137     root = rotateRight(root, x = xp);
3138     xpp = (xp = x.parent) == null ? null : xp.parent;
3139     }
3140     if (xp != null) {
3141     xp.red = false;
3142     if (xpp != null) {
3143     xpp.red = true;
3144     root = rotateLeft(root, xpp);
3145     }
3146     }
3147     }
3148     }
3149     }
3150     }
3151    
3152     static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3153     TreeNode<K,V> x) {
3154     for (TreeNode<K,V> xp, xpl, xpr;;) {
3155     if (x == null || x == root)
3156     return root;
3157     else if ((xp = x.parent) == null) {
3158     x.red = false;
3159     return x;
3160     }
3161     else if (x.red) {
3162     x.red = false;
3163     return root;
3164     }
3165     else if ((xpl = xp.left) == x) {
3166     if ((xpr = xp.right) != null && xpr.red) {
3167     xpr.red = false;
3168     xp.red = true;
3169     root = rotateLeft(root, xp);
3170     xpr = (xp = x.parent) == null ? null : xp.right;
3171     }
3172     if (xpr == null)
3173     x = xp;
3174     else {
3175     TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3176     if ((sr == null || !sr.red) &&
3177     (sl == null || !sl.red)) {
3178     xpr.red = true;
3179     x = xp;
3180     }
3181     else {
3182     if (sr == null || !sr.red) {
3183     if (sl != null)
3184     sl.red = false;
3185     xpr.red = true;
3186     root = rotateRight(root, xpr);
3187     xpr = (xp = x.parent) == null ?
3188     null : xp.right;
3189     }
3190     if (xpr != null) {
3191     xpr.red = (xp == null) ? false : xp.red;
3192     if ((sr = xpr.right) != null)
3193     sr.red = false;
3194     }
3195     if (xp != null) {
3196     xp.red = false;
3197     root = rotateLeft(root, xp);
3198     }
3199     x = root;
3200     }
3201     }
3202     }
3203     else { // symmetric
3204     if (xpl != null && xpl.red) {
3205     xpl.red = false;
3206     xp.red = true;
3207     root = rotateRight(root, xp);
3208     xpl = (xp = x.parent) == null ? null : xp.left;
3209     }
3210     if (xpl == null)
3211     x = xp;
3212     else {
3213     TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3214     if ((sl == null || !sl.red) &&
3215     (sr == null || !sr.red)) {
3216     xpl.red = true;
3217     x = xp;
3218     }
3219     else {
3220     if (sl == null || !sl.red) {
3221     if (sr != null)
3222     sr.red = false;
3223     xpl.red = true;
3224     root = rotateLeft(root, xpl);
3225     xpl = (xp = x.parent) == null ?
3226     null : xp.left;
3227     }
3228     if (xpl != null) {
3229     xpl.red = (xp == null) ? false : xp.red;
3230     if ((sl = xpl.left) != null)
3231     sl.red = false;
3232     }
3233     if (xp != null) {
3234     xp.red = false;
3235     root = rotateRight(root, xp);
3236     }
3237     x = root;
3238     }
3239     }
3240     }
3241     }
3242     }
3243    
3244     /**
3245     * Checks invariants recursively for the tree of Nodes rooted at t.
3246     */
3247     static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3248     TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3249     tb = t.prev, tn = (TreeNode<K,V>)t.next;
3250     if (tb != null && tb.next != t)
3251     return false;
3252     if (tn != null && tn.prev != t)
3253     return false;
3254     if (tp != null && t != tp.left && t != tp.right)
3255     return false;
3256     if (tl != null && (tl.parent != t || tl.hash > t.hash))
3257     return false;
3258     if (tr != null && (tr.parent != t || tr.hash < t.hash))
3259     return false;
3260     if (t.red && tl != null && tl.red && tr != null && tr.red)
3261     return false;
3262     if (tl != null && !checkInvariants(tl))
3263     return false;
3264     if (tr != null && !checkInvariants(tr))
3265     return false;
3266     return true;
3267     }
3268    
3269     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3270     private static final long LOCKSTATE;
3271     static {
3272     try {
3273     LOCKSTATE = U.objectFieldOffset
3274     (TreeBin.class.getDeclaredField("lockState"));
3275     } catch (ReflectiveOperationException e) {
3276     throw new Error(e);
3277     }
3278     }
3279     }
3280    
3281     /* ----------------Table Traversal -------------- */
3282    
3283     /**
3284     * Records the table, its length, and current traversal index for a
3285     * traverser that must process a region of a forwarded table before
3286     * proceeding with current table.
3287     */
3288     static final class TableStack<K,V> {
3289     int length;
3290     int index;
3291     Node<K,V>[] tab;
3292     TableStack<K,V> next;
3293     }
3294    
3295     /**
3296     * Encapsulates traversal for methods such as containsValue; also
3297     * serves as a base class for other iterators and spliterators.
3298     *
3299     * Method advance visits once each still-valid node that was
3300     * reachable upon iterator construction. It might miss some that
3301     * were added to a bin after the bin was visited, which is OK wrt
3302     * consistency guarantees. Maintaining this property in the face
3303     * of possible ongoing resizes requires a fair amount of
3304     * bookkeeping state that is difficult to optimize away amidst
3305     * volatile accesses. Even so, traversal maintains reasonable
3306     * throughput.
3307     *
3308     * Normally, iteration proceeds bin-by-bin traversing lists.
3309     * However, if the table has been resized, then all future steps
3310     * must traverse both the bin at the current index as well as at
3311     * (index + baseSize); and so on for further resizings. To
3312     * paranoically cope with potential sharing by users of iterators
3313     * across threads, iteration terminates if a bounds checks fails
3314     * for a table read.
3315     */
3316     static class Traverser<K,V> {
3317     Node<K,V>[] tab; // current table; updated if resized
3318     Node<K,V> next; // the next entry to use
3319     TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3320     int index; // index of bin to use next
3321     int baseIndex; // current index of initial table
3322     int baseLimit; // index bound for initial table
3323     final int baseSize; // initial table size
3324    
3325     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3326     this.tab = tab;
3327     this.baseSize = size;
3328     this.baseIndex = this.index = index;
3329     this.baseLimit = limit;
3330     this.next = null;
3331     }
3332    
3333     /**
3334     * Advances if possible, returning next valid node, or null if none.
3335     */
3336     final Node<K,V> advance() {
3337     Node<K,V> e;
3338     if ((e = next) != null)
3339     e = e.next;
3340     for (;;) {
3341     Node<K,V>[] t; int i, n; // must use locals in checks
3342     if (e != null)
3343     return next = e;
3344     if (baseIndex >= baseLimit || (t = tab) == null ||
3345     (n = t.length) <= (i = index) || i < 0)
3346     return next = null;
3347     if ((e = tabAt(t, i)) != null && e.hash < 0) {
3348     if (e instanceof ForwardingNode) {
3349     tab = ((ForwardingNode<K,V>)e).nextTable;
3350     e = null;
3351     pushState(t, i, n);
3352     continue;
3353     }
3354     else if (e instanceof TreeBin)
3355     e = ((TreeBin<K,V>)e).first;
3356     else
3357     e = null;
3358     }
3359     if (stack != null)
3360     recoverState(n);
3361     else if ((index = i + baseSize) >= n)
3362     index = ++baseIndex; // visit upper slots if present
3363     }
3364     }
3365    
3366     /**
3367     * Saves traversal state upon encountering a forwarding node.
3368     */
3369     private void pushState(Node<K,V>[] t, int i, int n) {
3370     TableStack<K,V> s = spare; // reuse if possible
3371     if (s != null)
3372     spare = s.next;
3373     else
3374     s = new TableStack<K,V>();
3375     s.tab = t;
3376     s.length = n;
3377     s.index = i;
3378     s.next = stack;
3379     stack = s;
3380     }
3381    
3382     /**
3383     * Possibly pops traversal state.
3384     *
3385     * @param n length of current table
3386     */
3387     private void recoverState(int n) {
3388     TableStack<K,V> s; int len;
3389     while ((s = stack) != null && (index += (len = s.length)) >= n) {
3390     n = len;
3391     index = s.index;
3392     tab = s.tab;
3393     s.tab = null;
3394     TableStack<K,V> next = s.next;
3395     s.next = spare; // save for reuse
3396     stack = next;
3397     spare = s;
3398     }
3399     if (s == null && (index += baseSize) >= n)
3400     index = ++baseIndex;
3401     }
3402     }
3403    
3404     /**
3405     * Base of key, value, and entry Iterators. Adds fields to
3406     * Traverser to support iterator.remove.
3407     */
3408     static class BaseIterator<K,V> extends Traverser<K,V> {
3409     final ConcurrentHashMap<K,V> map;
3410     Node<K,V> lastReturned;
3411     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3412     ConcurrentHashMap<K,V> map) {
3413     super(tab, size, index, limit);
3414     this.map = map;
3415     advance();
3416     }
3417    
3418     public final boolean hasNext() { return next != null; }
3419     public final boolean hasMoreElements() { return next != null; }
3420    
3421     public final void remove() {
3422     Node<K,V> p;
3423     if ((p = lastReturned) == null)
3424     throw new IllegalStateException();
3425     lastReturned = null;
3426     map.replaceNode(p.key, null, null);
3427     }
3428     }
3429    
3430     static final class KeyIterator<K,V> extends BaseIterator<K,V>
3431     implements Iterator<K>, Enumeration<K> {
3432     KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3433     ConcurrentHashMap<K,V> map) {
3434     super(tab, index, size, limit, map);
3435     }
3436    
3437     public final K next() {
3438     Node<K,V> p;
3439     if ((p = next) == null)
3440     throw new NoSuchElementException();
3441     K k = p.key;
3442     lastReturned = p;
3443     advance();
3444     return k;
3445     }
3446    
3447     public final K nextElement() { return next(); }
3448     }
3449    
3450     static final class ValueIterator<K,V> extends BaseIterator<K,V>
3451     implements Iterator<V>, Enumeration<V> {
3452     ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3453     ConcurrentHashMap<K,V> map) {
3454     super(tab, index, size, limit, map);
3455     }
3456    
3457     public final V next() {
3458     Node<K,V> p;
3459     if ((p = next) == null)
3460     throw new NoSuchElementException();
3461     V v = p.val;
3462     lastReturned = p;
3463     advance();
3464     return v;
3465     }
3466    
3467     public final V nextElement() { return next(); }
3468     }
3469    
3470     static final class EntryIterator<K,V> extends BaseIterator<K,V>
3471     implements Iterator<Map.Entry<K,V>> {
3472     EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3473     ConcurrentHashMap<K,V> map) {
3474     super(tab, index, size, limit, map);
3475     }
3476    
3477     public final Map.Entry<K,V> next() {
3478     Node<K,V> p;
3479     if ((p = next) == null)
3480     throw new NoSuchElementException();
3481     K k = p.key;
3482     V v = p.val;
3483     lastReturned = p;
3484     advance();
3485     return new MapEntry<K,V>(k, v, map);
3486     }
3487     }
3488    
3489     /**
3490     * Exported Entry for EntryIterator.
3491     */
3492     static final class MapEntry<K,V> implements Map.Entry<K,V> {
3493     final K key; // non-null
3494     V val; // non-null
3495     final ConcurrentHashMap<K,V> map;
3496     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3497     this.key = key;
3498     this.val = val;
3499     this.map = map;
3500     }
3501     public K getKey() { return key; }
3502     public V getValue() { return val; }
3503     public int hashCode() { return key.hashCode() ^ val.hashCode(); }
3504     public String toString() {
3505     return Helpers.mapEntryToString(key, val);
3506     }
3507    
3508     public boolean equals(Object o) {
3509     Object k, v; Map.Entry<?,?> e;
3510     return ((o instanceof Map.Entry) &&
3511     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3512     (v = e.getValue()) != null &&
3513     (k == key || k.equals(key)) &&
3514     (v == val || v.equals(val)));
3515     }
3516    
3517     /**
3518     * Sets our entry's value and writes through to the map. The
3519     * value to return is somewhat arbitrary here. Since we do not
3520     * necessarily track asynchronous changes, the most recent
3521     * "previous" value could be different from what we return (or
3522     * could even have been removed, in which case the put will
3523     * re-establish). We do not and cannot guarantee more.
3524     */
3525     public V setValue(V value) {
3526     if (value == null) throw new NullPointerException();
3527     V v = val;
3528     val = value;
3529     map.put(key, value);
3530     return v;
3531     }
3532     }
3533    
3534     static final class KeySpliterator<K,V> extends Traverser<K,V>
3535     implements Spliterator<K> {
3536     long est; // size estimate
3537     KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3538     long est) {
3539     super(tab, size, index, limit);
3540     this.est = est;
3541     }
3542    
3543     public KeySpliterator<K,V> trySplit() {
3544     int i, f, h;
3545     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3546     new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3547     f, est >>>= 1);
3548     }
3549    
3550     public void forEachRemaining(Consumer<? super K> action) {
3551     if (action == null) throw new NullPointerException();
3552     for (Node<K,V> p; (p = advance()) != null;)
3553     action.accept(p.key);
3554     }
3555    
3556     public boolean tryAdvance(Consumer<? super K> action) {
3557     if (action == null) throw new NullPointerException();
3558     Node<K,V> p;
3559     if ((p = advance()) == null)
3560     return false;
3561     action.accept(p.key);
3562     return true;
3563     }
3564    
3565     public long estimateSize() { return est; }
3566    
3567     public int characteristics() {
3568     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3569     Spliterator.NONNULL;
3570     }
3571     }
3572    
3573     static final class ValueSpliterator<K,V> extends Traverser<K,V>
3574     implements Spliterator<V> {
3575     long est; // size estimate
3576     ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3577     long est) {
3578     super(tab, size, index, limit);
3579     this.est = est;
3580     }
3581    
3582     public ValueSpliterator<K,V> trySplit() {
3583     int i, f, h;
3584     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3585     new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3586     f, est >>>= 1);
3587     }
3588    
3589     public void forEachRemaining(Consumer<? super V> action) {
3590     if (action == null) throw new NullPointerException();
3591     for (Node<K,V> p; (p = advance()) != null;)
3592     action.accept(p.val);
3593     }
3594    
3595     public boolean tryAdvance(Consumer<? super V> action) {
3596     if (action == null) throw new NullPointerException();
3597     Node<K,V> p;
3598     if ((p = advance()) == null)
3599     return false;
3600     action.accept(p.val);
3601     return true;
3602     }
3603    
3604     public long estimateSize() { return est; }
3605    
3606     public int characteristics() {
3607     return Spliterator.CONCURRENT | Spliterator.NONNULL;
3608     }
3609     }
3610    
3611     static final class EntrySpliterator<K,V> extends Traverser<K,V>
3612     implements Spliterator<Map.Entry<K,V>> {
3613     final ConcurrentHashMap<K,V> map; // To export MapEntry
3614     long est; // size estimate
3615     EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3616     long est, ConcurrentHashMap<K,V> map) {
3617     super(tab, size, index, limit);
3618     this.map = map;
3619     this.est = est;
3620     }
3621    
3622     public EntrySpliterator<K,V> trySplit() {
3623     int i, f, h;
3624     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3625     new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3626     f, est >>>= 1, map);
3627     }
3628    
3629     public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3630     if (action == null) throw new NullPointerException();
3631     for (Node<K,V> p; (p = advance()) != null; )
3632     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3633     }
3634    
3635     public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3636     if (action == null) throw new NullPointerException();
3637     Node<K,V> p;
3638     if ((p = advance()) == null)
3639     return false;
3640     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3641     return true;
3642     }
3643    
3644     public long estimateSize() { return est; }
3645    
3646     public int characteristics() {
3647     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3648     Spliterator.NONNULL;
3649     }
3650     }
3651    
3652     // Parallel bulk operations
3653    
3654     /**
3655     * Computes initial batch value for bulk tasks. The returned value
3656     * is approximately exp2 of the number of times (minus one) to
3657     * split task by two before executing leaf action. This value is
3658     * faster to compute and more convenient to use as a guide to
3659     * splitting than is the depth, since it is used while dividing by
3660     * two anyway.
3661     */
3662     final int batchFor(long b) {
3663     long n;
3664     if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3665     return 0;
3666     int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3667     return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3668     }
3669    
3670     /**
3671     * Performs the given action for each (key, value).
3672     *
3673     * @param parallelismThreshold the (estimated) number of elements
3674     * needed for this operation to be executed in parallel
3675     * @param action the action
3676     * @since 1.8
3677     */
3678     public void forEach(long parallelismThreshold,
3679     BiConsumer<? super K,? super V> action) {
3680     if (action == null) throw new NullPointerException();
3681     new ForEachMappingTask<K,V>
3682     (null, batchFor(parallelismThreshold), 0, 0, table,
3683     action).invoke();
3684     }
3685    
3686     /**
3687     * Performs the given action for each non-null transformation
3688     * of each (key, value).
3689     *
3690     * @param parallelismThreshold the (estimated) number of elements
3691     * needed for this operation to be executed in parallel
3692     * @param transformer a function returning the transformation
3693     * for an element, or null if there is no transformation (in
3694     * which case the action is not applied)
3695     * @param action the action
3696     * @param <U> the return type of the transformer
3697     * @since 1.8
3698     */
3699     public <U> void forEach(long parallelismThreshold,
3700     BiFunction<? super K, ? super V, ? extends U> transformer,
3701     Consumer<? super U> action) {
3702     if (transformer == null || action == null)
3703     throw new NullPointerException();
3704     new ForEachTransformedMappingTask<K,V,U>
3705     (null, batchFor(parallelismThreshold), 0, 0, table,
3706     transformer, action).invoke();
3707     }
3708    
3709     /**
3710     * Returns a non-null result from applying the given search
3711     * function on each (key, value), or null if none. Upon
3712     * success, further element processing is suppressed and the
3713     * results of any other parallel invocations of the search
3714     * function are ignored.
3715     *
3716     * @param parallelismThreshold the (estimated) number of elements
3717     * needed for this operation to be executed in parallel
3718     * @param searchFunction a function returning a non-null
3719     * result on success, else null
3720     * @param <U> the return type of the search function
3721     * @return a non-null result from applying the given search
3722     * function on each (key, value), or null if none
3723     * @since 1.8
3724     */
3725     public <U> U search(long parallelismThreshold,
3726     BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3727     if (searchFunction == null) throw new NullPointerException();
3728     return new SearchMappingsTask<K,V,U>
3729     (null, batchFor(parallelismThreshold), 0, 0, table,
3730     searchFunction, new AtomicReference<U>()).invoke();
3731     }
3732    
3733     /**
3734     * Returns the result of accumulating the given transformation
3735     * of all (key, value) pairs using the given reducer to
3736     * combine values, or null if none.
3737     *
3738     * @param parallelismThreshold the (estimated) number of elements
3739     * needed for this operation to be executed in parallel
3740     * @param transformer a function returning the transformation
3741     * for an element, or null if there is no transformation (in
3742     * which case it is not combined)
3743     * @param reducer a commutative associative combining function
3744     * @param <U> the return type of the transformer
3745     * @return the result of accumulating the given transformation
3746     * of all (key, value) pairs
3747     * @since 1.8
3748     */
3749     public <U> U reduce(long parallelismThreshold,
3750     BiFunction<? super K, ? super V, ? extends U> transformer,
3751     BiFunction<? super U, ? super U, ? extends U> reducer) {
3752     if (transformer == null || reducer == null)
3753     throw new NullPointerException();
3754     return new MapReduceMappingsTask<K,V,U>
3755     (null, batchFor(parallelismThreshold), 0, 0, table,
3756     null, transformer, reducer).invoke();
3757     }
3758    
3759     /**
3760     * Returns the result of accumulating the given transformation
3761     * of all (key, value) pairs using the given reducer to
3762     * combine values, and the given basis as an identity value.
3763     *
3764     * @param parallelismThreshold the (estimated) number of elements
3765     * needed for this operation to be executed in parallel
3766     * @param transformer a function returning the transformation
3767     * for an element
3768     * @param basis the identity (initial default value) for the reduction
3769     * @param reducer a commutative associative combining function
3770     * @return the result of accumulating the given transformation
3771     * of all (key, value) pairs
3772     * @since 1.8
3773     */
3774     public double reduceToDouble(long parallelismThreshold,
3775     ToDoubleBiFunction<? super K, ? super V> transformer,
3776     double basis,
3777     DoubleBinaryOperator reducer) {
3778     if (transformer == null || reducer == null)
3779     throw new NullPointerException();
3780     return new MapReduceMappingsToDoubleTask<K,V>
3781     (null, batchFor(parallelismThreshold), 0, 0, table,
3782     null, transformer, basis, reducer).invoke();
3783     }
3784    
3785     /**
3786     * Returns the result of accumulating the given transformation
3787     * of all (key, value) pairs using the given reducer to
3788     * combine values, and the given basis as an identity value.
3789     *
3790     * @param parallelismThreshold the (estimated) number of elements
3791     * needed for this operation to be executed in parallel
3792     * @param transformer a function returning the transformation
3793     * for an element
3794     * @param basis the identity (initial default value) for the reduction
3795     * @param reducer a commutative associative combining function
3796     * @return the result of accumulating the given transformation
3797     * of all (key, value) pairs
3798     * @since 1.8
3799     */
3800     public long reduceToLong(long parallelismThreshold,
3801     ToLongBiFunction<? super K, ? super V> transformer,
3802     long basis,
3803     LongBinaryOperator reducer) {
3804     if (transformer == null || reducer == null)
3805     throw new NullPointerException();
3806     return new MapReduceMappingsToLongTask<K,V>
3807     (null, batchFor(parallelismThreshold), 0, 0, table,
3808     null, transformer, basis, reducer).invoke();
3809     }
3810    
3811     /**
3812     * Returns the result of accumulating the given transformation
3813     * of all (key, value) pairs using the given reducer to
3814     * combine values, and the given basis as an identity value.
3815     *
3816     * @param parallelismThreshold the (estimated) number of elements
3817     * needed for this operation to be executed in parallel
3818     * @param transformer a function returning the transformation
3819     * for an element
3820     * @param basis the identity (initial default value) for the reduction
3821     * @param reducer a commutative associative combining function
3822     * @return the result of accumulating the given transformation
3823     * of all (key, value) pairs
3824     * @since 1.8
3825     */
3826     public int reduceToInt(long parallelismThreshold,
3827     ToIntBiFunction<? super K, ? super V> transformer,
3828     int basis,
3829     IntBinaryOperator reducer) {
3830     if (transformer == null || reducer == null)
3831     throw new NullPointerException();
3832     return new MapReduceMappingsToIntTask<K,V>
3833     (null, batchFor(parallelismThreshold), 0, 0, table,
3834     null, transformer, basis, reducer).invoke();
3835     }
3836    
3837     /**
3838     * Performs the given action for each key.
3839     *
3840     * @param parallelismThreshold the (estimated) number of elements
3841     * needed for this operation to be executed in parallel
3842     * @param action the action
3843     * @since 1.8
3844     */
3845     public void forEachKey(long parallelismThreshold,
3846     Consumer<? super K> action) {
3847     if (action == null) throw new NullPointerException();
3848     new ForEachKeyTask<K,V>
3849     (null, batchFor(parallelismThreshold), 0, 0, table,
3850     action).invoke();
3851     }
3852    
3853     /**
3854     * Performs the given action for each non-null transformation
3855     * of each key.
3856     *
3857     * @param parallelismThreshold the (estimated) number of elements
3858     * needed for this operation to be executed in parallel
3859     * @param transformer a function returning the transformation
3860     * for an element, or null if there is no transformation (in
3861     * which case the action is not applied)
3862     * @param action the action
3863     * @param <U> the return type of the transformer
3864     * @since 1.8
3865     */
3866     public <U> void forEachKey(long parallelismThreshold,
3867     Function<? super K, ? extends U> transformer,
3868     Consumer<? super U> action) {
3869     if (transformer == null || action == null)
3870     throw new NullPointerException();
3871     new ForEachTransformedKeyTask<K,V,U>
3872     (null, batchFor(parallelismThreshold), 0, 0, table,
3873     transformer, action).invoke();
3874     }
3875    
3876     /**
3877     * Returns a non-null result from applying the given search
3878     * function on each key, or null if none. Upon success,
3879     * further element processing is suppressed and the results of
3880     * any other parallel invocations of the search function are
3881     * ignored.
3882     *
3883     * @param parallelismThreshold the (estimated) number of elements
3884     * needed for this operation to be executed in parallel
3885     * @param searchFunction a function returning a non-null
3886     * result on success, else null
3887     * @param <U> the return type of the search function
3888     * @return a non-null result from applying the given search
3889     * function on each key, or null if none
3890     * @since 1.8
3891     */
3892     public <U> U searchKeys(long parallelismThreshold,
3893     Function<? super K, ? extends U> searchFunction) {
3894     if (searchFunction == null) throw new NullPointerException();
3895     return new SearchKeysTask<K,V,U>
3896     (null, batchFor(parallelismThreshold), 0, 0, table,
3897     searchFunction, new AtomicReference<U>()).invoke();
3898     }
3899    
3900     /**
3901     * Returns the result of accumulating all keys using the given
3902     * reducer to combine values, or null if none.
3903     *
3904     * @param parallelismThreshold the (estimated) number of elements
3905     * needed for this operation to be executed in parallel
3906     * @param reducer a commutative associative combining function
3907     * @return the result of accumulating all keys using the given
3908     * reducer to combine values, or null if none
3909     * @since 1.8
3910     */
3911     public K reduceKeys(long parallelismThreshold,
3912     BiFunction<? super K, ? super K, ? extends K> reducer) {
3913     if (reducer == null) throw new NullPointerException();
3914     return new ReduceKeysTask<K,V>
3915     (null, batchFor(parallelismThreshold), 0, 0, table,
3916     null, reducer).invoke();
3917     }
3918    
3919     /**
3920     * Returns the result of accumulating the given transformation
3921     * of all keys using the given reducer to combine values, or
3922     * null if none.
3923     *
3924     * @param parallelismThreshold the (estimated) number of elements
3925     * needed for this operation to be executed in parallel
3926     * @param transformer a function returning the transformation
3927     * for an element, or null if there is no transformation (in
3928     * which case it is not combined)
3929     * @param reducer a commutative associative combining function
3930     * @param <U> the return type of the transformer
3931     * @return the result of accumulating the given transformation
3932     * of all keys
3933     * @since 1.8
3934     */
3935     public <U> U reduceKeys(long parallelismThreshold,
3936     Function<? super K, ? extends U> transformer,
3937     BiFunction<? super U, ? super U, ? extends U> reducer) {
3938     if (transformer == null || reducer == null)
3939     throw new NullPointerException();
3940     return new MapReduceKeysTask<K,V,U>
3941     (null, batchFor(parallelismThreshold), 0, 0, table,
3942     null, transformer, reducer).invoke();
3943     }
3944    
3945     /**
3946     * Returns the result of accumulating the given transformation
3947     * of all keys using the given reducer to combine values, and
3948     * the given basis as an identity value.
3949     *
3950     * @param parallelismThreshold the (estimated) number of elements
3951     * needed for this operation to be executed in parallel
3952     * @param transformer a function returning the transformation
3953     * for an element
3954     * @param basis the identity (initial default value) for the reduction
3955     * @param reducer a commutative associative combining function
3956     * @return the result of accumulating the given transformation
3957     * of all keys
3958     * @since 1.8
3959     */
3960     public double reduceKeysToDouble(long parallelismThreshold,
3961     ToDoubleFunction<? super K> transformer,
3962     double basis,
3963     DoubleBinaryOperator reducer) {
3964     if (transformer == null || reducer == null)
3965     throw new NullPointerException();
3966     return new MapReduceKeysToDoubleTask<K,V>
3967     (null, batchFor(parallelismThreshold), 0, 0, table,
3968     null, transformer, basis, reducer).invoke();
3969     }
3970    
3971     /**
3972     * Returns the result of accumulating the given transformation
3973     * of all keys using the given reducer to combine values, and
3974     * the given basis as an identity value.
3975     *
3976     * @param parallelismThreshold the (estimated) number of elements
3977     * needed for this operation to be executed in parallel
3978     * @param transformer a function returning the transformation
3979     * for an element
3980     * @param basis the identity (initial default value) for the reduction
3981     * @param reducer a commutative associative combining function
3982     * @return the result of accumulating the given transformation
3983     * of all keys
3984     * @since 1.8
3985     */
3986     public long reduceKeysToLong(long parallelismThreshold,
3987     ToLongFunction<? super K> transformer,
3988     long basis,
3989     LongBinaryOperator reducer) {
3990     if (transformer == null || reducer == null)
3991     throw new NullPointerException();
3992     return new MapReduceKeysToLongTask<K,V>
3993     (null, batchFor(parallelismThreshold), 0, 0, table,
3994     null, transformer, basis, reducer).invoke();
3995     }
3996    
3997     /**
3998     * Returns the result of accumulating the given transformation
3999     * of all keys using the given reducer to combine values, and
4000     * the given basis as an identity value.
4001     *
4002     * @param parallelismThreshold the (estimated) number of elements
4003     * needed for this operation to be executed in parallel
4004     * @param transformer a function returning the transformation
4005     * for an element
4006     * @param basis the identity (initial default value) for the reduction
4007     * @param reducer a commutative associative combining function
4008     * @return the result of accumulating the given transformation
4009     * of all keys
4010     * @since 1.8
4011     */
4012     public int reduceKeysToInt(long parallelismThreshold,
4013     ToIntFunction<? super K> transformer,
4014     int basis,
4015     IntBinaryOperator reducer) {
4016     if (transformer == null || reducer == null)
4017     throw new NullPointerException();
4018     return new MapReduceKeysToIntTask<K,V>
4019     (null, batchFor(parallelismThreshold), 0, 0, table,
4020     null, transformer, basis, reducer).invoke();
4021     }
4022    
4023     /**
4024     * Performs the given action for each value.
4025     *
4026     * @param parallelismThreshold the (estimated) number of elements
4027     * needed for this operation to be executed in parallel
4028     * @param action the action
4029     * @since 1.8
4030     */
4031     public void forEachValue(long parallelismThreshold,
4032     Consumer<? super V> action) {
4033     if (action == null)
4034     throw new NullPointerException();
4035     new ForEachValueTask<K,V>
4036     (null, batchFor(parallelismThreshold), 0, 0, table,
4037     action).invoke();
4038     }
4039    
4040     /**
4041     * Performs the given action for each non-null transformation
4042     * of each value.
4043     *
4044     * @param parallelismThreshold the (estimated) number of elements
4045     * needed for this operation to be executed in parallel
4046     * @param transformer a function returning the transformation
4047     * for an element, or null if there is no transformation (in
4048     * which case the action is not applied)
4049     * @param action the action
4050     * @param <U> the return type of the transformer
4051     * @since 1.8
4052     */
4053     public <U> void forEachValue(long parallelismThreshold,
4054     Function<? super V, ? extends U> transformer,
4055     Consumer<? super U> action) {
4056     if (transformer == null || action == null)
4057     throw new NullPointerException();
4058     new ForEachTransformedValueTask<K,V,U>
4059     (null, batchFor(parallelismThreshold), 0, 0, table,
4060     transformer, action).invoke();
4061     }
4062    
4063     /**
4064     * Returns a non-null result from applying the given search
4065     * function on each value, or null if none. Upon success,
4066     * further element processing is suppressed and the results of
4067     * any other parallel invocations of the search function are
4068     * ignored.
4069     *
4070     * @param parallelismThreshold the (estimated) number of elements
4071     * needed for this operation to be executed in parallel
4072     * @param searchFunction a function returning a non-null
4073     * result on success, else null
4074     * @param <U> the return type of the search function
4075     * @return a non-null result from applying the given search
4076     * function on each value, or null if none
4077     * @since 1.8
4078     */
4079     public <U> U searchValues(long parallelismThreshold,
4080     Function<? super V, ? extends U> searchFunction) {
4081     if (searchFunction == null) throw new NullPointerException();
4082     return new SearchValuesTask<K,V,U>
4083     (null, batchFor(parallelismThreshold), 0, 0, table,
4084     searchFunction, new AtomicReference<U>()).invoke();
4085     }
4086    
4087     /**
4088     * Returns the result of accumulating all values using the
4089     * given reducer to combine values, or null if none.
4090     *
4091     * @param parallelismThreshold the (estimated) number of elements
4092     * needed for this operation to be executed in parallel
4093     * @param reducer a commutative associative combining function
4094     * @return the result of accumulating all values
4095     * @since 1.8
4096     */
4097     public V reduceValues(long parallelismThreshold,
4098     BiFunction<? super V, ? super V, ? extends V> reducer) {
4099     if (reducer == null) throw new NullPointerException();
4100     return new ReduceValuesTask<K,V>
4101     (null, batchFor(parallelismThreshold), 0, 0, table,
4102     null, reducer).invoke();
4103     }
4104    
4105     /**
4106     * Returns the result of accumulating the given transformation
4107     * of all values using the given reducer to combine values, or
4108     * null if none.
4109     *
4110     * @param parallelismThreshold the (estimated) number of elements
4111     * needed for this operation to be executed in parallel
4112     * @param transformer a function returning the transformation
4113     * for an element, or null if there is no transformation (in
4114     * which case it is not combined)
4115     * @param reducer a commutative associative combining function
4116     * @param <U> the return type of the transformer
4117     * @return the result of accumulating the given transformation
4118     * of all values
4119     * @since 1.8
4120     */
4121     public <U> U reduceValues(long parallelismThreshold,
4122     Function<? super V, ? extends U> transformer,
4123     BiFunction<? super U, ? super U, ? extends U> reducer) {
4124     if (transformer == null || reducer == null)
4125     throw new NullPointerException();
4126     return new MapReduceValuesTask<K,V,U>
4127     (null, batchFor(parallelismThreshold), 0, 0, table,
4128     null, transformer, reducer).invoke();
4129     }
4130    
4131     /**
4132     * Returns the result of accumulating the given transformation
4133     * of all values using the given reducer to combine values,
4134     * and the given basis as an identity value.
4135     *
4136     * @param parallelismThreshold the (estimated) number of elements
4137     * needed for this operation to be executed in parallel
4138     * @param transformer a function returning the transformation
4139     * for an element
4140     * @param basis the identity (initial default value) for the reduction
4141     * @param reducer a commutative associative combining function
4142     * @return the result of accumulating the given transformation
4143     * of all values
4144     * @since 1.8
4145     */
4146     public double reduceValuesToDouble(long parallelismThreshold,
4147     ToDoubleFunction<? super V> transformer,
4148     double basis,
4149     DoubleBinaryOperator reducer) {
4150     if (transformer == null || reducer == null)
4151     throw new NullPointerException();
4152     return new MapReduceValuesToDoubleTask<K,V>
4153     (null, batchFor(parallelismThreshold), 0, 0, table,
4154     null, transformer, basis, reducer).invoke();
4155     }
4156    
4157     /**
4158     * Returns the result of accumulating the given transformation
4159     * of all values using the given reducer to combine values,
4160     * and the given basis as an identity value.
4161     *
4162     * @param parallelismThreshold the (estimated) number of elements
4163     * needed for this operation to be executed in parallel
4164     * @param transformer a function returning the transformation
4165     * for an element
4166     * @param basis the identity (initial default value) for the reduction
4167     * @param reducer a commutative associative combining function
4168     * @return the result of accumulating the given transformation
4169     * of all values
4170     * @since 1.8
4171     */
4172     public long reduceValuesToLong(long parallelismThreshold,
4173     ToLongFunction<? super V> transformer,
4174     long basis,
4175     LongBinaryOperator reducer) {
4176     if (transformer == null || reducer == null)
4177     throw new NullPointerException();
4178     return new MapReduceValuesToLongTask<K,V>
4179     (null, batchFor(parallelismThreshold), 0, 0, table,
4180     null, transformer, basis, reducer).invoke();
4181     }
4182    
4183     /**
4184     * Returns the result of accumulating the given transformation
4185     * of all values using the given reducer to combine values,
4186     * and the given basis as an identity value.
4187     *
4188     * @param parallelismThreshold the (estimated) number of elements
4189     * needed for this operation to be executed in parallel
4190     * @param transformer a function returning the transformation
4191     * for an element
4192     * @param basis the identity (initial default value) for the reduction
4193     * @param reducer a commutative associative combining function
4194     * @return the result of accumulating the given transformation
4195     * of all values
4196     * @since 1.8
4197     */
4198     public int reduceValuesToInt(long parallelismThreshold,
4199     ToIntFunction<? super V> transformer,
4200     int basis,
4201     IntBinaryOperator reducer) {
4202     if (transformer == null || reducer == null)
4203     throw new NullPointerException();
4204     return new MapReduceValuesToIntTask<K,V>
4205     (null, batchFor(parallelismThreshold), 0, 0, table,
4206     null, transformer, basis, reducer).invoke();
4207     }
4208    
4209     /**
4210     * Performs the given action for each entry.
4211     *
4212     * @param parallelismThreshold the (estimated) number of elements
4213     * needed for this operation to be executed in parallel
4214     * @param action the action
4215     * @since 1.8
4216     */
4217     public void forEachEntry(long parallelismThreshold,
4218     Consumer<? super Map.Entry<K,V>> action) {
4219     if (action == null) throw new NullPointerException();
4220     new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4221     action).invoke();
4222     }
4223    
4224     /**
4225     * Performs the given action for each non-null transformation
4226     * of each entry.
4227     *
4228     * @param parallelismThreshold the (estimated) number of elements
4229     * needed for this operation to be executed in parallel
4230     * @param transformer a function returning the transformation
4231     * for an element, or null if there is no transformation (in
4232     * which case the action is not applied)
4233     * @param action the action
4234     * @param <U> the return type of the transformer
4235     * @since 1.8
4236     */
4237     public <U> void forEachEntry(long parallelismThreshold,
4238     Function<Map.Entry<K,V>, ? extends U> transformer,
4239     Consumer<? super U> action) {
4240     if (transformer == null || action == null)
4241     throw new NullPointerException();
4242     new ForEachTransformedEntryTask<K,V,U>
4243     (null, batchFor(parallelismThreshold), 0, 0, table,
4244     transformer, action).invoke();
4245     }
4246    
4247     /**
4248     * Returns a non-null result from applying the given search
4249     * function on each entry, or null if none. Upon success,
4250     * further element processing is suppressed and the results of
4251     * any other parallel invocations of the search function are
4252     * ignored.
4253     *
4254     * @param parallelismThreshold the (estimated) number of elements
4255     * needed for this operation to be executed in parallel
4256     * @param searchFunction a function returning a non-null
4257     * result on success, else null
4258     * @param <U> the return type of the search function
4259     * @return a non-null result from applying the given search
4260     * function on each entry, or null if none
4261     * @since 1.8
4262     */
4263     public <U> U searchEntries(long parallelismThreshold,
4264     Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4265     if (searchFunction == null) throw new NullPointerException();
4266     return new SearchEntriesTask<K,V,U>
4267     (null, batchFor(parallelismThreshold), 0, 0, table,
4268     searchFunction, new AtomicReference<U>()).invoke();
4269     }
4270    
4271     /**
4272     * Returns the result of accumulating all entries using the
4273     * given reducer to combine values, or null if none.
4274     *
4275     * @param parallelismThreshold the (estimated) number of elements
4276     * needed for this operation to be executed in parallel
4277     * @param reducer a commutative associative combining function
4278     * @return the result of accumulating all entries
4279     * @since 1.8
4280     */
4281     public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4282     BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4283     if (reducer == null) throw new NullPointerException();
4284     return new ReduceEntriesTask<K,V>
4285     (null, batchFor(parallelismThreshold), 0, 0, table,
4286     null, reducer).invoke();
4287     }
4288    
4289     /**
4290     * Returns the result of accumulating the given transformation
4291     * of all entries using the given reducer to combine values,
4292     * or null if none.
4293     *
4294     * @param parallelismThreshold the (estimated) number of elements
4295     * needed for this operation to be executed in parallel
4296     * @param transformer a function returning the transformation
4297     * for an element, or null if there is no transformation (in
4298     * which case it is not combined)
4299     * @param reducer a commutative associative combining function
4300     * @param <U> the return type of the transformer
4301     * @return the result of accumulating the given transformation
4302     * of all entries
4303     * @since 1.8
4304     */
4305     public <U> U reduceEntries(long parallelismThreshold,
4306     Function<Map.Entry<K,V>, ? extends U> transformer,
4307     BiFunction<? super U, ? super U, ? extends U> reducer) {
4308     if (transformer == null || reducer == null)
4309     throw new NullPointerException();
4310     return new MapReduceEntriesTask<K,V,U>
4311     (null, batchFor(parallelismThreshold), 0, 0, table,
4312     null, transformer, reducer).invoke();
4313     }
4314    
4315     /**
4316     * Returns the result of accumulating the given transformation
4317     * of all entries using the given reducer to combine values,
4318     * and the given basis as an identity value.
4319     *
4320     * @param parallelismThreshold the (estimated) number of elements
4321     * needed for this operation to be executed in parallel
4322     * @param transformer a function returning the transformation
4323     * for an element
4324     * @param basis the identity (initial default value) for the reduction
4325     * @param reducer a commutative associative combining function
4326     * @return the result of accumulating the given transformation
4327     * of all entries
4328     * @since 1.8
4329     */
4330     public double reduceEntriesToDouble(long parallelismThreshold,
4331     ToDoubleFunction<Map.Entry<K,V>> transformer,
4332     double basis,
4333     DoubleBinaryOperator reducer) {
4334     if (transformer == null || reducer == null)
4335     throw new NullPointerException();
4336     return new MapReduceEntriesToDoubleTask<K,V>
4337     (null, batchFor(parallelismThreshold), 0, 0, table,
4338     null, transformer, basis, reducer).invoke();
4339     }
4340    
4341     /**
4342     * Returns the result of accumulating the given transformation
4343     * of all entries using the given reducer to combine values,
4344     * and the given basis as an identity value.
4345     *
4346     * @param parallelismThreshold the (estimated) number of elements
4347     * needed for this operation to be executed in parallel
4348     * @param transformer a function returning the transformation
4349     * for an element
4350     * @param basis the identity (initial default value) for the reduction
4351     * @param reducer a commutative associative combining function
4352     * @return the result of accumulating the given transformation
4353     * of all entries
4354     * @since 1.8
4355     */
4356     public long reduceEntriesToLong(long parallelismThreshold,
4357     ToLongFunction<Map.Entry<K,V>> transformer,
4358     long basis,
4359     LongBinaryOperator reducer) {
4360     if (transformer == null || reducer == null)
4361     throw new NullPointerException();
4362     return new MapReduceEntriesToLongTask<K,V>
4363     (null, batchFor(parallelismThreshold), 0, 0, table,
4364     null, transformer, basis, reducer).invoke();
4365     }
4366    
4367     /**
4368     * Returns the result of accumulating the given transformation
4369     * of all entries using the given reducer to combine values,
4370     * and the given basis as an identity value.
4371     *
4372     * @param parallelismThreshold the (estimated) number of elements
4373     * needed for this operation to be executed in parallel
4374     * @param transformer a function returning the transformation
4375     * for an element
4376     * @param basis the identity (initial default value) for the reduction
4377     * @param reducer a commutative associative combining function
4378     * @return the result of accumulating the given transformation
4379     * of all entries
4380     * @since 1.8
4381     */
4382     public int reduceEntriesToInt(long parallelismThreshold,
4383     ToIntFunction<Map.Entry<K,V>> transformer,
4384     int basis,
4385     IntBinaryOperator reducer) {
4386     if (transformer == null || reducer == null)
4387     throw new NullPointerException();
4388     return new MapReduceEntriesToIntTask<K,V>
4389     (null, batchFor(parallelismThreshold), 0, 0, table,
4390     null, transformer, basis, reducer).invoke();
4391     }
4392    
4393    
4394     /* ----------------Views -------------- */
4395    
4396     /**
4397     * Base class for views.
4398     */
4399     abstract static class CollectionView<K,V,E>
4400     implements Collection<E>, java.io.Serializable {
4401     private static final long serialVersionUID = 7249069246763182397L;
4402     final ConcurrentHashMap<K,V> map;
4403     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4404    
4405     /**
4406     * Returns the map backing this view.
4407     *
4408     * @return the map backing this view
4409     */
4410     public ConcurrentHashMap<K,V> getMap() { return map; }
4411    
4412     /**
4413     * Removes all of the elements from this view, by removing all
4414     * the mappings from the map backing this view.
4415     */
4416     public final void clear() { map.clear(); }
4417     public final int size() { return map.size(); }
4418     public final boolean isEmpty() { return map.isEmpty(); }
4419    
4420     // implementations below rely on concrete classes supplying these
4421     // abstract methods
4422     /**
4423     * Returns an iterator over the elements in this collection.
4424     *
4425     * <p>The returned iterator is
4426     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4427     *
4428     * @return an iterator over the elements in this collection
4429     */
4430     public abstract Iterator<E> iterator();
4431     public abstract boolean contains(Object o);
4432     public abstract boolean remove(Object o);
4433    
4434     private static final String OOME_MSG = "Required array size too large";
4435    
4436     public final Object[] toArray() {
4437     long sz = map.mappingCount();
4438     if (sz > MAX_ARRAY_SIZE)
4439     throw new OutOfMemoryError(OOME_MSG);
4440     int n = (int)sz;
4441     Object[] r = new Object[n];
4442     int i = 0;
4443     for (E e : this) {
4444     if (i == n) {
4445     if (n >= MAX_ARRAY_SIZE)
4446     throw new OutOfMemoryError(OOME_MSG);
4447     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4448     n = MAX_ARRAY_SIZE;
4449     else
4450     n += (n >>> 1) + 1;
4451     r = Arrays.copyOf(r, n);
4452     }
4453     r[i++] = e;
4454     }
4455     return (i == n) ? r : Arrays.copyOf(r, i);
4456     }
4457    
4458     @SuppressWarnings("unchecked")
4459     public final <T> T[] toArray(T[] a) {
4460     long sz = map.mappingCount();
4461     if (sz > MAX_ARRAY_SIZE)
4462     throw new OutOfMemoryError(OOME_MSG);
4463     int m = (int)sz;
4464     T[] r = (a.length >= m) ? a :
4465     (T[])java.lang.reflect.Array
4466     .newInstance(a.getClass().getComponentType(), m);
4467     int n = r.length;
4468     int i = 0;
4469     for (E e : this) {
4470     if (i == n) {
4471     if (n >= MAX_ARRAY_SIZE)
4472     throw new OutOfMemoryError(OOME_MSG);
4473     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4474     n = MAX_ARRAY_SIZE;
4475     else
4476     n += (n >>> 1) + 1;
4477     r = Arrays.copyOf(r, n);
4478     }
4479     r[i++] = (T)e;
4480     }
4481     if (a == r && i < n) {
4482     r[i] = null; // null-terminate
4483     return r;
4484     }
4485     return (i == n) ? r : Arrays.copyOf(r, i);
4486     }
4487    
4488     /**
4489     * Returns a string representation of this collection.
4490     * The string representation consists of the string representations
4491     * of the collection's elements in the order they are returned by
4492     * its iterator, enclosed in square brackets ({@code "[]"}).
4493     * Adjacent elements are separated by the characters {@code ", "}
4494     * (comma and space). Elements are converted to strings as by
4495     * {@link String#valueOf(Object)}.
4496     *
4497     * @return a string representation of this collection
4498     */
4499     public final String toString() {
4500     StringBuilder sb = new StringBuilder();
4501     sb.append('[');
4502     Iterator<E> it = iterator();
4503     if (it.hasNext()) {
4504     for (;;) {
4505     Object e = it.next();
4506     sb.append(e == this ? "(this Collection)" : e);
4507     if (!it.hasNext())
4508     break;
4509     sb.append(',').append(' ');
4510     }
4511     }
4512     return sb.append(']').toString();
4513     }
4514    
4515     public final boolean containsAll(Collection<?> c) {
4516     if (c != this) {
4517     for (Object e : c) {
4518     if (e == null || !contains(e))
4519     return false;
4520     }
4521     }
4522     return true;
4523     }
4524    
4525     public final boolean removeAll(Collection<?> c) {
4526     if (c == null) throw new NullPointerException();
4527     boolean modified = false;
4528     for (Iterator<E> it = iterator(); it.hasNext();) {
4529     if (c.contains(it.next())) {
4530     it.remove();
4531     modified = true;
4532     }
4533     }
4534     return modified;
4535     }
4536    
4537     public final boolean retainAll(Collection<?> c) {
4538     if (c == null) throw new NullPointerException();
4539     boolean modified = false;
4540     for (Iterator<E> it = iterator(); it.hasNext();) {
4541     if (!c.contains(it.next())) {
4542     it.remove();
4543     modified = true;
4544     }
4545     }
4546     return modified;
4547     }
4548    
4549     }
4550    
4551     /**
4552     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4553     * which additions may optionally be enabled by mapping to a
4554     * common value. This class cannot be directly instantiated.
4555     * See {@link #keySet() keySet()},
4556     * {@link #keySet(Object) keySet(V)},
4557     * {@link #newKeySet() newKeySet()},
4558     * {@link #newKeySet(int) newKeySet(int)}.
4559     *
4560     * @since 1.8
4561     */
4562     public static class KeySetView<K,V> extends CollectionView<K,V,K>
4563     implements Set<K>, java.io.Serializable {
4564     private static final long serialVersionUID = 7249069246763182397L;
4565     private final V value;
4566     KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4567     super(map);
4568     this.value = value;
4569     }
4570    
4571     /**
4572     * Returns the default mapped value for additions,
4573     * or {@code null} if additions are not supported.
4574     *
4575     * @return the default mapped value for additions, or {@code null}
4576     * if not supported
4577     */
4578     public V getMappedValue() { return value; }
4579    
4580     /**
4581     * {@inheritDoc}
4582     * @throws NullPointerException if the specified key is null
4583     */
4584     public boolean contains(Object o) { return map.containsKey(o); }
4585    
4586     /**
4587     * Removes the key from this map view, by removing the key (and its
4588     * corresponding value) from the backing map. This method does
4589     * nothing if the key is not in the map.
4590     *
4591     * @param o the key to be removed from the backing map
4592     * @return {@code true} if the backing map contained the specified key
4593     * @throws NullPointerException if the specified key is null
4594     */
4595     public boolean remove(Object o) { return map.remove(o) != null; }
4596    
4597     /**
4598     * @return an iterator over the keys of the backing map
4599     */
4600     public Iterator<K> iterator() {
4601     Node<K,V>[] t;
4602     ConcurrentHashMap<K,V> m = map;
4603     int f = (t = m.table) == null ? 0 : t.length;
4604     return new KeyIterator<K,V>(t, f, 0, f, m);
4605     }
4606    
4607     /**
4608     * Adds the specified key to this set view by mapping the key to
4609     * the default mapped value in the backing map, if defined.
4610     *
4611     * @param e key to be added
4612     * @return {@code true} if this set changed as a result of the call
4613     * @throws NullPointerException if the specified key is null
4614     * @throws UnsupportedOperationException if no default mapped value
4615     * for additions was provided
4616     */
4617     public boolean add(K e) {
4618     V v;
4619     if ((v = value) == null)
4620     throw new UnsupportedOperationException();
4621     return map.putVal(e, v, true) == null;
4622     }
4623    
4624     /**
4625     * Adds all of the elements in the specified collection to this set,
4626     * as if by calling {@link #add} on each one.
4627     *
4628     * @param c the elements to be inserted into this set
4629     * @return {@code true} if this set changed as a result of the call
4630     * @throws NullPointerException if the collection or any of its
4631     * elements are {@code null}
4632     * @throws UnsupportedOperationException if no default mapped value
4633     * for additions was provided
4634     */
4635     public boolean addAll(Collection<? extends K> c) {
4636     boolean added = false;
4637     V v;
4638     if ((v = value) == null)
4639     throw new UnsupportedOperationException();
4640     for (K e : c) {
4641     if (map.putVal(e, v, true) == null)
4642     added = true;
4643     }
4644     return added;
4645     }
4646    
4647     public int hashCode() {
4648     int h = 0;
4649     for (K e : this)
4650     h += e.hashCode();
4651     return h;
4652     }
4653    
4654     public boolean equals(Object o) {
4655     Set<?> c;
4656     return ((o instanceof Set) &&
4657     ((c = (Set<?>)o) == this ||
4658     (containsAll(c) && c.containsAll(this))));
4659     }
4660    
4661     public Spliterator<K> spliterator() {
4662     Node<K,V>[] t;
4663     ConcurrentHashMap<K,V> m = map;
4664     long n = m.sumCount();
4665     int f = (t = m.table) == null ? 0 : t.length;
4666     return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4667     }
4668    
4669     public void forEach(Consumer<? super K> action) {
4670     if (action == null) throw new NullPointerException();
4671     Node<K,V>[] t;
4672     if ((t = map.table) != null) {
4673     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4674     for (Node<K,V> p; (p = it.advance()) != null; )
4675     action.accept(p.key);
4676     }
4677     }
4678     }
4679    
4680     /**
4681     * A view of a ConcurrentHashMap as a {@link Collection} of
4682     * values, in which additions are disabled. This class cannot be
4683     * directly instantiated. See {@link #values()}.
4684     */
4685     static final class ValuesView<K,V> extends CollectionView<K,V,V>
4686     implements Collection<V>, java.io.Serializable {
4687     private static final long serialVersionUID = 2249069246763182397L;
4688     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4689     public final boolean contains(Object o) {
4690     return map.containsValue(o);
4691     }
4692    
4693     public final boolean remove(Object o) {
4694     if (o != null) {
4695     for (Iterator<V> it = iterator(); it.hasNext();) {
4696     if (o.equals(it.next())) {
4697     it.remove();
4698     return true;
4699     }
4700     }
4701     }
4702     return false;
4703     }
4704    
4705     public final Iterator<V> iterator() {
4706     ConcurrentHashMap<K,V> m = map;
4707     Node<K,V>[] t;
4708     int f = (t = m.table) == null ? 0 : t.length;
4709     return new ValueIterator<K,V>(t, f, 0, f, m);
4710     }
4711    
4712     public final boolean add(V e) {
4713     throw new UnsupportedOperationException();
4714     }
4715     public final boolean addAll(Collection<? extends V> c) {
4716     throw new UnsupportedOperationException();
4717     }
4718    
4719     public boolean removeIf(Predicate<? super V> filter) {
4720     return map.removeValueIf(filter);
4721     }
4722    
4723     public Spliterator<V> spliterator() {
4724     Node<K,V>[] t;
4725     ConcurrentHashMap<K,V> m = map;
4726     long n = m.sumCount();
4727     int f = (t = m.table) == null ? 0 : t.length;
4728     return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4729     }
4730    
4731     public void forEach(Consumer<? super V> action) {
4732     if (action == null) throw new NullPointerException();
4733     Node<K,V>[] t;
4734     if ((t = map.table) != null) {
4735     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4736     for (Node<K,V> p; (p = it.advance()) != null; )
4737     action.accept(p.val);
4738     }
4739     }
4740     }
4741    
4742     /**
4743     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4744     * entries. This class cannot be directly instantiated. See
4745     * {@link #entrySet()}.
4746     */
4747     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4748     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4749     private static final long serialVersionUID = 2249069246763182397L;
4750     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4751    
4752     public boolean contains(Object o) {
4753     Object k, v, r; Map.Entry<?,?> e;
4754     return ((o instanceof Map.Entry) &&
4755     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4756     (r = map.get(k)) != null &&
4757     (v = e.getValue()) != null &&
4758     (v == r || v.equals(r)));
4759     }
4760    
4761     public boolean remove(Object o) {
4762     Object k, v; Map.Entry<?,?> e;
4763     return ((o instanceof Map.Entry) &&
4764     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4765     (v = e.getValue()) != null &&
4766     map.remove(k, v));
4767     }
4768    
4769     /**
4770     * @return an iterator over the entries of the backing map
4771     */
4772     public Iterator<Map.Entry<K,V>> iterator() {
4773     ConcurrentHashMap<K,V> m = map;
4774     Node<K,V>[] t;
4775     int f = (t = m.table) == null ? 0 : t.length;
4776     return new EntryIterator<K,V>(t, f, 0, f, m);
4777     }
4778    
4779     public boolean add(Entry<K,V> e) {
4780     return map.putVal(e.getKey(), e.getValue(), false) == null;
4781     }
4782    
4783     public boolean addAll(Collection<? extends Entry<K,V>> c) {
4784     boolean added = false;
4785     for (Entry<K,V> e : c) {
4786     if (add(e))
4787     added = true;
4788     }
4789     return added;
4790     }
4791    
4792     public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4793     return map.removeEntryIf(filter);
4794     }
4795    
4796     public final int hashCode() {
4797     int h = 0;
4798     Node<K,V>[] t;
4799     if ((t = map.table) != null) {
4800     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4801     for (Node<K,V> p; (p = it.advance()) != null; ) {
4802     h += p.hashCode();
4803     }
4804     }
4805     return h;
4806     }
4807    
4808     public final boolean equals(Object o) {
4809     Set<?> c;
4810     return ((o instanceof Set) &&
4811     ((c = (Set<?>)o) == this ||
4812     (containsAll(c) && c.containsAll(this))));
4813     }
4814    
4815     public Spliterator<Map.Entry<K,V>> spliterator() {
4816     Node<K,V>[] t;
4817     ConcurrentHashMap<K,V> m = map;
4818     long n = m.sumCount();
4819     int f = (t = m.table) == null ? 0 : t.length;
4820     return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4821     }
4822    
4823     public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4824     if (action == null) throw new NullPointerException();
4825     Node<K,V>[] t;
4826     if ((t = map.table) != null) {
4827     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4828     for (Node<K,V> p; (p = it.advance()) != null; )
4829     action.accept(new MapEntry<K,V>(p.key, p.val, map));
4830     }
4831     }
4832    
4833     }
4834    
4835     // -------------------------------------------------------
4836    
4837     /**
4838     * Base class for bulk tasks. Repeats some fields and code from
4839     * class Traverser, because we need to subclass CountedCompleter.
4840     */
4841     @SuppressWarnings("serial")
4842     abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4843     Node<K,V>[] tab; // same as Traverser
4844     Node<K,V> next;
4845     TableStack<K,V> stack, spare;
4846     int index;
4847     int baseIndex;
4848     int baseLimit;
4849     final int baseSize;
4850     int batch; // split control
4851    
4852     BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4853     super(par);
4854     this.batch = b;
4855     this.index = this.baseIndex = i;
4856     if ((this.tab = t) == null)
4857     this.baseSize = this.baseLimit = 0;
4858     else if (par == null)
4859     this.baseSize = this.baseLimit = t.length;
4860     else {
4861     this.baseLimit = f;
4862     this.baseSize = par.baseSize;
4863     }
4864     }
4865    
4866     /**
4867     * Same as Traverser version.
4868     */
4869     final Node<K,V> advance() {
4870     Node<K,V> e;
4871     if ((e = next) != null)
4872     e = e.next;
4873     for (;;) {
4874     Node<K,V>[] t; int i, n;
4875     if (e != null)
4876     return next = e;
4877     if (baseIndex >= baseLimit || (t = tab) == null ||
4878     (n = t.length) <= (i = index) || i < 0)
4879     return next = null;
4880     if ((e = tabAt(t, i)) != null && e.hash < 0) {
4881     if (e instanceof ForwardingNode) {
4882     tab = ((ForwardingNode<K,V>)e).nextTable;
4883     e = null;
4884     pushState(t, i, n);
4885     continue;
4886     }
4887     else if (e instanceof TreeBin)
4888     e = ((TreeBin<K,V>)e).first;
4889     else
4890     e = null;
4891     }
4892     if (stack != null)
4893     recoverState(n);
4894     else if ((index = i + baseSize) >= n)
4895     index = ++baseIndex;
4896     }
4897     }
4898    
4899     private void pushState(Node<K,V>[] t, int i, int n) {
4900     TableStack<K,V> s = spare;
4901     if (s != null)
4902     spare = s.next;
4903     else
4904     s = new TableStack<K,V>();
4905     s.tab = t;
4906     s.length = n;
4907     s.index = i;
4908     s.next = stack;
4909     stack = s;
4910     }
4911    
4912     private void recoverState(int n) {
4913     TableStack<K,V> s; int len;
4914     while ((s = stack) != null && (index += (len = s.length)) >= n) {
4915     n = len;
4916     index = s.index;
4917     tab = s.tab;
4918     s.tab = null;
4919     TableStack<K,V> next = s.next;
4920     s.next = spare; // save for reuse
4921     stack = next;
4922     spare = s;
4923     }
4924     if (s == null && (index += baseSize) >= n)
4925     index = ++baseIndex;
4926     }
4927     }
4928    
4929     /*
4930     * Task classes. Coded in a regular but ugly format/style to
4931     * simplify checks that each variant differs in the right way from
4932     * others. The null screenings exist because compilers cannot tell
4933     * that we've already null-checked task arguments, so we force
4934     * simplest hoisted bypass to help avoid convoluted traps.
4935     */
4936     @SuppressWarnings("serial")
4937     static final class ForEachKeyTask<K,V>
4938     extends BulkTask<K,V,Void> {
4939     final Consumer<? super K> action;
4940     ForEachKeyTask
4941     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4942     Consumer<? super K> action) {
4943     super(p, b, i, f, t);
4944     this.action = action;
4945     }
4946     public final void compute() {
4947     final Consumer<? super K> action;
4948     if ((action = this.action) != null) {
4949     for (int i = baseIndex, f, h; batch > 0 &&
4950     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4951     addToPendingCount(1);
4952     new ForEachKeyTask<K,V>
4953     (this, batch >>>= 1, baseLimit = h, f, tab,
4954     action).fork();
4955     }
4956     for (Node<K,V> p; (p = advance()) != null;)
4957     action.accept(p.key);
4958     propagateCompletion();
4959     }
4960     }
4961     }
4962    
4963     @SuppressWarnings("serial")
4964     static final class ForEachValueTask<K,V>
4965     extends BulkTask<K,V,Void> {
4966     final Consumer<? super V> action;
4967     ForEachValueTask
4968     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4969     Consumer<? super V> action) {
4970     super(p, b, i, f, t);
4971     this.action = action;
4972     }
4973     public final void compute() {
4974     final Consumer<? super V> action;
4975     if ((action = this.action) != null) {
4976     for (int i = baseIndex, f, h; batch > 0 &&
4977     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4978     addToPendingCount(1);
4979     new ForEachValueTask<K,V>
4980     (this, batch >>>= 1, baseLimit = h, f, tab,
4981     action).fork();
4982     }
4983     for (Node<K,V> p; (p = advance()) != null;)
4984     action.accept(p.val);
4985     propagateCompletion();
4986     }
4987     }
4988     }
4989    
4990     @SuppressWarnings("serial")
4991     static final class ForEachEntryTask<K,V>
4992     extends BulkTask<K,V,Void> {
4993     final Consumer<? super Entry<K,V>> action;
4994     ForEachEntryTask
4995     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4996     Consumer<? super Entry<K,V>> action) {
4997     super(p, b, i, f, t);
4998     this.action = action;
4999     }
5000     public final void compute() {
5001     final Consumer<? super Entry<K,V>> action;
5002     if ((action = this.action) != null) {
5003     for (int i = baseIndex, f, h; batch > 0 &&
5004     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5005     addToPendingCount(1);
5006     new ForEachEntryTask<K,V>
5007     (this, batch >>>= 1, baseLimit = h, f, tab,
5008     action).fork();
5009     }
5010     for (Node<K,V> p; (p = advance()) != null; )
5011     action.accept(p);
5012     propagateCompletion();
5013     }
5014     }
5015     }
5016    
5017     @SuppressWarnings("serial")
5018     static final class ForEachMappingTask<K,V>
5019     extends BulkTask<K,V,Void> {
5020     final BiConsumer<? super K, ? super V> action;
5021     ForEachMappingTask
5022     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5023     BiConsumer<? super K,? super V> action) {
5024     super(p, b, i, f, t);
5025     this.action = action;
5026     }
5027     public final void compute() {
5028     final BiConsumer<? super K, ? super V> action;
5029     if ((action = this.action) != null) {
5030     for (int i = baseIndex, f, h; batch > 0 &&
5031     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5032     addToPendingCount(1);
5033     new ForEachMappingTask<K,V>
5034     (this, batch >>>= 1, baseLimit = h, f, tab,
5035     action).fork();
5036     }
5037     for (Node<K,V> p; (p = advance()) != null; )
5038     action.accept(p.key, p.val);
5039     propagateCompletion();
5040     }
5041     }
5042     }
5043    
5044     @SuppressWarnings("serial")
5045     static final class ForEachTransformedKeyTask<K,V,U>
5046     extends BulkTask<K,V,Void> {
5047     final Function<? super K, ? extends U> transformer;
5048     final Consumer<? super U> action;
5049     ForEachTransformedKeyTask
5050     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5051     Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5052     super(p, b, i, f, t);
5053     this.transformer = transformer; this.action = action;
5054     }
5055     public final void compute() {
5056     final Function<? super K, ? extends U> transformer;
5057     final Consumer<? super U> action;
5058     if ((transformer = this.transformer) != null &&
5059     (action = this.action) != null) {
5060     for (int i = baseIndex, f, h; batch > 0 &&
5061     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5062     addToPendingCount(1);
5063     new ForEachTransformedKeyTask<K,V,U>
5064     (this, batch >>>= 1, baseLimit = h, f, tab,
5065     transformer, action).fork();
5066     }
5067     for (Node<K,V> p; (p = advance()) != null; ) {
5068     U u;
5069     if ((u = transformer.apply(p.key)) != null)
5070     action.accept(u);
5071     }
5072     propagateCompletion();
5073     }
5074     }
5075     }
5076    
5077     @SuppressWarnings("serial")
5078     static final class ForEachTransformedValueTask<K,V,U>
5079     extends BulkTask<K,V,Void> {
5080     final Function<? super V, ? extends U> transformer;
5081     final Consumer<? super U> action;
5082     ForEachTransformedValueTask
5083     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5084     Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5085     super(p, b, i, f, t);
5086     this.transformer = transformer; this.action = action;
5087     }
5088     public final void compute() {
5089     final Function<? super V, ? extends U> transformer;
5090     final Consumer<? super U> action;
5091     if ((transformer = this.transformer) != null &&
5092     (action = this.action) != null) {
5093     for (int i = baseIndex, f, h; batch > 0 &&
5094     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5095     addToPendingCount(1);
5096     new ForEachTransformedValueTask<K,V,U>
5097     (this, batch >>>= 1, baseLimit = h, f, tab,
5098     transformer, action).fork();
5099     }
5100     for (Node<K,V> p; (p = advance()) != null; ) {
5101     U u;
5102     if ((u = transformer.apply(p.val)) != null)
5103     action.accept(u);
5104     }
5105     propagateCompletion();
5106     }
5107     }
5108     }
5109    
5110     @SuppressWarnings("serial")
5111     static final class ForEachTransformedEntryTask<K,V,U>
5112     extends BulkTask<K,V,Void> {
5113     final Function<Map.Entry<K,V>, ? extends U> transformer;
5114     final Consumer<? super U> action;
5115     ForEachTransformedEntryTask
5116     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5117     Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5118     super(p, b, i, f, t);
5119     this.transformer = transformer; this.action = action;
5120     }
5121     public final void compute() {
5122     final Function<Map.Entry<K,V>, ? extends U> transformer;
5123     final Consumer<? super U> action;
5124     if ((transformer = this.transformer) != null &&
5125     (action = this.action) != null) {
5126     for (int i = baseIndex, f, h; batch > 0 &&
5127     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5128     addToPendingCount(1);
5129     new ForEachTransformedEntryTask<K,V,U>
5130     (this, batch >>>= 1, baseLimit = h, f, tab,
5131     transformer, action).fork();
5132     }
5133     for (Node<K,V> p; (p = advance()) != null; ) {
5134     U u;
5135     if ((u = transformer.apply(p)) != null)
5136     action.accept(u);
5137     }
5138     propagateCompletion();
5139     }
5140     }
5141     }
5142    
5143     @SuppressWarnings("serial")
5144     static final class ForEachTransformedMappingTask<K,V,U>
5145     extends BulkTask<K,V,Void> {
5146     final BiFunction<? super K, ? super V, ? extends U> transformer;
5147     final Consumer<? super U> action;
5148     ForEachTransformedMappingTask
5149     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5150     BiFunction<? super K, ? super V, ? extends U> transformer,
5151     Consumer<? super U> action) {
5152     super(p, b, i, f, t);
5153     this.transformer = transformer; this.action = action;
5154     }
5155     public final void compute() {
5156     final BiFunction<? super K, ? super V, ? extends U> transformer;
5157     final Consumer<? super U> action;
5158     if ((transformer = this.transformer) != null &&
5159     (action = this.action) != null) {
5160     for (int i = baseIndex, f, h; batch > 0 &&
5161     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5162     addToPendingCount(1);
5163     new ForEachTransformedMappingTask<K,V,U>
5164     (this, batch >>>= 1, baseLimit = h, f, tab,
5165     transformer, action).fork();
5166     }
5167     for (Node<K,V> p; (p = advance()) != null; ) {
5168     U u;
5169     if ((u = transformer.apply(p.key, p.val)) != null)
5170     action.accept(u);
5171     }
5172     propagateCompletion();
5173     }
5174     }
5175     }
5176    
5177     @SuppressWarnings("serial")
5178     static final class SearchKeysTask<K,V,U>
5179     extends BulkTask<K,V,U> {
5180     final Function<? super K, ? extends U> searchFunction;
5181     final AtomicReference<U> result;
5182     SearchKeysTask
5183     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5184     Function<? super K, ? extends U> searchFunction,
5185     AtomicReference<U> result) {
5186     super(p, b, i, f, t);
5187     this.searchFunction = searchFunction; this.result = result;
5188     }
5189     public final U getRawResult() { return result.get(); }
5190     public final void compute() {
5191     final Function<? super K, ? extends U> searchFunction;
5192     final AtomicReference<U> result;
5193     if ((searchFunction = this.searchFunction) != null &&
5194     (result = this.result) != null) {
5195     for (int i = baseIndex, f, h; batch > 0 &&
5196     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5197     if (result.get() != null)
5198     return;
5199     addToPendingCount(1);
5200     new SearchKeysTask<K,V,U>
5201     (this, batch >>>= 1, baseLimit = h, f, tab,
5202     searchFunction, result).fork();
5203     }
5204     while (result.get() == null) {
5205     U u;
5206     Node<K,V> p;
5207     if ((p = advance()) == null) {
5208     propagateCompletion();
5209     break;
5210     }
5211     if ((u = searchFunction.apply(p.key)) != null) {
5212     if (result.compareAndSet(null, u))
5213     quietlyCompleteRoot();
5214     break;
5215     }
5216     }
5217     }
5218     }
5219     }
5220    
5221     @SuppressWarnings("serial")
5222     static final class SearchValuesTask<K,V,U>
5223     extends BulkTask<K,V,U> {
5224     final Function<? super V, ? extends U> searchFunction;
5225     final AtomicReference<U> result;
5226     SearchValuesTask
5227     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5228     Function<? super V, ? extends U> searchFunction,
5229     AtomicReference<U> result) {
5230     super(p, b, i, f, t);
5231     this.searchFunction = searchFunction; this.result = result;
5232     }
5233     public final U getRawResult() { return result.get(); }
5234     public final void compute() {
5235     final Function<? super V, ? extends U> searchFunction;
5236     final AtomicReference<U> result;
5237     if ((searchFunction = this.searchFunction) != null &&
5238     (result = this.result) != null) {
5239     for (int i = baseIndex, f, h; batch > 0 &&
5240     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5241     if (result.get() != null)
5242     return;
5243     addToPendingCount(1);
5244     new SearchValuesTask<K,V,U>
5245     (this, batch >>>= 1, baseLimit = h, f, tab,
5246     searchFunction, result).fork();
5247     }
5248     while (result.get() == null) {
5249     U u;
5250     Node<K,V> p;
5251     if ((p = advance()) == null) {
5252     propagateCompletion();
5253     break;
5254     }
5255     if ((u = searchFunction.apply(p.val)) != null) {
5256     if (result.compareAndSet(null, u))
5257     quietlyCompleteRoot();
5258     break;
5259     }
5260     }
5261     }
5262     }
5263     }
5264    
5265     @SuppressWarnings("serial")
5266     static final class SearchEntriesTask<K,V,U>
5267     extends BulkTask<K,V,U> {
5268     final Function<Entry<K,V>, ? extends U> searchFunction;
5269     final AtomicReference<U> result;
5270     SearchEntriesTask
5271     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5272     Function<Entry<K,V>, ? extends U> searchFunction,
5273     AtomicReference<U> result) {
5274     super(p, b, i, f, t);
5275     this.searchFunction = searchFunction; this.result = result;
5276     }
5277     public final U getRawResult() { return result.get(); }
5278     public final void compute() {
5279     final Function<Entry<K,V>, ? extends U> searchFunction;
5280     final AtomicReference<U> result;
5281     if ((searchFunction = this.searchFunction) != null &&
5282     (result = this.result) != null) {
5283     for (int i = baseIndex, f, h; batch > 0 &&
5284     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5285     if (result.get() != null)
5286     return;
5287     addToPendingCount(1);
5288     new SearchEntriesTask<K,V,U>
5289     (this, batch >>>= 1, baseLimit = h, f, tab,
5290     searchFunction, result).fork();
5291     }
5292     while (result.get() == null) {
5293     U u;
5294     Node<K,V> p;
5295     if ((p = advance()) == null) {
5296     propagateCompletion();
5297     break;
5298     }
5299     if ((u = searchFunction.apply(p)) != null) {
5300     if (result.compareAndSet(null, u))
5301     quietlyCompleteRoot();
5302     return;
5303     }
5304     }
5305     }
5306     }
5307     }
5308    
5309     @SuppressWarnings("serial")
5310     static final class SearchMappingsTask<K,V,U>
5311     extends BulkTask<K,V,U> {
5312     final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5313     final AtomicReference<U> result;
5314     SearchMappingsTask
5315     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5316     BiFunction<? super K, ? super V, ? extends U> searchFunction,
5317     AtomicReference<U> result) {
5318     super(p, b, i, f, t);
5319     this.searchFunction = searchFunction; this.result = result;
5320     }
5321     public final U getRawResult() { return result.get(); }
5322     public final void compute() {
5323     final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5324     final AtomicReference<U> result;
5325     if ((searchFunction = this.searchFunction) != null &&
5326     (result = this.result) != null) {
5327     for (int i = baseIndex, f, h; batch > 0 &&
5328     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5329     if (result.get() != null)
5330     return;
5331     addToPendingCount(1);
5332     new SearchMappingsTask<K,V,U>
5333     (this, batch >>>= 1, baseLimit = h, f, tab,
5334     searchFunction, result).fork();
5335     }
5336     while (result.get() == null) {
5337     U u;
5338     Node<K,V> p;
5339     if ((p = advance()) == null) {
5340     propagateCompletion();
5341     break;
5342     }
5343     if ((u = searchFunction.apply(p.key, p.val)) != null) {
5344     if (result.compareAndSet(null, u))
5345     quietlyCompleteRoot();
5346     break;
5347     }
5348     }
5349     }
5350     }
5351     }
5352    
5353     @SuppressWarnings("serial")
5354     static final class ReduceKeysTask<K,V>
5355     extends BulkTask<K,V,K> {
5356     final BiFunction<? super K, ? super K, ? extends K> reducer;
5357     K result;
5358     ReduceKeysTask<K,V> rights, nextRight;
5359     ReduceKeysTask
5360     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5361     ReduceKeysTask<K,V> nextRight,
5362     BiFunction<? super K, ? super K, ? extends K> reducer) {
5363     super(p, b, i, f, t); this.nextRight = nextRight;
5364     this.reducer = reducer;
5365     }
5366     public final K getRawResult() { return result; }
5367     public final void compute() {
5368     final BiFunction<? super K, ? super K, ? extends K> reducer;
5369     if ((reducer = this.reducer) != null) {
5370     for (int i = baseIndex, f, h; batch > 0 &&
5371     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5372     addToPendingCount(1);
5373     (rights = new ReduceKeysTask<K,V>
5374     (this, batch >>>= 1, baseLimit = h, f, tab,
5375     rights, reducer)).fork();
5376     }
5377     K r = null;
5378     for (Node<K,V> p; (p = advance()) != null; ) {
5379     K u = p.key;
5380     r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5381     }
5382     result = r;
5383     CountedCompleter<?> c;
5384     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5385     @SuppressWarnings("unchecked")
5386     ReduceKeysTask<K,V>
5387     t = (ReduceKeysTask<K,V>)c,
5388     s = t.rights;
5389     while (s != null) {
5390     K tr, sr;
5391     if ((sr = s.result) != null)
5392     t.result = (((tr = t.result) == null) ? sr :
5393     reducer.apply(tr, sr));
5394     s = t.rights = s.nextRight;
5395     }
5396     }
5397     }
5398     }
5399     }
5400    
5401     @SuppressWarnings("serial")
5402     static final class ReduceValuesTask<K,V>
5403     extends BulkTask<K,V,V> {
5404     final BiFunction<? super V, ? super V, ? extends V> reducer;
5405     V result;
5406     ReduceValuesTask<K,V> rights, nextRight;
5407     ReduceValuesTask
5408     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5409     ReduceValuesTask<K,V> nextRight,
5410     BiFunction<? super V, ? super V, ? extends V> reducer) {
5411     super(p, b, i, f, t); this.nextRight = nextRight;
5412     this.reducer = reducer;
5413     }
5414     public final V getRawResult() { return result; }
5415     public final void compute() {
5416     final BiFunction<? super V, ? super V, ? extends V> reducer;
5417     if ((reducer = this.reducer) != null) {
5418     for (int i = baseIndex, f, h; batch > 0 &&
5419     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5420     addToPendingCount(1);
5421     (rights = new ReduceValuesTask<K,V>
5422     (this, batch >>>= 1, baseLimit = h, f, tab,
5423     rights, reducer)).fork();
5424     }
5425     V r = null;
5426     for (Node<K,V> p; (p = advance()) != null; ) {
5427     V v = p.val;
5428     r = (r == null) ? v : reducer.apply(r, v);
5429     }
5430     result = r;
5431     CountedCompleter<?> c;
5432     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5433     @SuppressWarnings("unchecked")
5434     ReduceValuesTask<K,V>
5435     t = (ReduceValuesTask<K,V>)c,
5436     s = t.rights;
5437     while (s != null) {
5438     V tr, sr;
5439     if ((sr = s.result) != null)
5440     t.result = (((tr = t.result) == null) ? sr :
5441     reducer.apply(tr, sr));
5442     s = t.rights = s.nextRight;
5443     }
5444     }
5445     }
5446     }
5447     }
5448    
5449     @SuppressWarnings("serial")
5450     static final class ReduceEntriesTask<K,V>
5451     extends BulkTask<K,V,Map.Entry<K,V>> {
5452     final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5453     Map.Entry<K,V> result;
5454     ReduceEntriesTask<K,V> rights, nextRight;
5455     ReduceEntriesTask
5456     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5457     ReduceEntriesTask<K,V> nextRight,
5458     BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5459     super(p, b, i, f, t); this.nextRight = nextRight;
5460     this.reducer = reducer;
5461     }
5462     public final Map.Entry<K,V> getRawResult() { return result; }
5463     public final void compute() {
5464     final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5465     if ((reducer = this.reducer) != null) {
5466     for (int i = baseIndex, f, h; batch > 0 &&
5467     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5468     addToPendingCount(1);
5469     (rights = new ReduceEntriesTask<K,V>
5470     (this, batch >>>= 1, baseLimit = h, f, tab,
5471     rights, reducer)).fork();
5472     }
5473     Map.Entry<K,V> r = null;
5474     for (Node<K,V> p; (p = advance()) != null; )
5475     r = (r == null) ? p : reducer.apply(r, p);
5476     result = r;
5477     CountedCompleter<?> c;
5478     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5479     @SuppressWarnings("unchecked")
5480     ReduceEntriesTask<K,V>
5481     t = (ReduceEntriesTask<K,V>)c,
5482     s = t.rights;
5483     while (s != null) {
5484     Map.Entry<K,V> tr, sr;
5485     if ((sr = s.result) != null)
5486     t.result = (((tr = t.result) == null) ? sr :
5487     reducer.apply(tr, sr));
5488     s = t.rights = s.nextRight;
5489     }
5490     }
5491     }
5492     }
5493     }
5494    
5495     @SuppressWarnings("serial")
5496     static final class MapReduceKeysTask<K,V,U>
5497     extends BulkTask<K,V,U> {
5498     final Function<? super K, ? extends U> transformer;
5499     final BiFunction<? super U, ? super U, ? extends U> reducer;
5500     U result;
5501     MapReduceKeysTask<K,V,U> rights, nextRight;
5502     MapReduceKeysTask
5503     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5504     MapReduceKeysTask<K,V,U> nextRight,
5505     Function<? super K, ? extends U> transformer,
5506     BiFunction<? super U, ? super U, ? extends U> reducer) {
5507     super(p, b, i, f, t); this.nextRight = nextRight;
5508     this.transformer = transformer;
5509     this.reducer = reducer;
5510     }
5511     public final U getRawResult() { return result; }
5512     public final void compute() {
5513     final Function<? super K, ? extends U> transformer;
5514     final BiFunction<? super U, ? super U, ? extends U> reducer;
5515     if ((transformer = this.transformer) != null &&
5516     (reducer = this.reducer) != null) {
5517     for (int i = baseIndex, f, h; batch > 0 &&
5518     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5519     addToPendingCount(1);
5520     (rights = new MapReduceKeysTask<K,V,U>
5521     (this, batch >>>= 1, baseLimit = h, f, tab,
5522     rights, transformer, reducer)).fork();
5523     }
5524     U r = null;
5525     for (Node<K,V> p; (p = advance()) != null; ) {
5526     U u;
5527     if ((u = transformer.apply(p.key)) != null)
5528     r = (r == null) ? u : reducer.apply(r, u);
5529     }
5530     result = r;
5531     CountedCompleter<?> c;
5532     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5533     @SuppressWarnings("unchecked")
5534     MapReduceKeysTask<K,V,U>
5535     t = (MapReduceKeysTask<K,V,U>)c,
5536     s = t.rights;
5537     while (s != null) {
5538     U tr, sr;
5539     if ((sr = s.result) != null)
5540     t.result = (((tr = t.result) == null) ? sr :
5541     reducer.apply(tr, sr));
5542     s = t.rights = s.nextRight;
5543     }
5544     }
5545     }
5546     }
5547     }
5548    
5549     @SuppressWarnings("serial")
5550     static final class MapReduceValuesTask<K,V,U>
5551     extends BulkTask<K,V,U> {
5552     final Function<? super V, ? extends U> transformer;
5553     final BiFunction<? super U, ? super U, ? extends U> reducer;
5554     U result;
5555     MapReduceValuesTask<K,V,U> rights, nextRight;
5556     MapReduceValuesTask
5557     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5558     MapReduceValuesTask<K,V,U> nextRight,
5559     Function<? super V, ? extends U> transformer,
5560     BiFunction<? super U, ? super U, ? extends U> reducer) {
5561     super(p, b, i, f, t); this.nextRight = nextRight;
5562     this.transformer = transformer;
5563     this.reducer = reducer;
5564     }
5565     public final U getRawResult() { return result; }
5566     public final void compute() {
5567     final Function<? super V, ? extends U> transformer;
5568     final BiFunction<? super U, ? super U, ? extends U> reducer;
5569     if ((transformer = this.transformer) != null &&
5570     (reducer = this.reducer) != null) {
5571     for (int i = baseIndex, f, h; batch > 0 &&
5572     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5573     addToPendingCount(1);
5574     (rights = new MapReduceValuesTask<K,V,U>
5575     (this, batch >>>= 1, baseLimit = h, f, tab,
5576     rights, transformer, reducer)).fork();
5577     }
5578     U r = null;
5579     for (Node<K,V> p; (p = advance()) != null; ) {
5580     U u;
5581     if ((u = transformer.apply(p.val)) != null)
5582     r = (r == null) ? u : reducer.apply(r, u);
5583     }
5584     result = r;
5585     CountedCompleter<?> c;
5586     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5587     @SuppressWarnings("unchecked")
5588     MapReduceValuesTask<K,V,U>
5589     t = (MapReduceValuesTask<K,V,U>)c,
5590     s = t.rights;
5591     while (s != null) {
5592     U tr, sr;
5593     if ((sr = s.result) != null)
5594     t.result = (((tr = t.result) == null) ? sr :
5595     reducer.apply(tr, sr));
5596     s = t.rights = s.nextRight;
5597     }
5598     }
5599     }
5600     }
5601     }
5602    
5603     @SuppressWarnings("serial")
5604     static final class MapReduceEntriesTask<K,V,U>
5605     extends BulkTask<K,V,U> {
5606     final Function<Map.Entry<K,V>, ? extends U> transformer;
5607     final BiFunction<? super U, ? super U, ? extends U> reducer;
5608     U result;
5609     MapReduceEntriesTask<K,V,U> rights, nextRight;
5610     MapReduceEntriesTask
5611     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5612     MapReduceEntriesTask<K,V,U> nextRight,
5613     Function<Map.Entry<K,V>, ? extends U> transformer,
5614     BiFunction<? super U, ? super U, ? extends U> reducer) {
5615     super(p, b, i, f, t); this.nextRight = nextRight;
5616     this.transformer = transformer;
5617     this.reducer = reducer;
5618     }
5619     public final U getRawResult() { return result; }
5620     public final void compute() {
5621     final Function<Map.Entry<K,V>, ? extends U> transformer;
5622     final BiFunction<? super U, ? super U, ? extends U> reducer;
5623     if ((transformer = this.transformer) != null &&
5624     (reducer = this.reducer) != null) {
5625     for (int i = baseIndex, f, h; batch > 0 &&
5626     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5627     addToPendingCount(1);
5628     (rights = new MapReduceEntriesTask<K,V,U>
5629     (this, batch >>>= 1, baseLimit = h, f, tab,
5630     rights, transformer, reducer)).fork();
5631     }
5632     U r = null;
5633     for (Node<K,V> p; (p = advance()) != null; ) {
5634     U u;
5635     if ((u = transformer.apply(p)) != null)
5636     r = (r == null) ? u : reducer.apply(r, u);
5637     }
5638     result = r;
5639     CountedCompleter<?> c;
5640     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5641     @SuppressWarnings("unchecked")
5642     MapReduceEntriesTask<K,V,U>
5643     t = (MapReduceEntriesTask<K,V,U>)c,
5644     s = t.rights;
5645     while (s != null) {
5646     U tr, sr;
5647     if ((sr = s.result) != null)
5648     t.result = (((tr = t.result) == null) ? sr :
5649     reducer.apply(tr, sr));
5650     s = t.rights = s.nextRight;
5651     }
5652     }
5653     }
5654     }
5655     }
5656    
5657     @SuppressWarnings("serial")
5658     static final class MapReduceMappingsTask<K,V,U>
5659     extends BulkTask<K,V,U> {
5660     final BiFunction<? super K, ? super V, ? extends U> transformer;
5661     final BiFunction<? super U, ? super U, ? extends U> reducer;
5662     U result;
5663     MapReduceMappingsTask<K,V,U> rights, nextRight;
5664     MapReduceMappingsTask
5665     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5666     MapReduceMappingsTask<K,V,U> nextRight,
5667     BiFunction<? super K, ? super V, ? extends U> transformer,
5668     BiFunction<? super U, ? super U, ? extends U> reducer) {
5669     super(p, b, i, f, t); this.nextRight = nextRight;
5670     this.transformer = transformer;
5671     this.reducer = reducer;
5672     }
5673     public final U getRawResult() { return result; }
5674     public final void compute() {
5675     final BiFunction<? super K, ? super V, ? extends U> transformer;
5676     final BiFunction<? super U, ? super U, ? extends U> reducer;
5677     if ((transformer = this.transformer) != null &&
5678     (reducer = this.reducer) != null) {
5679     for (int i = baseIndex, f, h; batch > 0 &&
5680     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5681     addToPendingCount(1);
5682     (rights = new MapReduceMappingsTask<K,V,U>
5683     (this, batch >>>= 1, baseLimit = h, f, tab,
5684     rights, transformer, reducer)).fork();
5685     }
5686     U r = null;
5687     for (Node<K,V> p; (p = advance()) != null; ) {
5688     U u;
5689     if ((u = transformer.apply(p.key, p.val)) != null)
5690     r = (r == null) ? u : reducer.apply(r, u);
5691     }
5692     result = r;
5693     CountedCompleter<?> c;
5694     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5695     @SuppressWarnings("unchecked")
5696     MapReduceMappingsTask<K,V,U>
5697     t = (MapReduceMappingsTask<K,V,U>)c,
5698     s = t.rights;
5699     while (s != null) {
5700     U tr, sr;
5701     if ((sr = s.result) != null)
5702     t.result = (((tr = t.result) == null) ? sr :
5703     reducer.apply(tr, sr));
5704     s = t.rights = s.nextRight;
5705     }
5706     }
5707     }
5708     }
5709     }
5710    
5711     @SuppressWarnings("serial")
5712     static final class MapReduceKeysToDoubleTask<K,V>
5713     extends BulkTask<K,V,Double> {
5714     final ToDoubleFunction<? super K> transformer;
5715     final DoubleBinaryOperator reducer;
5716     final double basis;
5717     double result;
5718     MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5719     MapReduceKeysToDoubleTask
5720     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5721     MapReduceKeysToDoubleTask<K,V> nextRight,
5722     ToDoubleFunction<? super K> transformer,
5723     double basis,
5724     DoubleBinaryOperator reducer) {
5725     super(p, b, i, f, t); this.nextRight = nextRight;
5726     this.transformer = transformer;
5727     this.basis = basis; this.reducer = reducer;
5728     }
5729     public final Double getRawResult() { return result; }
5730     public final void compute() {
5731     final ToDoubleFunction<? super K> transformer;
5732     final DoubleBinaryOperator reducer;
5733     if ((transformer = this.transformer) != null &&
5734     (reducer = this.reducer) != null) {
5735     double r = this.basis;
5736     for (int i = baseIndex, f, h; batch > 0 &&
5737     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5738     addToPendingCount(1);
5739     (rights = new MapReduceKeysToDoubleTask<K,V>
5740     (this, batch >>>= 1, baseLimit = h, f, tab,
5741     rights, transformer, r, reducer)).fork();
5742     }
5743     for (Node<K,V> p; (p = advance()) != null; )
5744     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5745     result = r;
5746     CountedCompleter<?> c;
5747     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5748     @SuppressWarnings("unchecked")
5749     MapReduceKeysToDoubleTask<K,V>
5750     t = (MapReduceKeysToDoubleTask<K,V>)c,
5751     s = t.rights;
5752     while (s != null) {
5753     t.result = reducer.applyAsDouble(t.result, s.result);
5754     s = t.rights = s.nextRight;
5755     }
5756     }
5757     }
5758     }
5759     }
5760    
5761     @SuppressWarnings("serial")
5762     static final class MapReduceValuesToDoubleTask<K,V>
5763     extends BulkTask<K,V,Double> {
5764     final ToDoubleFunction<? super V> transformer;
5765     final DoubleBinaryOperator reducer;
5766     final double basis;
5767     double result;
5768     MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5769     MapReduceValuesToDoubleTask
5770     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5771     MapReduceValuesToDoubleTask<K,V> nextRight,
5772     ToDoubleFunction<? super V> transformer,
5773     double basis,
5774     DoubleBinaryOperator reducer) {
5775     super(p, b, i, f, t); this.nextRight = nextRight;
5776     this.transformer = transformer;
5777     this.basis = basis; this.reducer = reducer;
5778     }
5779     public final Double getRawResult() { return result; }
5780     public final void compute() {
5781     final ToDoubleFunction<? super V> transformer;
5782     final DoubleBinaryOperator reducer;
5783     if ((transformer = this.transformer) != null &&
5784     (reducer = this.reducer) != null) {
5785     double r = this.basis;
5786     for (int i = baseIndex, f, h; batch > 0 &&
5787     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5788     addToPendingCount(1);
5789     (rights = new MapReduceValuesToDoubleTask<K,V>
5790     (this, batch >>>= 1, baseLimit = h, f, tab,
5791     rights, transformer, r, reducer)).fork();
5792     }
5793     for (Node<K,V> p; (p = advance()) != null; )
5794     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5795     result = r;
5796     CountedCompleter<?> c;
5797     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5798     @SuppressWarnings("unchecked")
5799     MapReduceValuesToDoubleTask<K,V>
5800     t = (MapReduceValuesToDoubleTask<K,V>)c,
5801     s = t.rights;
5802     while (s != null) {
5803     t.result = reducer.applyAsDouble(t.result, s.result);
5804     s = t.rights = s.nextRight;
5805     }
5806     }
5807     }
5808     }
5809     }
5810    
5811     @SuppressWarnings("serial")
5812     static final class MapReduceEntriesToDoubleTask<K,V>
5813     extends BulkTask<K,V,Double> {
5814     final ToDoubleFunction<Map.Entry<K,V>> transformer;
5815     final DoubleBinaryOperator reducer;
5816     final double basis;
5817     double result;
5818     MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5819     MapReduceEntriesToDoubleTask
5820     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5821     MapReduceEntriesToDoubleTask<K,V> nextRight,
5822     ToDoubleFunction<Map.Entry<K,V>> transformer,
5823     double basis,
5824     DoubleBinaryOperator reducer) {
5825     super(p, b, i, f, t); this.nextRight = nextRight;
5826     this.transformer = transformer;
5827     this.basis = basis; this.reducer = reducer;
5828     }
5829     public final Double getRawResult() { return result; }
5830     public final void compute() {
5831     final ToDoubleFunction<Map.Entry<K,V>> transformer;
5832     final DoubleBinaryOperator reducer;
5833     if ((transformer = this.transformer) != null &&
5834     (reducer = this.reducer) != null) {
5835     double r = this.basis;
5836     for (int i = baseIndex, f, h; batch > 0 &&
5837     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5838     addToPendingCount(1);
5839     (rights = new MapReduceEntriesToDoubleTask<K,V>
5840     (this, batch >>>= 1, baseLimit = h, f, tab,
5841     rights, transformer, r, reducer)).fork();
5842     }
5843     for (Node<K,V> p; (p = advance()) != null; )
5844     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5845     result = r;
5846     CountedCompleter<?> c;
5847     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5848     @SuppressWarnings("unchecked")
5849     MapReduceEntriesToDoubleTask<K,V>
5850     t = (MapReduceEntriesToDoubleTask<K,V>)c,
5851     s = t.rights;
5852     while (s != null) {
5853     t.result = reducer.applyAsDouble(t.result, s.result);
5854     s = t.rights = s.nextRight;
5855     }
5856     }
5857     }
5858     }
5859     }
5860    
5861     @SuppressWarnings("serial")
5862     static final class MapReduceMappingsToDoubleTask<K,V>
5863     extends BulkTask<K,V,Double> {
5864     final ToDoubleBiFunction<? super K, ? super V> transformer;
5865     final DoubleBinaryOperator reducer;
5866     final double basis;
5867     double result;
5868     MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5869     MapReduceMappingsToDoubleTask
5870     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5871     MapReduceMappingsToDoubleTask<K,V> nextRight,
5872     ToDoubleBiFunction<? super K, ? super V> transformer,
5873     double basis,
5874     DoubleBinaryOperator reducer) {
5875     super(p, b, i, f, t); this.nextRight = nextRight;
5876     this.transformer = transformer;
5877     this.basis = basis; this.reducer = reducer;
5878     }
5879     public final Double getRawResult() { return result; }
5880     public final void compute() {
5881     final ToDoubleBiFunction<? super K, ? super V> transformer;
5882     final DoubleBinaryOperator reducer;
5883     if ((transformer = this.transformer) != null &&
5884     (reducer = this.reducer) != null) {
5885     double r = this.basis;
5886     for (int i = baseIndex, f, h; batch > 0 &&
5887     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5888     addToPendingCount(1);
5889     (rights = new MapReduceMappingsToDoubleTask<K,V>
5890     (this, batch >>>= 1, baseLimit = h, f, tab,
5891     rights, transformer, r, reducer)).fork();
5892     }
5893     for (Node<K,V> p; (p = advance()) != null; )
5894     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5895     result = r;
5896     CountedCompleter<?> c;
5897     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5898     @SuppressWarnings("unchecked")
5899     MapReduceMappingsToDoubleTask<K,V>
5900     t = (MapReduceMappingsToDoubleTask<K,V>)c,
5901     s = t.rights;
5902     while (s != null) {
5903     t.result = reducer.applyAsDouble(t.result, s.result);
5904     s = t.rights = s.nextRight;
5905     }
5906     }
5907     }
5908     }
5909     }
5910    
5911     @SuppressWarnings("serial")
5912     static final class MapReduceKeysToLongTask<K,V>
5913     extends BulkTask<K,V,Long> {
5914     final ToLongFunction<? super K> transformer;
5915     final LongBinaryOperator reducer;
5916     final long basis;
5917     long result;
5918     MapReduceKeysToLongTask<K,V> rights, nextRight;
5919     MapReduceKeysToLongTask
5920     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5921     MapReduceKeysToLongTask<K,V> nextRight,
5922     ToLongFunction<? super K> transformer,
5923     long basis,
5924     LongBinaryOperator reducer) {
5925     super(p, b, i, f, t); this.nextRight = nextRight;
5926     this.transformer = transformer;
5927     this.basis = basis; this.reducer = reducer;
5928     }
5929     public final Long getRawResult() { return result; }
5930     public final void compute() {
5931     final ToLongFunction<? super K> transformer;
5932     final LongBinaryOperator reducer;
5933     if ((transformer = this.transformer) != null &&
5934     (reducer = this.reducer) != null) {
5935     long r = this.basis;
5936     for (int i = baseIndex, f, h; batch > 0 &&
5937     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5938     addToPendingCount(1);
5939     (rights = new MapReduceKeysToLongTask<K,V>
5940     (this, batch >>>= 1, baseLimit = h, f, tab,
5941     rights, transformer, r, reducer)).fork();
5942     }
5943     for (Node<K,V> p; (p = advance()) != null; )
5944     r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5945     result = r;
5946     CountedCompleter<?> c;
5947     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5948     @SuppressWarnings("unchecked")
5949     MapReduceKeysToLongTask<K,V>
5950     t = (MapReduceKeysToLongTask<K,V>)c,
5951     s = t.rights;
5952     while (s != null) {
5953     t.result = reducer.applyAsLong(t.result, s.result);
5954     s = t.rights = s.nextRight;
5955     }
5956     }
5957     }
5958     }
5959     }
5960    
5961     @SuppressWarnings("serial")
5962     static final class MapReduceValuesToLongTask<K,V>
5963     extends BulkTask<K,V,Long> {
5964     final ToLongFunction<? super V> transformer;
5965     final LongBinaryOperator reducer;
5966     final long basis;
5967     long result;
5968     MapReduceValuesToLongTask<K,V> rights, nextRight;
5969     MapReduceValuesToLongTask
5970     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5971     MapReduceValuesToLongTask<K,V> nextRight,
5972     ToLongFunction<? super V> transformer,
5973     long basis,
5974     LongBinaryOperator reducer) {
5975     super(p, b, i, f, t); this.nextRight = nextRight;
5976     this.transformer = transformer;
5977     this.basis = basis; this.reducer = reducer;
5978     }
5979     public final Long getRawResult() { return result; }
5980     public final void compute() {
5981     final ToLongFunction<? super V> transformer;
5982     final LongBinaryOperator reducer;
5983     if ((transformer = this.transformer) != null &&
5984     (reducer = this.reducer) != null) {
5985     long r = this.basis;
5986     for (int i = baseIndex, f, h; batch > 0 &&
5987     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5988     addToPendingCount(1);
5989     (rights = new MapReduceValuesToLongTask<K,V>
5990     (this, batch >>>= 1, baseLimit = h, f, tab,
5991     rights, transformer, r, reducer)).fork();
5992     }
5993     for (Node<K,V> p; (p = advance()) != null; )
5994     r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5995     result = r;
5996     CountedCompleter<?> c;
5997     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5998     @SuppressWarnings("unchecked")
5999     MapReduceValuesToLongTask<K,V>
6000     t = (MapReduceValuesToLongTask<K,V>)c,
6001     s = t.rights;
6002     while (s != null) {
6003     t.result = reducer.applyAsLong(t.result, s.result);
6004     s = t.rights = s.nextRight;
6005     }
6006     }
6007     }
6008     }
6009     }
6010    
6011     @SuppressWarnings("serial")
6012     static final class MapReduceEntriesToLongTask<K,V>
6013     extends BulkTask<K,V,Long> {
6014     final ToLongFunction<Map.Entry<K,V>> transformer;
6015     final LongBinaryOperator reducer;
6016     final long basis;
6017     long result;
6018     MapReduceEntriesToLongTask<K,V> rights, nextRight;
6019     MapReduceEntriesToLongTask
6020     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6021     MapReduceEntriesToLongTask<K,V> nextRight,
6022     ToLongFunction<Map.Entry<K,V>> transformer,
6023     long basis,
6024     LongBinaryOperator reducer) {
6025     super(p, b, i, f, t); this.nextRight = nextRight;
6026     this.transformer = transformer;
6027     this.basis = basis; this.reducer = reducer;
6028     }
6029     public final Long getRawResult() { return result; }
6030     public final void compute() {
6031     final ToLongFunction<Map.Entry<K,V>> transformer;
6032     final LongBinaryOperator reducer;
6033     if ((transformer = this.transformer) != null &&
6034     (reducer = this.reducer) != null) {
6035     long r = this.basis;
6036     for (int i = baseIndex, f, h; batch > 0 &&
6037     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6038     addToPendingCount(1);
6039     (rights = new MapReduceEntriesToLongTask<K,V>
6040     (this, batch >>>= 1, baseLimit = h, f, tab,
6041     rights, transformer, r, reducer)).fork();
6042     }
6043     for (Node<K,V> p; (p = advance()) != null; )
6044     r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6045     result = r;
6046     CountedCompleter<?> c;
6047     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6048     @SuppressWarnings("unchecked")
6049     MapReduceEntriesToLongTask<K,V>
6050     t = (MapReduceEntriesToLongTask<K,V>)c,
6051     s = t.rights;
6052     while (s != null) {
6053     t.result = reducer.applyAsLong(t.result, s.result);
6054     s = t.rights = s.nextRight;
6055     }
6056     }
6057     }
6058     }
6059     }
6060    
6061     @SuppressWarnings("serial")
6062     static final class MapReduceMappingsToLongTask<K,V>
6063     extends BulkTask<K,V,Long> {
6064     final ToLongBiFunction<? super K, ? super V> transformer;
6065     final LongBinaryOperator reducer;
6066     final long basis;
6067     long result;
6068     MapReduceMappingsToLongTask<K,V> rights, nextRight;
6069     MapReduceMappingsToLongTask
6070     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6071     MapReduceMappingsToLongTask<K,V> nextRight,
6072     ToLongBiFunction<? super K, ? super V> transformer,
6073     long basis,
6074     LongBinaryOperator reducer) {
6075     super(p, b, i, f, t); this.nextRight = nextRight;
6076     this.transformer = transformer;
6077     this.basis = basis; this.reducer = reducer;
6078     }
6079     public final Long getRawResult() { return result; }
6080     public final void compute() {
6081     final ToLongBiFunction<? super K, ? super V> transformer;
6082     final LongBinaryOperator reducer;
6083     if ((transformer = this.transformer) != null &&
6084     (reducer = this.reducer) != null) {
6085     long r = this.basis;
6086     for (int i = baseIndex, f, h; batch > 0 &&
6087     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6088     addToPendingCount(1);
6089     (rights = new MapReduceMappingsToLongTask<K,V>
6090     (this, batch >>>= 1, baseLimit = h, f, tab,
6091     rights, transformer, r, reducer)).fork();
6092     }
6093     for (Node<K,V> p; (p = advance()) != null; )
6094     r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6095     result = r;
6096     CountedCompleter<?> c;
6097     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6098     @SuppressWarnings("unchecked")
6099     MapReduceMappingsToLongTask<K,V>
6100     t = (MapReduceMappingsToLongTask<K,V>)c,
6101     s = t.rights;
6102     while (s != null) {
6103     t.result = reducer.applyAsLong(t.result, s.result);
6104     s = t.rights = s.nextRight;
6105     }
6106     }
6107     }
6108     }
6109     }
6110    
6111     @SuppressWarnings("serial")
6112     static final class MapReduceKeysToIntTask<K,V>
6113     extends BulkTask<K,V,Integer> {
6114     final ToIntFunction<? super K> transformer;
6115     final IntBinaryOperator reducer;
6116     final int basis;
6117     int result;
6118     MapReduceKeysToIntTask<K,V> rights, nextRight;
6119     MapReduceKeysToIntTask
6120     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6121     MapReduceKeysToIntTask<K,V> nextRight,
6122     ToIntFunction<? super K> transformer,
6123     int basis,
6124     IntBinaryOperator reducer) {
6125     super(p, b, i, f, t); this.nextRight = nextRight;
6126     this.transformer = transformer;
6127     this.basis = basis; this.reducer = reducer;
6128     }
6129     public final Integer getRawResult() { return result; }
6130     public final void compute() {
6131     final ToIntFunction<? super K> transformer;
6132     final IntBinaryOperator reducer;
6133     if ((transformer = this.transformer) != null &&
6134     (reducer = this.reducer) != null) {
6135     int r = this.basis;
6136     for (int i = baseIndex, f, h; batch > 0 &&
6137     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6138     addToPendingCount(1);
6139     (rights = new MapReduceKeysToIntTask<K,V>
6140     (this, batch >>>= 1, baseLimit = h, f, tab,
6141     rights, transformer, r, reducer)).fork();
6142     }
6143     for (Node<K,V> p; (p = advance()) != null; )
6144     r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6145     result = r;
6146     CountedCompleter<?> c;
6147     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6148     @SuppressWarnings("unchecked")
6149     MapReduceKeysToIntTask<K,V>
6150     t = (MapReduceKeysToIntTask<K,V>)c,
6151     s = t.rights;
6152     while (s != null) {
6153     t.result = reducer.applyAsInt(t.result, s.result);
6154     s = t.rights = s.nextRight;
6155     }
6156     }
6157     }
6158     }
6159     }
6160    
6161     @SuppressWarnings("serial")
6162     static final class MapReduceValuesToIntTask<K,V>
6163     extends BulkTask<K,V,Integer> {
6164     final ToIntFunction<? super V> transformer;
6165     final IntBinaryOperator reducer;
6166     final int basis;
6167     int result;
6168     MapReduceValuesToIntTask<K,V> rights, nextRight;
6169     MapReduceValuesToIntTask
6170     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6171     MapReduceValuesToIntTask<K,V> nextRight,
6172     ToIntFunction<? super V> transformer,
6173     int basis,
6174     IntBinaryOperator reducer) {
6175     super(p, b, i, f, t); this.nextRight = nextRight;
6176     this.transformer = transformer;
6177     this.basis = basis; this.reducer = reducer;
6178     }
6179     public final Integer getRawResult() { return result; }
6180     public final void compute() {
6181     final ToIntFunction<? super V> transformer;
6182     final IntBinaryOperator reducer;
6183     if ((transformer = this.transformer) != null &&
6184     (reducer = this.reducer) != null) {
6185     int r = this.basis;
6186     for (int i = baseIndex, f, h; batch > 0 &&
6187     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6188     addToPendingCount(1);
6189     (rights = new MapReduceValuesToIntTask<K,V>
6190     (this, batch >>>= 1, baseLimit = h, f, tab,
6191     rights, transformer, r, reducer)).fork();
6192     }
6193     for (Node<K,V> p; (p = advance()) != null; )
6194     r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6195     result = r;
6196     CountedCompleter<?> c;
6197     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6198     @SuppressWarnings("unchecked")
6199     MapReduceValuesToIntTask<K,V>
6200     t = (MapReduceValuesToIntTask<K,V>)c,
6201     s = t.rights;
6202     while (s != null) {
6203     t.result = reducer.applyAsInt(t.result, s.result);
6204     s = t.rights = s.nextRight;
6205     }
6206     }
6207     }
6208     }
6209     }
6210    
6211     @SuppressWarnings("serial")
6212     static final class MapReduceEntriesToIntTask<K,V>
6213     extends BulkTask<K,V,Integer> {
6214     final ToIntFunction<Map.Entry<K,V>> transformer;
6215     final IntBinaryOperator reducer;
6216     final int basis;
6217     int result;
6218     MapReduceEntriesToIntTask<K,V> rights, nextRight;
6219     MapReduceEntriesToIntTask
6220     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6221     MapReduceEntriesToIntTask<K,V> nextRight,
6222     ToIntFunction<Map.Entry<K,V>> transformer,
6223     int basis,
6224     IntBinaryOperator reducer) {
6225     super(p, b, i, f, t); this.nextRight = nextRight;
6226     this.transformer = transformer;
6227     this.basis = basis; this.reducer = reducer;
6228     }
6229     public final Integer getRawResult() { return result; }
6230     public final void compute() {
6231     final ToIntFunction<Map.Entry<K,V>> transformer;
6232     final IntBinaryOperator reducer;
6233     if ((transformer = this.transformer) != null &&
6234     (reducer = this.reducer) != null) {
6235     int r = this.basis;
6236     for (int i = baseIndex, f, h; batch > 0 &&
6237     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6238     addToPendingCount(1);
6239     (rights = new MapReduceEntriesToIntTask<K,V>
6240     (this, batch >>>= 1, baseLimit = h, f, tab,
6241     rights, transformer, r, reducer)).fork();
6242     }
6243     for (Node<K,V> p; (p = advance()) != null; )
6244     r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6245     result = r;
6246     CountedCompleter<?> c;
6247     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6248     @SuppressWarnings("unchecked")
6249     MapReduceEntriesToIntTask<K,V>
6250     t = (MapReduceEntriesToIntTask<K,V>)c,
6251     s = t.rights;
6252     while (s != null) {
6253     t.result = reducer.applyAsInt(t.result, s.result);
6254     s = t.rights = s.nextRight;
6255     }
6256     }
6257     }
6258     }
6259     }
6260    
6261     @SuppressWarnings("serial")
6262     static final class MapReduceMappingsToIntTask<K,V>
6263     extends BulkTask<K,V,Integer> {
6264     final ToIntBiFunction<? super K, ? super V> transformer;
6265     final IntBinaryOperator reducer;
6266     final int basis;
6267     int result;
6268     MapReduceMappingsToIntTask<K,V> rights, nextRight;
6269     MapReduceMappingsToIntTask
6270     (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6271     MapReduceMappingsToIntTask<K,V> nextRight,
6272     ToIntBiFunction<? super K, ? super V> transformer,
6273     int basis,
6274     IntBinaryOperator reducer) {
6275     super(p, b, i, f, t); this.nextRight = nextRight;
6276     this.transformer = transformer;
6277     this.basis = basis; this.reducer = reducer;
6278     }
6279     public final Integer getRawResult() { return result; }
6280     public final void compute() {
6281     final ToIntBiFunction<? super K, ? super V> transformer;
6282     final IntBinaryOperator reducer;
6283     if ((transformer = this.transformer) != null &&
6284     (reducer = this.reducer) != null) {
6285     int r = this.basis;
6286     for (int i = baseIndex, f, h; batch > 0 &&
6287     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6288     addToPendingCount(1);
6289     (rights = new MapReduceMappingsToIntTask<K,V>
6290     (this, batch >>>= 1, baseLimit = h, f, tab,
6291     rights, transformer, r, reducer)).fork();
6292     }
6293     for (Node<K,V> p; (p = advance()) != null; )
6294     r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6295     result = r;
6296     CountedCompleter<?> c;
6297     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6298     @SuppressWarnings("unchecked")
6299     MapReduceMappingsToIntTask<K,V>
6300     t = (MapReduceMappingsToIntTask<K,V>)c,
6301     s = t.rights;
6302     while (s != null) {
6303     t.result = reducer.applyAsInt(t.result, s.result);
6304     s = t.rights = s.nextRight;
6305     }
6306     }
6307     }
6308     }
6309     }
6310    
6311     // Unsafe mechanics
6312     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
6313     private static final long SIZECTL;
6314     private static final long TRANSFERINDEX;
6315     private static final long BASECOUNT;
6316     private static final long CELLSBUSY;
6317     private static final long CELLVALUE;
6318     private static final int ABASE;
6319     private static final int ASHIFT;
6320    
6321     static {
6322     try {
6323     SIZECTL = U.objectFieldOffset
6324     (ConcurrentHashMap.class.getDeclaredField("sizeCtl"));
6325     TRANSFERINDEX = U.objectFieldOffset
6326     (ConcurrentHashMap.class.getDeclaredField("transferIndex"));
6327     BASECOUNT = U.objectFieldOffset
6328     (ConcurrentHashMap.class.getDeclaredField("baseCount"));
6329     CELLSBUSY = U.objectFieldOffset
6330     (ConcurrentHashMap.class.getDeclaredField("cellsBusy"));
6331    
6332     CELLVALUE = U.objectFieldOffset
6333     (CounterCell.class.getDeclaredField("value"));
6334    
6335     ABASE = U.arrayBaseOffset(Node[].class);
6336     int scale = U.arrayIndexScale(Node[].class);
6337     if ((scale & (scale - 1)) != 0)
6338     throw new Error("array index scale not a power of two");
6339     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6340     } catch (ReflectiveOperationException e) {
6341     throw new Error(e);
6342     }
6343    
6344     // Reduce the risk of rare disastrous classloading in first call to
6345     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6346     Class<?> ensureLoaded = LockSupport.class;
6347     }
6348     }