ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.299
Committed: Sat Mar 18 19:19:04 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.298: +7 -6 lines
Log Message:
errorprone [OperatorPrecedence]

File Contents

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