ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.233
Committed: Wed Jul 3 18:16:08 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.232: +17 -14 lines
Log Message:
More conservative use of volatiles

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