ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.315
Committed: Wed Nov 28 23:52:49 2018 UTC (5 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.314: +3 -3 lines
Log Message:
Fix resize help-out check

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