ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.297
Committed: Mon Aug 22 18:38:27 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.296: +4 -1 lines
Log Message:
fix JDK-8163353: NPE in ConcurrentHashMap.removeAll()

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