ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.304
Committed: Sun Jan 7 04:59:42 2018 UTC (6 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.303: +2 -6 lines
Log Message:
replace manual loop with Arrays.copyOf

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 jsr166 1.300 * {@link Map.Entry} objects do not support method {@code setValue}.
134 dl 1.137 *
135     * <ul>
136 jsr166 1.280 * <li>forEach: Performs a given action on each element.
137 dl 1.137 * A variant form applies a given transformation on each element
138 jsr166 1.280 * before performing the action.
139 dl 1.137 *
140 jsr166 1.280 * <li>search: Returns the first available non-null result of
141 dl 1.137 * applying a given function on each element; skipping further
142 jsr166 1.280 * search when a result is found.
143 dl 1.137 *
144 jsr166 1.280 * <li>reduce: Accumulates each element. The supplied reduction
145 dl 1.137 * function cannot rely on ordering (more formally, it should be
146     * both associative and commutative). There are five variants:
147     *
148     * <ul>
149     *
150 jsr166 1.280 * <li>Plain reductions. (There is not a form of this method for
151 dl 1.137 * (key, value) function arguments since there is no corresponding
152 jsr166 1.280 * return type.)
153 dl 1.137 *
154 jsr166 1.280 * <li>Mapped reductions that accumulate the results of a given
155     * function applied to each element.
156 dl 1.137 *
157 jsr166 1.280 * <li>Reductions to scalar doubles, longs, and ints, using a
158     * given basis value.
159 dl 1.137 *
160 jsr166 1.178 * </ul>
161 dl 1.137 * </ul>
162     *
163 dl 1.210 * <p>These bulk operations accept a {@code parallelismThreshold}
164     * argument. Methods proceed sequentially if the current map size is
165     * estimated to be less than the given threshold. Using a value of
166     * {@code Long.MAX_VALUE} suppresses all parallelism. Using a value
167 dl 1.217 * of {@code 1} results in maximal parallelism by partitioning into
168 dl 1.219 * enough subtasks to fully utilize the {@link
169     * ForkJoinPool#commonPool()} that is used for all parallel
170     * computations. Normally, you would initially choose one of these
171     * extreme values, and then measure performance of using in-between
172     * values that trade off overhead versus throughput.
173 dl 1.210 *
174 dl 1.137 * <p>The concurrency properties of bulk operations follow
175     * from those of ConcurrentHashMap: Any non-null result returned
176     * from {@code get(key)} and related access methods bears a
177     * happens-before relation with the associated insertion or
178     * update. The result of any bulk operation reflects the
179     * composition of these per-element relations (but is not
180     * necessarily atomic with respect to the map as a whole unless it
181     * is somehow known to be quiescent). Conversely, because keys
182     * and values in the map are never null, null serves as a reliable
183     * atomic indicator of the current lack of any result. To
184     * maintain this property, null serves as an implicit basis for
185     * all non-scalar reduction operations. For the double, long, and
186     * int versions, the basis should be one that, when combined with
187     * any other value, returns that other value (more formally, it
188     * should be the identity element for the reduction). Most common
189     * reductions have these properties; for example, computing a sum
190     * with basis 0 or a minimum with basis MAX_VALUE.
191     *
192     * <p>Search and transformation functions provided as arguments
193     * should similarly return null to indicate the lack of any result
194     * (in which case it is not used). In the case of mapped
195     * reductions, this also enables transformations to serve as
196     * filters, returning null (or, in the case of primitive
197     * specializations, the identity basis) if the element should not
198     * be combined. You can create compound transformations and
199     * filterings by composing them yourself under this "null means
200     * there is nothing there now" rule before using them in search or
201     * reduce operations.
202     *
203     * <p>Methods accepting and/or returning Entry arguments maintain
204     * key-value associations. They may be useful for example when
205     * finding the key for the greatest value. Note that "plain" Entry
206     * arguments can be supplied using {@code new
207     * AbstractMap.SimpleEntry(k,v)}.
208     *
209 jsr166 1.145 * <p>Bulk operations may complete abruptly, throwing an
210 dl 1.137 * exception encountered in the application of a supplied
211     * function. Bear in mind when handling such exceptions that other
212     * concurrently executing functions could also have thrown
213     * exceptions, or would have done so if the first exception had
214     * not occurred.
215     *
216 dl 1.151 * <p>Speedups for parallel compared to sequential forms are common
217     * but not guaranteed. Parallel operations involving brief functions
218     * on small maps may execute more slowly than sequential forms if the
219     * underlying work to parallelize the computation is more expensive
220     * than the computation itself. Similarly, parallelization may not
221     * lead to much actual parallelism if all processors are busy
222     * performing unrelated tasks.
223 dl 1.137 *
224 jsr166 1.145 * <p>All arguments to all task methods must be non-null.
225 dl 1.137 *
226 dl 1.42 * <p>This class is a member of the
227 jsr166 1.301 * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
228 dl 1.42 * Java Collections Framework</a>.
229     *
230 dl 1.8 * @since 1.5
231     * @author Doug Lea
232 dl 1.27 * @param <K> the type of keys maintained by this map
233 jsr166 1.64 * @param <V> the type of mapped values
234 dl 1.8 */
235 dl 1.240 public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
236     implements ConcurrentMap<K,V>, Serializable {
237 dl 1.20 private static final long serialVersionUID = 7249069246763182397L;
238 tim 1.1
239     /*
240 dl 1.119 * Overview:
241     *
242     * The primary design goal of this hash table is to maintain
243     * concurrent readability (typically method get(), but also
244     * iterators and related methods) while minimizing update
245     * contention. Secondary goals are to keep space consumption about
246     * the same or better than java.util.HashMap, and to support high
247     * initial insertion rates on an empty table by many threads.
248     *
249 dl 1.224 * This map usually acts as a binned (bucketed) hash table. Each
250     * key-value mapping is held in a Node. Most nodes are instances
251     * of the basic Node class with hash, key, value, and next
252     * fields. However, various subclasses exist: TreeNodes are
253 dl 1.222 * arranged in balanced trees, not lists. TreeBins hold the roots
254     * of sets of TreeNodes. ForwardingNodes are placed at the heads
255     * of bins during resizing. ReservationNodes are used as
256     * placeholders while establishing values in computeIfAbsent and
257 dl 1.224 * related methods. The types TreeBin, ForwardingNode, and
258 dl 1.222 * ReservationNode do not hold normal user keys, values, or
259     * hashes, and are readily distinguishable during search etc
260     * because they have negative hash fields and null key and value
261     * fields. (These special nodes are either uncommon or transient,
262     * so the impact of carrying around some unused fields is
263 jsr166 1.232 * insignificant.)
264 dl 1.119 *
265     * The table is lazily initialized to a power-of-two size upon the
266     * first insertion. Each bin in the table normally contains a
267     * list of Nodes (most often, the list has only zero or one Node).
268     * Table accesses require volatile/atomic reads, writes, and
269     * CASes. Because there is no other way to arrange this without
270     * adding further indirections, we use intrinsics
271 jsr166 1.291 * (jdk.internal.misc.Unsafe) operations.
272 dl 1.119 *
273 dl 1.149 * We use the top (sign) bit of Node hash fields for control
274     * purposes -- it is available anyway because of addressing
275 dl 1.222 * constraints. Nodes with negative hash fields are specially
276     * handled or ignored in map methods.
277 dl 1.119 *
278     * Insertion (via put or its variants) of the first node in an
279     * empty bin is performed by just CASing it to the bin. This is
280     * by far the most common case for put operations under most
281     * key/hash distributions. Other update operations (insert,
282     * delete, and replace) require locks. We do not want to waste
283     * the space required to associate a distinct lock object with
284     * each bin, so instead use the first node of a bin list itself as
285 dl 1.149 * a lock. Locking support for these locks relies on builtin
286     * "synchronized" monitors.
287 dl 1.119 *
288     * Using the first node of a list as a lock does not by itself
289     * suffice though: When a node is locked, any update must first
290     * validate that it is still the first node after locking it, and
291     * retry if not. Because new nodes are always appended to lists,
292     * once a node is first in a bin, it remains first until deleted
293 dl 1.210 * or the bin becomes invalidated (upon resizing).
294 dl 1.119 *
295     * The main disadvantage of per-bin locks is that other update
296     * operations on other nodes in a bin list protected by the same
297     * lock can stall, for example when user equals() or mapping
298     * functions take a long time. However, statistically, under
299     * random hash codes, this is not a common problem. Ideally, the
300     * frequency of nodes in bins follows a Poisson distribution
301     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
302     * parameter of about 0.5 on average, given the resizing threshold
303     * of 0.75, although with a large variance because of resizing
304     * granularity. Ignoring variance, the expected occurrences of
305     * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
306     * first values are:
307     *
308     * 0: 0.60653066
309     * 1: 0.30326533
310     * 2: 0.07581633
311     * 3: 0.01263606
312     * 4: 0.00157952
313     * 5: 0.00015795
314     * 6: 0.00001316
315     * 7: 0.00000094
316     * 8: 0.00000006
317     * more: less than 1 in ten million
318     *
319     * Lock contention probability for two threads accessing distinct
320     * elements is roughly 1 / (8 * #elements) under random hashes.
321     *
322     * Actual hash code distributions encountered in practice
323     * sometimes deviate significantly from uniform randomness. This
324     * includes the case when N > (1<<30), so some keys MUST collide.
325     * Similarly for dumb or hostile usages in which multiple keys are
326 dl 1.222 * designed to have identical hash codes or ones that differs only
327 dl 1.224 * in masked-out high bits. So we use a secondary strategy that
328     * applies when the number of nodes in a bin exceeds a
329     * threshold. These TreeBins use a balanced tree to hold nodes (a
330     * specialized form of red-black trees), bounding search time to
331     * O(log N). Each search step in a TreeBin is at least twice as
332     * slow as in a regular list, but given that N cannot exceed
333     * (1<<64) (before running out of addresses) this bounds search
334     * steps, lock hold times, etc, to reasonable constants (roughly
335     * 100 nodes inspected per operation worst case) so long as keys
336     * are Comparable (which is very common -- String, Long, etc).
337 dl 1.119 * TreeBin nodes (TreeNodes) also maintain the same "next"
338     * traversal pointers as regular nodes, so can be traversed in
339     * iterators in the same way.
340     *
341     * The table is resized when occupancy exceeds a percentage
342 dl 1.149 * threshold (nominally, 0.75, but see below). Any thread
343     * noticing an overfull bin may assist in resizing after the
344 jsr166 1.248 * initiating thread allocates and sets up the replacement array.
345     * However, rather than stalling, these other threads may proceed
346     * with insertions etc. The use of TreeBins shields us from the
347     * worst case effects of overfilling while resizes are in
348 dl 1.149 * progress. Resizing proceeds by transferring bins, one by one,
349 dl 1.246 * from the table to the next table. However, threads claim small
350     * blocks of indices to transfer (via field transferIndex) before
351 dl 1.252 * doing so, reducing contention. A generation stamp in field
352     * sizeCtl ensures that resizings do not overlap. Because we are
353     * using power-of-two expansion, the elements from each bin must
354     * either stay at same index, or move with a power of two
355     * offset. We eliminate unnecessary node creation by catching
356     * cases where old nodes can be reused because their next fields
357     * won't change. On average, only about one-sixth of them need
358     * cloning when a table doubles. The nodes they replace will be
359     * garbage collectable as soon as they are no longer referenced by
360     * any reader thread that may be in the midst of concurrently
361     * traversing table. Upon transfer, the old table bin contains
362     * only a special forwarding node (with hash field "MOVED") that
363     * contains the next table as its key. On encountering a
364     * forwarding node, access and update operations restart, using
365     * the new table.
366 dl 1.149 *
367     * Each bin transfer requires its bin lock, which can stall
368     * waiting for locks while resizing. However, because other
369     * threads can join in and help resize rather than contend for
370     * locks, average aggregate waits become shorter as resizing
371     * progresses. The transfer operation must also ensure that all
372     * accessible bins in both the old and new table are usable by any
373 dl 1.246 * traversal. This is arranged in part by proceeding from the
374     * last bin (table.length - 1) up towards the first. Upon seeing
375     * a forwarding node, traversals (see class Traverser) arrange to
376     * move to the new table without revisiting nodes. To ensure that
377     * no intervening nodes are skipped even when moved out of order,
378     * a stack (see class TableStack) is created on first encounter of
379     * a forwarding node during a traversal, to maintain its place if
380     * later processing the current table. The need for these
381     * save/restore mechanics is relatively rare, but when one
382 jsr166 1.248 * forwarding node is encountered, typically many more will be.
383 dl 1.246 * So Traversers use a simple caching scheme to avoid creating so
384     * many new TableStack nodes. (Thanks to Peter Levart for
385     * suggesting use of a stack here.)
386 dl 1.119 *
387     * The traversal scheme also applies to partial traversals of
388     * ranges of bins (via an alternate Traverser constructor)
389     * to support partitioned aggregate operations. Also, read-only
390     * operations give up if ever forwarded to a null table, which
391     * provides support for shutdown-style clearing, which is also not
392     * currently implemented.
393     *
394     * Lazy table initialization minimizes footprint until first use,
395     * and also avoids resizings when the first operation is from a
396     * putAll, constructor with map argument, or deserialization.
397     * These cases attempt to override the initial capacity settings,
398     * but harmlessly fail to take effect in cases of races.
399     *
400 dl 1.149 * The element count is maintained using a specialization of
401     * LongAdder. We need to incorporate a specialization rather than
402     * just use a LongAdder in order to access implicit
403     * contention-sensing that leads to creation of multiple
404 dl 1.222 * CounterCells. The counter mechanics avoid contention on
405 dl 1.149 * updates but can encounter cache thrashing if read too
406     * frequently during concurrent access. To avoid reading so often,
407     * resizing under contention is attempted only upon adding to a
408     * bin already holding two or more nodes. Under uniform hash
409     * distributions, the probability of this occurring at threshold
410     * is around 13%, meaning that only about 1 in 8 puts check
411 dl 1.222 * threshold (and after resizing, many fewer do so).
412     *
413     * TreeBins use a special form of comparison for search and
414     * related operations (which is the main reason we cannot use
415     * existing collections such as TreeMaps). TreeBins contain
416     * Comparable elements, but may contain others, as well as
417 dl 1.240 * elements that are Comparable but not necessarily Comparable for
418     * the same T, so we cannot invoke compareTo among them. To handle
419     * this, the tree is ordered primarily by hash value, then by
420     * Comparable.compareTo order if applicable. On lookup at a node,
421     * if elements are not comparable or compare as 0 then both left
422     * and right children may need to be searched in the case of tied
423     * hash values. (This corresponds to the full list search that
424     * would be necessary if all elements were non-Comparable and had
425     * tied hashes.) On insertion, to keep a total ordering (or as
426     * close as is required here) across rebalancings, we compare
427     * classes and identityHashCodes as tie-breakers. The red-black
428     * balancing code is updated from pre-jdk-collections
429 dl 1.222 * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
430     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
431     * Algorithms" (CLR).
432     *
433     * TreeBins also require an additional locking mechanism. While
434 dl 1.224 * list traversal is always possible by readers even during
435 jsr166 1.232 * updates, tree traversal is not, mainly because of tree-rotations
436 dl 1.222 * that may change the root node and/or its linkages. TreeBins
437     * include a simple read-write lock mechanism parasitic on the
438     * main bin-synchronization strategy: Structural adjustments
439     * associated with an insertion or removal are already bin-locked
440     * (and so cannot conflict with other writers) but must wait for
441     * ongoing readers to finish. Since there can be only one such
442     * waiter, we use a simple scheme using a single "waiter" field to
443     * block writers. However, readers need never block. If the root
444     * lock is held, they proceed along the slow traversal path (via
445     * next-pointers) until the lock becomes available or the list is
446     * exhausted, whichever comes first. These cases are not fast, but
447     * maximize aggregate expected throughput.
448 dl 1.119 *
449     * Maintaining API and serialization compatibility with previous
450     * versions of this class introduces several oddities. Mainly: We
451 jsr166 1.274 * leave untouched but unused constructor arguments referring to
452 dl 1.119 * concurrencyLevel. We accept a loadFactor constructor argument,
453     * but apply it only to initial table capacity (which is the only
454     * time that we can guarantee to honor it.) We also declare an
455     * unused "Segment" class that is instantiated in minimal form
456     * only when serializing.
457 dl 1.222 *
458 dl 1.240 * Also, solely for compatibility with previous versions of this
459     * class, it extends AbstractMap, even though all of its methods
460     * are overridden, so it is just useless baggage.
461     *
462 dl 1.222 * This file is organized to make things a little easier to follow
463 dl 1.224 * while reading than they might otherwise: First the main static
464 dl 1.222 * declarations and utilities, then fields, then main public
465     * methods (with a few factorings of multiple public methods into
466     * internal ones), then sizing methods, trees, traversers, and
467     * bulk operations.
468 dl 1.4 */
469 tim 1.1
470 dl 1.4 /* ---------------- Constants -------------- */
471 tim 1.11
472 dl 1.4 /**
473 dl 1.119 * The largest possible table capacity. This value must be
474     * exactly 1<<30 to stay within Java array allocation and indexing
475     * bounds for power of two table sizes, and is further required
476     * because the top two bits of 32bit hash fields are used for
477     * control purposes.
478 dl 1.4 */
479 dl 1.119 private static final int MAXIMUM_CAPACITY = 1 << 30;
480 dl 1.56
481     /**
482 dl 1.119 * The default initial table capacity. Must be a power of 2
483     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
484 dl 1.56 */
485 dl 1.119 private static final int DEFAULT_CAPACITY = 16;
486 dl 1.56
487     /**
488 dl 1.119 * The largest possible (non-power of two) array size.
489     * Needed by toArray and related methods.
490 jsr166 1.59 */
491 dl 1.119 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
492 tim 1.1
493     /**
494 dl 1.119 * The default concurrency level for this table. Unused but
495     * defined for compatibility with previous versions of this class.
496 dl 1.4 */
497 dl 1.119 private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
498 tim 1.11
499 tim 1.1 /**
500 dl 1.119 * The load factor for this table. Overrides of this value in
501     * constructors affect only the initial table capacity. The
502     * actual floating point value isn't normally used -- it is
503     * simpler to use expressions such as {@code n - (n >>> 2)} for
504     * the associated resizing threshold.
505 dl 1.99 */
506 dl 1.119 private static final float LOAD_FACTOR = 0.75f;
507 dl 1.99
508     /**
509 dl 1.119 * The bin count threshold for using a tree rather than list for a
510 dl 1.222 * bin. Bins are converted to trees when adding an element to a
511 dl 1.224 * bin with at least this many nodes. The value must be greater
512     * than 2, and should be at least 8 to mesh with assumptions in
513     * tree removal about conversion back to plain bins upon
514     * shrinkage.
515 dl 1.222 */
516     static final int TREEIFY_THRESHOLD = 8;
517    
518     /**
519     * The bin count threshold for untreeifying a (split) bin during a
520     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
521     * most 6 to mesh with shrinkage detection under removal.
522     */
523     static final int UNTREEIFY_THRESHOLD = 6;
524    
525     /**
526     * The smallest table capacity for which bins may be treeified.
527     * (Otherwise the table is resized if too many nodes in a bin.)
528 dl 1.224 * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
529     * conflicts between resizing and treeification thresholds.
530 dl 1.119 */
531 dl 1.222 static final int MIN_TREEIFY_CAPACITY = 64;
532 dl 1.119
533 dl 1.149 /**
534     * Minimum number of rebinnings per transfer step. Ranges are
535     * subdivided to allow multiple resizer threads. This value
536     * serves as a lower bound to avoid resizers encountering
537     * excessive memory contention. The value should be at least
538     * DEFAULT_CAPACITY.
539     */
540     private static final int MIN_TRANSFER_STRIDE = 16;
541    
542 dl 1.252 /**
543     * The number of bits used for generation stamp in sizeCtl.
544     * Must be at least 6 for 32bit arrays.
545     */
546 jsr166 1.282 private static final int RESIZE_STAMP_BITS = 16;
547 dl 1.252
548     /**
549     * The maximum number of threads that can help resize.
550     * Must fit in 32 - RESIZE_STAMP_BITS bits.
551     */
552     private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
553    
554     /**
555     * The bit shift for recording size stamp in sizeCtl.
556     */
557     private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
558    
559 dl 1.119 /*
560 dl 1.149 * Encodings for Node hash fields. See above for explanation.
561 dl 1.46 */
562 dl 1.233 static final int MOVED = -1; // hash for forwarding nodes
563     static final int TREEBIN = -2; // hash for roots of trees
564     static final int RESERVED = -3; // hash for transient reservations
565 dl 1.149 static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
566    
567     /** Number of CPUS, to place bounds on some sizings */
568     static final int NCPU = Runtime.getRuntime().availableProcessors();
569    
570 jsr166 1.287 /**
571     * Serialized pseudo-fields, provided only for jdk7 compatibility.
572     * @serialField segments Segment[]
573     * The segments, each of which is a specialized hash table.
574     * @serialField segmentMask int
575     * Mask value for indexing into segments. The upper bits of a
576     * key's hash code are used to choose the segment.
577     * @serialField segmentShift int
578     * Shift value for indexing within segments.
579     */
580 dl 1.208 private static final ObjectStreamField[] serialPersistentFields = {
581 dl 1.209 new ObjectStreamField("segments", Segment[].class),
582     new ObjectStreamField("segmentMask", Integer.TYPE),
583 jsr166 1.283 new ObjectStreamField("segmentShift", Integer.TYPE),
584 dl 1.208 };
585    
586 dl 1.222 /* ---------------- Nodes -------------- */
587    
588     /**
589     * Key-value entry. This class is never exported out as a
590     * user-mutable Map.Entry (i.e., one supporting setValue; see
591     * MapEntry below), but can be used for read-only traversals used
592 jsr166 1.232 * in bulk tasks. Subclasses of Node with a negative hash field
593 dl 1.224 * are special, and contain null keys and values (but are never
594     * exported). Otherwise, keys and vals are never null.
595 dl 1.222 */
596     static class Node<K,V> implements Map.Entry<K,V> {
597     final int hash;
598     final K key;
599     volatile V val;
600 dl 1.233 volatile Node<K,V> next;
601 dl 1.222
602 jsr166 1.290 Node(int hash, K key, V val) {
603 dl 1.222 this.hash = hash;
604     this.key = key;
605     this.val = val;
606 jsr166 1.290 }
607    
608     Node(int hash, K key, V val, Node<K,V> next) {
609     this(hash, key, val);
610 dl 1.222 this.next = next;
611     }
612    
613 jsr166 1.268 public final K getKey() { return key; }
614     public final V getValue() { return val; }
615     public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
616     public final String toString() {
617     return Helpers.mapEntryToString(key, val);
618 jsr166 1.265 }
619 dl 1.222 public final V setValue(V value) {
620     throw new UnsupportedOperationException();
621     }
622    
623     public final boolean equals(Object o) {
624     Object k, v, u; Map.Entry<?,?> e;
625     return ((o instanceof Map.Entry) &&
626     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
627     (v = e.getValue()) != null &&
628     (k == key || k.equals(key)) &&
629     (v == (u = val) || v.equals(u)));
630     }
631    
632 dl 1.224 /**
633     * Virtualized support for map.get(); overridden in subclasses.
634     */
635 dl 1.222 Node<K,V> find(int h, Object k) {
636     Node<K,V> e = this;
637     if (k != null) {
638     do {
639     K ek;
640     if (e.hash == h &&
641     ((ek = e.key) == k || (ek != null && k.equals(ek))))
642     return e;
643     } while ((e = e.next) != null);
644     }
645     return null;
646     }
647     }
648    
649     /* ---------------- Static utilities -------------- */
650    
651     /**
652     * Spreads (XORs) higher bits of hash to lower and also forces top
653     * bit to 0. Because the table uses power-of-two masking, sets of
654     * hashes that vary only in bits above the current mask will
655     * always collide. (Among known examples are sets of Float keys
656     * holding consecutive whole numbers in small tables.) So we
657     * apply a transform that spreads the impact of higher bits
658     * downward. There is a tradeoff between speed, utility, and
659     * quality of bit-spreading. Because many common sets of hashes
660     * are already reasonably distributed (so don't benefit from
661     * spreading), and because we use trees to handle large sets of
662     * collisions in bins, we just XOR some shifted bits in the
663     * cheapest possible way to reduce systematic lossage, as well as
664     * to incorporate impact of the highest bits that would otherwise
665     * never be used in index calculations because of table bounds.
666     */
667     static final int spread(int h) {
668     return (h ^ (h >>> 16)) & HASH_BITS;
669     }
670    
671     /**
672     * Returns a power of two table size for the given desired capacity.
673     * See Hackers Delight, sec 3.2
674     */
675     private static final int tableSizeFor(int c) {
676     int n = c - 1;
677     n |= n >>> 1;
678     n |= n >>> 2;
679     n |= n >>> 4;
680     n |= n >>> 8;
681     n |= n >>> 16;
682     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
683     }
684    
685     /**
686     * Returns x's Class if it is of the form "class C implements
687     * Comparable<C>", else null.
688     */
689     static Class<?> comparableClassFor(Object x) {
690     if (x instanceof Comparable) {
691     Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
692     if ((c = x.getClass()) == String.class) // bypass checks
693     return c;
694     if ((ts = c.getGenericInterfaces()) != null) {
695     for (int i = 0; i < ts.length; ++i) {
696     if (((t = ts[i]) instanceof ParameterizedType) &&
697     ((p = (ParameterizedType)t).getRawType() ==
698     Comparable.class) &&
699     (as = p.getActualTypeArguments()) != null &&
700     as.length == 1 && as[0] == c) // type arg is c
701     return c;
702     }
703     }
704     }
705     return null;
706     }
707    
708 dl 1.210 /**
709 dl 1.222 * Returns k.compareTo(x) if x matches kc (k's screened comparable
710     * class), else 0.
711     */
712     @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
713     static int compareComparables(Class<?> kc, Object k, Object x) {
714     return (x == null || x.getClass() != kc ? 0 :
715     ((Comparable)k).compareTo(x));
716     }
717    
718     /* ---------------- Table element access -------------- */
719    
720     /*
721 dl 1.294 * Atomic access methods are used for table elements as well as
722 dl 1.222 * elements of in-progress next table while resizing. All uses of
723     * the tab arguments must be null checked by callers. All callers
724     * also paranoically precheck that tab's length is not zero (or an
725     * equivalent check), thus ensuring that any index argument taking
726     * the form of a hash value anded with (length - 1) is a valid
727     * index. Note that, to be correct wrt arbitrary concurrency
728     * errors by users, these checks must operate on local variables,
729     * which accounts for some odd-looking inline assignments below.
730     * Note that calls to setTabAt always occur within locked regions,
731 dl 1.294 * and so require only release ordering.
732 dl 1.210 */
733 dl 1.222
734     @SuppressWarnings("unchecked")
735     static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
736 dl 1.294 return (Node<K,V>)U.getObjectAcquire(tab, ((long)i << ASHIFT) + ABASE);
737 dl 1.222 }
738    
739     static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
740     Node<K,V> c, Node<K,V> v) {
741 jsr166 1.302 return U.compareAndSetObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
742 dl 1.222 }
743    
744     static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
745 dl 1.294 U.putObjectRelease(tab, ((long)i << ASHIFT) + ABASE, v);
746 dl 1.149 }
747    
748 dl 1.4 /* ---------------- Fields -------------- */
749 tim 1.1
750     /**
751 dl 1.119 * The array of bins. Lazily initialized upon first insertion.
752     * Size is always a power of two. Accessed directly by iterators.
753 jsr166 1.59 */
754 dl 1.210 transient volatile Node<K,V>[] table;
755 tim 1.1
756     /**
757 dl 1.149 * The next table to use; non-null only while resizing.
758 jsr166 1.59 */
759 dl 1.210 private transient volatile Node<K,V>[] nextTable;
760 dl 1.149
761     /**
762     * Base counter value, used mainly when there is no contention,
763     * but also as a fallback during table initialization
764     * races. Updated via CAS.
765     */
766     private transient volatile long baseCount;
767 tim 1.1
768     /**
769 dl 1.119 * Table initialization and resizing control. When negative, the
770 dl 1.149 * table is being initialized or resized: -1 for initialization,
771     * else -(1 + the number of active resizing threads). Otherwise,
772     * when table is null, holds the initial table size to use upon
773     * creation, or 0 for default. After initialization, holds the
774     * next element count value upon which to resize the table.
775 tim 1.1 */
776 dl 1.119 private transient volatile int sizeCtl;
777 dl 1.4
778 dl 1.149 /**
779     * The next table index (plus one) to split while resizing.
780     */
781     private transient volatile int transferIndex;
782    
783     /**
784 dl 1.222 * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
785 dl 1.149 */
786 dl 1.153 private transient volatile int cellsBusy;
787 dl 1.149
788     /**
789     * Table of counter cells. When non-null, size is a power of 2.
790     */
791 dl 1.222 private transient volatile CounterCell[] counterCells;
792 dl 1.149
793 dl 1.119 // views
794 dl 1.137 private transient KeySetView<K,V> keySet;
795 dl 1.142 private transient ValuesView<K,V> values;
796     private transient EntrySetView<K,V> entrySet;
797 dl 1.119
798    
799 dl 1.222 /* ---------------- Public operations -------------- */
800    
801     /**
802     * Creates a new, empty map with the default initial table size (16).
803 dl 1.119 */
804 dl 1.222 public ConcurrentHashMap() {
805     }
806 dl 1.119
807 dl 1.222 /**
808     * Creates a new, empty map with an initial table size
809     * accommodating the specified number of elements without the need
810     * to dynamically resize.
811     *
812     * @param initialCapacity The implementation performs internal
813     * sizing to accommodate this many elements.
814     * @throws IllegalArgumentException if the initial capacity of
815     * elements is negative
816     */
817     public ConcurrentHashMap(int initialCapacity) {
818     if (initialCapacity < 0)
819     throw new IllegalArgumentException();
820     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
821     MAXIMUM_CAPACITY :
822     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
823     this.sizeCtl = cap;
824 dl 1.119 }
825    
826 dl 1.222 /**
827     * Creates a new map with the same mappings as the given map.
828     *
829     * @param m the map
830     */
831     public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
832     this.sizeCtl = DEFAULT_CAPACITY;
833     putAll(m);
834 dl 1.119 }
835    
836 dl 1.222 /**
837     * Creates a new, empty map with an initial table size based on
838     * the given number of elements ({@code initialCapacity}) and
839     * initial table density ({@code loadFactor}).
840     *
841     * @param initialCapacity the initial capacity. The implementation
842     * performs internal sizing to accommodate this many elements,
843     * given the specified load factor.
844     * @param loadFactor the load factor (table density) for
845     * establishing the initial table size
846     * @throws IllegalArgumentException if the initial capacity of
847     * elements is negative or the load factor is nonpositive
848     *
849     * @since 1.6
850     */
851     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
852     this(initialCapacity, loadFactor, 1);
853 dl 1.119 }
854    
855 dl 1.99 /**
856 dl 1.222 * Creates a new, empty map with an initial table size based on
857     * the given number of elements ({@code initialCapacity}), table
858     * density ({@code loadFactor}), and number of concurrently
859     * updating threads ({@code concurrencyLevel}).
860     *
861     * @param initialCapacity the initial capacity. The implementation
862     * performs internal sizing to accommodate this many elements,
863     * given the specified load factor.
864     * @param loadFactor the load factor (table density) for
865     * establishing the initial table size
866     * @param concurrencyLevel the estimated number of concurrently
867     * updating threads. The implementation may use this value as
868     * a sizing hint.
869     * @throws IllegalArgumentException if the initial capacity is
870     * negative or the load factor or concurrencyLevel are
871     * nonpositive
872 dl 1.99 */
873 dl 1.222 public ConcurrentHashMap(int initialCapacity,
874     float loadFactor, int concurrencyLevel) {
875     if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
876     throw new IllegalArgumentException();
877     if (initialCapacity < concurrencyLevel) // Use at least as many bins
878     initialCapacity = concurrencyLevel; // as estimated threads
879     long size = (long)(1.0 + (long)initialCapacity / loadFactor);
880     int cap = (size >= (long)MAXIMUM_CAPACITY) ?
881     MAXIMUM_CAPACITY : tableSizeFor((int)size);
882     this.sizeCtl = cap;
883     }
884 dl 1.99
885 dl 1.222 // Original (since JDK1.2) Map methods
886 dl 1.210
887 dl 1.222 /**
888     * {@inheritDoc}
889     */
890     public int size() {
891     long n = sumCount();
892     return ((n < 0L) ? 0 :
893     (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
894     (int)n);
895     }
896 dl 1.210
897 dl 1.222 /**
898     * {@inheritDoc}
899     */
900     public boolean isEmpty() {
901     return sumCount() <= 0L; // ignore transient negative values
902 dl 1.210 }
903    
904     /**
905 dl 1.222 * Returns the value to which the specified key is mapped,
906     * or {@code null} if this map contains no mapping for the key.
907     *
908     * <p>More formally, if this map contains a mapping from a key
909     * {@code k} to a value {@code v} such that {@code key.equals(k)},
910     * then this method returns {@code v}; otherwise it returns
911     * {@code null}. (There can be at most one such mapping.)
912     *
913     * @throws NullPointerException if the specified key is null
914 dl 1.210 */
915 dl 1.222 public V get(Object key) {
916     Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
917     int h = spread(key.hashCode());
918     if ((tab = table) != null && (n = tab.length) > 0 &&
919     (e = tabAt(tab, (n - 1) & h)) != null) {
920     if ((eh = e.hash) == h) {
921     if ((ek = e.key) == key || (ek != null && key.equals(ek)))
922     return e.val;
923     }
924     else if (eh < 0)
925     return (p = e.find(h, key)) != null ? p.val : null;
926     while ((e = e.next) != null) {
927     if (e.hash == h &&
928     ((ek = e.key) == key || (ek != null && key.equals(ek))))
929     return e.val;
930     }
931 dl 1.210 }
932 dl 1.222 return null;
933 dl 1.99 }
934    
935     /**
936 dl 1.222 * Tests if the specified object is a key in this table.
937     *
938     * @param key possible key
939     * @return {@code true} if and only if the specified object
940     * is a key in this table, as determined by the
941     * {@code equals} method; {@code false} otherwise
942     * @throws NullPointerException if the specified key is null
943 dl 1.99 */
944 dl 1.222 public boolean containsKey(Object key) {
945     return get(key) != null;
946 dl 1.99 }
947 tim 1.1
948 dl 1.201 /**
949 dl 1.222 * Returns {@code true} if this map maps one or more keys to the
950     * specified value. Note: This method may require a full traversal
951     * of the map, and is much slower than method {@code containsKey}.
952     *
953     * @param value value whose presence in this map is to be tested
954     * @return {@code true} if this map maps one or more keys to the
955     * specified value
956     * @throws NullPointerException if the specified value is null
957     */
958     public boolean containsValue(Object value) {
959     if (value == null)
960     throw new NullPointerException();
961     Node<K,V>[] t;
962     if ((t = table) != null) {
963     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
964     for (Node<K,V> p; (p = it.advance()) != null; ) {
965     V v;
966     if ((v = p.val) == value || (v != null && value.equals(v)))
967     return true;
968 dl 1.201 }
969     }
970 dl 1.222 return false;
971 dl 1.201 }
972    
973 tim 1.1 /**
974 dl 1.222 * Maps the specified key to the specified value in this table.
975     * Neither the key nor the value can be null.
976 dl 1.119 *
977 dl 1.222 * <p>The value can be retrieved by calling the {@code get} method
978     * with a key that is equal to the original key.
979 dl 1.119 *
980 dl 1.222 * @param key key with which the specified value is to be associated
981     * @param value value to be associated with the specified key
982     * @return the previous value associated with {@code key}, or
983     * {@code null} if there was no mapping for {@code key}
984     * @throws NullPointerException if the specified key or value is null
985 dl 1.119 */
986 dl 1.222 public V put(K key, V value) {
987     return putVal(key, value, false);
988     }
989 dl 1.119
990 dl 1.222 /** Implementation for put and putIfAbsent */
991     final V putVal(K key, V value, boolean onlyIfAbsent) {
992     if (key == null || value == null) throw new NullPointerException();
993     int hash = spread(key.hashCode());
994     int binCount = 0;
995     for (Node<K,V>[] tab = table;;) {
996 dl 1.296 Node<K,V> f; int n, i, fh; K fk; V fv;
997 dl 1.222 if (tab == null || (n = tab.length) == 0)
998     tab = initTable();
999     else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
1000 jsr166 1.290 if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
1001 dl 1.222 break; // no lock when adding to empty bin
1002 dl 1.119 }
1003 dl 1.222 else if ((fh = f.hash) == MOVED)
1004     tab = helpTransfer(tab, f);
1005 jsr166 1.299 else if (onlyIfAbsent // check first node without acquiring lock
1006     && fh == hash
1007     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1008     && (fv = f.val) != null)
1009 dl 1.296 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 jsr166 1.303 * Saves this map to a stream (that is, serializes it).
1369     *
1370 dl 1.222 * @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 jsr166 1.303 * Reconstitutes this map from a stream (that is, deserializes it).
1414 dl 1.222 * @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 jsr166 1.299 else if (fh == h // check first node without acquiring lock
1703     && ((fk = f.key) == key || (fk != null && key.equals(fk)))
1704     && (fv = f.val) != null)
1705 dl 1.296 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 jsr166 1.302 else if (U.compareAndSetInt(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 jsr166 1.302 !U.compareAndSetLong(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 jsr166 1.302 U.compareAndSetLong(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 jsr166 1.302 if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1))
2329 dl 1.149 transfer(tab, nt);
2330 dl 1.119 }
2331 jsr166 1.302 else if (U.compareAndSetInt(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 jsr166 1.302 if (U.compareAndSetInt(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 jsr166 1.302 if (U.compareAndSetInt(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 jsr166 1.302 if (U.compareAndSetInt(this, SIZECTL, sc,
2393 dl 1.258 (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 jsr166 1.302 else if (U.compareAndSetInt
2434 dl 1.149 (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 jsr166 1.302 if (U.compareAndSetInt(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 jsr166 1.302 U.compareAndSetInt(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 jsr166 1.302 else if (U.compareAndSetLong(a, CELLVALUE, v = a.value, v + x))
2598 dl 1.149 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 jsr166 1.302 U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2605 dl 1.149 try {
2606 jsr166 1.304 if (counterCells == as) // Expand table unless stale
2607     counterCells = Arrays.copyOf(as, n << 1);
2608 dl 1.119 } finally {
2609 dl 1.153 cellsBusy = 0;
2610 dl 1.119 }
2611 dl 1.149 collide = false;
2612     continue; // Retry with expanded table
2613 dl 1.119 }
2614 dl 1.160 h = ThreadLocalRandom.advanceProbe(h);
2615 dl 1.149 }
2616 dl 1.153 else if (cellsBusy == 0 && counterCells == as &&
2617 jsr166 1.302 U.compareAndSetInt(this, CELLSBUSY, 0, 1)) {
2618 dl 1.149 boolean init = false;
2619     try { // Initialize table
2620     if (counterCells == as) {
2621 dl 1.222 CounterCell[] rs = new CounterCell[2];
2622     rs[h & 1] = new CounterCell(x);
2623 dl 1.149 counterCells = rs;
2624     init = true;
2625 dl 1.119 }
2626     } finally {
2627 dl 1.153 cellsBusy = 0;
2628 dl 1.119 }
2629 dl 1.149 if (init)
2630     break;
2631 dl 1.119 }
2632 jsr166 1.302 else if (U.compareAndSetLong(this, BASECOUNT, v = baseCount, v + x))
2633 dl 1.149 break; // Fall back on using base
2634 dl 1.119 }
2635     }
2636    
2637 dl 1.222 /* ---------------- Conversion from/to TreeBins -------------- */
2638 dl 1.119
2639     /**
2640 dl 1.222 * Replaces all linked nodes in bin at given index unless table is
2641     * too small, in which case resizes instead.
2642 dl 1.119 */
2643 dl 1.222 private final void treeifyBin(Node<K,V>[] tab, int index) {
2644 jsr166 1.267 Node<K,V> b; int n;
2645 dl 1.222 if (tab != null) {
2646 dl 1.252 if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
2647     tryPresize(n << 1);
2648 dl 1.233 else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2649 jsr166 1.223 synchronized (b) {
2650 dl 1.222 if (tabAt(tab, index) == b) {
2651     TreeNode<K,V> hd = null, tl = null;
2652     for (Node<K,V> e = b; e != null; e = e.next) {
2653     TreeNode<K,V> p =
2654     new TreeNode<K,V>(e.hash, e.key, e.val,
2655     null, null);
2656     if ((p.prev = tl) == null)
2657     hd = p;
2658     else
2659     tl.next = p;
2660     tl = p;
2661     }
2662     setTabAt(tab, index, new TreeBin<K,V>(hd));
2663 dl 1.210 }
2664     }
2665     }
2666     }
2667     }
2668    
2669     /**
2670 jsr166 1.289 * Returns a list of non-TreeNodes replacing those in given list.
2671 dl 1.210 */
2672 dl 1.222 static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2673     Node<K,V> hd = null, tl = null;
2674     for (Node<K,V> q = b; q != null; q = q.next) {
2675 jsr166 1.290 Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val);
2676 dl 1.222 if (tl == null)
2677     hd = p;
2678     else
2679     tl.next = p;
2680     tl = p;
2681 dl 1.210 }
2682 dl 1.222 return hd;
2683     }
2684 dl 1.210
2685 dl 1.222 /* ---------------- TreeNodes -------------- */
2686    
2687     /**
2688 jsr166 1.285 * Nodes for use in TreeBins.
2689 dl 1.222 */
2690     static final class TreeNode<K,V> extends Node<K,V> {
2691     TreeNode<K,V> parent; // red-black tree links
2692     TreeNode<K,V> left;
2693     TreeNode<K,V> right;
2694     TreeNode<K,V> prev; // needed to unlink next upon deletion
2695     boolean red;
2696 dl 1.210
2697 dl 1.222 TreeNode(int hash, K key, V val, Node<K,V> next,
2698     TreeNode<K,V> parent) {
2699     super(hash, key, val, next);
2700     this.parent = parent;
2701 dl 1.210 }
2702    
2703 dl 1.222 Node<K,V> find(int h, Object k) {
2704     return findTreeNode(h, k, null);
2705 dl 1.210 }
2706    
2707 dl 1.222 /**
2708     * Returns the TreeNode (or null if not found) for the given key
2709     * starting at given root.
2710     */
2711     final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2712 dl 1.224 if (k != null) {
2713     TreeNode<K,V> p = this;
2714 jsr166 1.256 do {
2715 dl 1.224 int ph, dir; K pk; TreeNode<K,V> q;
2716     TreeNode<K,V> pl = p.left, pr = p.right;
2717     if ((ph = p.hash) > h)
2718     p = pl;
2719     else if (ph < h)
2720     p = pr;
2721     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2722     return p;
2723 dl 1.240 else if (pl == null)
2724     p = pr;
2725     else if (pr == null)
2726     p = pl;
2727 jsr166 1.225 else if ((kc != null ||
2728 dl 1.224 (kc = comparableClassFor(k)) != null) &&
2729     (dir = compareComparables(kc, k, pk)) != 0)
2730     p = (dir < 0) ? pl : pr;
2731 dl 1.240 else if ((q = pr.findTreeNode(h, k, kc)) != null)
2732     return q;
2733     else
2734 dl 1.224 p = pl;
2735     } while (p != null);
2736     }
2737 dl 1.222 return null;
2738 dl 1.210 }
2739     }
2740 dl 1.192
2741 dl 1.222 /* ---------------- TreeBins -------------- */
2742 dl 1.119
2743 dl 1.222 /**
2744     * TreeNodes used at the heads of bins. TreeBins do not hold user
2745     * keys or values, but instead point to list of TreeNodes and
2746     * their root. They also maintain a parasitic read-write lock
2747     * forcing writers (who hold bin lock) to wait for readers (who do
2748     * not) to complete before tree restructuring operations.
2749     */
2750     static final class TreeBin<K,V> extends Node<K,V> {
2751     TreeNode<K,V> root;
2752     volatile TreeNode<K,V> first;
2753     volatile Thread waiter;
2754     volatile int lockState;
2755 dl 1.224 // values for lockState
2756     static final int WRITER = 1; // set while holding write lock
2757     static final int WAITER = 2; // set when waiting for write lock
2758     static final int READER = 4; // increment value for setting read lock
2759 dl 1.119
2760 dl 1.222 /**
2761 dl 1.240 * Tie-breaking utility for ordering insertions when equal
2762     * hashCodes and non-comparable. We don't require a total
2763     * order, just a consistent insertion rule to maintain
2764     * equivalence across rebalancings. Tie-breaking further than
2765     * necessary simplifies testing a bit.
2766     */
2767     static int tieBreakOrder(Object a, Object b) {
2768     int d;
2769     if (a == null || b == null ||
2770     (d = a.getClass().getName().
2771     compareTo(b.getClass().getName())) == 0)
2772     d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
2773     -1 : 1);
2774     return d;
2775     }
2776    
2777     /**
2778 dl 1.222 * Creates bin with initial set of nodes headed by b.
2779     */
2780     TreeBin(TreeNode<K,V> b) {
2781 jsr166 1.290 super(TREEBIN, null, null);
2782 dl 1.224 this.first = b;
2783 dl 1.222 TreeNode<K,V> r = null;
2784     for (TreeNode<K,V> x = b, next; x != null; x = next) {
2785     next = (TreeNode<K,V>)x.next;
2786     x.left = x.right = null;
2787     if (r == null) {
2788     x.parent = null;
2789     x.red = false;
2790     r = x;
2791     }
2792     else {
2793 dl 1.240 K k = x.key;
2794     int h = x.hash;
2795 dl 1.222 Class<?> kc = null;
2796     for (TreeNode<K,V> p = r;;) {
2797     int dir, ph;
2798 dl 1.240 K pk = p.key;
2799     if ((ph = p.hash) > h)
2800 dl 1.222 dir = -1;
2801 dl 1.240 else if (ph < h)
2802 dl 1.222 dir = 1;
2803 dl 1.240 else if ((kc == null &&
2804     (kc = comparableClassFor(k)) == null) ||
2805     (dir = compareComparables(kc, k, pk)) == 0)
2806     dir = tieBreakOrder(k, pk);
2807 jsr166 1.260 TreeNode<K,V> xp = p;
2808 dl 1.222 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2809     x.parent = xp;
2810     if (dir <= 0)
2811     xp.left = x;
2812     else
2813     xp.right = x;
2814     r = balanceInsertion(r, x);
2815     break;
2816     }
2817     }
2818     }
2819     }
2820 dl 1.224 this.root = r;
2821 dl 1.240 assert checkInvariants(root);
2822 dl 1.222 }
2823 dl 1.210
2824 dl 1.222 /**
2825 jsr166 1.229 * Acquires write lock for tree restructuring.
2826 dl 1.222 */
2827     private final void lockRoot() {
2828 jsr166 1.302 if (!U.compareAndSetInt(this, LOCKSTATE, 0, WRITER))
2829 dl 1.222 contendedLock(); // offload to separate method
2830 dl 1.153 }
2831    
2832 dl 1.222 /**
2833 jsr166 1.229 * Releases write lock for tree restructuring.
2834 dl 1.222 */
2835     private final void unlockRoot() {
2836     lockState = 0;
2837 dl 1.191 }
2838    
2839 dl 1.222 /**
2840 jsr166 1.229 * Possibly blocks awaiting root lock.
2841 dl 1.222 */
2842     private final void contendedLock() {
2843     boolean waiting = false;
2844     for (int s;;) {
2845 dl 1.252 if (((s = lockState) & ~WAITER) == 0) {
2846 jsr166 1.302 if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {
2847 dl 1.222 if (waiting)
2848     waiter = null;
2849     return;
2850     }
2851     }
2852 dl 1.244 else if ((s & WAITER) == 0) {
2853 jsr166 1.302 if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {
2854 dl 1.222 waiting = true;
2855     waiter = Thread.currentThread();
2856     }
2857     }
2858     else if (waiting)
2859     LockSupport.park(this);
2860     }
2861 dl 1.192 }
2862    
2863 dl 1.222 /**
2864     * Returns matching node or null if none. Tries to search
2865 jsr166 1.232 * using tree comparisons from root, but continues linear
2866 dl 1.222 * search when lock not available.
2867     */
2868     final Node<K,V> find(int h, Object k) {
2869     if (k != null) {
2870 dl 1.253 for (Node<K,V> e = first; e != null; ) {
2871 dl 1.222 int s; K ek;
2872     if (((s = lockState) & (WAITER|WRITER)) != 0) {
2873     if (e.hash == h &&
2874     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2875     return e;
2876 dl 1.253 e = e.next;
2877 dl 1.222 }
2878 jsr166 1.302 else if (U.compareAndSetInt(this, LOCKSTATE, s,
2879 dl 1.222 s + READER)) {
2880     TreeNode<K,V> r, p;
2881     try {
2882     p = ((r = root) == null ? null :
2883     r.findTreeNode(h, k, null));
2884     } finally {
2885     Thread w;
2886     if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2887     (READER|WAITER) && (w = waiter) != null)
2888     LockSupport.unpark(w);
2889     }
2890     return p;
2891     }
2892     }
2893     }
2894     return null;
2895 dl 1.192 }
2896    
2897 dl 1.222 /**
2898     * Finds or adds a node.
2899     * @return null if added
2900     */
2901     final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2902     Class<?> kc = null;
2903 dl 1.240 boolean searched = false;
2904 dl 1.224 for (TreeNode<K,V> p = root;;) {
2905 dl 1.240 int dir, ph; K pk;
2906 dl 1.224 if (p == null) {
2907     first = root = new TreeNode<K,V>(h, k, v, null, null);
2908     break;
2909     }
2910     else if ((ph = p.hash) > h)
2911 dl 1.222 dir = -1;
2912     else if (ph < h)
2913     dir = 1;
2914     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2915     return p;
2916     else if ((kc == null &&
2917     (kc = comparableClassFor(k)) == null) ||
2918     (dir = compareComparables(kc, k, pk)) == 0) {
2919 dl 1.240 if (!searched) {
2920     TreeNode<K,V> q, ch;
2921     searched = true;
2922     if (((ch = p.left) != null &&
2923     (q = ch.findTreeNode(h, k, kc)) != null) ||
2924     ((ch = p.right) != null &&
2925     (q = ch.findTreeNode(h, k, kc)) != null))
2926     return q;
2927     }
2928     dir = tieBreakOrder(k, pk);
2929 dl 1.222 }
2930 dl 1.240
2931 dl 1.222 TreeNode<K,V> xp = p;
2932 dl 1.240 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2933 dl 1.222 TreeNode<K,V> x, f = first;
2934     first = x = new TreeNode<K,V>(h, k, v, f, xp);
2935     if (f != null)
2936     f.prev = x;
2937 dl 1.240 if (dir <= 0)
2938 dl 1.222 xp.left = x;
2939     else
2940     xp.right = x;
2941     if (!xp.red)
2942     x.red = true;
2943     else {
2944     lockRoot();
2945     try {
2946     root = balanceInsertion(root, x);
2947     } finally {
2948     unlockRoot();
2949     }
2950     }
2951 dl 1.224 break;
2952 dl 1.222 }
2953     }
2954 dl 1.224 assert checkInvariants(root);
2955     return null;
2956 dl 1.192 }
2957    
2958 dl 1.222 /**
2959     * Removes the given node, that must be present before this
2960     * call. This is messier than typical red-black deletion code
2961     * because we cannot swap the contents of an interior node
2962     * with a leaf successor that is pinned by "next" pointers
2963     * that are accessible independently of lock. So instead we
2964     * swap the tree linkages.
2965     *
2966 jsr166 1.230 * @return true if now too small, so should be untreeified
2967 dl 1.222 */
2968     final boolean removeTreeNode(TreeNode<K,V> p) {
2969     TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2970     TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2971     TreeNode<K,V> r, rl;
2972     if (pred == null)
2973     first = next;
2974     else
2975     pred.next = next;
2976     if (next != null)
2977     next.prev = pred;
2978     if (first == null) {
2979     root = null;
2980     return true;
2981     }
2982 dl 1.224 if ((r = root) == null || r.right == null || // too small
2983 dl 1.222 (rl = r.left) == null || rl.left == null)
2984     return true;
2985     lockRoot();
2986     try {
2987     TreeNode<K,V> replacement;
2988     TreeNode<K,V> pl = p.left;
2989     TreeNode<K,V> pr = p.right;
2990     if (pl != null && pr != null) {
2991     TreeNode<K,V> s = pr, sl;
2992     while ((sl = s.left) != null) // find successor
2993     s = sl;
2994     boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2995     TreeNode<K,V> sr = s.right;
2996     TreeNode<K,V> pp = p.parent;
2997     if (s == pr) { // p was s's direct parent
2998     p.parent = s;
2999     s.right = p;
3000     }
3001     else {
3002     TreeNode<K,V> sp = s.parent;
3003     if ((p.parent = sp) != null) {
3004     if (s == sp.left)
3005     sp.left = p;
3006     else
3007     sp.right = p;
3008     }
3009     if ((s.right = pr) != null)
3010     pr.parent = s;
3011     }
3012     p.left = null;
3013     if ((p.right = sr) != null)
3014     sr.parent = p;
3015     if ((s.left = pl) != null)
3016     pl.parent = s;
3017     if ((s.parent = pp) == null)
3018     r = s;
3019     else if (p == pp.left)
3020     pp.left = s;
3021     else
3022     pp.right = s;
3023     if (sr != null)
3024     replacement = sr;
3025     else
3026     replacement = p;
3027     }
3028     else if (pl != null)
3029     replacement = pl;
3030     else if (pr != null)
3031     replacement = pr;
3032     else
3033     replacement = p;
3034     if (replacement != p) {
3035     TreeNode<K,V> pp = replacement.parent = p.parent;
3036     if (pp == null)
3037     r = replacement;
3038     else if (p == pp.left)
3039     pp.left = replacement;
3040     else
3041     pp.right = replacement;
3042     p.left = p.right = p.parent = null;
3043     }
3044    
3045     root = (p.red) ? r : balanceDeletion(r, replacement);
3046    
3047     if (p == replacement) { // detach pointers
3048     TreeNode<K,V> pp;
3049     if ((pp = p.parent) != null) {
3050     if (p == pp.left)
3051     pp.left = null;
3052     else if (p == pp.right)
3053     pp.right = null;
3054     p.parent = null;
3055     }
3056     }
3057     } finally {
3058     unlockRoot();
3059     }
3060 dl 1.224 assert checkInvariants(root);
3061 dl 1.222 return false;
3062 dl 1.210 }
3063    
3064 dl 1.222 /* ------------------------------------------------------------ */
3065     // Red-black tree methods, all adapted from CLR
3066 dl 1.210
3067 dl 1.222 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3068     TreeNode<K,V> p) {
3069 dl 1.224 TreeNode<K,V> r, pp, rl;
3070     if (p != null && (r = p.right) != null) {
3071 dl 1.222 if ((rl = p.right = r.left) != null)
3072     rl.parent = p;
3073     if ((pp = r.parent = p.parent) == null)
3074     (root = r).red = false;
3075     else if (pp.left == p)
3076     pp.left = r;
3077     else
3078     pp.right = r;
3079     r.left = p;
3080     p.parent = r;
3081     }
3082     return root;
3083 dl 1.119 }
3084    
3085 dl 1.222 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3086     TreeNode<K,V> p) {
3087 dl 1.224 TreeNode<K,V> l, pp, lr;
3088     if (p != null && (l = p.left) != null) {
3089 dl 1.222 if ((lr = p.left = l.right) != null)
3090     lr.parent = p;
3091     if ((pp = l.parent = p.parent) == null)
3092     (root = l).red = false;
3093     else if (pp.right == p)
3094     pp.right = l;
3095     else
3096     pp.left = l;
3097     l.right = p;
3098     p.parent = l;
3099     }
3100     return root;
3101 dl 1.119 }
3102    
3103 dl 1.222 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3104     TreeNode<K,V> x) {
3105     x.red = true;
3106     for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3107     if ((xp = x.parent) == null) {
3108     x.red = false;
3109     return x;
3110     }
3111     else if (!xp.red || (xpp = xp.parent) == null)
3112     return root;
3113     if (xp == (xppl = xpp.left)) {
3114     if ((xppr = xpp.right) != null && xppr.red) {
3115     xppr.red = false;
3116     xp.red = false;
3117     xpp.red = true;
3118     x = xpp;
3119     }
3120     else {
3121     if (x == xp.right) {
3122     root = rotateLeft(root, x = xp);
3123     xpp = (xp = x.parent) == null ? null : xp.parent;
3124     }
3125     if (xp != null) {
3126     xp.red = false;
3127     if (xpp != null) {
3128     xpp.red = true;
3129     root = rotateRight(root, xpp);
3130     }
3131     }
3132     }
3133     }
3134     else {
3135     if (xppl != null && xppl.red) {
3136     xppl.red = false;
3137     xp.red = false;
3138     xpp.red = true;
3139     x = xpp;
3140     }
3141     else {
3142     if (x == xp.left) {
3143     root = rotateRight(root, x = xp);
3144     xpp = (xp = x.parent) == null ? null : xp.parent;
3145     }
3146     if (xp != null) {
3147     xp.red = false;
3148     if (xpp != null) {
3149     xpp.red = true;
3150     root = rotateLeft(root, xpp);
3151     }
3152     }
3153     }
3154     }
3155     }
3156 dl 1.119 }
3157    
3158 dl 1.222 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3159     TreeNode<K,V> x) {
3160 jsr166 1.256 for (TreeNode<K,V> xp, xpl, xpr;;) {
3161 dl 1.222 if (x == null || x == root)
3162     return root;
3163     else if ((xp = x.parent) == null) {
3164     x.red = false;
3165     return x;
3166     }
3167     else if (x.red) {
3168     x.red = false;
3169     return root;
3170     }
3171     else if ((xpl = xp.left) == x) {
3172     if ((xpr = xp.right) != null && xpr.red) {
3173     xpr.red = false;
3174     xp.red = true;
3175     root = rotateLeft(root, xp);
3176     xpr = (xp = x.parent) == null ? null : xp.right;
3177     }
3178     if (xpr == null)
3179     x = xp;
3180     else {
3181     TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3182     if ((sr == null || !sr.red) &&
3183     (sl == null || !sl.red)) {
3184     xpr.red = true;
3185     x = xp;
3186     }
3187     else {
3188     if (sr == null || !sr.red) {
3189     if (sl != null)
3190     sl.red = false;
3191     xpr.red = true;
3192     root = rotateRight(root, xpr);
3193     xpr = (xp = x.parent) == null ?
3194     null : xp.right;
3195     }
3196     if (xpr != null) {
3197     xpr.red = (xp == null) ? false : xp.red;
3198     if ((sr = xpr.right) != null)
3199     sr.red = false;
3200     }
3201     if (xp != null) {
3202     xp.red = false;
3203     root = rotateLeft(root, xp);
3204     }
3205     x = root;
3206     }
3207     }
3208     }
3209     else { // symmetric
3210     if (xpl != null && xpl.red) {
3211     xpl.red = false;
3212     xp.red = true;
3213     root = rotateRight(root, xp);
3214     xpl = (xp = x.parent) == null ? null : xp.left;
3215     }
3216     if (xpl == null)
3217     x = xp;
3218     else {
3219     TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3220     if ((sl == null || !sl.red) &&
3221     (sr == null || !sr.red)) {
3222     xpl.red = true;
3223     x = xp;
3224     }
3225     else {
3226     if (sl == null || !sl.red) {
3227     if (sr != null)
3228     sr.red = false;
3229     xpl.red = true;
3230     root = rotateLeft(root, xpl);
3231     xpl = (xp = x.parent) == null ?
3232     null : xp.left;
3233     }
3234     if (xpl != null) {
3235     xpl.red = (xp == null) ? false : xp.red;
3236     if ((sl = xpl.left) != null)
3237     sl.red = false;
3238     }
3239     if (xp != null) {
3240     xp.red = false;
3241     root = rotateRight(root, xp);
3242     }
3243     x = root;
3244     }
3245     }
3246     }
3247     }
3248 dl 1.210 }
3249 jsr166 1.225
3250 dl 1.222 /**
3251 jsr166 1.285 * Checks invariants recursively for the tree of Nodes rooted at t.
3252 dl 1.222 */
3253 dl 1.224 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3254 dl 1.222 TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3255     tb = t.prev, tn = (TreeNode<K,V>)t.next;
3256     if (tb != null && tb.next != t)
3257     return false;
3258     if (tn != null && tn.prev != t)
3259     return false;
3260     if (tp != null && t != tp.left && t != tp.right)
3261     return false;
3262     if (tl != null && (tl.parent != t || tl.hash > t.hash))
3263     return false;
3264     if (tr != null && (tr.parent != t || tr.hash < t.hash))
3265     return false;
3266     if (t.red && tl != null && tl.red && tr != null && tr.red)
3267     return false;
3268 dl 1.224 if (tl != null && !checkInvariants(tl))
3269 dl 1.222 return false;
3270 dl 1.224 if (tr != null && !checkInvariants(tr))
3271 dl 1.210 return false;
3272     return true;
3273     }
3274 dl 1.146
3275 jsr166 1.293 private static final Unsafe U = Unsafe.getUnsafe();
3276 dl 1.222 private static final long LOCKSTATE;
3277     static {
3278     try {
3279     LOCKSTATE = U.objectFieldOffset
3280 jsr166 1.264 (TreeBin.class.getDeclaredField("lockState"));
3281 jsr166 1.262 } catch (ReflectiveOperationException e) {
3282 dl 1.222 throw new Error(e);
3283     }
3284 dl 1.146 }
3285 dl 1.119 }
3286    
3287 dl 1.222 /* ----------------Table Traversal -------------- */
3288    
3289 jsr166 1.247 /**
3290     * Records the table, its length, and current traversal index for a
3291     * traverser that must process a region of a forwarded table before
3292     * proceeding with current table.
3293     */
3294     static final class TableStack<K,V> {
3295 dl 1.246 int length;
3296     int index;
3297     Node<K,V>[] tab;
3298 jsr166 1.247 TableStack<K,V> next;
3299 dl 1.246 }
3300    
3301 dl 1.222 /**
3302     * Encapsulates traversal for methods such as containsValue; also
3303     * serves as a base class for other iterators and spliterators.
3304     *
3305     * Method advance visits once each still-valid node that was
3306     * reachable upon iterator construction. It might miss some that
3307     * were added to a bin after the bin was visited, which is OK wrt
3308     * consistency guarantees. Maintaining this property in the face
3309     * of possible ongoing resizes requires a fair amount of
3310     * bookkeeping state that is difficult to optimize away amidst
3311     * volatile accesses. Even so, traversal maintains reasonable
3312     * throughput.
3313     *
3314     * Normally, iteration proceeds bin-by-bin traversing lists.
3315     * However, if the table has been resized, then all future steps
3316     * must traverse both the bin at the current index as well as at
3317     * (index + baseSize); and so on for further resizings. To
3318     * paranoically cope with potential sharing by users of iterators
3319     * across threads, iteration terminates if a bounds checks fails
3320     * for a table read.
3321     */
3322     static class Traverser<K,V> {
3323     Node<K,V>[] tab; // current table; updated if resized
3324     Node<K,V> next; // the next entry to use
3325 dl 1.246 TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3326 dl 1.222 int index; // index of bin to use next
3327     int baseIndex; // current index of initial table
3328     int baseLimit; // index bound for initial table
3329     final int baseSize; // initial table size
3330    
3331     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3332     this.tab = tab;
3333     this.baseSize = size;
3334     this.baseIndex = this.index = index;
3335     this.baseLimit = limit;
3336     this.next = null;
3337     }
3338    
3339     /**
3340     * Advances if possible, returning next valid node, or null if none.
3341     */
3342     final Node<K,V> advance() {
3343     Node<K,V> e;
3344     if ((e = next) != null)
3345     e = e.next;
3346     for (;;) {
3347 dl 1.246 Node<K,V>[] t; int i, n; // must use locals in checks
3348 dl 1.222 if (e != null)
3349     return next = e;
3350     if (baseIndex >= baseLimit || (t = tab) == null ||
3351     (n = t.length) <= (i = index) || i < 0)
3352     return next = null;
3353 dl 1.246 if ((e = tabAt(t, i)) != null && e.hash < 0) {
3354 dl 1.222 if (e instanceof ForwardingNode) {
3355     tab = ((ForwardingNode<K,V>)e).nextTable;
3356     e = null;
3357 dl 1.246 pushState(t, i, n);
3358 dl 1.222 continue;
3359     }
3360     else if (e instanceof TreeBin)
3361     e = ((TreeBin<K,V>)e).first;
3362     else
3363     e = null;
3364     }
3365 dl 1.246 if (stack != null)
3366     recoverState(n);
3367     else if ((index = i + baseSize) >= n)
3368     index = ++baseIndex; // visit upper slots if present
3369 dl 1.222 }
3370     }
3371 dl 1.246
3372     /**
3373 jsr166 1.249 * Saves traversal state upon encountering a forwarding node.
3374 dl 1.246 */
3375     private void pushState(Node<K,V>[] t, int i, int n) {
3376     TableStack<K,V> s = spare; // reuse if possible
3377     if (s != null)
3378     spare = s.next;
3379     else
3380     s = new TableStack<K,V>();
3381     s.tab = t;
3382     s.length = n;
3383     s.index = i;
3384     s.next = stack;
3385     stack = s;
3386     }
3387    
3388     /**
3389 jsr166 1.249 * Possibly pops traversal state.
3390 dl 1.246 *
3391     * @param n length of current table
3392     */
3393     private void recoverState(int n) {
3394     TableStack<K,V> s; int len;
3395     while ((s = stack) != null && (index += (len = s.length)) >= n) {
3396     n = len;
3397     index = s.index;
3398     tab = s.tab;
3399     s.tab = null;
3400     TableStack<K,V> next = s.next;
3401     s.next = spare; // save for reuse
3402     stack = next;
3403     spare = s;
3404     }
3405     if (s == null && (index += baseSize) >= n)
3406     index = ++baseIndex;
3407     }
3408 dl 1.222 }
3409    
3410     /**
3411     * Base of key, value, and entry Iterators. Adds fields to
3412 jsr166 1.229 * Traverser to support iterator.remove.
3413 dl 1.222 */
3414     static class BaseIterator<K,V> extends Traverser<K,V> {
3415     final ConcurrentHashMap<K,V> map;
3416     Node<K,V> lastReturned;
3417     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3418     ConcurrentHashMap<K,V> map) {
3419 dl 1.210 super(tab, size, index, limit);
3420     this.map = map;
3421 dl 1.222 advance();
3422 dl 1.210 }
3423    
3424 dl 1.222 public final boolean hasNext() { return next != null; }
3425     public final boolean hasMoreElements() { return next != null; }
3426    
3427     public final void remove() {
3428     Node<K,V> p;
3429     if ((p = lastReturned) == null)
3430     throw new IllegalStateException();
3431     lastReturned = null;
3432     map.replaceNode(p.key, null, null);
3433 dl 1.210 }
3434 dl 1.222 }
3435 dl 1.210
3436 dl 1.222 static final class KeyIterator<K,V> extends BaseIterator<K,V>
3437     implements Iterator<K>, Enumeration<K> {
3438 jsr166 1.298 KeyIterator(Node<K,V>[] tab, int size, int index, int limit,
3439 dl 1.222 ConcurrentHashMap<K,V> map) {
3440 jsr166 1.298 super(tab, size, index, limit, map);
3441 dl 1.210 }
3442    
3443 dl 1.222 public final K next() {
3444 dl 1.210 Node<K,V> p;
3445 dl 1.222 if ((p = next) == null)
3446     throw new NoSuchElementException();
3447     K k = p.key;
3448     lastReturned = p;
3449     advance();
3450     return k;
3451 dl 1.210 }
3452    
3453 dl 1.222 public final K nextElement() { return next(); }
3454     }
3455    
3456     static final class ValueIterator<K,V> extends BaseIterator<K,V>
3457     implements Iterator<V>, Enumeration<V> {
3458 jsr166 1.298 ValueIterator(Node<K,V>[] tab, int size, int index, int limit,
3459 dl 1.222 ConcurrentHashMap<K,V> map) {
3460 jsr166 1.298 super(tab, size, index, limit, map);
3461 dl 1.222 }
3462 dl 1.210
3463 dl 1.222 public final V next() {
3464     Node<K,V> p;
3465     if ((p = next) == null)
3466     throw new NoSuchElementException();
3467     V v = p.val;
3468     lastReturned = p;
3469     advance();
3470     return v;
3471 dl 1.210 }
3472 dl 1.222
3473     public final V nextElement() { return next(); }
3474 dl 1.210 }
3475    
3476 dl 1.222 static final class EntryIterator<K,V> extends BaseIterator<K,V>
3477     implements Iterator<Map.Entry<K,V>> {
3478 jsr166 1.298 EntryIterator(Node<K,V>[] tab, int size, int index, int limit,
3479 dl 1.222 ConcurrentHashMap<K,V> map) {
3480 jsr166 1.298 super(tab, size, index, limit, map);
3481 dl 1.222 }
3482 dl 1.210
3483 dl 1.222 public final Map.Entry<K,V> next() {
3484     Node<K,V> p;
3485     if ((p = next) == null)
3486     throw new NoSuchElementException();
3487     K k = p.key;
3488     V v = p.val;
3489     lastReturned = p;
3490     advance();
3491     return new MapEntry<K,V>(k, v, map);
3492     }
3493     }
3494 dl 1.119
3495     /**
3496 jsr166 1.285 * Exported Entry for EntryIterator.
3497 dl 1.119 */
3498 dl 1.222 static final class MapEntry<K,V> implements Map.Entry<K,V> {
3499     final K key; // non-null
3500     V val; // non-null
3501     final ConcurrentHashMap<K,V> map;
3502     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3503     this.key = key;
3504     this.val = val;
3505     this.map = map;
3506     }
3507     public K getKey() { return key; }
3508     public V getValue() { return val; }
3509     public int hashCode() { return key.hashCode() ^ val.hashCode(); }
3510 jsr166 1.268 public String toString() {
3511     return Helpers.mapEntryToString(key, val);
3512     }
3513 dl 1.119
3514 dl 1.222 public boolean equals(Object o) {
3515     Object k, v; Map.Entry<?,?> e;
3516     return ((o instanceof Map.Entry) &&
3517     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3518     (v = e.getValue()) != null &&
3519     (k == key || k.equals(key)) &&
3520     (v == val || v.equals(val)));
3521     }
3522 dl 1.119
3523 dl 1.222 /**
3524     * Sets our entry's value and writes through to the map. The
3525     * value to return is somewhat arbitrary here. Since we do not
3526     * necessarily track asynchronous changes, the most recent
3527     * "previous" value could be different from what we return (or
3528     * could even have been removed, in which case the put will
3529     * re-establish). We do not and cannot guarantee more.
3530     */
3531     public V setValue(V value) {
3532     if (value == null) throw new NullPointerException();
3533     V v = val;
3534     val = value;
3535     map.put(key, value);
3536     return v;
3537     }
3538 dl 1.119 }
3539    
3540 dl 1.222 static final class KeySpliterator<K,V> extends Traverser<K,V>
3541     implements Spliterator<K> {
3542     long est; // size estimate
3543     KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3544     long est) {
3545     super(tab, size, index, limit);
3546     this.est = est;
3547     }
3548 dl 1.119
3549 jsr166 1.286 public KeySpliterator<K,V> trySplit() {
3550 dl 1.222 int i, f, h;
3551     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3552     new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3553     f, est >>>= 1);
3554 dl 1.119 }
3555    
3556 dl 1.222 public void forEachRemaining(Consumer<? super K> action) {
3557     if (action == null) throw new NullPointerException();
3558     for (Node<K,V> p; (p = advance()) != null;)
3559     action.accept(p.key);
3560 dl 1.119 }
3561    
3562 dl 1.222 public boolean tryAdvance(Consumer<? super K> action) {
3563     if (action == null) throw new NullPointerException();
3564     Node<K,V> p;
3565     if ((p = advance()) == null)
3566 dl 1.119 return false;
3567 dl 1.222 action.accept(p.key);
3568     return true;
3569 dl 1.119 }
3570    
3571 dl 1.222 public long estimateSize() { return est; }
3572 dl 1.119
3573 dl 1.222 public int characteristics() {
3574     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3575     Spliterator.NONNULL;
3576     }
3577 dl 1.142 }
3578 dl 1.119
3579 dl 1.222 static final class ValueSpliterator<K,V> extends Traverser<K,V>
3580     implements Spliterator<V> {
3581     long est; // size estimate
3582     ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3583     long est) {
3584     super(tab, size, index, limit);
3585     this.est = est;
3586 dl 1.209 }
3587    
3588 jsr166 1.286 public ValueSpliterator<K,V> trySplit() {
3589 dl 1.222 int i, f, h;
3590     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3591     new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3592     f, est >>>= 1);
3593 dl 1.142 }
3594 dl 1.119
3595 dl 1.222 public void forEachRemaining(Consumer<? super V> action) {
3596     if (action == null) throw new NullPointerException();
3597     for (Node<K,V> p; (p = advance()) != null;)
3598     action.accept(p.val);
3599     }
3600 dl 1.119
3601 dl 1.222 public boolean tryAdvance(Consumer<? super V> action) {
3602     if (action == null) throw new NullPointerException();
3603     Node<K,V> p;
3604     if ((p = advance()) == null)
3605     return false;
3606     action.accept(p.val);
3607     return true;
3608 dl 1.119 }
3609 dl 1.222
3610     public long estimateSize() { return est; }
3611    
3612     public int characteristics() {
3613     return Spliterator.CONCURRENT | Spliterator.NONNULL;
3614 dl 1.119 }
3615 dl 1.142 }
3616 dl 1.119
3617 dl 1.222 static final class EntrySpliterator<K,V> extends Traverser<K,V>
3618     implements Spliterator<Map.Entry<K,V>> {
3619     final ConcurrentHashMap<K,V> map; // To export MapEntry
3620     long est; // size estimate
3621     EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3622     long est, ConcurrentHashMap<K,V> map) {
3623     super(tab, size, index, limit);
3624     this.map = map;
3625     this.est = est;
3626     }
3627    
3628 jsr166 1.286 public EntrySpliterator<K,V> trySplit() {
3629 dl 1.222 int i, f, h;
3630     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3631     new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3632     f, est >>>= 1, map);
3633     }
3634 dl 1.142
3635 dl 1.222 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3636     if (action == null) throw new NullPointerException();
3637     for (Node<K,V> p; (p = advance()) != null; )
3638     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3639     }
3640 dl 1.210
3641 dl 1.222 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3642     if (action == null) throw new NullPointerException();
3643     Node<K,V> p;
3644     if ((p = advance()) == null)
3645     return false;
3646     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3647     return true;
3648 dl 1.210 }
3649    
3650 dl 1.222 public long estimateSize() { return est; }
3651    
3652     public int characteristics() {
3653     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3654     Spliterator.NONNULL;
3655 dl 1.210 }
3656     }
3657    
3658     // Parallel bulk operations
3659    
3660     /**
3661     * Computes initial batch value for bulk tasks. The returned value
3662     * is approximately exp2 of the number of times (minus one) to
3663     * split task by two before executing leaf action. This value is
3664     * faster to compute and more convenient to use as a guide to
3665     * splitting than is the depth, since it is used while dividing by
3666     * two anyway.
3667     */
3668     final int batchFor(long b) {
3669     long n;
3670     if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3671     return 0;
3672     int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3673     return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3674     }
3675 dl 1.151
3676 dl 1.119 /**
3677 dl 1.137 * Performs the given action for each (key, value).
3678 dl 1.119 *
3679 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3680 jsr166 1.213 * needed for this operation to be executed in parallel
3681 dl 1.137 * @param action the action
3682 jsr166 1.220 * @since 1.8
3683 dl 1.119 */
3684 dl 1.210 public void forEach(long parallelismThreshold,
3685     BiConsumer<? super K,? super V> action) {
3686 dl 1.151 if (action == null) throw new NullPointerException();
3687 dl 1.210 new ForEachMappingTask<K,V>
3688     (null, batchFor(parallelismThreshold), 0, 0, table,
3689     action).invoke();
3690 dl 1.119 }
3691    
3692     /**
3693 dl 1.137 * Performs the given action for each non-null transformation
3694     * of each (key, value).
3695     *
3696 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3697 jsr166 1.213 * needed for this operation to be executed in parallel
3698 dl 1.137 * @param transformer a function returning the transformation
3699 jsr166 1.169 * for an element, or null if there is no transformation (in
3700 jsr166 1.172 * which case the action is not applied)
3701 dl 1.137 * @param action the action
3702 jsr166 1.237 * @param <U> the return type of the transformer
3703 jsr166 1.220 * @since 1.8
3704 dl 1.119 */
3705 dl 1.210 public <U> void forEach(long parallelismThreshold,
3706     BiFunction<? super K, ? super V, ? extends U> transformer,
3707     Consumer<? super U> action) {
3708 dl 1.151 if (transformer == null || action == null)
3709     throw new NullPointerException();
3710 dl 1.210 new ForEachTransformedMappingTask<K,V,U>
3711     (null, batchFor(parallelismThreshold), 0, 0, table,
3712     transformer, action).invoke();
3713 dl 1.137 }
3714    
3715     /**
3716     * Returns a non-null result from applying the given search
3717 dl 1.210 * function on each (key, value), or null if none. Upon
3718     * success, further element processing is suppressed and the
3719     * results of any other parallel invocations of the search
3720     * function are ignored.
3721 dl 1.137 *
3722 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3723 jsr166 1.213 * needed for this operation to be executed in parallel
3724 dl 1.137 * @param searchFunction a function returning a non-null
3725     * result on success, else null
3726 jsr166 1.237 * @param <U> the return type of the search function
3727 dl 1.137 * @return a non-null result from applying the given search
3728     * function on each (key, value), or null if none
3729 jsr166 1.220 * @since 1.8
3730 dl 1.137 */
3731 dl 1.210 public <U> U search(long parallelismThreshold,
3732     BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3733 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3734 dl 1.210 return new SearchMappingsTask<K,V,U>
3735     (null, batchFor(parallelismThreshold), 0, 0, table,
3736     searchFunction, new AtomicReference<U>()).invoke();
3737 dl 1.137 }
3738    
3739     /**
3740     * Returns the result of accumulating the given transformation
3741     * of all (key, value) pairs using the given reducer to
3742     * combine values, or null if none.
3743     *
3744 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3745 jsr166 1.213 * needed for this operation to be executed in parallel
3746 dl 1.137 * @param transformer a function returning the transformation
3747 jsr166 1.169 * for an element, or null if there is no transformation (in
3748 jsr166 1.172 * which case it is not combined)
3749 dl 1.137 * @param reducer a commutative associative combining function
3750 jsr166 1.237 * @param <U> the return type of the transformer
3751 dl 1.137 * @return the result of accumulating the given transformation
3752     * of all (key, value) pairs
3753 jsr166 1.220 * @since 1.8
3754 dl 1.137 */
3755 dl 1.210 public <U> U reduce(long parallelismThreshold,
3756     BiFunction<? super K, ? super V, ? extends U> transformer,
3757     BiFunction<? super U, ? super U, ? extends U> reducer) {
3758 dl 1.151 if (transformer == null || reducer == null)
3759     throw new NullPointerException();
3760 dl 1.210 return new MapReduceMappingsTask<K,V,U>
3761     (null, batchFor(parallelismThreshold), 0, 0, table,
3762     null, transformer, reducer).invoke();
3763 dl 1.137 }
3764    
3765     /**
3766     * Returns the result of accumulating the given transformation
3767     * of all (key, value) pairs using the given reducer to
3768     * combine values, and the given basis as an identity value.
3769     *
3770 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3771 jsr166 1.213 * needed for this operation to be executed in parallel
3772 dl 1.137 * @param transformer a function returning the transformation
3773     * for an element
3774     * @param basis the identity (initial default value) for the reduction
3775     * @param reducer a commutative associative combining function
3776     * @return the result of accumulating the given transformation
3777     * of all (key, value) pairs
3778 jsr166 1.220 * @since 1.8
3779 dl 1.137 */
3780 dl 1.231 public double reduceToDouble(long parallelismThreshold,
3781     ToDoubleBiFunction<? super K, ? super V> transformer,
3782     double basis,
3783     DoubleBinaryOperator reducer) {
3784 dl 1.151 if (transformer == null || reducer == null)
3785     throw new NullPointerException();
3786 dl 1.210 return new MapReduceMappingsToDoubleTask<K,V>
3787     (null, batchFor(parallelismThreshold), 0, 0, table,
3788     null, transformer, basis, reducer).invoke();
3789 dl 1.137 }
3790 dl 1.119
3791 dl 1.137 /**
3792     * Returns the result of accumulating the given transformation
3793     * of all (key, value) pairs using the given reducer to
3794     * combine values, and the given basis as an identity value.
3795     *
3796 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3797 jsr166 1.213 * needed for this operation to be executed in parallel
3798 dl 1.137 * @param transformer a function returning the transformation
3799     * for an element
3800     * @param basis the identity (initial default value) for the reduction
3801     * @param reducer a commutative associative combining function
3802     * @return the result of accumulating the given transformation
3803     * of all (key, value) pairs
3804 jsr166 1.220 * @since 1.8
3805 dl 1.137 */
3806 dl 1.210 public long reduceToLong(long parallelismThreshold,
3807     ToLongBiFunction<? super K, ? super V> transformer,
3808     long basis,
3809     LongBinaryOperator reducer) {
3810 dl 1.151 if (transformer == null || reducer == null)
3811     throw new NullPointerException();
3812 dl 1.210 return new MapReduceMappingsToLongTask<K,V>
3813     (null, batchFor(parallelismThreshold), 0, 0, table,
3814     null, transformer, basis, reducer).invoke();
3815 dl 1.137 }
3816    
3817     /**
3818     * Returns the result of accumulating the given transformation
3819     * of all (key, value) pairs using the given reducer to
3820     * combine values, and the given basis as an identity value.
3821     *
3822 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3823 jsr166 1.213 * needed for this operation to be executed in parallel
3824 dl 1.137 * @param transformer a function returning the transformation
3825     * for an element
3826     * @param basis the identity (initial default value) for the reduction
3827     * @param reducer a commutative associative combining function
3828     * @return the result of accumulating the given transformation
3829     * of all (key, value) pairs
3830 jsr166 1.220 * @since 1.8
3831 dl 1.137 */
3832 dl 1.210 public int reduceToInt(long parallelismThreshold,
3833     ToIntBiFunction<? super K, ? super V> transformer,
3834     int basis,
3835     IntBinaryOperator reducer) {
3836 dl 1.151 if (transformer == null || reducer == null)
3837     throw new NullPointerException();
3838 dl 1.210 return new MapReduceMappingsToIntTask<K,V>
3839     (null, batchFor(parallelismThreshold), 0, 0, table,
3840     null, transformer, basis, reducer).invoke();
3841 dl 1.137 }
3842    
3843     /**
3844     * Performs the given action for each key.
3845     *
3846 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3847 jsr166 1.213 * needed for this operation to be executed in parallel
3848 dl 1.137 * @param action the action
3849 jsr166 1.220 * @since 1.8
3850 dl 1.137 */
3851 dl 1.210 public void forEachKey(long parallelismThreshold,
3852     Consumer<? super K> action) {
3853     if (action == null) throw new NullPointerException();
3854     new ForEachKeyTask<K,V>
3855     (null, batchFor(parallelismThreshold), 0, 0, table,
3856     action).invoke();
3857 dl 1.137 }
3858 dl 1.119
3859 dl 1.137 /**
3860     * Performs the given action for each non-null transformation
3861     * of each key.
3862     *
3863 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3864 jsr166 1.213 * needed for this operation to be executed in parallel
3865 dl 1.137 * @param transformer a function returning the transformation
3866 jsr166 1.169 * for an element, or null if there is no transformation (in
3867 jsr166 1.172 * which case the action is not applied)
3868 dl 1.137 * @param action the action
3869 jsr166 1.237 * @param <U> the return type of the transformer
3870 jsr166 1.220 * @since 1.8
3871 dl 1.137 */
3872 dl 1.210 public <U> void forEachKey(long parallelismThreshold,
3873     Function<? super K, ? extends U> transformer,
3874     Consumer<? super U> action) {
3875 dl 1.151 if (transformer == null || action == null)
3876     throw new NullPointerException();
3877 dl 1.210 new ForEachTransformedKeyTask<K,V,U>
3878     (null, batchFor(parallelismThreshold), 0, 0, table,
3879     transformer, action).invoke();
3880 dl 1.137 }
3881 dl 1.119
3882 dl 1.137 /**
3883     * Returns a non-null result from applying the given search
3884 dl 1.210 * function on each key, or null if none. Upon success,
3885     * further element processing is suppressed and the results of
3886     * any other parallel invocations of the search function are
3887     * ignored.
3888 dl 1.137 *
3889 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3890 jsr166 1.213 * needed for this operation to be executed in parallel
3891 dl 1.137 * @param searchFunction a function returning a non-null
3892     * result on success, else null
3893 jsr166 1.237 * @param <U> the return type of the search function
3894 dl 1.137 * @return a non-null result from applying the given search
3895     * function on each key, or null if none
3896 jsr166 1.220 * @since 1.8
3897 dl 1.137 */
3898 dl 1.210 public <U> U searchKeys(long parallelismThreshold,
3899     Function<? super K, ? extends U> searchFunction) {
3900     if (searchFunction == null) throw new NullPointerException();
3901     return new SearchKeysTask<K,V,U>
3902     (null, batchFor(parallelismThreshold), 0, 0, table,
3903     searchFunction, new AtomicReference<U>()).invoke();
3904 dl 1.137 }
3905 dl 1.119
3906 dl 1.137 /**
3907     * Returns the result of accumulating all keys using the given
3908     * reducer to combine values, or null if none.
3909     *
3910 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3911 jsr166 1.213 * needed for this operation to be executed in parallel
3912 dl 1.137 * @param reducer a commutative associative combining function
3913     * @return the result of accumulating all keys using the given
3914     * reducer to combine values, or null if none
3915 jsr166 1.220 * @since 1.8
3916 dl 1.137 */
3917 dl 1.210 public K reduceKeys(long parallelismThreshold,
3918     BiFunction<? super K, ? super K, ? extends K> reducer) {
3919 dl 1.151 if (reducer == null) throw new NullPointerException();
3920 dl 1.210 return new ReduceKeysTask<K,V>
3921     (null, batchFor(parallelismThreshold), 0, 0, table,
3922     null, reducer).invoke();
3923 dl 1.137 }
3924 dl 1.119
3925 dl 1.137 /**
3926     * Returns the result of accumulating the given transformation
3927     * of all keys using the given reducer to combine values, or
3928     * null if none.
3929     *
3930 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3931 jsr166 1.213 * needed for this operation to be executed in parallel
3932 dl 1.137 * @param transformer a function returning the transformation
3933 jsr166 1.169 * for an element, or null if there is no transformation (in
3934 jsr166 1.172 * which case it is not combined)
3935 dl 1.137 * @param reducer a commutative associative combining function
3936 jsr166 1.237 * @param <U> the return type of the transformer
3937 dl 1.137 * @return the result of accumulating the given transformation
3938     * of all keys
3939 jsr166 1.220 * @since 1.8
3940 dl 1.137 */
3941 dl 1.210 public <U> U reduceKeys(long parallelismThreshold,
3942     Function<? super K, ? extends U> transformer,
3943 dl 1.153 BiFunction<? super U, ? super U, ? extends U> reducer) {
3944 dl 1.151 if (transformer == null || reducer == null)
3945     throw new NullPointerException();
3946 dl 1.210 return new MapReduceKeysTask<K,V,U>
3947     (null, batchFor(parallelismThreshold), 0, 0, table,
3948     null, transformer, reducer).invoke();
3949 dl 1.137 }
3950 dl 1.119
3951 dl 1.137 /**
3952     * Returns the result of accumulating the given transformation
3953     * of all keys using the given reducer to combine values, and
3954     * the given basis as an identity value.
3955     *
3956 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3957 jsr166 1.213 * needed for this operation to be executed in parallel
3958 dl 1.137 * @param transformer a function returning the transformation
3959     * for an element
3960     * @param basis the identity (initial default value) for the reduction
3961     * @param reducer a commutative associative combining function
3962 jsr166 1.157 * @return the result of accumulating the given transformation
3963 dl 1.137 * of all keys
3964 jsr166 1.220 * @since 1.8
3965 dl 1.137 */
3966 dl 1.210 public double reduceKeysToDouble(long parallelismThreshold,
3967     ToDoubleFunction<? super K> transformer,
3968     double basis,
3969     DoubleBinaryOperator reducer) {
3970 dl 1.151 if (transformer == null || reducer == null)
3971     throw new NullPointerException();
3972 dl 1.210 return new MapReduceKeysToDoubleTask<K,V>
3973     (null, batchFor(parallelismThreshold), 0, 0, table,
3974     null, transformer, basis, reducer).invoke();
3975 dl 1.137 }
3976 dl 1.119
3977 dl 1.137 /**
3978     * Returns the result of accumulating the given transformation
3979     * of all keys using the given reducer to combine values, and
3980     * the given basis as an identity value.
3981     *
3982 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3983 jsr166 1.213 * needed for this operation to be executed in parallel
3984 dl 1.137 * @param transformer a function returning the transformation
3985     * for an element
3986     * @param basis the identity (initial default value) for the reduction
3987     * @param reducer a commutative associative combining function
3988     * @return the result of accumulating the given transformation
3989     * of all keys
3990 jsr166 1.220 * @since 1.8
3991 dl 1.137 */
3992 dl 1.210 public long reduceKeysToLong(long parallelismThreshold,
3993     ToLongFunction<? super K> transformer,
3994     long basis,
3995     LongBinaryOperator reducer) {
3996 dl 1.151 if (transformer == null || reducer == null)
3997     throw new NullPointerException();
3998 dl 1.210 return new MapReduceKeysToLongTask<K,V>
3999     (null, batchFor(parallelismThreshold), 0, 0, table,
4000     null, transformer, basis, reducer).invoke();
4001 dl 1.137 }
4002 dl 1.119
4003 dl 1.137 /**
4004     * Returns the result of accumulating the given transformation
4005     * of all keys using the given reducer to combine values, and
4006     * the given basis as an identity value.
4007     *
4008 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4009 jsr166 1.213 * needed for this operation to be executed in parallel
4010 dl 1.137 * @param transformer a function returning the transformation
4011     * for an element
4012     * @param basis the identity (initial default value) for the reduction
4013     * @param reducer a commutative associative combining function
4014     * @return the result of accumulating the given transformation
4015     * of all keys
4016 jsr166 1.220 * @since 1.8
4017 dl 1.137 */
4018 dl 1.210 public int reduceKeysToInt(long parallelismThreshold,
4019     ToIntFunction<? super K> transformer,
4020     int basis,
4021     IntBinaryOperator reducer) {
4022 dl 1.151 if (transformer == null || reducer == null)
4023     throw new NullPointerException();
4024 dl 1.210 return new MapReduceKeysToIntTask<K,V>
4025     (null, batchFor(parallelismThreshold), 0, 0, table,
4026     null, transformer, basis, reducer).invoke();
4027 dl 1.137 }
4028 dl 1.119
4029 dl 1.137 /**
4030     * Performs the given action for each value.
4031     *
4032 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4033 jsr166 1.213 * needed for this operation to be executed in parallel
4034 dl 1.137 * @param action the action
4035 jsr166 1.220 * @since 1.8
4036 dl 1.137 */
4037 dl 1.210 public void forEachValue(long parallelismThreshold,
4038     Consumer<? super V> action) {
4039     if (action == null)
4040     throw new NullPointerException();
4041     new ForEachValueTask<K,V>
4042     (null, batchFor(parallelismThreshold), 0, 0, table,
4043     action).invoke();
4044 dl 1.137 }
4045 dl 1.119
4046 dl 1.137 /**
4047     * Performs the given action for each non-null transformation
4048     * of each value.
4049     *
4050 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4051 jsr166 1.213 * needed for this operation to be executed in parallel
4052 dl 1.137 * @param transformer a function returning the transformation
4053 jsr166 1.169 * for an element, or null if there is no transformation (in
4054 jsr166 1.172 * which case the action is not applied)
4055 jsr166 1.179 * @param action the action
4056 jsr166 1.237 * @param <U> the return type of the transformer
4057 jsr166 1.220 * @since 1.8
4058 dl 1.137 */
4059 dl 1.210 public <U> void forEachValue(long parallelismThreshold,
4060     Function<? super V, ? extends U> transformer,
4061     Consumer<? super U> action) {
4062 dl 1.151 if (transformer == null || action == null)
4063     throw new NullPointerException();
4064 dl 1.210 new ForEachTransformedValueTask<K,V,U>
4065     (null, batchFor(parallelismThreshold), 0, 0, table,
4066     transformer, action).invoke();
4067 dl 1.137 }
4068 dl 1.119
4069 dl 1.137 /**
4070     * Returns a non-null result from applying the given search
4071 dl 1.210 * function on each value, or null if none. Upon success,
4072     * further element processing is suppressed and the results of
4073     * any other parallel invocations of the search function are
4074     * ignored.
4075 dl 1.137 *
4076 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4077 jsr166 1.213 * needed for this operation to be executed in parallel
4078 dl 1.137 * @param searchFunction a function returning a non-null
4079     * result on success, else null
4080 jsr166 1.237 * @param <U> the return type of the search function
4081 dl 1.137 * @return a non-null result from applying the given search
4082     * function on each value, or null if none
4083 jsr166 1.220 * @since 1.8
4084 dl 1.137 */
4085 dl 1.210 public <U> U searchValues(long parallelismThreshold,
4086     Function<? super V, ? extends U> searchFunction) {
4087 dl 1.151 if (searchFunction == null) throw new NullPointerException();
4088 dl 1.210 return new SearchValuesTask<K,V,U>
4089     (null, batchFor(parallelismThreshold), 0, 0, table,
4090     searchFunction, new AtomicReference<U>()).invoke();
4091 dl 1.137 }
4092 dl 1.119
4093 dl 1.137 /**
4094     * Returns the result of accumulating all values using the
4095     * given reducer to combine values, or null if none.
4096     *
4097 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4098 jsr166 1.213 * needed for this operation to be executed in parallel
4099 dl 1.137 * @param reducer a commutative associative combining function
4100 jsr166 1.157 * @return the result of accumulating all values
4101 jsr166 1.220 * @since 1.8
4102 dl 1.137 */
4103 dl 1.210 public V reduceValues(long parallelismThreshold,
4104     BiFunction<? super V, ? super V, ? extends V> reducer) {
4105 dl 1.151 if (reducer == null) throw new NullPointerException();
4106 dl 1.210 return new ReduceValuesTask<K,V>
4107     (null, batchFor(parallelismThreshold), 0, 0, table,
4108     null, reducer).invoke();
4109 dl 1.137 }
4110 dl 1.119
4111 dl 1.137 /**
4112     * Returns the result of accumulating the given transformation
4113     * of all values using the given reducer to combine values, or
4114     * null if none.
4115     *
4116 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4117 jsr166 1.213 * needed for this operation to be executed in parallel
4118 dl 1.137 * @param transformer a function returning the transformation
4119 jsr166 1.169 * for an element, or null if there is no transformation (in
4120 jsr166 1.172 * which case it is not combined)
4121 dl 1.137 * @param reducer a commutative associative combining function
4122 jsr166 1.237 * @param <U> the return type of the transformer
4123 dl 1.137 * @return the result of accumulating the given transformation
4124     * of all values
4125 jsr166 1.220 * @since 1.8
4126 dl 1.137 */
4127 dl 1.210 public <U> U reduceValues(long parallelismThreshold,
4128     Function<? super V, ? extends U> transformer,
4129     BiFunction<? super U, ? super U, ? extends U> reducer) {
4130 dl 1.151 if (transformer == null || reducer == null)
4131     throw new NullPointerException();
4132 dl 1.210 return new MapReduceValuesTask<K,V,U>
4133     (null, batchFor(parallelismThreshold), 0, 0, table,
4134     null, transformer, reducer).invoke();
4135 dl 1.137 }
4136 dl 1.119
4137 dl 1.137 /**
4138     * Returns the result of accumulating the given transformation
4139     * of all values using the given reducer to combine values,
4140     * and the given basis as an identity value.
4141     *
4142 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4143 jsr166 1.213 * needed for this operation to be executed in parallel
4144 dl 1.137 * @param transformer a function returning the transformation
4145     * for an element
4146     * @param basis the identity (initial default value) for the reduction
4147     * @param reducer a commutative associative combining function
4148     * @return the result of accumulating the given transformation
4149     * of all values
4150 jsr166 1.220 * @since 1.8
4151 dl 1.137 */
4152 dl 1.210 public double reduceValuesToDouble(long parallelismThreshold,
4153     ToDoubleFunction<? super V> transformer,
4154     double basis,
4155     DoubleBinaryOperator reducer) {
4156 dl 1.151 if (transformer == null || reducer == null)
4157     throw new NullPointerException();
4158 dl 1.210 return new MapReduceValuesToDoubleTask<K,V>
4159     (null, batchFor(parallelismThreshold), 0, 0, table,
4160     null, transformer, basis, reducer).invoke();
4161 dl 1.137 }
4162 dl 1.119
4163 dl 1.137 /**
4164     * Returns the result of accumulating the given transformation
4165     * of all values using the given reducer to combine values,
4166     * and the given basis as an identity value.
4167     *
4168 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4169 jsr166 1.213 * needed for this operation to be executed in parallel
4170 dl 1.137 * @param transformer a function returning the transformation
4171     * for an element
4172     * @param basis the identity (initial default value) for the reduction
4173     * @param reducer a commutative associative combining function
4174     * @return the result of accumulating the given transformation
4175     * of all values
4176 jsr166 1.220 * @since 1.8
4177 dl 1.137 */
4178 dl 1.210 public long reduceValuesToLong(long parallelismThreshold,
4179     ToLongFunction<? super V> transformer,
4180     long basis,
4181     LongBinaryOperator reducer) {
4182 dl 1.151 if (transformer == null || reducer == null)
4183     throw new NullPointerException();
4184 dl 1.210 return new MapReduceValuesToLongTask<K,V>
4185     (null, batchFor(parallelismThreshold), 0, 0, table,
4186     null, transformer, basis, reducer).invoke();
4187 dl 1.137 }
4188 dl 1.119
4189 dl 1.137 /**
4190     * Returns the result of accumulating the given transformation
4191     * of all values using the given reducer to combine values,
4192     * and the given basis as an identity value.
4193     *
4194 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4195 jsr166 1.213 * needed for this operation to be executed in parallel
4196 dl 1.137 * @param transformer a function returning the transformation
4197     * for an element
4198     * @param basis the identity (initial default value) for the reduction
4199     * @param reducer a commutative associative combining function
4200     * @return the result of accumulating the given transformation
4201     * of all values
4202 jsr166 1.220 * @since 1.8
4203 dl 1.137 */
4204 dl 1.210 public int reduceValuesToInt(long parallelismThreshold,
4205     ToIntFunction<? super V> transformer,
4206     int basis,
4207     IntBinaryOperator reducer) {
4208 dl 1.151 if (transformer == null || reducer == null)
4209     throw new NullPointerException();
4210 dl 1.210 return new MapReduceValuesToIntTask<K,V>
4211     (null, batchFor(parallelismThreshold), 0, 0, table,
4212     null, transformer, basis, reducer).invoke();
4213 dl 1.137 }
4214 dl 1.119
4215 dl 1.137 /**
4216     * Performs the given action for each entry.
4217     *
4218 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4219 jsr166 1.213 * needed for this operation to be executed in parallel
4220 dl 1.137 * @param action the action
4221 jsr166 1.220 * @since 1.8
4222 dl 1.137 */
4223 dl 1.210 public void forEachEntry(long parallelismThreshold,
4224     Consumer<? super Map.Entry<K,V>> action) {
4225 dl 1.151 if (action == null) throw new NullPointerException();
4226 dl 1.210 new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4227     action).invoke();
4228 dl 1.137 }
4229 dl 1.119
4230 dl 1.137 /**
4231     * Performs the given action for each non-null transformation
4232     * of each entry.
4233     *
4234 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4235 jsr166 1.213 * needed for this operation to be executed in parallel
4236 dl 1.137 * @param transformer a function returning the transformation
4237 jsr166 1.169 * for an element, or null if there is no transformation (in
4238 jsr166 1.172 * which case the action is not applied)
4239 dl 1.137 * @param action the action
4240 jsr166 1.237 * @param <U> the return type of the transformer
4241 jsr166 1.220 * @since 1.8
4242 dl 1.137 */
4243 dl 1.210 public <U> void forEachEntry(long parallelismThreshold,
4244     Function<Map.Entry<K,V>, ? extends U> transformer,
4245     Consumer<? super U> action) {
4246 dl 1.151 if (transformer == null || action == null)
4247     throw new NullPointerException();
4248 dl 1.210 new ForEachTransformedEntryTask<K,V,U>
4249     (null, batchFor(parallelismThreshold), 0, 0, table,
4250     transformer, action).invoke();
4251 dl 1.137 }
4252 dl 1.119
4253 dl 1.137 /**
4254     * Returns a non-null result from applying the given search
4255 dl 1.210 * function on each entry, or null if none. Upon success,
4256     * further element processing is suppressed and the results of
4257     * any other parallel invocations of the search function are
4258     * ignored.
4259 dl 1.137 *
4260 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4261 jsr166 1.213 * needed for this operation to be executed in parallel
4262 dl 1.137 * @param searchFunction a function returning a non-null
4263     * result on success, else null
4264 jsr166 1.237 * @param <U> the return type of the search function
4265 dl 1.137 * @return a non-null result from applying the given search
4266     * function on each entry, or null if none
4267 jsr166 1.220 * @since 1.8
4268 dl 1.137 */
4269 dl 1.210 public <U> U searchEntries(long parallelismThreshold,
4270     Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4271 dl 1.151 if (searchFunction == null) throw new NullPointerException();
4272 dl 1.210 return new SearchEntriesTask<K,V,U>
4273     (null, batchFor(parallelismThreshold), 0, 0, table,
4274     searchFunction, new AtomicReference<U>()).invoke();
4275 dl 1.137 }
4276 dl 1.119
4277 dl 1.137 /**
4278     * Returns the result of accumulating all entries using the
4279     * given reducer to combine values, or null if none.
4280     *
4281 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4282 jsr166 1.213 * needed for this operation to be executed in parallel
4283 dl 1.137 * @param reducer a commutative associative combining function
4284     * @return the result of accumulating all entries
4285 jsr166 1.220 * @since 1.8
4286 dl 1.137 */
4287 dl 1.210 public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4288     BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4289 dl 1.151 if (reducer == null) throw new NullPointerException();
4290 dl 1.210 return new ReduceEntriesTask<K,V>
4291     (null, batchFor(parallelismThreshold), 0, 0, table,
4292     null, reducer).invoke();
4293 dl 1.137 }
4294 dl 1.119
4295 dl 1.137 /**
4296     * Returns the result of accumulating the given transformation
4297     * of all entries using the given reducer to combine values,
4298     * or null if none.
4299     *
4300 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4301 jsr166 1.213 * needed for this operation to be executed in parallel
4302 dl 1.137 * @param transformer a function returning the transformation
4303 jsr166 1.169 * for an element, or null if there is no transformation (in
4304 jsr166 1.172 * which case it is not combined)
4305 dl 1.137 * @param reducer a commutative associative combining function
4306 jsr166 1.237 * @param <U> the return type of the transformer
4307 dl 1.137 * @return the result of accumulating the given transformation
4308     * of all entries
4309 jsr166 1.220 * @since 1.8
4310 dl 1.137 */
4311 dl 1.210 public <U> U reduceEntries(long parallelismThreshold,
4312     Function<Map.Entry<K,V>, ? extends U> transformer,
4313     BiFunction<? super U, ? super U, ? extends U> reducer) {
4314 dl 1.151 if (transformer == null || reducer == null)
4315     throw new NullPointerException();
4316 dl 1.210 return new MapReduceEntriesTask<K,V,U>
4317     (null, batchFor(parallelismThreshold), 0, 0, table,
4318     null, transformer, reducer).invoke();
4319 dl 1.137 }
4320 dl 1.119
4321 dl 1.137 /**
4322     * Returns the result of accumulating the given transformation
4323     * of all entries using the given reducer to combine values,
4324     * and the given basis as an identity value.
4325     *
4326 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4327 jsr166 1.213 * needed for this operation to be executed in parallel
4328 dl 1.137 * @param transformer a function returning the transformation
4329     * for an element
4330     * @param basis the identity (initial default value) for the reduction
4331     * @param reducer a commutative associative combining function
4332     * @return the result of accumulating the given transformation
4333     * of all entries
4334 jsr166 1.220 * @since 1.8
4335 dl 1.137 */
4336 dl 1.210 public double reduceEntriesToDouble(long parallelismThreshold,
4337     ToDoubleFunction<Map.Entry<K,V>> transformer,
4338     double basis,
4339     DoubleBinaryOperator reducer) {
4340 dl 1.151 if (transformer == null || reducer == null)
4341     throw new NullPointerException();
4342 dl 1.210 return new MapReduceEntriesToDoubleTask<K,V>
4343     (null, batchFor(parallelismThreshold), 0, 0, table,
4344     null, transformer, basis, reducer).invoke();
4345 dl 1.137 }
4346 dl 1.119
4347 dl 1.137 /**
4348     * Returns the result of accumulating the given transformation
4349     * of all entries using the given reducer to combine values,
4350     * and the given basis as an identity value.
4351     *
4352 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4353 jsr166 1.213 * needed for this operation to be executed in parallel
4354 dl 1.137 * @param transformer a function returning the transformation
4355     * for an element
4356     * @param basis the identity (initial default value) for the reduction
4357     * @param reducer a commutative associative combining function
4358 jsr166 1.157 * @return the result of accumulating the given transformation
4359 dl 1.137 * of all entries
4360 jsr166 1.221 * @since 1.8
4361 dl 1.137 */
4362 dl 1.210 public long reduceEntriesToLong(long parallelismThreshold,
4363     ToLongFunction<Map.Entry<K,V>> transformer,
4364     long basis,
4365     LongBinaryOperator reducer) {
4366 dl 1.151 if (transformer == null || reducer == null)
4367     throw new NullPointerException();
4368 dl 1.210 return new MapReduceEntriesToLongTask<K,V>
4369     (null, batchFor(parallelismThreshold), 0, 0, table,
4370     null, transformer, basis, reducer).invoke();
4371 dl 1.137 }
4372 dl 1.119
4373 dl 1.137 /**
4374     * Returns the result of accumulating the given transformation
4375     * of all entries using the given reducer to combine values,
4376     * and the given basis as an identity value.
4377     *
4378 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4379 jsr166 1.213 * needed for this operation to be executed in parallel
4380 dl 1.137 * @param transformer a function returning the transformation
4381     * for an element
4382     * @param basis the identity (initial default value) for the reduction
4383     * @param reducer a commutative associative combining function
4384     * @return the result of accumulating the given transformation
4385     * of all entries
4386 jsr166 1.221 * @since 1.8
4387 dl 1.137 */
4388 dl 1.210 public int reduceEntriesToInt(long parallelismThreshold,
4389     ToIntFunction<Map.Entry<K,V>> transformer,
4390     int basis,
4391     IntBinaryOperator reducer) {
4392 dl 1.151 if (transformer == null || reducer == null)
4393     throw new NullPointerException();
4394 dl 1.210 return new MapReduceEntriesToIntTask<K,V>
4395     (null, batchFor(parallelismThreshold), 0, 0, table,
4396     null, transformer, basis, reducer).invoke();
4397 dl 1.119 }
4398    
4399 dl 1.209
4400 dl 1.210 /* ----------------Views -------------- */
4401 dl 1.142
4402     /**
4403 dl 1.210 * Base class for views.
4404 dl 1.142 */
4405 dl 1.210 abstract static class CollectionView<K,V,E>
4406     implements Collection<E>, java.io.Serializable {
4407     private static final long serialVersionUID = 7249069246763182397L;
4408     final ConcurrentHashMap<K,V> map;
4409     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4410    
4411     /**
4412     * Returns the map backing this view.
4413     *
4414     * @return the map backing this view
4415     */
4416     public ConcurrentHashMap<K,V> getMap() { return map; }
4417 dl 1.142
4418 dl 1.210 /**
4419     * Removes all of the elements from this view, by removing all
4420     * the mappings from the map backing this view.
4421 jsr166 1.184 */
4422     public final void clear() { map.clear(); }
4423     public final int size() { return map.size(); }
4424     public final boolean isEmpty() { return map.isEmpty(); }
4425 dl 1.151
4426     // implementations below rely on concrete classes supplying these
4427 jsr166 1.184 // abstract methods
4428     /**
4429 jsr166 1.242 * Returns an iterator over the elements in this collection.
4430     *
4431     * <p>The returned iterator is
4432     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4433     *
4434     * @return an iterator over the elements in this collection
4435 jsr166 1.184 */
4436     public abstract Iterator<E> iterator();
4437 jsr166 1.165 public abstract boolean contains(Object o);
4438     public abstract boolean remove(Object o);
4439 dl 1.151
4440 jsr166 1.284 private static final String OOME_MSG = "Required array size too large";
4441 dl 1.142
4442     public final Object[] toArray() {
4443     long sz = map.mappingCount();
4444 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4445 jsr166 1.284 throw new OutOfMemoryError(OOME_MSG);
4446 dl 1.142 int n = (int)sz;
4447     Object[] r = new Object[n];
4448     int i = 0;
4449 jsr166 1.184 for (E e : this) {
4450 dl 1.142 if (i == n) {
4451     if (n >= MAX_ARRAY_SIZE)
4452 jsr166 1.284 throw new OutOfMemoryError(OOME_MSG);
4453 dl 1.142 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4454     n = MAX_ARRAY_SIZE;
4455     else
4456     n += (n >>> 1) + 1;
4457     r = Arrays.copyOf(r, n);
4458     }
4459 jsr166 1.184 r[i++] = e;
4460 dl 1.142 }
4461     return (i == n) ? r : Arrays.copyOf(r, i);
4462     }
4463    
4464 dl 1.222 @SuppressWarnings("unchecked")
4465 jsr166 1.184 public final <T> T[] toArray(T[] a) {
4466 dl 1.142 long sz = map.mappingCount();
4467 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4468 jsr166 1.284 throw new OutOfMemoryError(OOME_MSG);
4469 dl 1.142 int m = (int)sz;
4470     T[] r = (a.length >= m) ? a :
4471     (T[])java.lang.reflect.Array
4472     .newInstance(a.getClass().getComponentType(), m);
4473     int n = r.length;
4474     int i = 0;
4475 jsr166 1.184 for (E e : this) {
4476 dl 1.142 if (i == n) {
4477     if (n >= MAX_ARRAY_SIZE)
4478 jsr166 1.284 throw new OutOfMemoryError(OOME_MSG);
4479 dl 1.142 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4480     n = MAX_ARRAY_SIZE;
4481     else
4482     n += (n >>> 1) + 1;
4483     r = Arrays.copyOf(r, n);
4484     }
4485 jsr166 1.184 r[i++] = (T)e;
4486 dl 1.142 }
4487     if (a == r && i < n) {
4488     r[i] = null; // null-terminate
4489     return r;
4490     }
4491     return (i == n) ? r : Arrays.copyOf(r, i);
4492     }
4493    
4494 jsr166 1.184 /**
4495     * Returns a string representation of this collection.
4496     * The string representation consists of the string representations
4497     * of the collection's elements in the order they are returned by
4498     * its iterator, enclosed in square brackets ({@code "[]"}).
4499     * Adjacent elements are separated by the characters {@code ", "}
4500     * (comma and space). Elements are converted to strings as by
4501     * {@link String#valueOf(Object)}.
4502     *
4503     * @return a string representation of this collection
4504     */
4505 dl 1.142 public final String toString() {
4506     StringBuilder sb = new StringBuilder();
4507     sb.append('[');
4508 jsr166 1.184 Iterator<E> it = iterator();
4509 dl 1.142 if (it.hasNext()) {
4510     for (;;) {
4511     Object e = it.next();
4512     sb.append(e == this ? "(this Collection)" : e);
4513     if (!it.hasNext())
4514     break;
4515     sb.append(',').append(' ');
4516     }
4517     }
4518     return sb.append(']').toString();
4519     }
4520    
4521     public final boolean containsAll(Collection<?> c) {
4522     if (c != this) {
4523 jsr166 1.184 for (Object e : c) {
4524 dl 1.142 if (e == null || !contains(e))
4525     return false;
4526     }
4527     }
4528     return true;
4529     }
4530    
4531 jsr166 1.295 public boolean removeAll(Collection<?> c) {
4532 dl 1.251 if (c == null) throw new NullPointerException();
4533 dl 1.142 boolean modified = false;
4534 jsr166 1.295 // Use (c instanceof Set) as a hint that lookup in c is as
4535     // efficient as this view
4536 jsr166 1.297 Node<K,V>[] t;
4537     if ((t = map.table) == null) {
4538     return false;
4539     } else if (c instanceof Set<?> && c.size() > t.length) {
4540 jsr166 1.295 for (Iterator<?> it = iterator(); it.hasNext(); ) {
4541     if (c.contains(it.next())) {
4542     it.remove();
4543     modified = true;
4544     }
4545 dl 1.142 }
4546 jsr166 1.295 } else {
4547     for (Object e : c)
4548     modified |= remove(e);
4549 dl 1.142 }
4550     return modified;
4551     }
4552    
4553     public final boolean retainAll(Collection<?> c) {
4554 dl 1.251 if (c == null) throw new NullPointerException();
4555 dl 1.142 boolean modified = false;
4556 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4557 dl 1.142 if (!c.contains(it.next())) {
4558     it.remove();
4559     modified = true;
4560     }
4561     }
4562     return modified;
4563     }
4564    
4565     }
4566    
4567     /**
4568     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4569     * which additions may optionally be enabled by mapping to a
4570 jsr166 1.185 * common value. This class cannot be directly instantiated.
4571     * See {@link #keySet() keySet()},
4572     * {@link #keySet(Object) keySet(V)},
4573     * {@link #newKeySet() newKeySet()},
4574     * {@link #newKeySet(int) newKeySet(int)}.
4575 jsr166 1.221 *
4576     * @since 1.8
4577 dl 1.142 */
4578 dl 1.210 public static class KeySetView<K,V> extends CollectionView<K,V,K>
4579     implements Set<K>, java.io.Serializable {
4580 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4581     private final V value;
4582 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4583 dl 1.142 super(map);
4584     this.value = value;
4585     }
4586    
4587     /**
4588     * Returns the default mapped value for additions,
4589     * or {@code null} if additions are not supported.
4590     *
4591     * @return the default mapped value for additions, or {@code null}
4592 jsr166 1.172 * if not supported
4593 dl 1.142 */
4594     public V getMappedValue() { return value; }
4595    
4596 jsr166 1.184 /**
4597     * {@inheritDoc}
4598     * @throws NullPointerException if the specified key is null
4599     */
4600     public boolean contains(Object o) { return map.containsKey(o); }
4601 dl 1.142
4602 jsr166 1.184 /**
4603     * Removes the key from this map view, by removing the key (and its
4604     * corresponding value) from the backing map. This method does
4605     * nothing if the key is not in the map.
4606     *
4607     * @param o the key to be removed from the backing map
4608     * @return {@code true} if the backing map contained the specified key
4609     * @throws NullPointerException if the specified key is null
4610     */
4611     public boolean remove(Object o) { return map.remove(o) != null; }
4612    
4613     /**
4614     * @return an iterator over the keys of the backing map
4615     */
4616 dl 1.210 public Iterator<K> iterator() {
4617     Node<K,V>[] t;
4618     ConcurrentHashMap<K,V> m = map;
4619     int f = (t = m.table) == null ? 0 : t.length;
4620     return new KeyIterator<K,V>(t, f, 0, f, m);
4621     }
4622 dl 1.142
4623     /**
4624 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4625     * the default mapped value in the backing map, if defined.
4626 dl 1.142 *
4627 jsr166 1.184 * @param e key to be added
4628     * @return {@code true} if this set changed as a result of the call
4629     * @throws NullPointerException if the specified key is null
4630     * @throws UnsupportedOperationException if no default mapped value
4631     * for additions was provided
4632 dl 1.142 */
4633     public boolean add(K e) {
4634     V v;
4635     if ((v = value) == null)
4636     throw new UnsupportedOperationException();
4637 dl 1.222 return map.putVal(e, v, true) == null;
4638 dl 1.142 }
4639 jsr166 1.184
4640     /**
4641     * Adds all of the elements in the specified collection to this set,
4642     * as if by calling {@link #add} on each one.
4643     *
4644     * @param c the elements to be inserted into this set
4645     * @return {@code true} if this set changed as a result of the call
4646     * @throws NullPointerException if the collection or any of its
4647     * elements are {@code null}
4648     * @throws UnsupportedOperationException if no default mapped value
4649     * for additions was provided
4650     */
4651 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4652     boolean added = false;
4653     V v;
4654     if ((v = value) == null)
4655     throw new UnsupportedOperationException();
4656     for (K e : c) {
4657 dl 1.222 if (map.putVal(e, v, true) == null)
4658 dl 1.142 added = true;
4659     }
4660     return added;
4661     }
4662 dl 1.153
4663 dl 1.210 public int hashCode() {
4664     int h = 0;
4665     for (K e : this)
4666     h += e.hashCode();
4667     return h;
4668 dl 1.191 }
4669    
4670 dl 1.210 public boolean equals(Object o) {
4671     Set<?> c;
4672     return ((o instanceof Set) &&
4673     ((c = (Set<?>)o) == this ||
4674     (containsAll(c) && c.containsAll(this))));
4675 dl 1.119 }
4676 jsr166 1.125
4677 dl 1.210 public Spliterator<K> spliterator() {
4678     Node<K,V>[] t;
4679     ConcurrentHashMap<K,V> m = map;
4680     long n = m.sumCount();
4681     int f = (t = m.table) == null ? 0 : t.length;
4682     return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4683 dl 1.119 }
4684    
4685 dl 1.210 public void forEach(Consumer<? super K> action) {
4686     if (action == null) throw new NullPointerException();
4687     Node<K,V>[] t;
4688     if ((t = map.table) != null) {
4689     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4690     for (Node<K,V> p; (p = it.advance()) != null; )
4691 dl 1.222 action.accept(p.key);
4692 dl 1.210 }
4693 dl 1.119 }
4694 dl 1.210 }
4695 dl 1.119
4696 dl 1.210 /**
4697     * A view of a ConcurrentHashMap as a {@link Collection} of
4698     * values, in which additions are disabled. This class cannot be
4699     * directly instantiated. See {@link #values()}.
4700     */
4701     static final class ValuesView<K,V> extends CollectionView<K,V,V>
4702     implements Collection<V>, java.io.Serializable {
4703     private static final long serialVersionUID = 2249069246763182397L;
4704     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4705     public final boolean contains(Object o) {
4706     return map.containsValue(o);
4707 dl 1.119 }
4708    
4709 dl 1.210 public final boolean remove(Object o) {
4710     if (o != null) {
4711     for (Iterator<V> it = iterator(); it.hasNext();) {
4712     if (o.equals(it.next())) {
4713     it.remove();
4714     return true;
4715     }
4716     }
4717     }
4718     return false;
4719 dl 1.119 }
4720    
4721 dl 1.210 public final Iterator<V> iterator() {
4722     ConcurrentHashMap<K,V> m = map;
4723     Node<K,V>[] t;
4724     int f = (t = m.table) == null ? 0 : t.length;
4725     return new ValueIterator<K,V>(t, f, 0, f, m);
4726 dl 1.119 }
4727    
4728 dl 1.210 public final boolean add(V e) {
4729     throw new UnsupportedOperationException();
4730     }
4731     public final boolean addAll(Collection<? extends V> c) {
4732     throw new UnsupportedOperationException();
4733 dl 1.119 }
4734    
4735 jsr166 1.295 @Override public boolean removeAll(Collection<?> c) {
4736     if (c == null) throw new NullPointerException();
4737     boolean modified = false;
4738     for (Iterator<V> it = iterator(); it.hasNext();) {
4739     if (c.contains(it.next())) {
4740     it.remove();
4741     modified = true;
4742     }
4743     }
4744     return modified;
4745     }
4746    
4747 dl 1.272 public boolean removeIf(Predicate<? super V> filter) {
4748     return map.removeValueIf(filter);
4749     }
4750    
4751 dl 1.210 public Spliterator<V> spliterator() {
4752     Node<K,V>[] t;
4753     ConcurrentHashMap<K,V> m = map;
4754     long n = m.sumCount();
4755     int f = (t = m.table) == null ? 0 : t.length;
4756     return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4757 dl 1.119 }
4758    
4759 dl 1.210 public void forEach(Consumer<? super V> action) {
4760     if (action == null) throw new NullPointerException();
4761     Node<K,V>[] t;
4762     if ((t = map.table) != null) {
4763     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4764     for (Node<K,V> p; (p = it.advance()) != null; )
4765     action.accept(p.val);
4766     }
4767 dl 1.119 }
4768 dl 1.210 }
4769    
4770     /**
4771     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4772     * entries. This class cannot be directly instantiated. See
4773     * {@link #entrySet()}.
4774     */
4775     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4776     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4777     private static final long serialVersionUID = 2249069246763182397L;
4778     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4779 dl 1.119
4780 dl 1.210 public boolean contains(Object o) {
4781     Object k, v, r; Map.Entry<?,?> e;
4782     return ((o instanceof Map.Entry) &&
4783     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4784     (r = map.get(k)) != null &&
4785     (v = e.getValue()) != null &&
4786     (v == r || v.equals(r)));
4787 dl 1.119 }
4788    
4789 dl 1.210 public boolean remove(Object o) {
4790     Object k, v; Map.Entry<?,?> e;
4791     return ((o instanceof Map.Entry) &&
4792     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4793     (v = e.getValue()) != null &&
4794     map.remove(k, v));
4795 dl 1.119 }
4796    
4797     /**
4798 dl 1.210 * @return an iterator over the entries of the backing map
4799 dl 1.119 */
4800 dl 1.210 public Iterator<Map.Entry<K,V>> iterator() {
4801     ConcurrentHashMap<K,V> m = map;
4802     Node<K,V>[] t;
4803     int f = (t = m.table) == null ? 0 : t.length;
4804     return new EntryIterator<K,V>(t, f, 0, f, m);
4805 dl 1.119 }
4806    
4807 dl 1.210 public boolean add(Entry<K,V> e) {
4808 dl 1.222 return map.putVal(e.getKey(), e.getValue(), false) == null;
4809 dl 1.119 }
4810    
4811 dl 1.210 public boolean addAll(Collection<? extends Entry<K,V>> c) {
4812     boolean added = false;
4813     for (Entry<K,V> e : c) {
4814     if (add(e))
4815     added = true;
4816     }
4817     return added;
4818 dl 1.119 }
4819    
4820 jsr166 1.273 public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
4821 dl 1.271 return map.removeEntryIf(filter);
4822     }
4823    
4824 dl 1.210 public final int hashCode() {
4825     int h = 0;
4826     Node<K,V>[] t;
4827     if ((t = map.table) != null) {
4828     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4829     for (Node<K,V> p; (p = it.advance()) != null; ) {
4830     h += p.hashCode();
4831     }
4832     }
4833     return h;
4834 dl 1.119 }
4835    
4836 dl 1.210 public final boolean equals(Object o) {
4837     Set<?> c;
4838     return ((o instanceof Set) &&
4839     ((c = (Set<?>)o) == this ||
4840     (containsAll(c) && c.containsAll(this))));
4841 dl 1.119 }
4842    
4843 dl 1.210 public Spliterator<Map.Entry<K,V>> spliterator() {
4844     Node<K,V>[] t;
4845     ConcurrentHashMap<K,V> m = map;
4846     long n = m.sumCount();
4847     int f = (t = m.table) == null ? 0 : t.length;
4848     return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4849 dl 1.119 }
4850    
4851 dl 1.210 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4852     if (action == null) throw new NullPointerException();
4853     Node<K,V>[] t;
4854     if ((t = map.table) != null) {
4855     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4856     for (Node<K,V> p; (p = it.advance()) != null; )
4857 dl 1.222 action.accept(new MapEntry<K,V>(p.key, p.val, map));
4858 dl 1.210 }
4859 dl 1.119 }
4860    
4861 dl 1.210 }
4862    
4863     // -------------------------------------------------------
4864 dl 1.119
4865 dl 1.210 /**
4866     * Base class for bulk tasks. Repeats some fields and code from
4867     * class Traverser, because we need to subclass CountedCompleter.
4868     */
4869 dl 1.243 @SuppressWarnings("serial")
4870 jsr166 1.211 abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4871 dl 1.210 Node<K,V>[] tab; // same as Traverser
4872     Node<K,V> next;
4873 dl 1.246 TableStack<K,V> stack, spare;
4874 dl 1.210 int index;
4875     int baseIndex;
4876     int baseLimit;
4877     final int baseSize;
4878     int batch; // split control
4879    
4880     BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4881     super(par);
4882     this.batch = b;
4883     this.index = this.baseIndex = i;
4884     if ((this.tab = t) == null)
4885     this.baseSize = this.baseLimit = 0;
4886     else if (par == null)
4887     this.baseSize = this.baseLimit = t.length;
4888     else {
4889     this.baseLimit = f;
4890     this.baseSize = par.baseSize;
4891     }
4892 dl 1.119 }
4893    
4894     /**
4895 jsr166 1.285 * Same as Traverser version.
4896 dl 1.119 */
4897 dl 1.210 final Node<K,V> advance() {
4898     Node<K,V> e;
4899     if ((e = next) != null)
4900     e = e.next;
4901     for (;;) {
4902 dl 1.246 Node<K,V>[] t; int i, n;
4903 dl 1.210 if (e != null)
4904     return next = e;
4905     if (baseIndex >= baseLimit || (t = tab) == null ||
4906     (n = t.length) <= (i = index) || i < 0)
4907     return next = null;
4908 dl 1.246 if ((e = tabAt(t, i)) != null && e.hash < 0) {
4909 dl 1.222 if (e instanceof ForwardingNode) {
4910     tab = ((ForwardingNode<K,V>)e).nextTable;
4911 dl 1.210 e = null;
4912 dl 1.246 pushState(t, i, n);
4913 dl 1.210 continue;
4914     }
4915 dl 1.222 else if (e instanceof TreeBin)
4916     e = ((TreeBin<K,V>)e).first;
4917     else
4918     e = null;
4919 dl 1.210 }
4920 dl 1.246 if (stack != null)
4921     recoverState(n);
4922     else if ((index = i + baseSize) >= n)
4923     index = ++baseIndex;
4924     }
4925     }
4926    
4927     private void pushState(Node<K,V>[] t, int i, int n) {
4928     TableStack<K,V> s = spare;
4929     if (s != null)
4930     spare = s.next;
4931     else
4932     s = new TableStack<K,V>();
4933     s.tab = t;
4934     s.length = n;
4935     s.index = i;
4936     s.next = stack;
4937     stack = s;
4938     }
4939    
4940     private void recoverState(int n) {
4941     TableStack<K,V> s; int len;
4942     while ((s = stack) != null && (index += (len = s.length)) >= n) {
4943     n = len;
4944     index = s.index;
4945     tab = s.tab;
4946     s.tab = null;
4947     TableStack<K,V> next = s.next;
4948     s.next = spare; // save for reuse
4949     stack = next;
4950     spare = s;
4951 dl 1.210 }
4952 dl 1.246 if (s == null && (index += baseSize) >= n)
4953     index = ++baseIndex;
4954 dl 1.119 }
4955     }
4956    
4957     /*
4958     * Task classes. Coded in a regular but ugly format/style to
4959     * simplify checks that each variant differs in the right way from
4960 dl 1.149 * others. The null screenings exist because compilers cannot tell
4961     * that we've already null-checked task arguments, so we force
4962     * simplest hoisted bypass to help avoid convoluted traps.
4963 dl 1.119 */
4964 dl 1.222 @SuppressWarnings("serial")
4965 dl 1.210 static final class ForEachKeyTask<K,V>
4966     extends BulkTask<K,V,Void> {
4967 dl 1.171 final Consumer<? super K> action;
4968 dl 1.119 ForEachKeyTask
4969 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4970 dl 1.171 Consumer<? super K> action) {
4971 dl 1.210 super(p, b, i, f, t);
4972 dl 1.119 this.action = action;
4973     }
4974 jsr166 1.168 public final void compute() {
4975 dl 1.171 final Consumer<? super K> action;
4976 dl 1.149 if ((action = this.action) != null) {
4977 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4978     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4979     addToPendingCount(1);
4980     new ForEachKeyTask<K,V>
4981     (this, batch >>>= 1, baseLimit = h, f, tab,
4982     action).fork();
4983     }
4984     for (Node<K,V> p; (p = advance()) != null;)
4985 dl 1.222 action.accept(p.key);
4986 dl 1.149 propagateCompletion();
4987     }
4988 dl 1.119 }
4989     }
4990    
4991 dl 1.222 @SuppressWarnings("serial")
4992 dl 1.210 static final class ForEachValueTask<K,V>
4993     extends BulkTask<K,V,Void> {
4994 dl 1.171 final Consumer<? super V> action;
4995 dl 1.119 ForEachValueTask
4996 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4997 dl 1.171 Consumer<? super V> action) {
4998 dl 1.210 super(p, b, i, f, t);
4999 dl 1.119 this.action = action;
5000     }
5001 jsr166 1.168 public final void compute() {
5002 dl 1.171 final Consumer<? super V> action;
5003 dl 1.149 if ((action = this.action) != null) {
5004 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5005     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5006     addToPendingCount(1);
5007     new ForEachValueTask<K,V>
5008     (this, batch >>>= 1, baseLimit = h, f, tab,
5009     action).fork();
5010     }
5011     for (Node<K,V> p; (p = advance()) != null;)
5012     action.accept(p.val);
5013 dl 1.149 propagateCompletion();
5014     }
5015 dl 1.119 }
5016     }
5017    
5018 dl 1.222 @SuppressWarnings("serial")
5019 dl 1.210 static final class ForEachEntryTask<K,V>
5020     extends BulkTask<K,V,Void> {
5021 dl 1.171 final Consumer<? super Entry<K,V>> action;
5022 dl 1.119 ForEachEntryTask
5023 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5024 dl 1.171 Consumer<? super Entry<K,V>> action) {
5025 dl 1.210 super(p, b, i, f, t);
5026 dl 1.119 this.action = action;
5027     }
5028 jsr166 1.168 public final void compute() {
5029 dl 1.171 final Consumer<? super Entry<K,V>> action;
5030 dl 1.149 if ((action = this.action) != null) {
5031 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5032     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5033     addToPendingCount(1);
5034     new ForEachEntryTask<K,V>
5035     (this, batch >>>= 1, baseLimit = h, f, tab,
5036     action).fork();
5037     }
5038     for (Node<K,V> p; (p = advance()) != null; )
5039     action.accept(p);
5040 dl 1.149 propagateCompletion();
5041     }
5042 dl 1.119 }
5043     }
5044    
5045 dl 1.222 @SuppressWarnings("serial")
5046 dl 1.210 static final class ForEachMappingTask<K,V>
5047     extends BulkTask<K,V,Void> {
5048 dl 1.171 final BiConsumer<? super K, ? super V> action;
5049 dl 1.119 ForEachMappingTask
5050 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5051 dl 1.171 BiConsumer<? super K,? super V> action) {
5052 dl 1.210 super(p, b, i, f, t);
5053 dl 1.119 this.action = action;
5054     }
5055 jsr166 1.168 public final void compute() {
5056 dl 1.171 final BiConsumer<? super K, ? super V> action;
5057 dl 1.149 if ((action = this.action) != null) {
5058 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5059     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5060     addToPendingCount(1);
5061     new ForEachMappingTask<K,V>
5062     (this, batch >>>= 1, baseLimit = h, f, tab,
5063     action).fork();
5064     }
5065     for (Node<K,V> p; (p = advance()) != null; )
5066 dl 1.222 action.accept(p.key, p.val);
5067 dl 1.149 propagateCompletion();
5068     }
5069 dl 1.119 }
5070     }
5071    
5072 dl 1.222 @SuppressWarnings("serial")
5073 dl 1.210 static final class ForEachTransformedKeyTask<K,V,U>
5074     extends BulkTask<K,V,Void> {
5075 dl 1.153 final Function<? super K, ? extends U> transformer;
5076 dl 1.171 final Consumer<? super U> action;
5077 dl 1.119 ForEachTransformedKeyTask
5078 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5079 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5080 dl 1.210 super(p, b, i, f, t);
5081 dl 1.146 this.transformer = transformer; this.action = action;
5082     }
5083 jsr166 1.168 public final void compute() {
5084 dl 1.153 final Function<? super K, ? extends U> transformer;
5085 dl 1.171 final Consumer<? super U> action;
5086 dl 1.149 if ((transformer = this.transformer) != null &&
5087     (action = this.action) != null) {
5088 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5089     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5090     addToPendingCount(1);
5091 dl 1.149 new ForEachTransformedKeyTask<K,V,U>
5092 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5093     transformer, action).fork();
5094     }
5095     for (Node<K,V> p; (p = advance()) != null; ) {
5096     U u;
5097 dl 1.222 if ((u = transformer.apply(p.key)) != null)
5098 dl 1.153 action.accept(u);
5099 dl 1.149 }
5100     propagateCompletion();
5101 dl 1.119 }
5102     }
5103     }
5104    
5105 dl 1.222 @SuppressWarnings("serial")
5106 dl 1.210 static final class ForEachTransformedValueTask<K,V,U>
5107     extends BulkTask<K,V,Void> {
5108 dl 1.153 final Function<? super V, ? extends U> transformer;
5109 dl 1.171 final Consumer<? super U> action;
5110 dl 1.119 ForEachTransformedValueTask
5111 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5112 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5113 dl 1.210 super(p, b, i, f, t);
5114 dl 1.146 this.transformer = transformer; this.action = action;
5115     }
5116 jsr166 1.168 public final void compute() {
5117 dl 1.153 final Function<? super V, ? extends U> transformer;
5118 dl 1.171 final Consumer<? super U> action;
5119 dl 1.149 if ((transformer = this.transformer) != null &&
5120     (action = this.action) != null) {
5121 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5122     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5123     addToPendingCount(1);
5124 dl 1.149 new ForEachTransformedValueTask<K,V,U>
5125 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5126     transformer, action).fork();
5127     }
5128     for (Node<K,V> p; (p = advance()) != null; ) {
5129     U u;
5130     if ((u = transformer.apply(p.val)) != null)
5131 dl 1.153 action.accept(u);
5132 dl 1.149 }
5133     propagateCompletion();
5134 dl 1.119 }
5135     }
5136 tim 1.1 }
5137    
5138 dl 1.222 @SuppressWarnings("serial")
5139 dl 1.210 static final class ForEachTransformedEntryTask<K,V,U>
5140     extends BulkTask<K,V,Void> {
5141 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5142 dl 1.171 final Consumer<? super U> action;
5143 dl 1.119 ForEachTransformedEntryTask
5144 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5145 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5146 dl 1.210 super(p, b, i, f, t);
5147 dl 1.146 this.transformer = transformer; this.action = action;
5148     }
5149 jsr166 1.168 public final void compute() {
5150 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5151 dl 1.171 final Consumer<? super U> action;
5152 dl 1.149 if ((transformer = this.transformer) != null &&
5153     (action = this.action) != null) {
5154 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5155     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5156     addToPendingCount(1);
5157 dl 1.149 new ForEachTransformedEntryTask<K,V,U>
5158 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5159     transformer, action).fork();
5160     }
5161     for (Node<K,V> p; (p = advance()) != null; ) {
5162     U u;
5163     if ((u = transformer.apply(p)) != null)
5164 dl 1.153 action.accept(u);
5165 dl 1.149 }
5166     propagateCompletion();
5167 dl 1.119 }
5168     }
5169 tim 1.1 }
5170    
5171 dl 1.222 @SuppressWarnings("serial")
5172 dl 1.210 static final class ForEachTransformedMappingTask<K,V,U>
5173     extends BulkTask<K,V,Void> {
5174 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5175 dl 1.171 final Consumer<? super U> action;
5176 dl 1.119 ForEachTransformedMappingTask
5177 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5178 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5179 dl 1.171 Consumer<? super U> action) {
5180 dl 1.210 super(p, b, i, f, t);
5181 dl 1.146 this.transformer = transformer; this.action = action;
5182 dl 1.119 }
5183 jsr166 1.168 public final void compute() {
5184 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5185 dl 1.171 final Consumer<? super U> action;
5186 dl 1.149 if ((transformer = this.transformer) != null &&
5187     (action = this.action) != null) {
5188 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5189     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5190     addToPendingCount(1);
5191 dl 1.149 new ForEachTransformedMappingTask<K,V,U>
5192 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5193     transformer, action).fork();
5194     }
5195     for (Node<K,V> p; (p = advance()) != null; ) {
5196     U u;
5197 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
5198 dl 1.153 action.accept(u);
5199 dl 1.149 }
5200     propagateCompletion();
5201 dl 1.119 }
5202     }
5203 tim 1.1 }
5204    
5205 dl 1.222 @SuppressWarnings("serial")
5206 dl 1.210 static final class SearchKeysTask<K,V,U>
5207     extends BulkTask<K,V,U> {
5208 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5209 dl 1.119 final AtomicReference<U> result;
5210     SearchKeysTask
5211 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5212 dl 1.153 Function<? super K, ? extends U> searchFunction,
5213 dl 1.119 AtomicReference<U> result) {
5214 dl 1.210 super(p, b, i, f, t);
5215 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5216     }
5217 dl 1.146 public final U getRawResult() { return result.get(); }
5218 jsr166 1.168 public final void compute() {
5219 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5220 dl 1.146 final AtomicReference<U> result;
5221 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5222     (result = this.result) != null) {
5223 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5224     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5225 dl 1.149 if (result.get() != null)
5226     return;
5227 dl 1.210 addToPendingCount(1);
5228 dl 1.149 new SearchKeysTask<K,V,U>
5229 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5230     searchFunction, result).fork();
5231 dl 1.128 }
5232 dl 1.149 while (result.get() == null) {
5233 dl 1.210 U u;
5234     Node<K,V> p;
5235     if ((p = advance()) == null) {
5236 dl 1.149 propagateCompletion();
5237     break;
5238     }
5239 dl 1.222 if ((u = searchFunction.apply(p.key)) != null) {
5240 dl 1.149 if (result.compareAndSet(null, u))
5241     quietlyCompleteRoot();
5242     break;
5243     }
5244 dl 1.119 }
5245     }
5246     }
5247 tim 1.1 }
5248    
5249 dl 1.222 @SuppressWarnings("serial")
5250 dl 1.210 static final class SearchValuesTask<K,V,U>
5251     extends BulkTask<K,V,U> {
5252 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5253 dl 1.119 final AtomicReference<U> result;
5254     SearchValuesTask
5255 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5256 dl 1.153 Function<? super V, ? extends U> searchFunction,
5257 dl 1.119 AtomicReference<U> result) {
5258 dl 1.210 super(p, b, i, f, t);
5259 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5260     }
5261 dl 1.146 public final U getRawResult() { return result.get(); }
5262 jsr166 1.168 public final void compute() {
5263 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5264 dl 1.146 final AtomicReference<U> result;
5265 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5266     (result = this.result) != null) {
5267 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5268     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5269 dl 1.149 if (result.get() != null)
5270     return;
5271 dl 1.210 addToPendingCount(1);
5272 dl 1.149 new SearchValuesTask<K,V,U>
5273 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5274     searchFunction, result).fork();
5275 dl 1.128 }
5276 dl 1.149 while (result.get() == null) {
5277 dl 1.210 U u;
5278     Node<K,V> p;
5279     if ((p = advance()) == null) {
5280 dl 1.149 propagateCompletion();
5281     break;
5282     }
5283 dl 1.210 if ((u = searchFunction.apply(p.val)) != null) {
5284 dl 1.149 if (result.compareAndSet(null, u))
5285     quietlyCompleteRoot();
5286     break;
5287     }
5288 dl 1.119 }
5289     }
5290     }
5291     }
5292 tim 1.11
5293 dl 1.222 @SuppressWarnings("serial")
5294 dl 1.210 static final class SearchEntriesTask<K,V,U>
5295     extends BulkTask<K,V,U> {
5296 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5297 dl 1.119 final AtomicReference<U> result;
5298     SearchEntriesTask
5299 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5300 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
5301 dl 1.119 AtomicReference<U> result) {
5302 dl 1.210 super(p, b, i, f, t);
5303 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5304     }
5305 dl 1.146 public final U getRawResult() { return result.get(); }
5306 jsr166 1.168 public final void compute() {
5307 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5308 dl 1.146 final AtomicReference<U> result;
5309 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5310     (result = this.result) != null) {
5311 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5312     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5313 dl 1.149 if (result.get() != null)
5314     return;
5315 dl 1.210 addToPendingCount(1);
5316 dl 1.149 new SearchEntriesTask<K,V,U>
5317 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5318     searchFunction, result).fork();
5319 dl 1.128 }
5320 dl 1.149 while (result.get() == null) {
5321 dl 1.210 U u;
5322     Node<K,V> p;
5323     if ((p = advance()) == null) {
5324 dl 1.149 propagateCompletion();
5325     break;
5326     }
5327 dl 1.210 if ((u = searchFunction.apply(p)) != null) {
5328 dl 1.149 if (result.compareAndSet(null, u))
5329     quietlyCompleteRoot();
5330     return;
5331     }
5332 dl 1.119 }
5333     }
5334     }
5335     }
5336 tim 1.1
5337 dl 1.222 @SuppressWarnings("serial")
5338 dl 1.210 static final class SearchMappingsTask<K,V,U>
5339     extends BulkTask<K,V,U> {
5340 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5341 dl 1.119 final AtomicReference<U> result;
5342     SearchMappingsTask
5343 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5344 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
5345 dl 1.119 AtomicReference<U> result) {
5346 dl 1.210 super(p, b, i, f, t);
5347 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5348     }
5349 dl 1.146 public final U getRawResult() { return result.get(); }
5350 jsr166 1.168 public final void compute() {
5351 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5352 dl 1.146 final AtomicReference<U> result;
5353 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5354     (result = this.result) != null) {
5355 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5356     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5357 dl 1.149 if (result.get() != null)
5358     return;
5359 dl 1.210 addToPendingCount(1);
5360 dl 1.149 new SearchMappingsTask<K,V,U>
5361 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5362     searchFunction, result).fork();
5363 dl 1.128 }
5364 dl 1.149 while (result.get() == null) {
5365 dl 1.210 U u;
5366     Node<K,V> p;
5367     if ((p = advance()) == null) {
5368 dl 1.149 propagateCompletion();
5369     break;
5370     }
5371 dl 1.222 if ((u = searchFunction.apply(p.key, p.val)) != null) {
5372 dl 1.149 if (result.compareAndSet(null, u))
5373     quietlyCompleteRoot();
5374     break;
5375     }
5376 dl 1.119 }
5377     }
5378 tim 1.1 }
5379 dl 1.119 }
5380 tim 1.1
5381 dl 1.222 @SuppressWarnings("serial")
5382 dl 1.210 static final class ReduceKeysTask<K,V>
5383     extends BulkTask<K,V,K> {
5384 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5385 dl 1.119 K result;
5386 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
5387 dl 1.119 ReduceKeysTask
5388 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5389 dl 1.128 ReduceKeysTask<K,V> nextRight,
5390 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5391 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5392 dl 1.119 this.reducer = reducer;
5393     }
5394 dl 1.146 public final K getRawResult() { return result; }
5395 dl 1.210 public final void compute() {
5396 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5397 dl 1.149 if ((reducer = this.reducer) != null) {
5398 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5399     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5400     addToPendingCount(1);
5401 dl 1.149 (rights = new ReduceKeysTask<K,V>
5402 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5403     rights, reducer)).fork();
5404     }
5405     K r = null;
5406     for (Node<K,V> p; (p = advance()) != null; ) {
5407 dl 1.222 K u = p.key;
5408 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5409 dl 1.149 }
5410     result = r;
5411     CountedCompleter<?> c;
5412     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5413 dl 1.246 @SuppressWarnings("unchecked")
5414     ReduceKeysTask<K,V>
5415 dl 1.149 t = (ReduceKeysTask<K,V>)c,
5416     s = t.rights;
5417     while (s != null) {
5418     K tr, sr;
5419     if ((sr = s.result) != null)
5420     t.result = (((tr = t.result) == null) ? sr :
5421     reducer.apply(tr, sr));
5422     s = t.rights = s.nextRight;
5423     }
5424 dl 1.99 }
5425 dl 1.138 }
5426 tim 1.1 }
5427 dl 1.119 }
5428 tim 1.1
5429 dl 1.222 @SuppressWarnings("serial")
5430 dl 1.210 static final class ReduceValuesTask<K,V>
5431     extends BulkTask<K,V,V> {
5432 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5433 dl 1.119 V result;
5434 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
5435 dl 1.119 ReduceValuesTask
5436 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5437 dl 1.128 ReduceValuesTask<K,V> nextRight,
5438 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5439 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5440 dl 1.119 this.reducer = reducer;
5441     }
5442 dl 1.146 public final V getRawResult() { return result; }
5443 dl 1.210 public final void compute() {
5444 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5445 dl 1.149 if ((reducer = this.reducer) != null) {
5446 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5447     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5448     addToPendingCount(1);
5449 dl 1.149 (rights = new ReduceValuesTask<K,V>
5450 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5451     rights, reducer)).fork();
5452     }
5453     V r = null;
5454     for (Node<K,V> p; (p = advance()) != null; ) {
5455     V v = p.val;
5456 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
5457 dl 1.210 }
5458 dl 1.149 result = r;
5459     CountedCompleter<?> c;
5460     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5461 dl 1.246 @SuppressWarnings("unchecked")
5462     ReduceValuesTask<K,V>
5463 dl 1.149 t = (ReduceValuesTask<K,V>)c,
5464     s = t.rights;
5465     while (s != null) {
5466     V tr, sr;
5467     if ((sr = s.result) != null)
5468     t.result = (((tr = t.result) == null) ? sr :
5469     reducer.apply(tr, sr));
5470     s = t.rights = s.nextRight;
5471     }
5472 dl 1.119 }
5473     }
5474 tim 1.1 }
5475 dl 1.119 }
5476 tim 1.1
5477 dl 1.222 @SuppressWarnings("serial")
5478 dl 1.210 static final class ReduceEntriesTask<K,V>
5479     extends BulkTask<K,V,Map.Entry<K,V>> {
5480 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5481 dl 1.119 Map.Entry<K,V> result;
5482 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
5483 dl 1.119 ReduceEntriesTask
5484 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5485 dl 1.130 ReduceEntriesTask<K,V> nextRight,
5486 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5487 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5488 dl 1.119 this.reducer = reducer;
5489     }
5490 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
5491 dl 1.210 public final void compute() {
5492 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5493 dl 1.149 if ((reducer = this.reducer) != null) {
5494 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5495     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5496     addToPendingCount(1);
5497 dl 1.149 (rights = new ReduceEntriesTask<K,V>
5498 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5499     rights, reducer)).fork();
5500     }
5501 dl 1.149 Map.Entry<K,V> r = null;
5502 dl 1.210 for (Node<K,V> p; (p = advance()) != null; )
5503     r = (r == null) ? p : reducer.apply(r, p);
5504 dl 1.149 result = r;
5505     CountedCompleter<?> c;
5506     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5507 dl 1.246 @SuppressWarnings("unchecked")
5508     ReduceEntriesTask<K,V>
5509 dl 1.149 t = (ReduceEntriesTask<K,V>)c,
5510     s = t.rights;
5511     while (s != null) {
5512     Map.Entry<K,V> tr, sr;
5513     if ((sr = s.result) != null)
5514     t.result = (((tr = t.result) == null) ? sr :
5515     reducer.apply(tr, sr));
5516     s = t.rights = s.nextRight;
5517     }
5518 dl 1.119 }
5519 dl 1.138 }
5520 dl 1.119 }
5521     }
5522 dl 1.99
5523 dl 1.222 @SuppressWarnings("serial")
5524 dl 1.210 static final class MapReduceKeysTask<K,V,U>
5525     extends BulkTask<K,V,U> {
5526 dl 1.153 final Function<? super K, ? extends U> transformer;
5527     final BiFunction<? super U, ? super U, ? extends U> reducer;
5528 dl 1.119 U result;
5529 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
5530 dl 1.119 MapReduceKeysTask
5531 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5532 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
5533 dl 1.153 Function<? super K, ? extends U> transformer,
5534     BiFunction<? super U, ? super U, ? extends U> reducer) {
5535 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5536 dl 1.119 this.transformer = transformer;
5537     this.reducer = reducer;
5538     }
5539 dl 1.146 public final U getRawResult() { return result; }
5540 dl 1.210 public final void compute() {
5541 dl 1.153 final Function<? super K, ? extends U> transformer;
5542     final BiFunction<? super U, ? super U, ? extends U> reducer;
5543 dl 1.149 if ((transformer = this.transformer) != null &&
5544     (reducer = this.reducer) != null) {
5545 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5546     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5547     addToPendingCount(1);
5548 dl 1.149 (rights = new MapReduceKeysTask<K,V,U>
5549 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5550     rights, transformer, reducer)).fork();
5551     }
5552     U r = null;
5553     for (Node<K,V> p; (p = advance()) != null; ) {
5554     U u;
5555 dl 1.222 if ((u = transformer.apply(p.key)) != null)
5556 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5557     }
5558     result = r;
5559     CountedCompleter<?> c;
5560     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5561 dl 1.246 @SuppressWarnings("unchecked")
5562     MapReduceKeysTask<K,V,U>
5563 dl 1.149 t = (MapReduceKeysTask<K,V,U>)c,
5564     s = t.rights;
5565     while (s != null) {
5566     U tr, sr;
5567     if ((sr = s.result) != null)
5568     t.result = (((tr = t.result) == null) ? sr :
5569     reducer.apply(tr, sr));
5570     s = t.rights = s.nextRight;
5571     }
5572 dl 1.119 }
5573 dl 1.138 }
5574 tim 1.1 }
5575 dl 1.4 }
5576    
5577 dl 1.222 @SuppressWarnings("serial")
5578 dl 1.210 static final class MapReduceValuesTask<K,V,U>
5579     extends BulkTask<K,V,U> {
5580 dl 1.153 final Function<? super V, ? extends U> transformer;
5581     final BiFunction<? super U, ? super U, ? extends U> reducer;
5582 dl 1.119 U result;
5583 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
5584 dl 1.119 MapReduceValuesTask
5585 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5586 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
5587 dl 1.153 Function<? super V, ? extends U> transformer,
5588     BiFunction<? super U, ? super U, ? extends U> reducer) {
5589 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5590 dl 1.119 this.transformer = transformer;
5591     this.reducer = reducer;
5592     }
5593 dl 1.146 public final U getRawResult() { return result; }
5594 dl 1.210 public final void compute() {
5595 dl 1.153 final Function<? super V, ? extends U> transformer;
5596     final BiFunction<? super U, ? super U, ? extends U> reducer;
5597 dl 1.149 if ((transformer = this.transformer) != null &&
5598     (reducer = this.reducer) != null) {
5599 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5600     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5601     addToPendingCount(1);
5602 dl 1.149 (rights = new MapReduceValuesTask<K,V,U>
5603 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5604     rights, transformer, reducer)).fork();
5605     }
5606     U r = null;
5607     for (Node<K,V> p; (p = advance()) != null; ) {
5608     U u;
5609     if ((u = transformer.apply(p.val)) != null)
5610 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5611     }
5612     result = r;
5613     CountedCompleter<?> c;
5614     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5615 dl 1.246 @SuppressWarnings("unchecked")
5616     MapReduceValuesTask<K,V,U>
5617 dl 1.149 t = (MapReduceValuesTask<K,V,U>)c,
5618     s = t.rights;
5619     while (s != null) {
5620     U tr, sr;
5621     if ((sr = s.result) != null)
5622     t.result = (((tr = t.result) == null) ? sr :
5623     reducer.apply(tr, sr));
5624     s = t.rights = s.nextRight;
5625     }
5626 dl 1.119 }
5627     }
5628     }
5629 dl 1.4 }
5630    
5631 dl 1.222 @SuppressWarnings("serial")
5632 dl 1.210 static final class MapReduceEntriesTask<K,V,U>
5633     extends BulkTask<K,V,U> {
5634 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5635     final BiFunction<? super U, ? super U, ? extends U> reducer;
5636 dl 1.119 U result;
5637 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
5638 dl 1.119 MapReduceEntriesTask
5639 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5640 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
5641 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5642     BiFunction<? super U, ? super U, ? extends U> reducer) {
5643 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5644 dl 1.119 this.transformer = transformer;
5645     this.reducer = reducer;
5646     }
5647 dl 1.146 public final U getRawResult() { return result; }
5648 dl 1.210 public final void compute() {
5649 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5650     final BiFunction<? super U, ? super U, ? extends U> reducer;
5651 dl 1.149 if ((transformer = this.transformer) != null &&
5652     (reducer = this.reducer) != null) {
5653 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5654     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5655     addToPendingCount(1);
5656 dl 1.149 (rights = new MapReduceEntriesTask<K,V,U>
5657 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5658     rights, transformer, reducer)).fork();
5659     }
5660     U r = null;
5661     for (Node<K,V> p; (p = advance()) != null; ) {
5662     U u;
5663     if ((u = transformer.apply(p)) != null)
5664 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5665     }
5666     result = r;
5667     CountedCompleter<?> c;
5668     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5669 dl 1.246 @SuppressWarnings("unchecked")
5670     MapReduceEntriesTask<K,V,U>
5671 dl 1.149 t = (MapReduceEntriesTask<K,V,U>)c,
5672     s = t.rights;
5673     while (s != null) {
5674     U tr, sr;
5675     if ((sr = s.result) != null)
5676     t.result = (((tr = t.result) == null) ? sr :
5677     reducer.apply(tr, sr));
5678     s = t.rights = s.nextRight;
5679     }
5680 dl 1.119 }
5681 dl 1.138 }
5682 dl 1.119 }
5683 dl 1.4 }
5684 tim 1.1
5685 dl 1.222 @SuppressWarnings("serial")
5686 dl 1.210 static final class MapReduceMappingsTask<K,V,U>
5687     extends BulkTask<K,V,U> {
5688 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5689     final BiFunction<? super U, ? super U, ? extends U> reducer;
5690 dl 1.119 U result;
5691 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
5692 dl 1.119 MapReduceMappingsTask
5693 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5694 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
5695 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5696     BiFunction<? super U, ? super U, ? extends U> reducer) {
5697 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5698 dl 1.119 this.transformer = transformer;
5699     this.reducer = reducer;
5700     }
5701 dl 1.146 public final U getRawResult() { return result; }
5702 dl 1.210 public final void compute() {
5703 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5704     final BiFunction<? super U, ? super U, ? extends U> reducer;
5705 dl 1.149 if ((transformer = this.transformer) != null &&
5706     (reducer = this.reducer) != null) {
5707 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5708     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5709     addToPendingCount(1);
5710 dl 1.149 (rights = new MapReduceMappingsTask<K,V,U>
5711 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5712     rights, transformer, reducer)).fork();
5713     }
5714     U r = null;
5715     for (Node<K,V> p; (p = advance()) != null; ) {
5716     U u;
5717 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
5718 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5719     }
5720     result = r;
5721     CountedCompleter<?> c;
5722     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5723 dl 1.246 @SuppressWarnings("unchecked")
5724     MapReduceMappingsTask<K,V,U>
5725 dl 1.149 t = (MapReduceMappingsTask<K,V,U>)c,
5726     s = t.rights;
5727     while (s != null) {
5728     U tr, sr;
5729     if ((sr = s.result) != null)
5730     t.result = (((tr = t.result) == null) ? sr :
5731     reducer.apply(tr, sr));
5732     s = t.rights = s.nextRight;
5733     }
5734 dl 1.119 }
5735     }
5736     }
5737     }
5738 jsr166 1.114
5739 dl 1.222 @SuppressWarnings("serial")
5740 dl 1.210 static final class MapReduceKeysToDoubleTask<K,V>
5741     extends BulkTask<K,V,Double> {
5742 dl 1.171 final ToDoubleFunction<? super K> transformer;
5743 dl 1.153 final DoubleBinaryOperator reducer;
5744 dl 1.119 final double basis;
5745     double result;
5746 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5747 dl 1.119 MapReduceKeysToDoubleTask
5748 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5749 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
5750 dl 1.171 ToDoubleFunction<? super K> transformer,
5751 dl 1.119 double basis,
5752 dl 1.153 DoubleBinaryOperator reducer) {
5753 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5754 dl 1.119 this.transformer = transformer;
5755     this.basis = basis; this.reducer = reducer;
5756     }
5757 dl 1.146 public final Double getRawResult() { return result; }
5758 dl 1.210 public final void compute() {
5759 dl 1.171 final ToDoubleFunction<? super K> transformer;
5760 dl 1.153 final DoubleBinaryOperator reducer;
5761 dl 1.149 if ((transformer = this.transformer) != null &&
5762     (reducer = this.reducer) != null) {
5763     double r = this.basis;
5764 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5765     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5766     addToPendingCount(1);
5767 dl 1.149 (rights = new MapReduceKeysToDoubleTask<K,V>
5768 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5769     rights, transformer, r, reducer)).fork();
5770     }
5771     for (Node<K,V> p; (p = advance()) != null; )
5772 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5773 dl 1.149 result = r;
5774     CountedCompleter<?> c;
5775     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5776 dl 1.246 @SuppressWarnings("unchecked")
5777     MapReduceKeysToDoubleTask<K,V>
5778 dl 1.149 t = (MapReduceKeysToDoubleTask<K,V>)c,
5779     s = t.rights;
5780     while (s != null) {
5781 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5782 dl 1.149 s = t.rights = s.nextRight;
5783     }
5784 dl 1.119 }
5785 dl 1.138 }
5786 dl 1.79 }
5787 dl 1.119 }
5788 dl 1.79
5789 dl 1.222 @SuppressWarnings("serial")
5790 dl 1.210 static final class MapReduceValuesToDoubleTask<K,V>
5791     extends BulkTask<K,V,Double> {
5792 dl 1.171 final ToDoubleFunction<? super V> transformer;
5793 dl 1.153 final DoubleBinaryOperator reducer;
5794 dl 1.119 final double basis;
5795     double result;
5796 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5797 dl 1.119 MapReduceValuesToDoubleTask
5798 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5799 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
5800 dl 1.171 ToDoubleFunction<? super V> transformer,
5801 dl 1.119 double basis,
5802 dl 1.153 DoubleBinaryOperator reducer) {
5803 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5804 dl 1.119 this.transformer = transformer;
5805     this.basis = basis; this.reducer = reducer;
5806     }
5807 dl 1.146 public final Double getRawResult() { return result; }
5808 dl 1.210 public final void compute() {
5809 dl 1.171 final ToDoubleFunction<? super V> transformer;
5810 dl 1.153 final DoubleBinaryOperator reducer;
5811 dl 1.149 if ((transformer = this.transformer) != null &&
5812     (reducer = this.reducer) != null) {
5813     double r = this.basis;
5814 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5815     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5816     addToPendingCount(1);
5817 dl 1.149 (rights = new MapReduceValuesToDoubleTask<K,V>
5818 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5819     rights, transformer, r, reducer)).fork();
5820     }
5821     for (Node<K,V> p; (p = advance()) != null; )
5822     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5823 dl 1.149 result = r;
5824     CountedCompleter<?> c;
5825     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5826 dl 1.246 @SuppressWarnings("unchecked")
5827     MapReduceValuesToDoubleTask<K,V>
5828 dl 1.149 t = (MapReduceValuesToDoubleTask<K,V>)c,
5829     s = t.rights;
5830     while (s != null) {
5831 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5832 dl 1.149 s = t.rights = s.nextRight;
5833     }
5834 dl 1.119 }
5835     }
5836 dl 1.30 }
5837 dl 1.79 }
5838 dl 1.30
5839 dl 1.222 @SuppressWarnings("serial")
5840 dl 1.210 static final class MapReduceEntriesToDoubleTask<K,V>
5841     extends BulkTask<K,V,Double> {
5842 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5843 dl 1.153 final DoubleBinaryOperator reducer;
5844 dl 1.119 final double basis;
5845     double result;
5846 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5847 dl 1.119 MapReduceEntriesToDoubleTask
5848 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5849 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
5850 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5851 dl 1.119 double basis,
5852 dl 1.153 DoubleBinaryOperator reducer) {
5853 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5854 dl 1.119 this.transformer = transformer;
5855     this.basis = basis; this.reducer = reducer;
5856     }
5857 dl 1.146 public final Double getRawResult() { return result; }
5858 dl 1.210 public final void compute() {
5859 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5860 dl 1.153 final DoubleBinaryOperator reducer;
5861 dl 1.149 if ((transformer = this.transformer) != null &&
5862     (reducer = this.reducer) != null) {
5863     double r = this.basis;
5864 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5865     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5866     addToPendingCount(1);
5867 dl 1.149 (rights = new MapReduceEntriesToDoubleTask<K,V>
5868 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5869     rights, transformer, r, reducer)).fork();
5870     }
5871     for (Node<K,V> p; (p = advance()) != null; )
5872     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5873 dl 1.149 result = r;
5874     CountedCompleter<?> c;
5875     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5876 dl 1.246 @SuppressWarnings("unchecked")
5877     MapReduceEntriesToDoubleTask<K,V>
5878 dl 1.149 t = (MapReduceEntriesToDoubleTask<K,V>)c,
5879     s = t.rights;
5880     while (s != null) {
5881 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5882 dl 1.149 s = t.rights = s.nextRight;
5883     }
5884 dl 1.119 }
5885 dl 1.138 }
5886 dl 1.30 }
5887 tim 1.1 }
5888    
5889 dl 1.222 @SuppressWarnings("serial")
5890 dl 1.210 static final class MapReduceMappingsToDoubleTask<K,V>
5891     extends BulkTask<K,V,Double> {
5892 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5893 dl 1.153 final DoubleBinaryOperator reducer;
5894 dl 1.119 final double basis;
5895     double result;
5896 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5897 dl 1.119 MapReduceMappingsToDoubleTask
5898 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5899 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
5900 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
5901 dl 1.119 double basis,
5902 dl 1.153 DoubleBinaryOperator reducer) {
5903 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5904 dl 1.119 this.transformer = transformer;
5905     this.basis = basis; this.reducer = reducer;
5906     }
5907 dl 1.146 public final Double getRawResult() { return result; }
5908 dl 1.210 public final void compute() {
5909 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5910 dl 1.153 final DoubleBinaryOperator reducer;
5911 dl 1.149 if ((transformer = this.transformer) != null &&
5912     (reducer = this.reducer) != null) {
5913     double r = this.basis;
5914 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5915     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5916     addToPendingCount(1);
5917 dl 1.149 (rights = new MapReduceMappingsToDoubleTask<K,V>
5918 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5919     rights, transformer, r, reducer)).fork();
5920     }
5921     for (Node<K,V> p; (p = advance()) != null; )
5922 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5923 dl 1.149 result = r;
5924     CountedCompleter<?> c;
5925     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5926 dl 1.246 @SuppressWarnings("unchecked")
5927     MapReduceMappingsToDoubleTask<K,V>
5928 dl 1.149 t = (MapReduceMappingsToDoubleTask<K,V>)c,
5929     s = t.rights;
5930     while (s != null) {
5931 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5932 dl 1.149 s = t.rights = s.nextRight;
5933     }
5934 dl 1.119 }
5935     }
5936 dl 1.4 }
5937 dl 1.119 }
5938    
5939 dl 1.222 @SuppressWarnings("serial")
5940 dl 1.210 static final class MapReduceKeysToLongTask<K,V>
5941     extends BulkTask<K,V,Long> {
5942 dl 1.171 final ToLongFunction<? super K> transformer;
5943 dl 1.153 final LongBinaryOperator reducer;
5944 dl 1.119 final long basis;
5945     long result;
5946 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
5947 dl 1.119 MapReduceKeysToLongTask
5948 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5949 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
5950 dl 1.171 ToLongFunction<? super K> transformer,
5951 dl 1.119 long basis,
5952 dl 1.153 LongBinaryOperator reducer) {
5953 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5954 dl 1.119 this.transformer = transformer;
5955     this.basis = basis; this.reducer = reducer;
5956     }
5957 dl 1.146 public final Long getRawResult() { return result; }
5958 dl 1.210 public final void compute() {
5959 dl 1.171 final ToLongFunction<? super K> transformer;
5960 dl 1.153 final LongBinaryOperator reducer;
5961 dl 1.149 if ((transformer = this.transformer) != null &&
5962     (reducer = this.reducer) != null) {
5963     long r = this.basis;
5964 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5965     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5966     addToPendingCount(1);
5967 dl 1.149 (rights = new MapReduceKeysToLongTask<K,V>
5968 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5969     rights, transformer, r, reducer)).fork();
5970     }
5971     for (Node<K,V> p; (p = advance()) != null; )
5972 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5973 dl 1.149 result = r;
5974     CountedCompleter<?> c;
5975     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5976 dl 1.246 @SuppressWarnings("unchecked")
5977     MapReduceKeysToLongTask<K,V>
5978 dl 1.149 t = (MapReduceKeysToLongTask<K,V>)c,
5979     s = t.rights;
5980     while (s != null) {
5981 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5982 dl 1.149 s = t.rights = s.nextRight;
5983     }
5984 dl 1.119 }
5985 dl 1.138 }
5986 dl 1.4 }
5987 dl 1.119 }
5988    
5989 dl 1.222 @SuppressWarnings("serial")
5990 dl 1.210 static final class MapReduceValuesToLongTask<K,V>
5991     extends BulkTask<K,V,Long> {
5992 dl 1.171 final ToLongFunction<? super V> transformer;
5993 dl 1.153 final LongBinaryOperator reducer;
5994 dl 1.119 final long basis;
5995     long result;
5996 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
5997 dl 1.119 MapReduceValuesToLongTask
5998 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5999 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
6000 dl 1.171 ToLongFunction<? super V> transformer,
6001 dl 1.119 long basis,
6002 dl 1.153 LongBinaryOperator reducer) {
6003 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6004 dl 1.119 this.transformer = transformer;
6005     this.basis = basis; this.reducer = reducer;
6006     }
6007 dl 1.146 public final Long getRawResult() { return result; }
6008 dl 1.210 public final void compute() {
6009 dl 1.171 final ToLongFunction<? super V> transformer;
6010 dl 1.153 final LongBinaryOperator reducer;
6011 dl 1.149 if ((transformer = this.transformer) != null &&
6012     (reducer = this.reducer) != null) {
6013     long r = this.basis;
6014 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6015     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6016     addToPendingCount(1);
6017 dl 1.149 (rights = new MapReduceValuesToLongTask<K,V>
6018 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6019     rights, transformer, r, reducer)).fork();
6020     }
6021     for (Node<K,V> p; (p = advance()) != null; )
6022     r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
6023 dl 1.149 result = r;
6024     CountedCompleter<?> c;
6025     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6026 dl 1.246 @SuppressWarnings("unchecked")
6027     MapReduceValuesToLongTask<K,V>
6028 dl 1.149 t = (MapReduceValuesToLongTask<K,V>)c,
6029     s = t.rights;
6030     while (s != null) {
6031 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6032 dl 1.149 s = t.rights = s.nextRight;
6033     }
6034 dl 1.119 }
6035     }
6036 jsr166 1.95 }
6037 dl 1.119 }
6038    
6039 dl 1.222 @SuppressWarnings("serial")
6040 dl 1.210 static final class MapReduceEntriesToLongTask<K,V>
6041     extends BulkTask<K,V,Long> {
6042 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6043 dl 1.153 final LongBinaryOperator reducer;
6044 dl 1.119 final long basis;
6045     long result;
6046 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
6047 dl 1.119 MapReduceEntriesToLongTask
6048 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6049 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
6050 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
6051 dl 1.119 long basis,
6052 dl 1.153 LongBinaryOperator reducer) {
6053 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6054 dl 1.119 this.transformer = transformer;
6055     this.basis = basis; this.reducer = reducer;
6056     }
6057 dl 1.146 public final Long getRawResult() { return result; }
6058 dl 1.210 public final void compute() {
6059 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6060 dl 1.153 final LongBinaryOperator reducer;
6061 dl 1.149 if ((transformer = this.transformer) != null &&
6062     (reducer = this.reducer) != null) {
6063     long r = this.basis;
6064 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6065     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6066     addToPendingCount(1);
6067 dl 1.149 (rights = new MapReduceEntriesToLongTask<K,V>
6068 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6069     rights, transformer, r, reducer)).fork();
6070     }
6071     for (Node<K,V> p; (p = advance()) != null; )
6072     r = reducer.applyAsLong(r, transformer.applyAsLong(p));
6073 dl 1.149 result = r;
6074     CountedCompleter<?> c;
6075     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6076 dl 1.246 @SuppressWarnings("unchecked")
6077     MapReduceEntriesToLongTask<K,V>
6078 dl 1.149 t = (MapReduceEntriesToLongTask<K,V>)c,
6079     s = t.rights;
6080     while (s != null) {
6081 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6082 dl 1.149 s = t.rights = s.nextRight;
6083     }
6084 dl 1.119 }
6085 dl 1.138 }
6086 dl 1.4 }
6087 tim 1.1 }
6088    
6089 dl 1.222 @SuppressWarnings("serial")
6090 dl 1.210 static final class MapReduceMappingsToLongTask<K,V>
6091     extends BulkTask<K,V,Long> {
6092 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6093 dl 1.153 final LongBinaryOperator reducer;
6094 dl 1.119 final long basis;
6095     long result;
6096 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6097 dl 1.119 MapReduceMappingsToLongTask
6098 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6099 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
6100 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
6101 dl 1.119 long basis,
6102 dl 1.153 LongBinaryOperator reducer) {
6103 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6104 dl 1.119 this.transformer = transformer;
6105     this.basis = basis; this.reducer = reducer;
6106     }
6107 dl 1.146 public final Long getRawResult() { return result; }
6108 dl 1.210 public final void compute() {
6109 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6110 dl 1.153 final LongBinaryOperator reducer;
6111 dl 1.149 if ((transformer = this.transformer) != null &&
6112     (reducer = this.reducer) != null) {
6113     long r = this.basis;
6114 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6115     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6116     addToPendingCount(1);
6117 dl 1.149 (rights = new MapReduceMappingsToLongTask<K,V>
6118 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6119     rights, transformer, r, reducer)).fork();
6120     }
6121     for (Node<K,V> p; (p = advance()) != null; )
6122 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6123 dl 1.149 result = r;
6124     CountedCompleter<?> c;
6125     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6126 dl 1.246 @SuppressWarnings("unchecked")
6127     MapReduceMappingsToLongTask<K,V>
6128 dl 1.149 t = (MapReduceMappingsToLongTask<K,V>)c,
6129     s = t.rights;
6130     while (s != null) {
6131 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6132 dl 1.149 s = t.rights = s.nextRight;
6133     }
6134 dl 1.119 }
6135     }
6136 dl 1.4 }
6137 tim 1.1 }
6138    
6139 dl 1.222 @SuppressWarnings("serial")
6140 dl 1.210 static final class MapReduceKeysToIntTask<K,V>
6141     extends BulkTask<K,V,Integer> {
6142 dl 1.171 final ToIntFunction<? super K> transformer;
6143 dl 1.153 final IntBinaryOperator reducer;
6144 dl 1.119 final int basis;
6145     int result;
6146 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
6147 dl 1.119 MapReduceKeysToIntTask
6148 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6149 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
6150 dl 1.171 ToIntFunction<? super K> transformer,
6151 dl 1.119 int basis,
6152 dl 1.153 IntBinaryOperator reducer) {
6153 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6154 dl 1.119 this.transformer = transformer;
6155     this.basis = basis; this.reducer = reducer;
6156     }
6157 dl 1.146 public final Integer getRawResult() { return result; }
6158 dl 1.210 public final void compute() {
6159 dl 1.171 final ToIntFunction<? super K> transformer;
6160 dl 1.153 final IntBinaryOperator reducer;
6161 dl 1.149 if ((transformer = this.transformer) != null &&
6162     (reducer = this.reducer) != null) {
6163     int r = this.basis;
6164 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6165     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6166     addToPendingCount(1);
6167 dl 1.149 (rights = new MapReduceKeysToIntTask<K,V>
6168 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6169     rights, transformer, r, reducer)).fork();
6170     }
6171     for (Node<K,V> p; (p = advance()) != null; )
6172 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6173 dl 1.149 result = r;
6174     CountedCompleter<?> c;
6175     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6176 dl 1.246 @SuppressWarnings("unchecked")
6177     MapReduceKeysToIntTask<K,V>
6178 dl 1.149 t = (MapReduceKeysToIntTask<K,V>)c,
6179     s = t.rights;
6180     while (s != null) {
6181 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6182 dl 1.149 s = t.rights = s.nextRight;
6183     }
6184 dl 1.119 }
6185 dl 1.138 }
6186 dl 1.30 }
6187     }
6188    
6189 dl 1.222 @SuppressWarnings("serial")
6190 dl 1.210 static final class MapReduceValuesToIntTask<K,V>
6191     extends BulkTask<K,V,Integer> {
6192 dl 1.171 final ToIntFunction<? super V> transformer;
6193 dl 1.153 final IntBinaryOperator reducer;
6194 dl 1.119 final int basis;
6195     int result;
6196 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
6197 dl 1.119 MapReduceValuesToIntTask
6198 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6199 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
6200 dl 1.171 ToIntFunction<? super V> transformer,
6201 dl 1.119 int basis,
6202 dl 1.153 IntBinaryOperator reducer) {
6203 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6204 dl 1.119 this.transformer = transformer;
6205     this.basis = basis; this.reducer = reducer;
6206     }
6207 dl 1.146 public final Integer getRawResult() { return result; }
6208 dl 1.210 public final void compute() {
6209 dl 1.171 final ToIntFunction<? super V> transformer;
6210 dl 1.153 final IntBinaryOperator reducer;
6211 dl 1.149 if ((transformer = this.transformer) != null &&
6212     (reducer = this.reducer) != null) {
6213     int r = this.basis;
6214 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6215     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6216     addToPendingCount(1);
6217 dl 1.149 (rights = new MapReduceValuesToIntTask<K,V>
6218 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6219     rights, transformer, r, reducer)).fork();
6220     }
6221     for (Node<K,V> p; (p = advance()) != null; )
6222     r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6223 dl 1.149 result = r;
6224     CountedCompleter<?> c;
6225     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6226 dl 1.246 @SuppressWarnings("unchecked")
6227     MapReduceValuesToIntTask<K,V>
6228 dl 1.149 t = (MapReduceValuesToIntTask<K,V>)c,
6229     s = t.rights;
6230     while (s != null) {
6231 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6232 dl 1.149 s = t.rights = s.nextRight;
6233     }
6234 dl 1.119 }
6235 dl 1.2 }
6236 tim 1.1 }
6237     }
6238    
6239 dl 1.222 @SuppressWarnings("serial")
6240 dl 1.210 static final class MapReduceEntriesToIntTask<K,V>
6241     extends BulkTask<K,V,Integer> {
6242 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6243 dl 1.153 final IntBinaryOperator reducer;
6244 dl 1.119 final int basis;
6245     int result;
6246 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6247 dl 1.119 MapReduceEntriesToIntTask
6248 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6249 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
6250 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
6251 dl 1.119 int basis,
6252 dl 1.153 IntBinaryOperator reducer) {
6253 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6254 dl 1.119 this.transformer = transformer;
6255     this.basis = basis; this.reducer = reducer;
6256     }
6257 dl 1.146 public final Integer getRawResult() { return result; }
6258 dl 1.210 public final void compute() {
6259 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6260 dl 1.153 final IntBinaryOperator reducer;
6261 dl 1.149 if ((transformer = this.transformer) != null &&
6262     (reducer = this.reducer) != null) {
6263     int r = this.basis;
6264 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6265     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6266     addToPendingCount(1);
6267 dl 1.149 (rights = new MapReduceEntriesToIntTask<K,V>
6268 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6269     rights, transformer, r, reducer)).fork();
6270     }
6271     for (Node<K,V> p; (p = advance()) != null; )
6272     r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6273 dl 1.149 result = r;
6274     CountedCompleter<?> c;
6275     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6276 dl 1.246 @SuppressWarnings("unchecked")
6277     MapReduceEntriesToIntTask<K,V>
6278 dl 1.149 t = (MapReduceEntriesToIntTask<K,V>)c,
6279     s = t.rights;
6280     while (s != null) {
6281 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6282 dl 1.149 s = t.rights = s.nextRight;
6283     }
6284 dl 1.119 }
6285 dl 1.138 }
6286 dl 1.4 }
6287 dl 1.119 }
6288 tim 1.1
6289 dl 1.222 @SuppressWarnings("serial")
6290 dl 1.210 static final class MapReduceMappingsToIntTask<K,V>
6291     extends BulkTask<K,V,Integer> {
6292 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6293 dl 1.153 final IntBinaryOperator reducer;
6294 dl 1.119 final int basis;
6295     int result;
6296 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6297 dl 1.119 MapReduceMappingsToIntTask
6298 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6299 dl 1.146 MapReduceMappingsToIntTask<K,V> nextRight,
6300 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
6301 dl 1.119 int basis,
6302 dl 1.153 IntBinaryOperator reducer) {
6303 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6304 dl 1.119 this.transformer = transformer;
6305     this.basis = basis; this.reducer = reducer;
6306     }
6307 dl 1.146 public final Integer getRawResult() { return result; }
6308 dl 1.210 public final void compute() {
6309 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6310 dl 1.153 final IntBinaryOperator reducer;
6311 dl 1.149 if ((transformer = this.transformer) != null &&
6312     (reducer = this.reducer) != null) {
6313     int r = this.basis;
6314 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6315     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6316     addToPendingCount(1);
6317 dl 1.149 (rights = new MapReduceMappingsToIntTask<K,V>
6318 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6319     rights, transformer, r, reducer)).fork();
6320     }
6321     for (Node<K,V> p; (p = advance()) != null; )
6322 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6323 dl 1.149 result = r;
6324     CountedCompleter<?> c;
6325     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6326 dl 1.246 @SuppressWarnings("unchecked")
6327     MapReduceMappingsToIntTask<K,V>
6328 dl 1.149 t = (MapReduceMappingsToIntTask<K,V>)c,
6329     s = t.rights;
6330     while (s != null) {
6331 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6332 dl 1.149 s = t.rights = s.nextRight;
6333     }
6334 dl 1.119 }
6335 dl 1.138 }
6336 tim 1.1 }
6337     }
6338 dl 1.99
6339     // Unsafe mechanics
6340 jsr166 1.293 private static final Unsafe U = Unsafe.getUnsafe();
6341 dl 1.149 private static final long SIZECTL;
6342     private static final long TRANSFERINDEX;
6343     private static final long BASECOUNT;
6344 dl 1.153 private static final long CELLSBUSY;
6345 dl 1.149 private static final long CELLVALUE;
6346 jsr166 1.264 private static final int ABASE;
6347 dl 1.119 private static final int ASHIFT;
6348 dl 1.99
6349     static {
6350     try {
6351 dl 1.149 SIZECTL = U.objectFieldOffset
6352 jsr166 1.264 (ConcurrentHashMap.class.getDeclaredField("sizeCtl"));
6353 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
6354 jsr166 1.264 (ConcurrentHashMap.class.getDeclaredField("transferIndex"));
6355 dl 1.149 BASECOUNT = U.objectFieldOffset
6356 jsr166 1.264 (ConcurrentHashMap.class.getDeclaredField("baseCount"));
6357 dl 1.153 CELLSBUSY = U.objectFieldOffset
6358 jsr166 1.264 (ConcurrentHashMap.class.getDeclaredField("cellsBusy"));
6359    
6360 dl 1.149 CELLVALUE = U.objectFieldOffset
6361 jsr166 1.264 (CounterCell.class.getDeclaredField("value"));
6362    
6363     ABASE = U.arrayBaseOffset(Node[].class);
6364     int scale = U.arrayIndexScale(Node[].class);
6365 jsr166 1.167 if ((scale & (scale - 1)) != 0)
6366 jsr166 1.263 throw new Error("array index scale not a power of two");
6367 jsr166 1.167 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6368 jsr166 1.262 } catch (ReflectiveOperationException e) {
6369 dl 1.99 throw new Error(e);
6370     }
6371 jsr166 1.269
6372     // Reduce the risk of rare disastrous classloading in first call to
6373     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
6374     Class<?> ensureLoaded = LockSupport.class;
6375 dl 1.99 }
6376 jsr166 1.152 }