ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.287
Committed: Sun Oct 25 03:34:04 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.286: +12 -4 lines
Log Message:
document the jdk7 compatibility pseudo-fields and delete the trailing assignment to segments

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