ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.234
Committed: Thu Jul 4 18:33:59 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.233: +31 -16 lines
Log Message:
Avoid unbounded recursion

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 dl 1.234 // loop to avoid arbitrarily deep recursion on forwarding nodes
2108     outer: for (Node<K,V>[] tab = nextTable;;) {
2109     Node<K,V> e; int n;
2110     if (k == null || tab == null || (n = tab.length) == 0 ||
2111     (e = tabAt(tab, (n - 1) & h)) == null)
2112     return null;
2113     for (;;) {
2114 dl 1.222 int eh; K ek;
2115     if ((eh = e.hash) == h &&
2116     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2117     return e;
2118 dl 1.234 if (eh < 0) {
2119     if (e instanceof ForwardingNode) {
2120     tab = ((ForwardingNode<K,V>)e).nextTable;
2121     continue outer;
2122     }
2123     else
2124     return e.find(h, k);
2125     }
2126     if ((e = e.next) == null)
2127     return null;
2128     }
2129 dl 1.222 }
2130     }
2131     }
2132    
2133     /**
2134     * A place-holder node used in computeIfAbsent and compute
2135     */
2136     static final class ReservationNode<K,V> extends Node<K,V> {
2137     ReservationNode() {
2138     super(RESERVED, null, null, null);
2139     }
2140    
2141     Node<K,V> find(int h, Object k) {
2142     return null;
2143     }
2144     }
2145    
2146     /* ---------------- Table Initialization and Resizing -------------- */
2147    
2148     /**
2149     * Initializes table, using the size recorded in sizeCtl.
2150 dl 1.119 */
2151 dl 1.210 private final Node<K,V>[] initTable() {
2152     Node<K,V>[] tab; int sc;
2153 dl 1.222 while ((tab = table) == null || tab.length == 0) {
2154 dl 1.119 if ((sc = sizeCtl) < 0)
2155     Thread.yield(); // lost initialization race; just spin
2156 dl 1.149 else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2157 dl 1.119 try {
2158 dl 1.222 if ((tab = table) == null || tab.length == 0) {
2159 dl 1.119 int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
2160 dl 1.222 @SuppressWarnings({"rawtypes","unchecked"})
2161     Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2162     table = tab = nt;
2163 dl 1.119 sc = n - (n >>> 2);
2164     }
2165     } finally {
2166     sizeCtl = sc;
2167     }
2168     break;
2169     }
2170     }
2171     return tab;
2172 dl 1.4 }
2173    
2174     /**
2175 dl 1.149 * Adds to count, and if table is too small and not already
2176     * resizing, initiates transfer. If already resizing, helps
2177     * perform transfer if work is available. Rechecks occupancy
2178     * after a transfer to see if another resize is already needed
2179     * because resizings are lagging additions.
2180     *
2181     * @param x the count to add
2182     * @param check if <0, don't check resize, if <= 1 only check if uncontended
2183     */
2184     private final void addCount(long x, int check) {
2185 dl 1.222 CounterCell[] as; long b, s;
2186 dl 1.149 if ((as = counterCells) != null ||
2187     !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
2188 dl 1.222 CounterCell a; long v; int m;
2189 dl 1.149 boolean uncontended = true;
2190 dl 1.160 if (as == null || (m = as.length - 1) < 0 ||
2191     (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
2192 dl 1.149 !(uncontended =
2193     U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
2194 dl 1.160 fullAddCount(x, uncontended);
2195 dl 1.149 return;
2196     }
2197     if (check <= 1)
2198     return;
2199     s = sumCount();
2200     }
2201     if (check >= 0) {
2202 dl 1.210 Node<K,V>[] tab, nt; int sc;
2203 dl 1.149 while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
2204     tab.length < MAXIMUM_CAPACITY) {
2205     if (sc < 0) {
2206     if (sc == -1 || transferIndex <= transferOrigin ||
2207     (nt = nextTable) == null)
2208     break;
2209     if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2210     transfer(tab, nt);
2211 dl 1.119 }
2212 dl 1.149 else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
2213     transfer(tab, null);
2214     s = sumCount();
2215 dl 1.119 }
2216     }
2217 dl 1.4 }
2218    
2219     /**
2220 dl 1.222 * Helps transfer if a resize is in progress.
2221     */
2222     final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
2223     Node<K,V>[] nextTab; int sc;
2224     if ((f instanceof ForwardingNode) &&
2225     (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
2226     if (nextTab == nextTable && tab == table &&
2227     transferIndex > transferOrigin && (sc = sizeCtl) < -1 &&
2228     U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
2229     transfer(tab, nextTab);
2230     return nextTab;
2231     }
2232     return table;
2233     }
2234    
2235     /**
2236 dl 1.119 * Tries to presize table to accommodate the given number of elements.
2237 tim 1.1 *
2238 dl 1.119 * @param size number of elements (doesn't need to be perfectly accurate)
2239 tim 1.1 */
2240 dl 1.210 private final void tryPresize(int size) {
2241 dl 1.119 int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
2242     tableSizeFor(size + (size >>> 1) + 1);
2243     int sc;
2244     while ((sc = sizeCtl) >= 0) {
2245 dl 1.210 Node<K,V>[] tab = table; int n;
2246 dl 1.119 if (tab == null || (n = tab.length) == 0) {
2247     n = (sc > c) ? sc : c;
2248 dl 1.149 if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
2249 dl 1.119 try {
2250     if (table == tab) {
2251 dl 1.222 @SuppressWarnings({"rawtypes","unchecked"})
2252     Node<K,V>[] nt = (Node<K,V>[])new Node[n];
2253     table = nt;
2254 dl 1.119 sc = n - (n >>> 2);
2255     }
2256     } finally {
2257     sizeCtl = sc;
2258     }
2259     }
2260     }
2261     else if (c <= sc || n >= MAXIMUM_CAPACITY)
2262     break;
2263 dl 1.149 else if (tab == table &&
2264     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2265     transfer(tab, null);
2266 dl 1.119 }
2267 dl 1.4 }
2268    
2269 jsr166 1.170 /**
2270 dl 1.119 * Moves and/or copies the nodes in each bin to new table. See
2271     * above for explanation.
2272 dl 1.4 */
2273 dl 1.210 private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
2274 dl 1.149 int n = tab.length, stride;
2275     if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
2276     stride = MIN_TRANSFER_STRIDE; // subdivide range
2277     if (nextTab == null) { // initiating
2278     try {
2279 dl 1.222 @SuppressWarnings({"rawtypes","unchecked"})
2280     Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
2281     nextTab = nt;
2282 jsr166 1.150 } catch (Throwable ex) { // try to cope with OOME
2283 dl 1.149 sizeCtl = Integer.MAX_VALUE;
2284     return;
2285     }
2286     nextTable = nextTab;
2287     transferOrigin = n;
2288     transferIndex = n;
2289 dl 1.222 ForwardingNode<K,V> rev = new ForwardingNode<K,V>(tab);
2290 dl 1.149 for (int k = n; k > 0;) { // progressively reveal ready slots
2291 jsr166 1.150 int nextk = (k > stride) ? k - stride : 0;
2292 dl 1.149 for (int m = nextk; m < k; ++m)
2293     nextTab[m] = rev;
2294     for (int m = n + nextk; m < n + k; ++m)
2295     nextTab[m] = rev;
2296     U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
2297     }
2298     }
2299     int nextn = nextTab.length;
2300 dl 1.222 ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
2301 dl 1.149 boolean advance = true;
2302 dl 1.234 boolean finishing = false; // to ensure sweep before committing nextTab
2303 dl 1.149 for (int i = 0, bound = 0;;) {
2304 dl 1.222 int nextIndex, nextBound, fh; Node<K,V> f;
2305 dl 1.149 while (advance) {
2306 dl 1.234 if (--i >= bound || finishing)
2307 dl 1.149 advance = false;
2308     else if ((nextIndex = transferIndex) <= transferOrigin) {
2309     i = -1;
2310     advance = false;
2311     }
2312     else if (U.compareAndSwapInt
2313     (this, TRANSFERINDEX, nextIndex,
2314 jsr166 1.150 nextBound = (nextIndex > stride ?
2315 dl 1.149 nextIndex - stride : 0))) {
2316     bound = nextBound;
2317     i = nextIndex - 1;
2318     advance = false;
2319     }
2320     }
2321     if (i < 0 || i >= n || i + n >= nextn) {
2322 dl 1.234 if (finishing) {
2323     nextTable = null;
2324     table = nextTab;
2325     sizeCtl = (n << 1) - (n >>> 1);
2326     return;
2327     }
2328 dl 1.149 for (int sc;;) {
2329     if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
2330 dl 1.234 if (sc != -1)
2331     return;
2332     finishing = advance = true;
2333     i = n; // recheck before commit
2334     break;
2335 dl 1.149 }
2336     }
2337     }
2338     else if ((f = tabAt(tab, i)) == null) {
2339     if (casTabAt(tab, i, null, fwd)) {
2340 dl 1.119 setTabAt(nextTab, i, null);
2341     setTabAt(nextTab, i + n, null);
2342 dl 1.149 advance = true;
2343     }
2344     }
2345 dl 1.222 else if ((fh = f.hash) == MOVED)
2346     advance = true; // already processed
2347     else {
2348 jsr166 1.150 synchronized (f) {
2349 dl 1.149 if (tabAt(tab, i) == f) {
2350 dl 1.222 Node<K,V> ln, hn;
2351     if (fh >= 0) {
2352     int runBit = fh & n;
2353     Node<K,V> lastRun = f;
2354     for (Node<K,V> p = f.next; p != null; p = p.next) {
2355     int b = p.hash & n;
2356     if (b != runBit) {
2357     runBit = b;
2358     lastRun = p;
2359     }
2360     }
2361     if (runBit == 0) {
2362     ln = lastRun;
2363     hn = null;
2364     }
2365     else {
2366     hn = lastRun;
2367     ln = null;
2368 dl 1.149 }
2369 dl 1.222 for (Node<K,V> p = f; p != lastRun; p = p.next) {
2370     int ph = p.hash; K pk = p.key; V pv = p.val;
2371     if ((ph & n) == 0)
2372     ln = new Node<K,V>(ph, pk, pv, ln);
2373 dl 1.210 else
2374 dl 1.222 hn = new Node<K,V>(ph, pk, pv, hn);
2375 dl 1.149 }
2376 dl 1.233 setTabAt(nextTab, i, ln);
2377     setTabAt(nextTab, i + n, hn);
2378     setTabAt(tab, i, fwd);
2379     advance = true;
2380 dl 1.222 }
2381     else if (f instanceof TreeBin) {
2382     TreeBin<K,V> t = (TreeBin<K,V>)f;
2383     TreeNode<K,V> lo = null, loTail = null;
2384     TreeNode<K,V> hi = null, hiTail = null;
2385     int lc = 0, hc = 0;
2386     for (Node<K,V> e = t.first; e != null; e = e.next) {
2387     int h = e.hash;
2388     TreeNode<K,V> p = new TreeNode<K,V>
2389     (h, e.key, e.val, null, null);
2390     if ((h & n) == 0) {
2391     if ((p.prev = loTail) == null)
2392     lo = p;
2393     else
2394     loTail.next = p;
2395     loTail = p;
2396     ++lc;
2397 dl 1.210 }
2398 dl 1.222 else {
2399     if ((p.prev = hiTail) == null)
2400     hi = p;
2401     else
2402     hiTail.next = p;
2403     hiTail = p;
2404     ++hc;
2405 dl 1.210 }
2406 dl 1.149 }
2407 jsr166 1.228 ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
2408     (hc != 0) ? new TreeBin<K,V>(lo) : t;
2409     hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
2410     (lc != 0) ? new TreeBin<K,V>(hi) : t;
2411 dl 1.233 setTabAt(nextTab, i, ln);
2412     setTabAt(nextTab, i + n, hn);
2413     setTabAt(tab, i, fwd);
2414     advance = true;
2415 dl 1.149 }
2416 dl 1.119 }
2417     }
2418     }
2419     }
2420 dl 1.4 }
2421 tim 1.1
2422 dl 1.149 /* ---------------- Counter support -------------- */
2423    
2424 dl 1.222 /**
2425     * A padded cell for distributing counts. Adapted from LongAdder
2426     * and Striped64. See their internal docs for explanation.
2427     */
2428     @sun.misc.Contended static final class CounterCell {
2429     volatile long value;
2430     CounterCell(long x) { value = x; }
2431     }
2432    
2433 dl 1.149 final long sumCount() {
2434 dl 1.222 CounterCell[] as = counterCells; CounterCell a;
2435 dl 1.149 long sum = baseCount;
2436     if (as != null) {
2437     for (int i = 0; i < as.length; ++i) {
2438     if ((a = as[i]) != null)
2439     sum += a.value;
2440 dl 1.119 }
2441     }
2442 dl 1.149 return sum;
2443 dl 1.119 }
2444    
2445 dl 1.149 // See LongAdder version for explanation
2446 dl 1.160 private final void fullAddCount(long x, boolean wasUncontended) {
2447 dl 1.149 int h;
2448 dl 1.160 if ((h = ThreadLocalRandom.getProbe()) == 0) {
2449     ThreadLocalRandom.localInit(); // force initialization
2450     h = ThreadLocalRandom.getProbe();
2451     wasUncontended = true;
2452 dl 1.119 }
2453 dl 1.149 boolean collide = false; // True if last slot nonempty
2454     for (;;) {
2455 dl 1.222 CounterCell[] as; CounterCell a; int n; long v;
2456 dl 1.149 if ((as = counterCells) != null && (n = as.length) > 0) {
2457     if ((a = as[(n - 1) & h]) == null) {
2458 dl 1.153 if (cellsBusy == 0) { // Try to attach new Cell
2459 dl 1.222 CounterCell r = new CounterCell(x); // Optimistic create
2460 dl 1.153 if (cellsBusy == 0 &&
2461     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2462 dl 1.149 boolean created = false;
2463     try { // Recheck under lock
2464 dl 1.222 CounterCell[] rs; int m, j;
2465 dl 1.149 if ((rs = counterCells) != null &&
2466     (m = rs.length) > 0 &&
2467     rs[j = (m - 1) & h] == null) {
2468     rs[j] = r;
2469     created = true;
2470 dl 1.128 }
2471 dl 1.149 } finally {
2472 dl 1.153 cellsBusy = 0;
2473 dl 1.119 }
2474 dl 1.149 if (created)
2475     break;
2476     continue; // Slot is now non-empty
2477     }
2478     }
2479     collide = false;
2480     }
2481     else if (!wasUncontended) // CAS already known to fail
2482     wasUncontended = true; // Continue after rehash
2483     else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
2484     break;
2485     else if (counterCells != as || n >= NCPU)
2486     collide = false; // At max size or stale
2487     else if (!collide)
2488     collide = true;
2489 dl 1.153 else if (cellsBusy == 0 &&
2490     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2491 dl 1.149 try {
2492     if (counterCells == as) {// Expand table unless stale
2493 dl 1.222 CounterCell[] rs = new CounterCell[n << 1];
2494 dl 1.149 for (int i = 0; i < n; ++i)
2495     rs[i] = as[i];
2496     counterCells = rs;
2497 dl 1.119 }
2498     } finally {
2499 dl 1.153 cellsBusy = 0;
2500 dl 1.119 }
2501 dl 1.149 collide = false;
2502     continue; // Retry with expanded table
2503 dl 1.119 }
2504 dl 1.160 h = ThreadLocalRandom.advanceProbe(h);
2505 dl 1.149 }
2506 dl 1.153 else if (cellsBusy == 0 && counterCells == as &&
2507     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
2508 dl 1.149 boolean init = false;
2509     try { // Initialize table
2510     if (counterCells == as) {
2511 dl 1.222 CounterCell[] rs = new CounterCell[2];
2512     rs[h & 1] = new CounterCell(x);
2513 dl 1.149 counterCells = rs;
2514     init = true;
2515 dl 1.119 }
2516     } finally {
2517 dl 1.153 cellsBusy = 0;
2518 dl 1.119 }
2519 dl 1.149 if (init)
2520     break;
2521 dl 1.119 }
2522 dl 1.149 else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
2523     break; // Fall back on using base
2524 dl 1.119 }
2525     }
2526    
2527 dl 1.222 /* ---------------- Conversion from/to TreeBins -------------- */
2528 dl 1.119
2529     /**
2530 dl 1.222 * Replaces all linked nodes in bin at given index unless table is
2531     * too small, in which case resizes instead.
2532 dl 1.119 */
2533 dl 1.222 private final void treeifyBin(Node<K,V>[] tab, int index) {
2534     Node<K,V> b; int n, sc;
2535     if (tab != null) {
2536 dl 1.224 if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
2537     if (tab == table && (sc = sizeCtl) >= 0 &&
2538     U.compareAndSwapInt(this, SIZECTL, sc, -2))
2539     transfer(tab, null);
2540     }
2541 dl 1.233 else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
2542 jsr166 1.223 synchronized (b) {
2543 dl 1.222 if (tabAt(tab, index) == b) {
2544     TreeNode<K,V> hd = null, tl = null;
2545     for (Node<K,V> e = b; e != null; e = e.next) {
2546     TreeNode<K,V> p =
2547     new TreeNode<K,V>(e.hash, e.key, e.val,
2548     null, null);
2549     if ((p.prev = tl) == null)
2550     hd = p;
2551     else
2552     tl.next = p;
2553     tl = p;
2554     }
2555     setTabAt(tab, index, new TreeBin<K,V>(hd));
2556 dl 1.210 }
2557     }
2558     }
2559     }
2560     }
2561    
2562     /**
2563 jsr166 1.229 * Returns a list on non-TreeNodes replacing those in given list.
2564 dl 1.210 */
2565 dl 1.222 static <K,V> Node<K,V> untreeify(Node<K,V> b) {
2566     Node<K,V> hd = null, tl = null;
2567     for (Node<K,V> q = b; q != null; q = q.next) {
2568     Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
2569     if (tl == null)
2570     hd = p;
2571     else
2572     tl.next = p;
2573     tl = p;
2574 dl 1.210 }
2575 dl 1.222 return hd;
2576     }
2577 dl 1.210
2578 dl 1.222 /* ---------------- TreeNodes -------------- */
2579    
2580     /**
2581     * Nodes for use in TreeBins
2582     */
2583     static final class TreeNode<K,V> extends Node<K,V> {
2584     TreeNode<K,V> parent; // red-black tree links
2585     TreeNode<K,V> left;
2586     TreeNode<K,V> right;
2587     TreeNode<K,V> prev; // needed to unlink next upon deletion
2588     boolean red;
2589 dl 1.210
2590 dl 1.222 TreeNode(int hash, K key, V val, Node<K,V> next,
2591     TreeNode<K,V> parent) {
2592     super(hash, key, val, next);
2593     this.parent = parent;
2594 dl 1.210 }
2595    
2596 dl 1.222 Node<K,V> find(int h, Object k) {
2597     return findTreeNode(h, k, null);
2598 dl 1.210 }
2599    
2600 dl 1.222 /**
2601     * Returns the TreeNode (or null if not found) for the given key
2602     * starting at given root.
2603     */
2604     final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
2605 dl 1.224 if (k != null) {
2606     TreeNode<K,V> p = this;
2607     do {
2608     int ph, dir; K pk; TreeNode<K,V> q;
2609     TreeNode<K,V> pl = p.left, pr = p.right;
2610     if ((ph = p.hash) > h)
2611     p = pl;
2612     else if (ph < h)
2613     p = pr;
2614     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2615     return p;
2616     else if (pl == null && pr == null)
2617     break;
2618 jsr166 1.225 else if ((kc != null ||
2619 dl 1.224 (kc = comparableClassFor(k)) != null) &&
2620     (dir = compareComparables(kc, k, pk)) != 0)
2621     p = (dir < 0) ? pl : pr;
2622     else if (pl == null)
2623     p = pr;
2624 jsr166 1.225 else if (pr == null ||
2625 dl 1.224 (q = pr.findTreeNode(h, k, kc)) == null)
2626     p = pl;
2627     else
2628     return q;
2629     } while (p != null);
2630     }
2631 dl 1.222 return null;
2632 dl 1.210 }
2633     }
2634 dl 1.192
2635 dl 1.222 /* ---------------- TreeBins -------------- */
2636 dl 1.119
2637 dl 1.222 /**
2638     * TreeNodes used at the heads of bins. TreeBins do not hold user
2639     * keys or values, but instead point to list of TreeNodes and
2640     * their root. They also maintain a parasitic read-write lock
2641     * forcing writers (who hold bin lock) to wait for readers (who do
2642     * not) to complete before tree restructuring operations.
2643     */
2644     static final class TreeBin<K,V> extends Node<K,V> {
2645     TreeNode<K,V> root;
2646     volatile TreeNode<K,V> first;
2647     volatile Thread waiter;
2648     volatile int lockState;
2649 dl 1.224 // values for lockState
2650     static final int WRITER = 1; // set while holding write lock
2651     static final int WAITER = 2; // set when waiting for write lock
2652     static final int READER = 4; // increment value for setting read lock
2653 dl 1.119
2654 dl 1.222 /**
2655     * Creates bin with initial set of nodes headed by b.
2656     */
2657     TreeBin(TreeNode<K,V> b) {
2658     super(TREEBIN, null, null, null);
2659 dl 1.224 this.first = b;
2660 dl 1.222 TreeNode<K,V> r = null;
2661     for (TreeNode<K,V> x = b, next; x != null; x = next) {
2662     next = (TreeNode<K,V>)x.next;
2663     x.left = x.right = null;
2664     if (r == null) {
2665     x.parent = null;
2666     x.red = false;
2667     r = x;
2668     }
2669     else {
2670     Object key = x.key;
2671     int hash = x.hash;
2672     Class<?> kc = null;
2673     for (TreeNode<K,V> p = r;;) {
2674     int dir, ph;
2675     if ((ph = p.hash) > hash)
2676     dir = -1;
2677     else if (ph < hash)
2678     dir = 1;
2679     else if ((kc != null ||
2680     (kc = comparableClassFor(key)) != null))
2681     dir = compareComparables(kc, key, p.key);
2682     else
2683     dir = 0;
2684     TreeNode<K,V> xp = p;
2685     if ((p = (dir <= 0) ? p.left : p.right) == null) {
2686     x.parent = xp;
2687     if (dir <= 0)
2688     xp.left = x;
2689     else
2690     xp.right = x;
2691     r = balanceInsertion(r, x);
2692     break;
2693     }
2694     }
2695     }
2696     }
2697 dl 1.224 this.root = r;
2698 dl 1.222 }
2699 dl 1.210
2700 dl 1.222 /**
2701 jsr166 1.229 * Acquires write lock for tree restructuring.
2702 dl 1.222 */
2703     private final void lockRoot() {
2704     if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2705     contendedLock(); // offload to separate method
2706 dl 1.153 }
2707    
2708 dl 1.222 /**
2709 jsr166 1.229 * Releases write lock for tree restructuring.
2710 dl 1.222 */
2711     private final void unlockRoot() {
2712     lockState = 0;
2713 dl 1.191 }
2714    
2715 dl 1.222 /**
2716 jsr166 1.229 * Possibly blocks awaiting root lock.
2717 dl 1.222 */
2718     private final void contendedLock() {
2719     boolean waiting = false;
2720     for (int s;;) {
2721     if (((s = lockState) & WRITER) == 0) {
2722     if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2723     if (waiting)
2724     waiter = null;
2725     return;
2726     }
2727     }
2728     else if ((s | WAITER) == 0) {
2729     if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2730     waiting = true;
2731     waiter = Thread.currentThread();
2732     }
2733     }
2734     else if (waiting)
2735     LockSupport.park(this);
2736     }
2737 dl 1.192 }
2738    
2739 dl 1.222 /**
2740     * Returns matching node or null if none. Tries to search
2741 jsr166 1.232 * using tree comparisons from root, but continues linear
2742 dl 1.222 * search when lock not available.
2743     */
2744     final Node<K,V> find(int h, Object k) {
2745     if (k != null) {
2746     for (Node<K,V> e = first; e != null; e = e.next) {
2747     int s; K ek;
2748     if (((s = lockState) & (WAITER|WRITER)) != 0) {
2749     if (e.hash == h &&
2750     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2751     return e;
2752     }
2753     else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2754     s + READER)) {
2755     TreeNode<K,V> r, p;
2756     try {
2757     p = ((r = root) == null ? null :
2758     r.findTreeNode(h, k, null));
2759     } finally {
2760     Thread w;
2761     if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2762     (READER|WAITER) && (w = waiter) != null)
2763     LockSupport.unpark(w);
2764     }
2765     return p;
2766     }
2767     }
2768     }
2769     return null;
2770 dl 1.192 }
2771    
2772 dl 1.222 /**
2773     * Finds or adds a node.
2774     * @return null if added
2775     */
2776     final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2777     Class<?> kc = null;
2778 dl 1.224 for (TreeNode<K,V> p = root;;) {
2779 dl 1.222 int dir, ph; K pk; TreeNode<K,V> q, pr;
2780 dl 1.224 if (p == null) {
2781     first = root = new TreeNode<K,V>(h, k, v, null, null);
2782     break;
2783     }
2784     else if ((ph = p.hash) > h)
2785 dl 1.222 dir = -1;
2786     else if (ph < h)
2787     dir = 1;
2788     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2789     return p;
2790     else if ((kc == null &&
2791     (kc = comparableClassFor(k)) == null) ||
2792     (dir = compareComparables(kc, k, pk)) == 0) {
2793     if (p.left == null)
2794     dir = 1;
2795     else if ((pr = p.right) == null ||
2796     (q = pr.findTreeNode(h, k, kc)) == null)
2797     dir = -1;
2798     else
2799     return q;
2800     }
2801     TreeNode<K,V> xp = p;
2802     if ((p = (dir < 0) ? p.left : p.right) == null) {
2803     TreeNode<K,V> x, f = first;
2804     first = x = new TreeNode<K,V>(h, k, v, f, xp);
2805     if (f != null)
2806     f.prev = x;
2807     if (dir < 0)
2808     xp.left = x;
2809     else
2810     xp.right = x;
2811     if (!xp.red)
2812     x.red = true;
2813     else {
2814     lockRoot();
2815     try {
2816     root = balanceInsertion(root, x);
2817     } finally {
2818     unlockRoot();
2819     }
2820     }
2821 dl 1.224 break;
2822 dl 1.222 }
2823     }
2824 dl 1.224 assert checkInvariants(root);
2825     return null;
2826 dl 1.192 }
2827    
2828 dl 1.222 /**
2829     * Removes the given node, that must be present before this
2830     * call. This is messier than typical red-black deletion code
2831     * because we cannot swap the contents of an interior node
2832     * with a leaf successor that is pinned by "next" pointers
2833     * that are accessible independently of lock. So instead we
2834     * swap the tree linkages.
2835     *
2836 jsr166 1.230 * @return true if now too small, so should be untreeified
2837 dl 1.222 */
2838     final boolean removeTreeNode(TreeNode<K,V> p) {
2839     TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2840     TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2841     TreeNode<K,V> r, rl;
2842     if (pred == null)
2843     first = next;
2844     else
2845     pred.next = next;
2846     if (next != null)
2847     next.prev = pred;
2848     if (first == null) {
2849     root = null;
2850     return true;
2851     }
2852 dl 1.224 if ((r = root) == null || r.right == null || // too small
2853 dl 1.222 (rl = r.left) == null || rl.left == null)
2854     return true;
2855     lockRoot();
2856     try {
2857     TreeNode<K,V> replacement;
2858     TreeNode<K,V> pl = p.left;
2859     TreeNode<K,V> pr = p.right;
2860     if (pl != null && pr != null) {
2861     TreeNode<K,V> s = pr, sl;
2862     while ((sl = s.left) != null) // find successor
2863     s = sl;
2864     boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2865     TreeNode<K,V> sr = s.right;
2866     TreeNode<K,V> pp = p.parent;
2867     if (s == pr) { // p was s's direct parent
2868     p.parent = s;
2869     s.right = p;
2870     }
2871     else {
2872     TreeNode<K,V> sp = s.parent;
2873     if ((p.parent = sp) != null) {
2874     if (s == sp.left)
2875     sp.left = p;
2876     else
2877     sp.right = p;
2878     }
2879     if ((s.right = pr) != null)
2880     pr.parent = s;
2881     }
2882     p.left = null;
2883     if ((p.right = sr) != null)
2884     sr.parent = p;
2885     if ((s.left = pl) != null)
2886     pl.parent = s;
2887     if ((s.parent = pp) == null)
2888     r = s;
2889     else if (p == pp.left)
2890     pp.left = s;
2891     else
2892     pp.right = s;
2893     if (sr != null)
2894     replacement = sr;
2895     else
2896     replacement = p;
2897     }
2898     else if (pl != null)
2899     replacement = pl;
2900     else if (pr != null)
2901     replacement = pr;
2902     else
2903     replacement = p;
2904     if (replacement != p) {
2905     TreeNode<K,V> pp = replacement.parent = p.parent;
2906     if (pp == null)
2907     r = replacement;
2908     else if (p == pp.left)
2909     pp.left = replacement;
2910     else
2911     pp.right = replacement;
2912     p.left = p.right = p.parent = null;
2913     }
2914    
2915     root = (p.red) ? r : balanceDeletion(r, replacement);
2916    
2917     if (p == replacement) { // detach pointers
2918     TreeNode<K,V> pp;
2919     if ((pp = p.parent) != null) {
2920     if (p == pp.left)
2921     pp.left = null;
2922     else if (p == pp.right)
2923     pp.right = null;
2924     p.parent = null;
2925     }
2926     }
2927     } finally {
2928     unlockRoot();
2929     }
2930 dl 1.224 assert checkInvariants(root);
2931 dl 1.222 return false;
2932 dl 1.210 }
2933    
2934 dl 1.222 /* ------------------------------------------------------------ */
2935     // Red-black tree methods, all adapted from CLR
2936 dl 1.210
2937 dl 1.222 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2938     TreeNode<K,V> p) {
2939 dl 1.224 TreeNode<K,V> r, pp, rl;
2940     if (p != null && (r = p.right) != null) {
2941 dl 1.222 if ((rl = p.right = r.left) != null)
2942     rl.parent = p;
2943     if ((pp = r.parent = p.parent) == null)
2944     (root = r).red = false;
2945     else if (pp.left == p)
2946     pp.left = r;
2947     else
2948     pp.right = r;
2949     r.left = p;
2950     p.parent = r;
2951     }
2952     return root;
2953 dl 1.119 }
2954    
2955 dl 1.222 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2956     TreeNode<K,V> p) {
2957 dl 1.224 TreeNode<K,V> l, pp, lr;
2958     if (p != null && (l = p.left) != null) {
2959 dl 1.222 if ((lr = p.left = l.right) != null)
2960     lr.parent = p;
2961     if ((pp = l.parent = p.parent) == null)
2962     (root = l).red = false;
2963     else if (pp.right == p)
2964     pp.right = l;
2965     else
2966     pp.left = l;
2967     l.right = p;
2968     p.parent = l;
2969     }
2970     return root;
2971 dl 1.119 }
2972    
2973 dl 1.222 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2974     TreeNode<K,V> x) {
2975     x.red = true;
2976     for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2977     if ((xp = x.parent) == null) {
2978     x.red = false;
2979     return x;
2980     }
2981     else if (!xp.red || (xpp = xp.parent) == null)
2982     return root;
2983     if (xp == (xppl = xpp.left)) {
2984     if ((xppr = xpp.right) != null && xppr.red) {
2985     xppr.red = false;
2986     xp.red = false;
2987     xpp.red = true;
2988     x = xpp;
2989     }
2990     else {
2991     if (x == xp.right) {
2992     root = rotateLeft(root, x = xp);
2993     xpp = (xp = x.parent) == null ? null : xp.parent;
2994     }
2995     if (xp != null) {
2996     xp.red = false;
2997     if (xpp != null) {
2998     xpp.red = true;
2999     root = rotateRight(root, xpp);
3000     }
3001     }
3002     }
3003     }
3004     else {
3005     if (xppl != null && xppl.red) {
3006     xppl.red = false;
3007     xp.red = false;
3008     xpp.red = true;
3009     x = xpp;
3010     }
3011     else {
3012     if (x == xp.left) {
3013     root = rotateRight(root, x = xp);
3014     xpp = (xp = x.parent) == null ? null : xp.parent;
3015     }
3016     if (xp != null) {
3017     xp.red = false;
3018     if (xpp != null) {
3019     xpp.red = true;
3020     root = rotateLeft(root, xpp);
3021     }
3022     }
3023     }
3024     }
3025     }
3026 dl 1.119 }
3027    
3028 dl 1.222 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3029     TreeNode<K,V> x) {
3030     for (TreeNode<K,V> xp, xpl, xpr;;) {
3031     if (x == null || x == root)
3032     return root;
3033     else if ((xp = x.parent) == null) {
3034     x.red = false;
3035     return x;
3036     }
3037     else if (x.red) {
3038     x.red = false;
3039     return root;
3040     }
3041     else if ((xpl = xp.left) == x) {
3042     if ((xpr = xp.right) != null && xpr.red) {
3043     xpr.red = false;
3044     xp.red = true;
3045     root = rotateLeft(root, xp);
3046     xpr = (xp = x.parent) == null ? null : xp.right;
3047     }
3048     if (xpr == null)
3049     x = xp;
3050     else {
3051     TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3052     if ((sr == null || !sr.red) &&
3053     (sl == null || !sl.red)) {
3054     xpr.red = true;
3055     x = xp;
3056     }
3057     else {
3058     if (sr == null || !sr.red) {
3059     if (sl != null)
3060     sl.red = false;
3061     xpr.red = true;
3062     root = rotateRight(root, xpr);
3063     xpr = (xp = x.parent) == null ?
3064     null : xp.right;
3065     }
3066     if (xpr != null) {
3067     xpr.red = (xp == null) ? false : xp.red;
3068     if ((sr = xpr.right) != null)
3069     sr.red = false;
3070     }
3071     if (xp != null) {
3072     xp.red = false;
3073     root = rotateLeft(root, xp);
3074     }
3075     x = root;
3076     }
3077     }
3078     }
3079     else { // symmetric
3080     if (xpl != null && xpl.red) {
3081     xpl.red = false;
3082     xp.red = true;
3083     root = rotateRight(root, xp);
3084     xpl = (xp = x.parent) == null ? null : xp.left;
3085     }
3086     if (xpl == null)
3087     x = xp;
3088     else {
3089     TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3090     if ((sl == null || !sl.red) &&
3091     (sr == null || !sr.red)) {
3092     xpl.red = true;
3093     x = xp;
3094     }
3095     else {
3096     if (sl == null || !sl.red) {
3097     if (sr != null)
3098     sr.red = false;
3099     xpl.red = true;
3100     root = rotateLeft(root, xpl);
3101     xpl = (xp = x.parent) == null ?
3102     null : xp.left;
3103     }
3104     if (xpl != null) {
3105     xpl.red = (xp == null) ? false : xp.red;
3106     if ((sl = xpl.left) != null)
3107     sl.red = false;
3108     }
3109     if (xp != null) {
3110     xp.red = false;
3111     root = rotateRight(root, xp);
3112     }
3113     x = root;
3114     }
3115     }
3116     }
3117     }
3118 dl 1.210 }
3119 jsr166 1.225
3120 dl 1.222 /**
3121     * Recursive invariant check
3122     */
3123 dl 1.224 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3124 dl 1.222 TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3125     tb = t.prev, tn = (TreeNode<K,V>)t.next;
3126     if (tb != null && tb.next != t)
3127     return false;
3128     if (tn != null && tn.prev != t)
3129     return false;
3130     if (tp != null && t != tp.left && t != tp.right)
3131     return false;
3132     if (tl != null && (tl.parent != t || tl.hash > t.hash))
3133     return false;
3134     if (tr != null && (tr.parent != t || tr.hash < t.hash))
3135     return false;
3136     if (t.red && tl != null && tl.red && tr != null && tr.red)
3137     return false;
3138 dl 1.224 if (tl != null && !checkInvariants(tl))
3139 dl 1.222 return false;
3140 dl 1.224 if (tr != null && !checkInvariants(tr))
3141 dl 1.210 return false;
3142     return true;
3143     }
3144 dl 1.146
3145 dl 1.222 private static final sun.misc.Unsafe U;
3146     private static final long LOCKSTATE;
3147     static {
3148     try {
3149     U = sun.misc.Unsafe.getUnsafe();
3150     Class<?> k = TreeBin.class;
3151     LOCKSTATE = U.objectFieldOffset
3152     (k.getDeclaredField("lockState"));
3153     } catch (Exception e) {
3154     throw new Error(e);
3155     }
3156 dl 1.146 }
3157 dl 1.119 }
3158    
3159 dl 1.222 /* ----------------Table Traversal -------------- */
3160    
3161     /**
3162     * Encapsulates traversal for methods such as containsValue; also
3163     * serves as a base class for other iterators and spliterators.
3164     *
3165     * Method advance visits once each still-valid node that was
3166     * reachable upon iterator construction. It might miss some that
3167     * were added to a bin after the bin was visited, which is OK wrt
3168     * consistency guarantees. Maintaining this property in the face
3169     * of possible ongoing resizes requires a fair amount of
3170     * bookkeeping state that is difficult to optimize away amidst
3171     * volatile accesses. Even so, traversal maintains reasonable
3172     * throughput.
3173     *
3174     * Normally, iteration proceeds bin-by-bin traversing lists.
3175     * However, if the table has been resized, then all future steps
3176     * must traverse both the bin at the current index as well as at
3177     * (index + baseSize); and so on for further resizings. To
3178     * paranoically cope with potential sharing by users of iterators
3179     * across threads, iteration terminates if a bounds checks fails
3180     * for a table read.
3181     */
3182     static class Traverser<K,V> {
3183     Node<K,V>[] tab; // current table; updated if resized
3184     Node<K,V> next; // the next entry to use
3185     int index; // index of bin to use next
3186     int baseIndex; // current index of initial table
3187     int baseLimit; // index bound for initial table
3188     final int baseSize; // initial table size
3189    
3190     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3191     this.tab = tab;
3192     this.baseSize = size;
3193     this.baseIndex = this.index = index;
3194     this.baseLimit = limit;
3195     this.next = null;
3196     }
3197    
3198     /**
3199     * Advances if possible, returning next valid node, or null if none.
3200     */
3201     final Node<K,V> advance() {
3202     Node<K,V> e;
3203     if ((e = next) != null)
3204     e = e.next;
3205     for (;;) {
3206     Node<K,V>[] t; int i, n; K ek; // must use locals in checks
3207     if (e != null)
3208     return next = e;
3209     if (baseIndex >= baseLimit || (t = tab) == null ||
3210     (n = t.length) <= (i = index) || i < 0)
3211     return next = null;
3212 dl 1.224 if ((e = tabAt(t, index)) != null && e.hash < 0) {
3213 dl 1.222 if (e instanceof ForwardingNode) {
3214     tab = ((ForwardingNode<K,V>)e).nextTable;
3215     e = null;
3216     continue;
3217     }
3218     else if (e instanceof TreeBin)
3219     e = ((TreeBin<K,V>)e).first;
3220     else
3221     e = null;
3222     }
3223     if ((index += baseSize) >= n)
3224     index = ++baseIndex; // visit upper slots if present
3225     }
3226     }
3227     }
3228    
3229     /**
3230     * Base of key, value, and entry Iterators. Adds fields to
3231 jsr166 1.229 * Traverser to support iterator.remove.
3232 dl 1.222 */
3233     static class BaseIterator<K,V> extends Traverser<K,V> {
3234     final ConcurrentHashMap<K,V> map;
3235     Node<K,V> lastReturned;
3236     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3237     ConcurrentHashMap<K,V> map) {
3238 dl 1.210 super(tab, size, index, limit);
3239     this.map = map;
3240 dl 1.222 advance();
3241 dl 1.210 }
3242    
3243 dl 1.222 public final boolean hasNext() { return next != null; }
3244     public final boolean hasMoreElements() { return next != null; }
3245    
3246     public final void remove() {
3247     Node<K,V> p;
3248     if ((p = lastReturned) == null)
3249     throw new IllegalStateException();
3250     lastReturned = null;
3251     map.replaceNode(p.key, null, null);
3252 dl 1.210 }
3253 dl 1.222 }
3254 dl 1.210
3255 dl 1.222 static final class KeyIterator<K,V> extends BaseIterator<K,V>
3256     implements Iterator<K>, Enumeration<K> {
3257     KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3258     ConcurrentHashMap<K,V> map) {
3259     super(tab, index, size, limit, map);
3260 dl 1.210 }
3261    
3262 dl 1.222 public final K next() {
3263 dl 1.210 Node<K,V> p;
3264 dl 1.222 if ((p = next) == null)
3265     throw new NoSuchElementException();
3266     K k = p.key;
3267     lastReturned = p;
3268     advance();
3269     return k;
3270 dl 1.210 }
3271    
3272 dl 1.222 public final K nextElement() { return next(); }
3273     }
3274    
3275     static final class ValueIterator<K,V> extends BaseIterator<K,V>
3276     implements Iterator<V>, Enumeration<V> {
3277     ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3278     ConcurrentHashMap<K,V> map) {
3279     super(tab, index, size, limit, map);
3280     }
3281 dl 1.210
3282 dl 1.222 public final V next() {
3283     Node<K,V> p;
3284     if ((p = next) == null)
3285     throw new NoSuchElementException();
3286     V v = p.val;
3287     lastReturned = p;
3288     advance();
3289     return v;
3290 dl 1.210 }
3291 dl 1.222
3292     public final V nextElement() { return next(); }
3293 dl 1.210 }
3294    
3295 dl 1.222 static final class EntryIterator<K,V> extends BaseIterator<K,V>
3296     implements Iterator<Map.Entry<K,V>> {
3297     EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3298     ConcurrentHashMap<K,V> map) {
3299     super(tab, index, size, limit, map);
3300     }
3301 dl 1.210
3302 dl 1.222 public final Map.Entry<K,V> next() {
3303     Node<K,V> p;
3304     if ((p = next) == null)
3305     throw new NoSuchElementException();
3306     K k = p.key;
3307     V v = p.val;
3308     lastReturned = p;
3309     advance();
3310     return new MapEntry<K,V>(k, v, map);
3311     }
3312     }
3313 dl 1.119
3314     /**
3315 dl 1.222 * Exported Entry for EntryIterator
3316 dl 1.119 */
3317 dl 1.222 static final class MapEntry<K,V> implements Map.Entry<K,V> {
3318     final K key; // non-null
3319     V val; // non-null
3320     final ConcurrentHashMap<K,V> map;
3321     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3322     this.key = key;
3323     this.val = val;
3324     this.map = map;
3325     }
3326     public K getKey() { return key; }
3327     public V getValue() { return val; }
3328     public int hashCode() { return key.hashCode() ^ val.hashCode(); }
3329     public String toString() { return key + "=" + val; }
3330 dl 1.119
3331 dl 1.222 public boolean equals(Object o) {
3332     Object k, v; Map.Entry<?,?> e;
3333     return ((o instanceof Map.Entry) &&
3334     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3335     (v = e.getValue()) != null &&
3336     (k == key || k.equals(key)) &&
3337     (v == val || v.equals(val)));
3338     }
3339 dl 1.119
3340 dl 1.222 /**
3341     * Sets our entry's value and writes through to the map. The
3342     * value to return is somewhat arbitrary here. Since we do not
3343     * necessarily track asynchronous changes, the most recent
3344     * "previous" value could be different from what we return (or
3345     * could even have been removed, in which case the put will
3346     * re-establish). We do not and cannot guarantee more.
3347     */
3348     public V setValue(V value) {
3349     if (value == null) throw new NullPointerException();
3350     V v = val;
3351     val = value;
3352     map.put(key, value);
3353     return v;
3354     }
3355 dl 1.119 }
3356    
3357 dl 1.222 static final class KeySpliterator<K,V> extends Traverser<K,V>
3358     implements Spliterator<K> {
3359     long est; // size estimate
3360     KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3361     long est) {
3362     super(tab, size, index, limit);
3363     this.est = est;
3364     }
3365 dl 1.119
3366 dl 1.222 public Spliterator<K> trySplit() {
3367     int i, f, h;
3368     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3369     new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3370     f, est >>>= 1);
3371 dl 1.119 }
3372    
3373 dl 1.222 public void forEachRemaining(Consumer<? super K> action) {
3374     if (action == null) throw new NullPointerException();
3375     for (Node<K,V> p; (p = advance()) != null;)
3376     action.accept(p.key);
3377 dl 1.119 }
3378    
3379 dl 1.222 public boolean tryAdvance(Consumer<? super K> action) {
3380     if (action == null) throw new NullPointerException();
3381     Node<K,V> p;
3382     if ((p = advance()) == null)
3383 dl 1.119 return false;
3384 dl 1.222 action.accept(p.key);
3385     return true;
3386 dl 1.119 }
3387    
3388 dl 1.222 public long estimateSize() { return est; }
3389 dl 1.119
3390 dl 1.222 public int characteristics() {
3391     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3392     Spliterator.NONNULL;
3393     }
3394 dl 1.142 }
3395 dl 1.119
3396 dl 1.222 static final class ValueSpliterator<K,V> extends Traverser<K,V>
3397     implements Spliterator<V> {
3398     long est; // size estimate
3399     ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3400     long est) {
3401     super(tab, size, index, limit);
3402     this.est = est;
3403 dl 1.209 }
3404    
3405 dl 1.222 public Spliterator<V> trySplit() {
3406     int i, f, h;
3407     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3408     new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3409     f, est >>>= 1);
3410 dl 1.142 }
3411 dl 1.119
3412 dl 1.222 public void forEachRemaining(Consumer<? super V> action) {
3413     if (action == null) throw new NullPointerException();
3414     for (Node<K,V> p; (p = advance()) != null;)
3415     action.accept(p.val);
3416     }
3417 dl 1.119
3418 dl 1.222 public boolean tryAdvance(Consumer<? super V> action) {
3419     if (action == null) throw new NullPointerException();
3420     Node<K,V> p;
3421     if ((p = advance()) == null)
3422     return false;
3423     action.accept(p.val);
3424     return true;
3425 dl 1.119 }
3426 dl 1.222
3427     public long estimateSize() { return est; }
3428    
3429     public int characteristics() {
3430     return Spliterator.CONCURRENT | Spliterator.NONNULL;
3431 dl 1.119 }
3432 dl 1.142 }
3433 dl 1.119
3434 dl 1.222 static final class EntrySpliterator<K,V> extends Traverser<K,V>
3435     implements Spliterator<Map.Entry<K,V>> {
3436     final ConcurrentHashMap<K,V> map; // To export MapEntry
3437     long est; // size estimate
3438     EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3439     long est, ConcurrentHashMap<K,V> map) {
3440     super(tab, size, index, limit);
3441     this.map = map;
3442     this.est = est;
3443     }
3444    
3445     public Spliterator<Map.Entry<K,V>> trySplit() {
3446     int i, f, h;
3447     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3448     new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3449     f, est >>>= 1, map);
3450     }
3451 dl 1.142
3452 dl 1.222 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3453     if (action == null) throw new NullPointerException();
3454     for (Node<K,V> p; (p = advance()) != null; )
3455     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3456     }
3457 dl 1.210
3458 dl 1.222 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3459     if (action == null) throw new NullPointerException();
3460     Node<K,V> p;
3461     if ((p = advance()) == null)
3462     return false;
3463     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3464     return true;
3465 dl 1.210 }
3466    
3467 dl 1.222 public long estimateSize() { return est; }
3468    
3469     public int characteristics() {
3470     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3471     Spliterator.NONNULL;
3472 dl 1.210 }
3473     }
3474    
3475     // Parallel bulk operations
3476    
3477     /**
3478     * Computes initial batch value for bulk tasks. The returned value
3479     * is approximately exp2 of the number of times (minus one) to
3480     * split task by two before executing leaf action. This value is
3481     * faster to compute and more convenient to use as a guide to
3482     * splitting than is the depth, since it is used while dividing by
3483     * two anyway.
3484     */
3485     final int batchFor(long b) {
3486     long n;
3487     if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3488     return 0;
3489     int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3490     return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3491     }
3492 dl 1.151
3493 dl 1.119 /**
3494 dl 1.137 * Performs the given action for each (key, value).
3495 dl 1.119 *
3496 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3497 jsr166 1.213 * needed for this operation to be executed in parallel
3498 dl 1.137 * @param action the action
3499 jsr166 1.220 * @since 1.8
3500 dl 1.119 */
3501 dl 1.210 public void forEach(long parallelismThreshold,
3502     BiConsumer<? super K,? super V> action) {
3503 dl 1.151 if (action == null) throw new NullPointerException();
3504 dl 1.210 new ForEachMappingTask<K,V>
3505     (null, batchFor(parallelismThreshold), 0, 0, table,
3506     action).invoke();
3507 dl 1.119 }
3508    
3509     /**
3510 dl 1.137 * Performs the given action for each non-null transformation
3511     * of each (key, value).
3512     *
3513 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3514 jsr166 1.213 * needed for this operation to be executed in parallel
3515 dl 1.137 * @param transformer a function returning the transformation
3516 jsr166 1.169 * for an element, or null if there is no transformation (in
3517 jsr166 1.172 * which case the action is not applied)
3518 dl 1.137 * @param action the action
3519 jsr166 1.220 * @since 1.8
3520 dl 1.119 */
3521 dl 1.210 public <U> void forEach(long parallelismThreshold,
3522     BiFunction<? super K, ? super V, ? extends U> transformer,
3523     Consumer<? super U> action) {
3524 dl 1.151 if (transformer == null || action == null)
3525     throw new NullPointerException();
3526 dl 1.210 new ForEachTransformedMappingTask<K,V,U>
3527     (null, batchFor(parallelismThreshold), 0, 0, table,
3528     transformer, action).invoke();
3529 dl 1.137 }
3530    
3531     /**
3532     * Returns a non-null result from applying the given search
3533 dl 1.210 * function on each (key, value), or null if none. Upon
3534     * success, further element processing is suppressed and the
3535     * results of any other parallel invocations of the search
3536     * function are ignored.
3537 dl 1.137 *
3538 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3539 jsr166 1.213 * needed for this operation to be executed in parallel
3540 dl 1.137 * @param searchFunction a function returning a non-null
3541     * result on success, else null
3542     * @return a non-null result from applying the given search
3543     * function on each (key, value), or null if none
3544 jsr166 1.220 * @since 1.8
3545 dl 1.137 */
3546 dl 1.210 public <U> U search(long parallelismThreshold,
3547     BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3548 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3549 dl 1.210 return new SearchMappingsTask<K,V,U>
3550     (null, batchFor(parallelismThreshold), 0, 0, table,
3551     searchFunction, new AtomicReference<U>()).invoke();
3552 dl 1.137 }
3553    
3554     /**
3555     * Returns the result of accumulating the given transformation
3556     * of all (key, value) pairs using the given reducer to
3557     * combine values, or null if none.
3558     *
3559 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3560 jsr166 1.213 * needed for this operation to be executed in parallel
3561 dl 1.137 * @param transformer a function returning the transformation
3562 jsr166 1.169 * for an element, or null if there is no transformation (in
3563 jsr166 1.172 * which case it is not combined)
3564 dl 1.137 * @param reducer a commutative associative combining function
3565     * @return the result of accumulating the given transformation
3566     * of all (key, value) pairs
3567 jsr166 1.220 * @since 1.8
3568 dl 1.137 */
3569 dl 1.210 public <U> U reduce(long parallelismThreshold,
3570     BiFunction<? super K, ? super V, ? extends U> transformer,
3571     BiFunction<? super U, ? super U, ? extends U> reducer) {
3572 dl 1.151 if (transformer == null || reducer == null)
3573     throw new NullPointerException();
3574 dl 1.210 return new MapReduceMappingsTask<K,V,U>
3575     (null, batchFor(parallelismThreshold), 0, 0, table,
3576     null, transformer, reducer).invoke();
3577 dl 1.137 }
3578    
3579     /**
3580     * Returns the result of accumulating the given transformation
3581     * of all (key, value) pairs using the given reducer to
3582     * combine values, and the given basis as an identity value.
3583     *
3584 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3585 jsr166 1.213 * needed for this operation to be executed in parallel
3586 dl 1.137 * @param transformer a function returning the transformation
3587     * for an element
3588     * @param basis the identity (initial default value) for the reduction
3589     * @param reducer a commutative associative combining function
3590     * @return the result of accumulating the given transformation
3591     * of all (key, value) pairs
3592 jsr166 1.220 * @since 1.8
3593 dl 1.137 */
3594 dl 1.231 public double reduceToDouble(long parallelismThreshold,
3595     ToDoubleBiFunction<? super K, ? super V> transformer,
3596     double basis,
3597     DoubleBinaryOperator reducer) {
3598 dl 1.151 if (transformer == null || reducer == null)
3599     throw new NullPointerException();
3600 dl 1.210 return new MapReduceMappingsToDoubleTask<K,V>
3601     (null, batchFor(parallelismThreshold), 0, 0, table,
3602     null, transformer, basis, reducer).invoke();
3603 dl 1.137 }
3604 dl 1.119
3605 dl 1.137 /**
3606     * Returns the result of accumulating the given transformation
3607     * of all (key, value) pairs using the given reducer to
3608     * combine values, and the given basis as an identity value.
3609     *
3610 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3611 jsr166 1.213 * needed for this operation to be executed in parallel
3612 dl 1.137 * @param transformer a function returning the transformation
3613     * for an element
3614     * @param basis the identity (initial default value) for the reduction
3615     * @param reducer a commutative associative combining function
3616     * @return the result of accumulating the given transformation
3617     * of all (key, value) pairs
3618 jsr166 1.220 * @since 1.8
3619 dl 1.137 */
3620 dl 1.210 public long reduceToLong(long parallelismThreshold,
3621     ToLongBiFunction<? super K, ? super V> transformer,
3622     long basis,
3623     LongBinaryOperator reducer) {
3624 dl 1.151 if (transformer == null || reducer == null)
3625     throw new NullPointerException();
3626 dl 1.210 return new MapReduceMappingsToLongTask<K,V>
3627     (null, batchFor(parallelismThreshold), 0, 0, table,
3628     null, transformer, basis, reducer).invoke();
3629 dl 1.137 }
3630    
3631     /**
3632     * Returns the result of accumulating the given transformation
3633     * of all (key, value) pairs using the given reducer to
3634     * combine values, and the given basis as an identity value.
3635     *
3636 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3637 jsr166 1.213 * needed for this operation to be executed in parallel
3638 dl 1.137 * @param transformer a function returning the transformation
3639     * for an element
3640     * @param basis the identity (initial default value) for the reduction
3641     * @param reducer a commutative associative combining function
3642     * @return the result of accumulating the given transformation
3643     * of all (key, value) pairs
3644 jsr166 1.220 * @since 1.8
3645 dl 1.137 */
3646 dl 1.210 public int reduceToInt(long parallelismThreshold,
3647     ToIntBiFunction<? super K, ? super V> transformer,
3648     int basis,
3649     IntBinaryOperator reducer) {
3650 dl 1.151 if (transformer == null || reducer == null)
3651     throw new NullPointerException();
3652 dl 1.210 return new MapReduceMappingsToIntTask<K,V>
3653     (null, batchFor(parallelismThreshold), 0, 0, table,
3654     null, transformer, basis, reducer).invoke();
3655 dl 1.137 }
3656    
3657     /**
3658     * Performs the given action for each key.
3659     *
3660 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3661 jsr166 1.213 * needed for this operation to be executed in parallel
3662 dl 1.137 * @param action the action
3663 jsr166 1.220 * @since 1.8
3664 dl 1.137 */
3665 dl 1.210 public void forEachKey(long parallelismThreshold,
3666     Consumer<? super K> action) {
3667     if (action == null) throw new NullPointerException();
3668     new ForEachKeyTask<K,V>
3669     (null, batchFor(parallelismThreshold), 0, 0, table,
3670     action).invoke();
3671 dl 1.137 }
3672 dl 1.119
3673 dl 1.137 /**
3674     * Performs the given action for each non-null transformation
3675     * of each key.
3676     *
3677 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3678 jsr166 1.213 * needed for this operation to be executed in parallel
3679 dl 1.137 * @param transformer a function returning the transformation
3680 jsr166 1.169 * for an element, or null if there is no transformation (in
3681 jsr166 1.172 * which case the action is not applied)
3682 dl 1.137 * @param action the action
3683 jsr166 1.220 * @since 1.8
3684 dl 1.137 */
3685 dl 1.210 public <U> void forEachKey(long parallelismThreshold,
3686     Function<? super K, ? extends U> transformer,
3687     Consumer<? super U> action) {
3688 dl 1.151 if (transformer == null || action == null)
3689     throw new NullPointerException();
3690 dl 1.210 new ForEachTransformedKeyTask<K,V,U>
3691     (null, batchFor(parallelismThreshold), 0, 0, table,
3692     transformer, action).invoke();
3693 dl 1.137 }
3694 dl 1.119
3695 dl 1.137 /**
3696     * Returns a non-null result from applying the given search
3697 dl 1.210 * function on each key, or null if none. Upon success,
3698     * further element processing is suppressed and the results of
3699     * any other parallel invocations of the search function are
3700     * ignored.
3701 dl 1.137 *
3702 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3703 jsr166 1.213 * needed for this operation to be executed in parallel
3704 dl 1.137 * @param searchFunction a function returning a non-null
3705     * result on success, else null
3706     * @return a non-null result from applying the given search
3707     * function on each key, or null if none
3708 jsr166 1.220 * @since 1.8
3709 dl 1.137 */
3710 dl 1.210 public <U> U searchKeys(long parallelismThreshold,
3711     Function<? super K, ? extends U> searchFunction) {
3712     if (searchFunction == null) throw new NullPointerException();
3713     return new SearchKeysTask<K,V,U>
3714     (null, batchFor(parallelismThreshold), 0, 0, table,
3715     searchFunction, new AtomicReference<U>()).invoke();
3716 dl 1.137 }
3717 dl 1.119
3718 dl 1.137 /**
3719     * Returns the result of accumulating all keys using the given
3720     * reducer to combine values, or null if none.
3721     *
3722 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3723 jsr166 1.213 * needed for this operation to be executed in parallel
3724 dl 1.137 * @param reducer a commutative associative combining function
3725     * @return the result of accumulating all keys using the given
3726     * reducer to combine values, or null if none
3727 jsr166 1.220 * @since 1.8
3728 dl 1.137 */
3729 dl 1.210 public K reduceKeys(long parallelismThreshold,
3730     BiFunction<? super K, ? super K, ? extends K> reducer) {
3731 dl 1.151 if (reducer == null) throw new NullPointerException();
3732 dl 1.210 return new ReduceKeysTask<K,V>
3733     (null, batchFor(parallelismThreshold), 0, 0, table,
3734     null, reducer).invoke();
3735 dl 1.137 }
3736 dl 1.119
3737 dl 1.137 /**
3738     * Returns the result of accumulating the given transformation
3739     * of all keys using the given reducer to combine values, or
3740     * null if none.
3741     *
3742 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3743 jsr166 1.213 * needed for this operation to be executed in parallel
3744 dl 1.137 * @param transformer a function returning the transformation
3745 jsr166 1.169 * for an element, or null if there is no transformation (in
3746 jsr166 1.172 * which case it is not combined)
3747 dl 1.137 * @param reducer a commutative associative combining function
3748     * @return the result of accumulating the given transformation
3749     * of all keys
3750 jsr166 1.220 * @since 1.8
3751 dl 1.137 */
3752 dl 1.210 public <U> U reduceKeys(long parallelismThreshold,
3753     Function<? super K, ? extends U> transformer,
3754 dl 1.153 BiFunction<? super U, ? super U, ? extends U> reducer) {
3755 dl 1.151 if (transformer == null || reducer == null)
3756     throw new NullPointerException();
3757 dl 1.210 return new MapReduceKeysTask<K,V,U>
3758     (null, batchFor(parallelismThreshold), 0, 0, table,
3759     null, transformer, reducer).invoke();
3760 dl 1.137 }
3761 dl 1.119
3762 dl 1.137 /**
3763     * Returns the result of accumulating the given transformation
3764     * of all keys using the given reducer to combine values, and
3765     * the given basis as an identity value.
3766     *
3767 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3768 jsr166 1.213 * needed for this operation to be executed in parallel
3769 dl 1.137 * @param transformer a function returning the transformation
3770     * for an element
3771     * @param basis the identity (initial default value) for the reduction
3772     * @param reducer a commutative associative combining function
3773 jsr166 1.157 * @return the result of accumulating the given transformation
3774 dl 1.137 * of all keys
3775 jsr166 1.220 * @since 1.8
3776 dl 1.137 */
3777 dl 1.210 public double reduceKeysToDouble(long parallelismThreshold,
3778     ToDoubleFunction<? super K> transformer,
3779     double basis,
3780     DoubleBinaryOperator reducer) {
3781 dl 1.151 if (transformer == null || reducer == null)
3782     throw new NullPointerException();
3783 dl 1.210 return new MapReduceKeysToDoubleTask<K,V>
3784     (null, batchFor(parallelismThreshold), 0, 0, table,
3785     null, transformer, basis, reducer).invoke();
3786 dl 1.137 }
3787 dl 1.119
3788 dl 1.137 /**
3789     * Returns the result of accumulating the given transformation
3790     * of all keys using the given reducer to combine values, and
3791     * the given basis as an identity value.
3792     *
3793 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3794 jsr166 1.213 * needed for this operation to be executed in parallel
3795 dl 1.137 * @param transformer a function returning the transformation
3796     * for an element
3797     * @param basis the identity (initial default value) for the reduction
3798     * @param reducer a commutative associative combining function
3799     * @return the result of accumulating the given transformation
3800     * of all keys
3801 jsr166 1.220 * @since 1.8
3802 dl 1.137 */
3803 dl 1.210 public long reduceKeysToLong(long parallelismThreshold,
3804     ToLongFunction<? super K> transformer,
3805     long basis,
3806     LongBinaryOperator reducer) {
3807 dl 1.151 if (transformer == null || reducer == null)
3808     throw new NullPointerException();
3809 dl 1.210 return new MapReduceKeysToLongTask<K,V>
3810     (null, batchFor(parallelismThreshold), 0, 0, table,
3811     null, transformer, basis, reducer).invoke();
3812 dl 1.137 }
3813 dl 1.119
3814 dl 1.137 /**
3815     * Returns the result of accumulating the given transformation
3816     * of all keys using the given reducer to combine values, and
3817     * the given basis as an identity value.
3818     *
3819 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3820 jsr166 1.213 * needed for this operation to be executed in parallel
3821 dl 1.137 * @param transformer a function returning the transformation
3822     * for an element
3823     * @param basis the identity (initial default value) for the reduction
3824     * @param reducer a commutative associative combining function
3825     * @return the result of accumulating the given transformation
3826     * of all keys
3827 jsr166 1.220 * @since 1.8
3828 dl 1.137 */
3829 dl 1.210 public int reduceKeysToInt(long parallelismThreshold,
3830     ToIntFunction<? super K> transformer,
3831     int basis,
3832     IntBinaryOperator reducer) {
3833 dl 1.151 if (transformer == null || reducer == null)
3834     throw new NullPointerException();
3835 dl 1.210 return new MapReduceKeysToIntTask<K,V>
3836     (null, batchFor(parallelismThreshold), 0, 0, table,
3837     null, transformer, basis, reducer).invoke();
3838 dl 1.137 }
3839 dl 1.119
3840 dl 1.137 /**
3841     * Performs the given action for each value.
3842     *
3843 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3844 jsr166 1.213 * needed for this operation to be executed in parallel
3845 dl 1.137 * @param action the action
3846 jsr166 1.220 * @since 1.8
3847 dl 1.137 */
3848 dl 1.210 public void forEachValue(long parallelismThreshold,
3849     Consumer<? super V> action) {
3850     if (action == null)
3851     throw new NullPointerException();
3852     new ForEachValueTask<K,V>
3853     (null, batchFor(parallelismThreshold), 0, 0, table,
3854     action).invoke();
3855 dl 1.137 }
3856 dl 1.119
3857 dl 1.137 /**
3858     * Performs the given action for each non-null transformation
3859     * of each value.
3860     *
3861 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3862 jsr166 1.213 * needed for this operation to be executed in parallel
3863 dl 1.137 * @param transformer a function returning the transformation
3864 jsr166 1.169 * for an element, or null if there is no transformation (in
3865 jsr166 1.172 * which case the action is not applied)
3866 jsr166 1.179 * @param action the action
3867 jsr166 1.220 * @since 1.8
3868 dl 1.137 */
3869 dl 1.210 public <U> void forEachValue(long parallelismThreshold,
3870     Function<? super V, ? extends U> transformer,
3871     Consumer<? super U> action) {
3872 dl 1.151 if (transformer == null || action == null)
3873     throw new NullPointerException();
3874 dl 1.210 new ForEachTransformedValueTask<K,V,U>
3875     (null, batchFor(parallelismThreshold), 0, 0, table,
3876     transformer, action).invoke();
3877 dl 1.137 }
3878 dl 1.119
3879 dl 1.137 /**
3880     * Returns a non-null result from applying the given search
3881 dl 1.210 * function on each value, or null if none. Upon success,
3882     * further element processing is suppressed and the results of
3883     * any other parallel invocations of the search function are
3884     * ignored.
3885 dl 1.137 *
3886 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3887 jsr166 1.213 * needed for this operation to be executed in parallel
3888 dl 1.137 * @param searchFunction a function returning a non-null
3889     * result on success, else null
3890     * @return a non-null result from applying the given search
3891     * function on each value, or null if none
3892 jsr166 1.220 * @since 1.8
3893 dl 1.137 */
3894 dl 1.210 public <U> U searchValues(long parallelismThreshold,
3895     Function<? super V, ? extends U> searchFunction) {
3896 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3897 dl 1.210 return new SearchValuesTask<K,V,U>
3898     (null, batchFor(parallelismThreshold), 0, 0, table,
3899     searchFunction, new AtomicReference<U>()).invoke();
3900 dl 1.137 }
3901 dl 1.119
3902 dl 1.137 /**
3903     * Returns the result of accumulating all values using the
3904     * given reducer to combine values, or null if none.
3905     *
3906 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3907 jsr166 1.213 * needed for this operation to be executed in parallel
3908 dl 1.137 * @param reducer a commutative associative combining function
3909 jsr166 1.157 * @return the result of accumulating all values
3910 jsr166 1.220 * @since 1.8
3911 dl 1.137 */
3912 dl 1.210 public V reduceValues(long parallelismThreshold,
3913     BiFunction<? super V, ? super V, ? extends V> reducer) {
3914 dl 1.151 if (reducer == null) throw new NullPointerException();
3915 dl 1.210 return new ReduceValuesTask<K,V>
3916     (null, batchFor(parallelismThreshold), 0, 0, table,
3917     null, reducer).invoke();
3918 dl 1.137 }
3919 dl 1.119
3920 dl 1.137 /**
3921     * Returns the result of accumulating the given transformation
3922     * of all values using the given reducer to combine values, or
3923     * null if none.
3924     *
3925 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3926 jsr166 1.213 * needed for this operation to be executed in parallel
3927 dl 1.137 * @param transformer a function returning the transformation
3928 jsr166 1.169 * for an element, or null if there is no transformation (in
3929 jsr166 1.172 * which case it is not combined)
3930 dl 1.137 * @param reducer a commutative associative combining function
3931     * @return the result of accumulating the given transformation
3932     * of all values
3933 jsr166 1.220 * @since 1.8
3934 dl 1.137 */
3935 dl 1.210 public <U> U reduceValues(long parallelismThreshold,
3936     Function<? super V, ? extends U> transformer,
3937     BiFunction<? super U, ? super U, ? extends U> reducer) {
3938 dl 1.151 if (transformer == null || reducer == null)
3939     throw new NullPointerException();
3940 dl 1.210 return new MapReduceValuesTask<K,V,U>
3941     (null, batchFor(parallelismThreshold), 0, 0, table,
3942     null, transformer, reducer).invoke();
3943 dl 1.137 }
3944 dl 1.119
3945 dl 1.137 /**
3946     * Returns the result of accumulating the given transformation
3947     * of all values using the given reducer to combine values,
3948     * and the given basis as an identity value.
3949     *
3950 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3951 jsr166 1.213 * needed for this operation to be executed in parallel
3952 dl 1.137 * @param transformer a function returning the transformation
3953     * for an element
3954     * @param basis the identity (initial default value) for the reduction
3955     * @param reducer a commutative associative combining function
3956     * @return the result of accumulating the given transformation
3957     * of all values
3958 jsr166 1.220 * @since 1.8
3959 dl 1.137 */
3960 dl 1.210 public double reduceValuesToDouble(long parallelismThreshold,
3961     ToDoubleFunction<? super V> transformer,
3962     double basis,
3963     DoubleBinaryOperator reducer) {
3964 dl 1.151 if (transformer == null || reducer == null)
3965     throw new NullPointerException();
3966 dl 1.210 return new MapReduceValuesToDoubleTask<K,V>
3967     (null, batchFor(parallelismThreshold), 0, 0, table,
3968     null, transformer, basis, reducer).invoke();
3969 dl 1.137 }
3970 dl 1.119
3971 dl 1.137 /**
3972     * Returns the result of accumulating the given transformation
3973     * of all values using the given reducer to combine values,
3974     * and the given basis as an identity value.
3975     *
3976 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3977 jsr166 1.213 * needed for this operation to be executed in parallel
3978 dl 1.137 * @param transformer a function returning the transformation
3979     * for an element
3980     * @param basis the identity (initial default value) for the reduction
3981     * @param reducer a commutative associative combining function
3982     * @return the result of accumulating the given transformation
3983     * of all values
3984 jsr166 1.220 * @since 1.8
3985 dl 1.137 */
3986 dl 1.210 public long reduceValuesToLong(long parallelismThreshold,
3987     ToLongFunction<? super V> transformer,
3988     long basis,
3989     LongBinaryOperator reducer) {
3990 dl 1.151 if (transformer == null || reducer == null)
3991     throw new NullPointerException();
3992 dl 1.210 return new MapReduceValuesToLongTask<K,V>
3993     (null, batchFor(parallelismThreshold), 0, 0, table,
3994     null, transformer, basis, reducer).invoke();
3995 dl 1.137 }
3996 dl 1.119
3997 dl 1.137 /**
3998     * Returns the result of accumulating the given transformation
3999     * of all values using the given reducer to combine values,
4000     * and the given basis as an identity value.
4001     *
4002 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4003 jsr166 1.213 * needed for this operation to be executed in parallel
4004 dl 1.137 * @param transformer a function returning the transformation
4005     * for an element
4006     * @param basis the identity (initial default value) for the reduction
4007     * @param reducer a commutative associative combining function
4008     * @return the result of accumulating the given transformation
4009     * of all values
4010 jsr166 1.220 * @since 1.8
4011 dl 1.137 */
4012 dl 1.210 public int reduceValuesToInt(long parallelismThreshold,
4013     ToIntFunction<? super V> transformer,
4014     int basis,
4015     IntBinaryOperator reducer) {
4016 dl 1.151 if (transformer == null || reducer == null)
4017     throw new NullPointerException();
4018 dl 1.210 return new MapReduceValuesToIntTask<K,V>
4019     (null, batchFor(parallelismThreshold), 0, 0, table,
4020     null, transformer, basis, reducer).invoke();
4021 dl 1.137 }
4022 dl 1.119
4023 dl 1.137 /**
4024     * Performs the given action for each entry.
4025     *
4026 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4027 jsr166 1.213 * needed for this operation to be executed in parallel
4028 dl 1.137 * @param action the action
4029 jsr166 1.220 * @since 1.8
4030 dl 1.137 */
4031 dl 1.210 public void forEachEntry(long parallelismThreshold,
4032     Consumer<? super Map.Entry<K,V>> action) {
4033 dl 1.151 if (action == null) throw new NullPointerException();
4034 dl 1.210 new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4035     action).invoke();
4036 dl 1.137 }
4037 dl 1.119
4038 dl 1.137 /**
4039     * Performs the given action for each non-null transformation
4040     * of each entry.
4041     *
4042 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4043 jsr166 1.213 * needed for this operation to be executed in parallel
4044 dl 1.137 * @param transformer a function returning the transformation
4045 jsr166 1.169 * for an element, or null if there is no transformation (in
4046 jsr166 1.172 * which case the action is not applied)
4047 dl 1.137 * @param action the action
4048 jsr166 1.220 * @since 1.8
4049 dl 1.137 */
4050 dl 1.210 public <U> void forEachEntry(long parallelismThreshold,
4051     Function<Map.Entry<K,V>, ? extends U> transformer,
4052     Consumer<? super U> action) {
4053 dl 1.151 if (transformer == null || action == null)
4054     throw new NullPointerException();
4055 dl 1.210 new ForEachTransformedEntryTask<K,V,U>
4056     (null, batchFor(parallelismThreshold), 0, 0, table,
4057     transformer, action).invoke();
4058 dl 1.137 }
4059 dl 1.119
4060 dl 1.137 /**
4061     * Returns a non-null result from applying the given search
4062 dl 1.210 * function on each entry, or null if none. Upon success,
4063     * further element processing is suppressed and the results of
4064     * any other parallel invocations of the search function are
4065     * ignored.
4066 dl 1.137 *
4067 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4068 jsr166 1.213 * needed for this operation to be executed in parallel
4069 dl 1.137 * @param searchFunction a function returning a non-null
4070     * result on success, else null
4071     * @return a non-null result from applying the given search
4072     * function on each entry, or null if none
4073 jsr166 1.220 * @since 1.8
4074 dl 1.137 */
4075 dl 1.210 public <U> U searchEntries(long parallelismThreshold,
4076     Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4077 dl 1.151 if (searchFunction == null) throw new NullPointerException();
4078 dl 1.210 return new SearchEntriesTask<K,V,U>
4079     (null, batchFor(parallelismThreshold), 0, 0, table,
4080     searchFunction, new AtomicReference<U>()).invoke();
4081 dl 1.137 }
4082 dl 1.119
4083 dl 1.137 /**
4084     * Returns the result of accumulating all entries using the
4085     * given reducer to combine values, or null if none.
4086     *
4087 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4088 jsr166 1.213 * needed for this operation to be executed in parallel
4089 dl 1.137 * @param reducer a commutative associative combining function
4090     * @return the result of accumulating all entries
4091 jsr166 1.220 * @since 1.8
4092 dl 1.137 */
4093 dl 1.210 public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4094     BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4095 dl 1.151 if (reducer == null) throw new NullPointerException();
4096 dl 1.210 return new ReduceEntriesTask<K,V>
4097     (null, batchFor(parallelismThreshold), 0, 0, table,
4098     null, reducer).invoke();
4099 dl 1.137 }
4100 dl 1.119
4101 dl 1.137 /**
4102     * Returns the result of accumulating the given transformation
4103     * of all entries using the given reducer to combine values,
4104     * or null if none.
4105     *
4106 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4107 jsr166 1.213 * needed for this operation to be executed in parallel
4108 dl 1.137 * @param transformer a function returning the transformation
4109 jsr166 1.169 * for an element, or null if there is no transformation (in
4110 jsr166 1.172 * which case it is not combined)
4111 dl 1.137 * @param reducer a commutative associative combining function
4112     * @return the result of accumulating the given transformation
4113     * of all entries
4114 jsr166 1.220 * @since 1.8
4115 dl 1.137 */
4116 dl 1.210 public <U> U reduceEntries(long parallelismThreshold,
4117     Function<Map.Entry<K,V>, ? extends U> transformer,
4118     BiFunction<? super U, ? super U, ? extends U> reducer) {
4119 dl 1.151 if (transformer == null || reducer == null)
4120     throw new NullPointerException();
4121 dl 1.210 return new MapReduceEntriesTask<K,V,U>
4122     (null, batchFor(parallelismThreshold), 0, 0, table,
4123     null, transformer, reducer).invoke();
4124 dl 1.137 }
4125 dl 1.119
4126 dl 1.137 /**
4127     * Returns the result of accumulating the given transformation
4128     * of all entries using the given reducer to combine values,
4129     * and the given basis as an identity value.
4130     *
4131 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4132 jsr166 1.213 * needed for this operation to be executed in parallel
4133 dl 1.137 * @param transformer a function returning the transformation
4134     * for an element
4135     * @param basis the identity (initial default value) for the reduction
4136     * @param reducer a commutative associative combining function
4137     * @return the result of accumulating the given transformation
4138     * of all entries
4139 jsr166 1.220 * @since 1.8
4140 dl 1.137 */
4141 dl 1.210 public double reduceEntriesToDouble(long parallelismThreshold,
4142     ToDoubleFunction<Map.Entry<K,V>> transformer,
4143     double basis,
4144     DoubleBinaryOperator reducer) {
4145 dl 1.151 if (transformer == null || reducer == null)
4146     throw new NullPointerException();
4147 dl 1.210 return new MapReduceEntriesToDoubleTask<K,V>
4148     (null, batchFor(parallelismThreshold), 0, 0, table,
4149     null, transformer, basis, reducer).invoke();
4150 dl 1.137 }
4151 dl 1.119
4152 dl 1.137 /**
4153     * Returns the result of accumulating the given transformation
4154     * of all entries using the given reducer to combine values,
4155     * and the given basis as an identity value.
4156     *
4157 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4158 jsr166 1.213 * needed for this operation to be executed in parallel
4159 dl 1.137 * @param transformer a function returning the transformation
4160     * for an element
4161     * @param basis the identity (initial default value) for the reduction
4162     * @param reducer a commutative associative combining function
4163 jsr166 1.157 * @return the result of accumulating the given transformation
4164 dl 1.137 * of all entries
4165 jsr166 1.221 * @since 1.8
4166 dl 1.137 */
4167 dl 1.210 public long reduceEntriesToLong(long parallelismThreshold,
4168     ToLongFunction<Map.Entry<K,V>> transformer,
4169     long basis,
4170     LongBinaryOperator reducer) {
4171 dl 1.151 if (transformer == null || reducer == null)
4172     throw new NullPointerException();
4173 dl 1.210 return new MapReduceEntriesToLongTask<K,V>
4174     (null, batchFor(parallelismThreshold), 0, 0, table,
4175     null, transformer, basis, reducer).invoke();
4176 dl 1.137 }
4177 dl 1.119
4178 dl 1.137 /**
4179     * Returns the result of accumulating the given transformation
4180     * of all entries using the given reducer to combine values,
4181     * and the given basis as an identity value.
4182     *
4183 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4184 jsr166 1.213 * needed for this operation to be executed in parallel
4185 dl 1.137 * @param transformer a function returning the transformation
4186     * for an element
4187     * @param basis the identity (initial default value) for the reduction
4188     * @param reducer a commutative associative combining function
4189     * @return the result of accumulating the given transformation
4190     * of all entries
4191 jsr166 1.221 * @since 1.8
4192 dl 1.137 */
4193 dl 1.210 public int reduceEntriesToInt(long parallelismThreshold,
4194     ToIntFunction<Map.Entry<K,V>> transformer,
4195     int basis,
4196     IntBinaryOperator reducer) {
4197 dl 1.151 if (transformer == null || reducer == null)
4198     throw new NullPointerException();
4199 dl 1.210 return new MapReduceEntriesToIntTask<K,V>
4200     (null, batchFor(parallelismThreshold), 0, 0, table,
4201     null, transformer, basis, reducer).invoke();
4202 dl 1.119 }
4203    
4204 dl 1.209
4205 dl 1.210 /* ----------------Views -------------- */
4206 dl 1.142
4207     /**
4208 dl 1.210 * Base class for views.
4209 dl 1.142 */
4210 dl 1.210 abstract static class CollectionView<K,V,E>
4211     implements Collection<E>, java.io.Serializable {
4212     private static final long serialVersionUID = 7249069246763182397L;
4213     final ConcurrentHashMap<K,V> map;
4214     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4215    
4216     /**
4217     * Returns the map backing this view.
4218     *
4219     * @return the map backing this view
4220     */
4221     public ConcurrentHashMap<K,V> getMap() { return map; }
4222 dl 1.142
4223 dl 1.210 /**
4224     * Removes all of the elements from this view, by removing all
4225     * the mappings from the map backing this view.
4226 jsr166 1.184 */
4227     public final void clear() { map.clear(); }
4228     public final int size() { return map.size(); }
4229     public final boolean isEmpty() { return map.isEmpty(); }
4230 dl 1.151
4231     // implementations below rely on concrete classes supplying these
4232 jsr166 1.184 // abstract methods
4233     /**
4234     * Returns a "weakly consistent" iterator that will never
4235     * throw {@link ConcurrentModificationException}, and
4236     * guarantees to traverse elements as they existed upon
4237     * construction of the iterator, and may (but is not
4238     * guaranteed to) reflect any modifications subsequent to
4239     * construction.
4240     */
4241     public abstract Iterator<E> iterator();
4242 jsr166 1.165 public abstract boolean contains(Object o);
4243     public abstract boolean remove(Object o);
4244 dl 1.151
4245     private static final String oomeMsg = "Required array size too large";
4246 dl 1.142
4247     public final Object[] toArray() {
4248     long sz = map.mappingCount();
4249 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4250 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4251     int n = (int)sz;
4252     Object[] r = new Object[n];
4253     int i = 0;
4254 jsr166 1.184 for (E e : this) {
4255 dl 1.142 if (i == n) {
4256     if (n >= MAX_ARRAY_SIZE)
4257     throw new OutOfMemoryError(oomeMsg);
4258     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4259     n = MAX_ARRAY_SIZE;
4260     else
4261     n += (n >>> 1) + 1;
4262     r = Arrays.copyOf(r, n);
4263     }
4264 jsr166 1.184 r[i++] = e;
4265 dl 1.142 }
4266     return (i == n) ? r : Arrays.copyOf(r, i);
4267     }
4268    
4269 dl 1.222 @SuppressWarnings("unchecked")
4270 jsr166 1.184 public final <T> T[] toArray(T[] a) {
4271 dl 1.142 long sz = map.mappingCount();
4272 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4273 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4274     int m = (int)sz;
4275     T[] r = (a.length >= m) ? a :
4276     (T[])java.lang.reflect.Array
4277     .newInstance(a.getClass().getComponentType(), m);
4278     int n = r.length;
4279     int i = 0;
4280 jsr166 1.184 for (E e : this) {
4281 dl 1.142 if (i == n) {
4282     if (n >= MAX_ARRAY_SIZE)
4283     throw new OutOfMemoryError(oomeMsg);
4284     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4285     n = MAX_ARRAY_SIZE;
4286     else
4287     n += (n >>> 1) + 1;
4288     r = Arrays.copyOf(r, n);
4289     }
4290 jsr166 1.184 r[i++] = (T)e;
4291 dl 1.142 }
4292     if (a == r && i < n) {
4293     r[i] = null; // null-terminate
4294     return r;
4295     }
4296     return (i == n) ? r : Arrays.copyOf(r, i);
4297     }
4298    
4299 jsr166 1.184 /**
4300     * Returns a string representation of this collection.
4301     * The string representation consists of the string representations
4302     * of the collection's elements in the order they are returned by
4303     * its iterator, enclosed in square brackets ({@code "[]"}).
4304     * Adjacent elements are separated by the characters {@code ", "}
4305     * (comma and space). Elements are converted to strings as by
4306     * {@link String#valueOf(Object)}.
4307     *
4308     * @return a string representation of this collection
4309     */
4310 dl 1.142 public final String toString() {
4311     StringBuilder sb = new StringBuilder();
4312     sb.append('[');
4313 jsr166 1.184 Iterator<E> it = iterator();
4314 dl 1.142 if (it.hasNext()) {
4315     for (;;) {
4316     Object e = it.next();
4317     sb.append(e == this ? "(this Collection)" : e);
4318     if (!it.hasNext())
4319     break;
4320     sb.append(',').append(' ');
4321     }
4322     }
4323     return sb.append(']').toString();
4324     }
4325    
4326     public final boolean containsAll(Collection<?> c) {
4327     if (c != this) {
4328 jsr166 1.184 for (Object e : c) {
4329 dl 1.142 if (e == null || !contains(e))
4330     return false;
4331     }
4332     }
4333     return true;
4334     }
4335    
4336     public final boolean removeAll(Collection<?> c) {
4337     boolean modified = false;
4338 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4339 dl 1.142 if (c.contains(it.next())) {
4340     it.remove();
4341     modified = true;
4342     }
4343     }
4344     return modified;
4345     }
4346    
4347     public final boolean retainAll(Collection<?> c) {
4348     boolean modified = false;
4349 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4350 dl 1.142 if (!c.contains(it.next())) {
4351     it.remove();
4352     modified = true;
4353     }
4354     }
4355     return modified;
4356     }
4357    
4358     }
4359    
4360     /**
4361     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4362     * which additions may optionally be enabled by mapping to a
4363 jsr166 1.185 * common value. This class cannot be directly instantiated.
4364     * See {@link #keySet() keySet()},
4365     * {@link #keySet(Object) keySet(V)},
4366     * {@link #newKeySet() newKeySet()},
4367     * {@link #newKeySet(int) newKeySet(int)}.
4368 jsr166 1.221 *
4369     * @since 1.8
4370 dl 1.142 */
4371 dl 1.210 public static class KeySetView<K,V> extends CollectionView<K,V,K>
4372     implements Set<K>, java.io.Serializable {
4373 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4374     private final V value;
4375 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4376 dl 1.142 super(map);
4377     this.value = value;
4378     }
4379    
4380     /**
4381     * Returns the default mapped value for additions,
4382     * or {@code null} if additions are not supported.
4383     *
4384     * @return the default mapped value for additions, or {@code null}
4385 jsr166 1.172 * if not supported
4386 dl 1.142 */
4387     public V getMappedValue() { return value; }
4388    
4389 jsr166 1.184 /**
4390     * {@inheritDoc}
4391     * @throws NullPointerException if the specified key is null
4392     */
4393     public boolean contains(Object o) { return map.containsKey(o); }
4394 dl 1.142
4395 jsr166 1.184 /**
4396     * Removes the key from this map view, by removing the key (and its
4397     * corresponding value) from the backing map. This method does
4398     * nothing if the key is not in the map.
4399     *
4400     * @param o the key to be removed from the backing map
4401     * @return {@code true} if the backing map contained the specified key
4402     * @throws NullPointerException if the specified key is null
4403     */
4404     public boolean remove(Object o) { return map.remove(o) != null; }
4405    
4406     /**
4407     * @return an iterator over the keys of the backing map
4408     */
4409 dl 1.210 public Iterator<K> iterator() {
4410     Node<K,V>[] t;
4411     ConcurrentHashMap<K,V> m = map;
4412     int f = (t = m.table) == null ? 0 : t.length;
4413     return new KeyIterator<K,V>(t, f, 0, f, m);
4414     }
4415 dl 1.142
4416     /**
4417 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4418     * the default mapped value in the backing map, if defined.
4419 dl 1.142 *
4420 jsr166 1.184 * @param e key to be added
4421     * @return {@code true} if this set changed as a result of the call
4422     * @throws NullPointerException if the specified key is null
4423     * @throws UnsupportedOperationException if no default mapped value
4424     * for additions was provided
4425 dl 1.142 */
4426     public boolean add(K e) {
4427     V v;
4428     if ((v = value) == null)
4429     throw new UnsupportedOperationException();
4430 dl 1.222 return map.putVal(e, v, true) == null;
4431 dl 1.142 }
4432 jsr166 1.184
4433     /**
4434     * Adds all of the elements in the specified collection to this set,
4435     * as if by calling {@link #add} on each one.
4436     *
4437     * @param c the elements to be inserted into this set
4438     * @return {@code true} if this set changed as a result of the call
4439     * @throws NullPointerException if the collection or any of its
4440     * elements are {@code null}
4441     * @throws UnsupportedOperationException if no default mapped value
4442     * for additions was provided
4443     */
4444 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4445     boolean added = false;
4446     V v;
4447     if ((v = value) == null)
4448     throw new UnsupportedOperationException();
4449     for (K e : c) {
4450 dl 1.222 if (map.putVal(e, v, true) == null)
4451 dl 1.142 added = true;
4452     }
4453     return added;
4454     }
4455 dl 1.153
4456 dl 1.210 public int hashCode() {
4457     int h = 0;
4458     for (K e : this)
4459     h += e.hashCode();
4460     return h;
4461 dl 1.191 }
4462    
4463 dl 1.210 public boolean equals(Object o) {
4464     Set<?> c;
4465     return ((o instanceof Set) &&
4466     ((c = (Set<?>)o) == this ||
4467     (containsAll(c) && c.containsAll(this))));
4468 dl 1.119 }
4469 jsr166 1.125
4470 dl 1.210 public Spliterator<K> spliterator() {
4471     Node<K,V>[] t;
4472     ConcurrentHashMap<K,V> m = map;
4473     long n = m.sumCount();
4474     int f = (t = m.table) == null ? 0 : t.length;
4475     return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4476 dl 1.119 }
4477    
4478 dl 1.210 public void forEach(Consumer<? super K> action) {
4479     if (action == null) throw new NullPointerException();
4480     Node<K,V>[] t;
4481     if ((t = map.table) != null) {
4482     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4483     for (Node<K,V> p; (p = it.advance()) != null; )
4484 dl 1.222 action.accept(p.key);
4485 dl 1.210 }
4486 dl 1.119 }
4487 dl 1.210 }
4488 dl 1.119
4489 dl 1.210 /**
4490     * A view of a ConcurrentHashMap as a {@link Collection} of
4491     * values, in which additions are disabled. This class cannot be
4492     * directly instantiated. See {@link #values()}.
4493     */
4494     static final class ValuesView<K,V> extends CollectionView<K,V,V>
4495     implements Collection<V>, java.io.Serializable {
4496     private static final long serialVersionUID = 2249069246763182397L;
4497     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4498     public final boolean contains(Object o) {
4499     return map.containsValue(o);
4500 dl 1.119 }
4501    
4502 dl 1.210 public final boolean remove(Object o) {
4503     if (o != null) {
4504     for (Iterator<V> it = iterator(); it.hasNext();) {
4505     if (o.equals(it.next())) {
4506     it.remove();
4507     return true;
4508     }
4509     }
4510     }
4511     return false;
4512 dl 1.119 }
4513    
4514 dl 1.210 public final Iterator<V> iterator() {
4515     ConcurrentHashMap<K,V> m = map;
4516     Node<K,V>[] t;
4517     int f = (t = m.table) == null ? 0 : t.length;
4518     return new ValueIterator<K,V>(t, f, 0, f, m);
4519 dl 1.119 }
4520    
4521 dl 1.210 public final boolean add(V e) {
4522     throw new UnsupportedOperationException();
4523     }
4524     public final boolean addAll(Collection<? extends V> c) {
4525     throw new UnsupportedOperationException();
4526 dl 1.119 }
4527    
4528 dl 1.210 public Spliterator<V> spliterator() {
4529     Node<K,V>[] t;
4530     ConcurrentHashMap<K,V> m = map;
4531     long n = m.sumCount();
4532     int f = (t = m.table) == null ? 0 : t.length;
4533     return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4534 dl 1.119 }
4535    
4536 dl 1.210 public void forEach(Consumer<? super V> action) {
4537     if (action == null) throw new NullPointerException();
4538     Node<K,V>[] t;
4539     if ((t = map.table) != null) {
4540     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4541     for (Node<K,V> p; (p = it.advance()) != null; )
4542     action.accept(p.val);
4543     }
4544 dl 1.119 }
4545 dl 1.210 }
4546    
4547     /**
4548     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4549     * entries. This class cannot be directly instantiated. See
4550     * {@link #entrySet()}.
4551     */
4552     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4553     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4554     private static final long serialVersionUID = 2249069246763182397L;
4555     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4556 dl 1.119
4557 dl 1.210 public boolean contains(Object o) {
4558     Object k, v, r; Map.Entry<?,?> e;
4559     return ((o instanceof Map.Entry) &&
4560     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4561     (r = map.get(k)) != null &&
4562     (v = e.getValue()) != null &&
4563     (v == r || v.equals(r)));
4564 dl 1.119 }
4565    
4566 dl 1.210 public boolean remove(Object o) {
4567     Object k, v; Map.Entry<?,?> e;
4568     return ((o instanceof Map.Entry) &&
4569     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4570     (v = e.getValue()) != null &&
4571     map.remove(k, v));
4572 dl 1.119 }
4573    
4574     /**
4575 dl 1.210 * @return an iterator over the entries of the backing map
4576 dl 1.119 */
4577 dl 1.210 public Iterator<Map.Entry<K,V>> iterator() {
4578     ConcurrentHashMap<K,V> m = map;
4579     Node<K,V>[] t;
4580     int f = (t = m.table) == null ? 0 : t.length;
4581     return new EntryIterator<K,V>(t, f, 0, f, m);
4582 dl 1.119 }
4583    
4584 dl 1.210 public boolean add(Entry<K,V> e) {
4585 dl 1.222 return map.putVal(e.getKey(), e.getValue(), false) == null;
4586 dl 1.119 }
4587    
4588 dl 1.210 public boolean addAll(Collection<? extends Entry<K,V>> c) {
4589     boolean added = false;
4590     for (Entry<K,V> e : c) {
4591     if (add(e))
4592     added = true;
4593     }
4594     return added;
4595 dl 1.119 }
4596    
4597 dl 1.210 public final int hashCode() {
4598     int h = 0;
4599     Node<K,V>[] t;
4600     if ((t = map.table) != null) {
4601     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4602     for (Node<K,V> p; (p = it.advance()) != null; ) {
4603     h += p.hashCode();
4604     }
4605     }
4606     return h;
4607 dl 1.119 }
4608    
4609 dl 1.210 public final boolean equals(Object o) {
4610     Set<?> c;
4611     return ((o instanceof Set) &&
4612     ((c = (Set<?>)o) == this ||
4613     (containsAll(c) && c.containsAll(this))));
4614 dl 1.119 }
4615    
4616 dl 1.210 public Spliterator<Map.Entry<K,V>> spliterator() {
4617     Node<K,V>[] t;
4618     ConcurrentHashMap<K,V> m = map;
4619     long n = m.sumCount();
4620     int f = (t = m.table) == null ? 0 : t.length;
4621     return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4622 dl 1.119 }
4623    
4624 dl 1.210 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4625     if (action == null) throw new NullPointerException();
4626     Node<K,V>[] t;
4627     if ((t = map.table) != null) {
4628     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4629     for (Node<K,V> p; (p = it.advance()) != null; )
4630 dl 1.222 action.accept(new MapEntry<K,V>(p.key, p.val, map));
4631 dl 1.210 }
4632 dl 1.119 }
4633    
4634 dl 1.210 }
4635    
4636     // -------------------------------------------------------
4637 dl 1.119
4638 dl 1.210 /**
4639     * Base class for bulk tasks. Repeats some fields and code from
4640     * class Traverser, because we need to subclass CountedCompleter.
4641     */
4642 jsr166 1.211 abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4643 dl 1.210 Node<K,V>[] tab; // same as Traverser
4644     Node<K,V> next;
4645     int index;
4646     int baseIndex;
4647     int baseLimit;
4648     final int baseSize;
4649     int batch; // split control
4650    
4651     BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4652     super(par);
4653     this.batch = b;
4654     this.index = this.baseIndex = i;
4655     if ((this.tab = t) == null)
4656     this.baseSize = this.baseLimit = 0;
4657     else if (par == null)
4658     this.baseSize = this.baseLimit = t.length;
4659     else {
4660     this.baseLimit = f;
4661     this.baseSize = par.baseSize;
4662     }
4663 dl 1.119 }
4664    
4665     /**
4666 dl 1.210 * Same as Traverser version
4667 dl 1.119 */
4668 dl 1.210 final Node<K,V> advance() {
4669     Node<K,V> e;
4670     if ((e = next) != null)
4671     e = e.next;
4672     for (;;) {
4673 dl 1.222 Node<K,V>[] t; int i, n; K ek; // must use locals in checks
4674 dl 1.210 if (e != null)
4675     return next = e;
4676     if (baseIndex >= baseLimit || (t = tab) == null ||
4677     (n = t.length) <= (i = index) || i < 0)
4678     return next = null;
4679 dl 1.224 if ((e = tabAt(t, index)) != null && e.hash < 0) {
4680 dl 1.222 if (e instanceof ForwardingNode) {
4681     tab = ((ForwardingNode<K,V>)e).nextTable;
4682 dl 1.210 e = null;
4683     continue;
4684     }
4685 dl 1.222 else if (e instanceof TreeBin)
4686     e = ((TreeBin<K,V>)e).first;
4687     else
4688     e = null;
4689 dl 1.210 }
4690     if ((index += baseSize) >= n)
4691 dl 1.222 index = ++baseIndex; // visit upper slots if present
4692 dl 1.210 }
4693 dl 1.119 }
4694     }
4695    
4696     /*
4697     * Task classes. Coded in a regular but ugly format/style to
4698     * simplify checks that each variant differs in the right way from
4699 dl 1.149 * others. The null screenings exist because compilers cannot tell
4700     * that we've already null-checked task arguments, so we force
4701     * simplest hoisted bypass to help avoid convoluted traps.
4702 dl 1.119 */
4703 dl 1.222 @SuppressWarnings("serial")
4704 dl 1.210 static final class ForEachKeyTask<K,V>
4705     extends BulkTask<K,V,Void> {
4706 dl 1.171 final Consumer<? super K> action;
4707 dl 1.119 ForEachKeyTask
4708 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4709 dl 1.171 Consumer<? super K> action) {
4710 dl 1.210 super(p, b, i, f, t);
4711 dl 1.119 this.action = action;
4712     }
4713 jsr166 1.168 public final void compute() {
4714 dl 1.171 final Consumer<? super K> action;
4715 dl 1.149 if ((action = this.action) != null) {
4716 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4717     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4718     addToPendingCount(1);
4719     new ForEachKeyTask<K,V>
4720     (this, batch >>>= 1, baseLimit = h, f, tab,
4721     action).fork();
4722     }
4723     for (Node<K,V> p; (p = advance()) != null;)
4724 dl 1.222 action.accept(p.key);
4725 dl 1.149 propagateCompletion();
4726     }
4727 dl 1.119 }
4728     }
4729    
4730 dl 1.222 @SuppressWarnings("serial")
4731 dl 1.210 static final class ForEachValueTask<K,V>
4732     extends BulkTask<K,V,Void> {
4733 dl 1.171 final Consumer<? super V> action;
4734 dl 1.119 ForEachValueTask
4735 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4736 dl 1.171 Consumer<? super V> action) {
4737 dl 1.210 super(p, b, i, f, t);
4738 dl 1.119 this.action = action;
4739     }
4740 jsr166 1.168 public final void compute() {
4741 dl 1.171 final Consumer<? super V> action;
4742 dl 1.149 if ((action = this.action) != null) {
4743 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4744     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4745     addToPendingCount(1);
4746     new ForEachValueTask<K,V>
4747     (this, batch >>>= 1, baseLimit = h, f, tab,
4748     action).fork();
4749     }
4750     for (Node<K,V> p; (p = advance()) != null;)
4751     action.accept(p.val);
4752 dl 1.149 propagateCompletion();
4753     }
4754 dl 1.119 }
4755     }
4756    
4757 dl 1.222 @SuppressWarnings("serial")
4758 dl 1.210 static final class ForEachEntryTask<K,V>
4759     extends BulkTask<K,V,Void> {
4760 dl 1.171 final Consumer<? super Entry<K,V>> action;
4761 dl 1.119 ForEachEntryTask
4762 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4763 dl 1.171 Consumer<? super Entry<K,V>> action) {
4764 dl 1.210 super(p, b, i, f, t);
4765 dl 1.119 this.action = action;
4766     }
4767 jsr166 1.168 public final void compute() {
4768 dl 1.171 final Consumer<? super Entry<K,V>> action;
4769 dl 1.149 if ((action = this.action) != null) {
4770 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4771     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4772     addToPendingCount(1);
4773     new ForEachEntryTask<K,V>
4774     (this, batch >>>= 1, baseLimit = h, f, tab,
4775     action).fork();
4776     }
4777     for (Node<K,V> p; (p = advance()) != null; )
4778     action.accept(p);
4779 dl 1.149 propagateCompletion();
4780     }
4781 dl 1.119 }
4782     }
4783    
4784 dl 1.222 @SuppressWarnings("serial")
4785 dl 1.210 static final class ForEachMappingTask<K,V>
4786     extends BulkTask<K,V,Void> {
4787 dl 1.171 final BiConsumer<? super K, ? super V> action;
4788 dl 1.119 ForEachMappingTask
4789 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4790 dl 1.171 BiConsumer<? super K,? super V> action) {
4791 dl 1.210 super(p, b, i, f, t);
4792 dl 1.119 this.action = action;
4793     }
4794 jsr166 1.168 public final void compute() {
4795 dl 1.171 final BiConsumer<? super K, ? super V> action;
4796 dl 1.149 if ((action = this.action) != null) {
4797 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4798     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4799     addToPendingCount(1);
4800     new ForEachMappingTask<K,V>
4801     (this, batch >>>= 1, baseLimit = h, f, tab,
4802     action).fork();
4803     }
4804     for (Node<K,V> p; (p = advance()) != null; )
4805 dl 1.222 action.accept(p.key, p.val);
4806 dl 1.149 propagateCompletion();
4807     }
4808 dl 1.119 }
4809     }
4810    
4811 dl 1.222 @SuppressWarnings("serial")
4812 dl 1.210 static final class ForEachTransformedKeyTask<K,V,U>
4813     extends BulkTask<K,V,Void> {
4814 dl 1.153 final Function<? super K, ? extends U> transformer;
4815 dl 1.171 final Consumer<? super U> action;
4816 dl 1.119 ForEachTransformedKeyTask
4817 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4818 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4819 dl 1.210 super(p, b, i, f, t);
4820 dl 1.146 this.transformer = transformer; this.action = action;
4821     }
4822 jsr166 1.168 public final void compute() {
4823 dl 1.153 final Function<? super K, ? extends U> transformer;
4824 dl 1.171 final Consumer<? super U> action;
4825 dl 1.149 if ((transformer = this.transformer) != null &&
4826     (action = this.action) != null) {
4827 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4828     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4829     addToPendingCount(1);
4830 dl 1.149 new ForEachTransformedKeyTask<K,V,U>
4831 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4832     transformer, action).fork();
4833     }
4834     for (Node<K,V> p; (p = advance()) != null; ) {
4835     U u;
4836 dl 1.222 if ((u = transformer.apply(p.key)) != null)
4837 dl 1.153 action.accept(u);
4838 dl 1.149 }
4839     propagateCompletion();
4840 dl 1.119 }
4841     }
4842     }
4843    
4844 dl 1.222 @SuppressWarnings("serial")
4845 dl 1.210 static final class ForEachTransformedValueTask<K,V,U>
4846     extends BulkTask<K,V,Void> {
4847 dl 1.153 final Function<? super V, ? extends U> transformer;
4848 dl 1.171 final Consumer<? super U> action;
4849 dl 1.119 ForEachTransformedValueTask
4850 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4851 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4852 dl 1.210 super(p, b, i, f, t);
4853 dl 1.146 this.transformer = transformer; this.action = action;
4854     }
4855 jsr166 1.168 public final void compute() {
4856 dl 1.153 final Function<? super V, ? extends U> transformer;
4857 dl 1.171 final Consumer<? super U> action;
4858 dl 1.149 if ((transformer = this.transformer) != null &&
4859     (action = this.action) != null) {
4860 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4861     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4862     addToPendingCount(1);
4863 dl 1.149 new ForEachTransformedValueTask<K,V,U>
4864 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4865     transformer, action).fork();
4866     }
4867     for (Node<K,V> p; (p = advance()) != null; ) {
4868     U u;
4869     if ((u = transformer.apply(p.val)) != null)
4870 dl 1.153 action.accept(u);
4871 dl 1.149 }
4872     propagateCompletion();
4873 dl 1.119 }
4874     }
4875 tim 1.1 }
4876    
4877 dl 1.222 @SuppressWarnings("serial")
4878 dl 1.210 static final class ForEachTransformedEntryTask<K,V,U>
4879     extends BulkTask<K,V,Void> {
4880 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
4881 dl 1.171 final Consumer<? super U> action;
4882 dl 1.119 ForEachTransformedEntryTask
4883 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4884 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4885 dl 1.210 super(p, b, i, f, t);
4886 dl 1.146 this.transformer = transformer; this.action = action;
4887     }
4888 jsr166 1.168 public final void compute() {
4889 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
4890 dl 1.171 final Consumer<? super U> action;
4891 dl 1.149 if ((transformer = this.transformer) != null &&
4892     (action = this.action) != null) {
4893 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4894     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4895     addToPendingCount(1);
4896 dl 1.149 new ForEachTransformedEntryTask<K,V,U>
4897 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4898     transformer, action).fork();
4899     }
4900     for (Node<K,V> p; (p = advance()) != null; ) {
4901     U u;
4902     if ((u = transformer.apply(p)) != null)
4903 dl 1.153 action.accept(u);
4904 dl 1.149 }
4905     propagateCompletion();
4906 dl 1.119 }
4907     }
4908 tim 1.1 }
4909    
4910 dl 1.222 @SuppressWarnings("serial")
4911 dl 1.210 static final class ForEachTransformedMappingTask<K,V,U>
4912     extends BulkTask<K,V,Void> {
4913 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
4914 dl 1.171 final Consumer<? super U> action;
4915 dl 1.119 ForEachTransformedMappingTask
4916 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4917 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
4918 dl 1.171 Consumer<? super U> action) {
4919 dl 1.210 super(p, b, i, f, t);
4920 dl 1.146 this.transformer = transformer; this.action = action;
4921 dl 1.119 }
4922 jsr166 1.168 public final void compute() {
4923 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
4924 dl 1.171 final Consumer<? super U> action;
4925 dl 1.149 if ((transformer = this.transformer) != null &&
4926     (action = this.action) != null) {
4927 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4928     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4929     addToPendingCount(1);
4930 dl 1.149 new ForEachTransformedMappingTask<K,V,U>
4931 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4932     transformer, action).fork();
4933     }
4934     for (Node<K,V> p; (p = advance()) != null; ) {
4935     U u;
4936 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
4937 dl 1.153 action.accept(u);
4938 dl 1.149 }
4939     propagateCompletion();
4940 dl 1.119 }
4941     }
4942 tim 1.1 }
4943    
4944 dl 1.222 @SuppressWarnings("serial")
4945 dl 1.210 static final class SearchKeysTask<K,V,U>
4946     extends BulkTask<K,V,U> {
4947 dl 1.153 final Function<? super K, ? extends U> searchFunction;
4948 dl 1.119 final AtomicReference<U> result;
4949     SearchKeysTask
4950 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4951 dl 1.153 Function<? super K, ? extends U> searchFunction,
4952 dl 1.119 AtomicReference<U> result) {
4953 dl 1.210 super(p, b, i, f, t);
4954 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4955     }
4956 dl 1.146 public final U getRawResult() { return result.get(); }
4957 jsr166 1.168 public final void compute() {
4958 dl 1.153 final Function<? super K, ? extends U> searchFunction;
4959 dl 1.146 final AtomicReference<U> result;
4960 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
4961     (result = this.result) != null) {
4962 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4963     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4964 dl 1.149 if (result.get() != null)
4965     return;
4966 dl 1.210 addToPendingCount(1);
4967 dl 1.149 new SearchKeysTask<K,V,U>
4968 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4969     searchFunction, result).fork();
4970 dl 1.128 }
4971 dl 1.149 while (result.get() == null) {
4972 dl 1.210 U u;
4973     Node<K,V> p;
4974     if ((p = advance()) == null) {
4975 dl 1.149 propagateCompletion();
4976     break;
4977     }
4978 dl 1.222 if ((u = searchFunction.apply(p.key)) != null) {
4979 dl 1.149 if (result.compareAndSet(null, u))
4980     quietlyCompleteRoot();
4981     break;
4982     }
4983 dl 1.119 }
4984     }
4985     }
4986 tim 1.1 }
4987    
4988 dl 1.222 @SuppressWarnings("serial")
4989 dl 1.210 static final class SearchValuesTask<K,V,U>
4990     extends BulkTask<K,V,U> {
4991 dl 1.153 final Function<? super V, ? extends U> searchFunction;
4992 dl 1.119 final AtomicReference<U> result;
4993     SearchValuesTask
4994 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4995 dl 1.153 Function<? super V, ? extends U> searchFunction,
4996 dl 1.119 AtomicReference<U> result) {
4997 dl 1.210 super(p, b, i, f, t);
4998 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4999     }
5000 dl 1.146 public final U getRawResult() { return result.get(); }
5001 jsr166 1.168 public final void compute() {
5002 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5003 dl 1.146 final AtomicReference<U> result;
5004 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5005     (result = this.result) != null) {
5006 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5007     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5008 dl 1.149 if (result.get() != null)
5009     return;
5010 dl 1.210 addToPendingCount(1);
5011 dl 1.149 new SearchValuesTask<K,V,U>
5012 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5013     searchFunction, result).fork();
5014 dl 1.128 }
5015 dl 1.149 while (result.get() == null) {
5016 dl 1.210 U u;
5017     Node<K,V> p;
5018     if ((p = advance()) == null) {
5019 dl 1.149 propagateCompletion();
5020     break;
5021     }
5022 dl 1.210 if ((u = searchFunction.apply(p.val)) != null) {
5023 dl 1.149 if (result.compareAndSet(null, u))
5024     quietlyCompleteRoot();
5025     break;
5026     }
5027 dl 1.119 }
5028     }
5029     }
5030     }
5031 tim 1.11
5032 dl 1.222 @SuppressWarnings("serial")
5033 dl 1.210 static final class SearchEntriesTask<K,V,U>
5034     extends BulkTask<K,V,U> {
5035 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5036 dl 1.119 final AtomicReference<U> result;
5037     SearchEntriesTask
5038 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5039 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
5040 dl 1.119 AtomicReference<U> result) {
5041 dl 1.210 super(p, b, i, f, t);
5042 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5043     }
5044 dl 1.146 public final U getRawResult() { return result.get(); }
5045 jsr166 1.168 public final void compute() {
5046 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5047 dl 1.146 final AtomicReference<U> result;
5048 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5049     (result = this.result) != null) {
5050 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5051     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5052 dl 1.149 if (result.get() != null)
5053     return;
5054 dl 1.210 addToPendingCount(1);
5055 dl 1.149 new SearchEntriesTask<K,V,U>
5056 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5057     searchFunction, result).fork();
5058 dl 1.128 }
5059 dl 1.149 while (result.get() == null) {
5060 dl 1.210 U u;
5061     Node<K,V> p;
5062     if ((p = advance()) == null) {
5063 dl 1.149 propagateCompletion();
5064     break;
5065     }
5066 dl 1.210 if ((u = searchFunction.apply(p)) != null) {
5067 dl 1.149 if (result.compareAndSet(null, u))
5068     quietlyCompleteRoot();
5069     return;
5070     }
5071 dl 1.119 }
5072     }
5073     }
5074     }
5075 tim 1.1
5076 dl 1.222 @SuppressWarnings("serial")
5077 dl 1.210 static final class SearchMappingsTask<K,V,U>
5078     extends BulkTask<K,V,U> {
5079 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5080 dl 1.119 final AtomicReference<U> result;
5081     SearchMappingsTask
5082 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5083 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
5084 dl 1.119 AtomicReference<U> result) {
5085 dl 1.210 super(p, b, i, f, t);
5086 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5087     }
5088 dl 1.146 public final U getRawResult() { return result.get(); }
5089 jsr166 1.168 public final void compute() {
5090 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5091 dl 1.146 final AtomicReference<U> result;
5092 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5093     (result = this.result) != null) {
5094 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5095     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5096 dl 1.149 if (result.get() != null)
5097     return;
5098 dl 1.210 addToPendingCount(1);
5099 dl 1.149 new SearchMappingsTask<K,V,U>
5100 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5101     searchFunction, result).fork();
5102 dl 1.128 }
5103 dl 1.149 while (result.get() == null) {
5104 dl 1.210 U u;
5105     Node<K,V> p;
5106     if ((p = advance()) == null) {
5107 dl 1.149 propagateCompletion();
5108     break;
5109     }
5110 dl 1.222 if ((u = searchFunction.apply(p.key, p.val)) != null) {
5111 dl 1.149 if (result.compareAndSet(null, u))
5112     quietlyCompleteRoot();
5113     break;
5114     }
5115 dl 1.119 }
5116     }
5117 tim 1.1 }
5118 dl 1.119 }
5119 tim 1.1
5120 dl 1.222 @SuppressWarnings("serial")
5121 dl 1.210 static final class ReduceKeysTask<K,V>
5122     extends BulkTask<K,V,K> {
5123 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5124 dl 1.119 K result;
5125 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
5126 dl 1.119 ReduceKeysTask
5127 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5128 dl 1.128 ReduceKeysTask<K,V> nextRight,
5129 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5130 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5131 dl 1.119 this.reducer = reducer;
5132     }
5133 dl 1.146 public final K getRawResult() { return result; }
5134 dl 1.210 public final void compute() {
5135 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5136 dl 1.149 if ((reducer = this.reducer) != null) {
5137 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5138     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5139     addToPendingCount(1);
5140 dl 1.149 (rights = new ReduceKeysTask<K,V>
5141 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5142     rights, reducer)).fork();
5143     }
5144     K r = null;
5145     for (Node<K,V> p; (p = advance()) != null; ) {
5146 dl 1.222 K u = p.key;
5147 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5148 dl 1.149 }
5149     result = r;
5150     CountedCompleter<?> c;
5151     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5152 dl 1.222 @SuppressWarnings("unchecked") ReduceKeysTask<K,V>
5153 dl 1.149 t = (ReduceKeysTask<K,V>)c,
5154     s = t.rights;
5155     while (s != null) {
5156     K tr, sr;
5157     if ((sr = s.result) != null)
5158     t.result = (((tr = t.result) == null) ? sr :
5159     reducer.apply(tr, sr));
5160     s = t.rights = s.nextRight;
5161     }
5162 dl 1.99 }
5163 dl 1.138 }
5164 tim 1.1 }
5165 dl 1.119 }
5166 tim 1.1
5167 dl 1.222 @SuppressWarnings("serial")
5168 dl 1.210 static final class ReduceValuesTask<K,V>
5169     extends BulkTask<K,V,V> {
5170 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5171 dl 1.119 V result;
5172 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
5173 dl 1.119 ReduceValuesTask
5174 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5175 dl 1.128 ReduceValuesTask<K,V> nextRight,
5176 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5177 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5178 dl 1.119 this.reducer = reducer;
5179     }
5180 dl 1.146 public final V getRawResult() { return result; }
5181 dl 1.210 public final void compute() {
5182 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5183 dl 1.149 if ((reducer = this.reducer) != null) {
5184 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5185     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5186     addToPendingCount(1);
5187 dl 1.149 (rights = new ReduceValuesTask<K,V>
5188 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5189     rights, reducer)).fork();
5190     }
5191     V r = null;
5192     for (Node<K,V> p; (p = advance()) != null; ) {
5193     V v = p.val;
5194 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
5195 dl 1.210 }
5196 dl 1.149 result = r;
5197     CountedCompleter<?> c;
5198     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5199 dl 1.222 @SuppressWarnings("unchecked") ReduceValuesTask<K,V>
5200 dl 1.149 t = (ReduceValuesTask<K,V>)c,
5201     s = t.rights;
5202     while (s != null) {
5203     V tr, sr;
5204     if ((sr = s.result) != null)
5205     t.result = (((tr = t.result) == null) ? sr :
5206     reducer.apply(tr, sr));
5207     s = t.rights = s.nextRight;
5208     }
5209 dl 1.119 }
5210     }
5211 tim 1.1 }
5212 dl 1.119 }
5213 tim 1.1
5214 dl 1.222 @SuppressWarnings("serial")
5215 dl 1.210 static final class ReduceEntriesTask<K,V>
5216     extends BulkTask<K,V,Map.Entry<K,V>> {
5217 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5218 dl 1.119 Map.Entry<K,V> result;
5219 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
5220 dl 1.119 ReduceEntriesTask
5221 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5222 dl 1.130 ReduceEntriesTask<K,V> nextRight,
5223 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5224 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5225 dl 1.119 this.reducer = reducer;
5226     }
5227 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
5228 dl 1.210 public final void compute() {
5229 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5230 dl 1.149 if ((reducer = this.reducer) != null) {
5231 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5232     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5233     addToPendingCount(1);
5234 dl 1.149 (rights = new ReduceEntriesTask<K,V>
5235 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5236     rights, reducer)).fork();
5237     }
5238 dl 1.149 Map.Entry<K,V> r = null;
5239 dl 1.210 for (Node<K,V> p; (p = advance()) != null; )
5240     r = (r == null) ? p : reducer.apply(r, p);
5241 dl 1.149 result = r;
5242     CountedCompleter<?> c;
5243     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5244 dl 1.222 @SuppressWarnings("unchecked") ReduceEntriesTask<K,V>
5245 dl 1.149 t = (ReduceEntriesTask<K,V>)c,
5246     s = t.rights;
5247     while (s != null) {
5248     Map.Entry<K,V> tr, sr;
5249     if ((sr = s.result) != null)
5250     t.result = (((tr = t.result) == null) ? sr :
5251     reducer.apply(tr, sr));
5252     s = t.rights = s.nextRight;
5253     }
5254 dl 1.119 }
5255 dl 1.138 }
5256 dl 1.119 }
5257     }
5258 dl 1.99
5259 dl 1.222 @SuppressWarnings("serial")
5260 dl 1.210 static final class MapReduceKeysTask<K,V,U>
5261     extends BulkTask<K,V,U> {
5262 dl 1.153 final Function<? super K, ? extends U> transformer;
5263     final BiFunction<? super U, ? super U, ? extends U> reducer;
5264 dl 1.119 U result;
5265 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
5266 dl 1.119 MapReduceKeysTask
5267 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5268 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
5269 dl 1.153 Function<? super K, ? extends U> transformer,
5270     BiFunction<? super U, ? super U, ? extends U> reducer) {
5271 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5272 dl 1.119 this.transformer = transformer;
5273     this.reducer = reducer;
5274     }
5275 dl 1.146 public final U getRawResult() { return result; }
5276 dl 1.210 public final void compute() {
5277 dl 1.153 final Function<? super K, ? extends U> transformer;
5278     final BiFunction<? super U, ? super U, ? extends U> reducer;
5279 dl 1.149 if ((transformer = this.transformer) != null &&
5280     (reducer = this.reducer) != null) {
5281 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5282     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5283     addToPendingCount(1);
5284 dl 1.149 (rights = new MapReduceKeysTask<K,V,U>
5285 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5286     rights, transformer, reducer)).fork();
5287     }
5288     U r = null;
5289     for (Node<K,V> p; (p = advance()) != null; ) {
5290     U u;
5291 dl 1.222 if ((u = transformer.apply(p.key)) != null)
5292 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5293     }
5294     result = r;
5295     CountedCompleter<?> c;
5296     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5297 dl 1.222 @SuppressWarnings("unchecked") MapReduceKeysTask<K,V,U>
5298 dl 1.149 t = (MapReduceKeysTask<K,V,U>)c,
5299     s = t.rights;
5300     while (s != null) {
5301     U tr, sr;
5302     if ((sr = s.result) != null)
5303     t.result = (((tr = t.result) == null) ? sr :
5304     reducer.apply(tr, sr));
5305     s = t.rights = s.nextRight;
5306     }
5307 dl 1.119 }
5308 dl 1.138 }
5309 tim 1.1 }
5310 dl 1.4 }
5311    
5312 dl 1.222 @SuppressWarnings("serial")
5313 dl 1.210 static final class MapReduceValuesTask<K,V,U>
5314     extends BulkTask<K,V,U> {
5315 dl 1.153 final Function<? super V, ? extends U> transformer;
5316     final BiFunction<? super U, ? super U, ? extends U> reducer;
5317 dl 1.119 U result;
5318 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
5319 dl 1.119 MapReduceValuesTask
5320 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5321 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
5322 dl 1.153 Function<? super V, ? extends U> transformer,
5323     BiFunction<? super U, ? super U, ? extends U> reducer) {
5324 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5325 dl 1.119 this.transformer = transformer;
5326     this.reducer = reducer;
5327     }
5328 dl 1.146 public final U getRawResult() { return result; }
5329 dl 1.210 public final void compute() {
5330 dl 1.153 final Function<? super V, ? extends U> transformer;
5331     final BiFunction<? super U, ? super U, ? extends U> reducer;
5332 dl 1.149 if ((transformer = this.transformer) != null &&
5333     (reducer = this.reducer) != null) {
5334 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5335     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5336     addToPendingCount(1);
5337 dl 1.149 (rights = new MapReduceValuesTask<K,V,U>
5338 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5339     rights, transformer, reducer)).fork();
5340     }
5341     U r = null;
5342     for (Node<K,V> p; (p = advance()) != null; ) {
5343     U u;
5344     if ((u = transformer.apply(p.val)) != null)
5345 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5346     }
5347     result = r;
5348     CountedCompleter<?> c;
5349     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5350 dl 1.222 @SuppressWarnings("unchecked") MapReduceValuesTask<K,V,U>
5351 dl 1.149 t = (MapReduceValuesTask<K,V,U>)c,
5352     s = t.rights;
5353     while (s != null) {
5354     U tr, sr;
5355     if ((sr = s.result) != null)
5356     t.result = (((tr = t.result) == null) ? sr :
5357     reducer.apply(tr, sr));
5358     s = t.rights = s.nextRight;
5359     }
5360 dl 1.119 }
5361     }
5362     }
5363 dl 1.4 }
5364    
5365 dl 1.222 @SuppressWarnings("serial")
5366 dl 1.210 static final class MapReduceEntriesTask<K,V,U>
5367     extends BulkTask<K,V,U> {
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.119 U result;
5371 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
5372 dl 1.119 MapReduceEntriesTask
5373 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5374 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
5375 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5376     BiFunction<? super U, ? super U, ? extends U> reducer) {
5377 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5378 dl 1.119 this.transformer = transformer;
5379     this.reducer = reducer;
5380     }
5381 dl 1.146 public final U getRawResult() { return result; }
5382 dl 1.210 public final void compute() {
5383 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5384     final BiFunction<? super U, ? super U, ? extends U> reducer;
5385 dl 1.149 if ((transformer = this.transformer) != null &&
5386     (reducer = this.reducer) != null) {
5387 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5388     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5389     addToPendingCount(1);
5390 dl 1.149 (rights = new MapReduceEntriesTask<K,V,U>
5391 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5392     rights, transformer, reducer)).fork();
5393     }
5394     U r = null;
5395     for (Node<K,V> p; (p = advance()) != null; ) {
5396     U u;
5397     if ((u = transformer.apply(p)) != null)
5398 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5399     }
5400     result = r;
5401     CountedCompleter<?> c;
5402     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5403 dl 1.222 @SuppressWarnings("unchecked") MapReduceEntriesTask<K,V,U>
5404 dl 1.149 t = (MapReduceEntriesTask<K,V,U>)c,
5405     s = t.rights;
5406     while (s != null) {
5407     U tr, sr;
5408     if ((sr = s.result) != null)
5409     t.result = (((tr = t.result) == null) ? sr :
5410     reducer.apply(tr, sr));
5411     s = t.rights = s.nextRight;
5412     }
5413 dl 1.119 }
5414 dl 1.138 }
5415 dl 1.119 }
5416 dl 1.4 }
5417 tim 1.1
5418 dl 1.222 @SuppressWarnings("serial")
5419 dl 1.210 static final class MapReduceMappingsTask<K,V,U>
5420     extends BulkTask<K,V,U> {
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.119 U result;
5424 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
5425 dl 1.119 MapReduceMappingsTask
5426 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5427 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
5428 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5429     BiFunction<? super U, ? super U, ? extends U> reducer) {
5430 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5431 dl 1.119 this.transformer = transformer;
5432     this.reducer = reducer;
5433     }
5434 dl 1.146 public final U getRawResult() { return result; }
5435 dl 1.210 public final void compute() {
5436 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5437     final BiFunction<? super U, ? super U, ? extends U> reducer;
5438 dl 1.149 if ((transformer = this.transformer) != null &&
5439     (reducer = this.reducer) != null) {
5440 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5441     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5442     addToPendingCount(1);
5443 dl 1.149 (rights = new MapReduceMappingsTask<K,V,U>
5444 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5445     rights, transformer, reducer)).fork();
5446     }
5447     U r = null;
5448     for (Node<K,V> p; (p = advance()) != null; ) {
5449     U u;
5450 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
5451 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5452     }
5453     result = r;
5454     CountedCompleter<?> c;
5455     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5456 dl 1.222 @SuppressWarnings("unchecked") MapReduceMappingsTask<K,V,U>
5457 dl 1.149 t = (MapReduceMappingsTask<K,V,U>)c,
5458     s = t.rights;
5459     while (s != null) {
5460     U tr, sr;
5461     if ((sr = s.result) != null)
5462     t.result = (((tr = t.result) == null) ? sr :
5463     reducer.apply(tr, sr));
5464     s = t.rights = s.nextRight;
5465     }
5466 dl 1.119 }
5467     }
5468     }
5469     }
5470 jsr166 1.114
5471 dl 1.222 @SuppressWarnings("serial")
5472 dl 1.210 static final class MapReduceKeysToDoubleTask<K,V>
5473     extends BulkTask<K,V,Double> {
5474 dl 1.171 final ToDoubleFunction<? super K> transformer;
5475 dl 1.153 final DoubleBinaryOperator reducer;
5476 dl 1.119 final double basis;
5477     double result;
5478 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5479 dl 1.119 MapReduceKeysToDoubleTask
5480 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5481 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
5482 dl 1.171 ToDoubleFunction<? super K> transformer,
5483 dl 1.119 double basis,
5484 dl 1.153 DoubleBinaryOperator reducer) {
5485 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5486 dl 1.119 this.transformer = transformer;
5487     this.basis = basis; this.reducer = reducer;
5488     }
5489 dl 1.146 public final Double getRawResult() { return result; }
5490 dl 1.210 public final void compute() {
5491 dl 1.171 final ToDoubleFunction<? super K> transformer;
5492 dl 1.153 final DoubleBinaryOperator reducer;
5493 dl 1.149 if ((transformer = this.transformer) != null &&
5494     (reducer = this.reducer) != null) {
5495     double r = this.basis;
5496 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5497     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5498     addToPendingCount(1);
5499 dl 1.149 (rights = new MapReduceKeysToDoubleTask<K,V>
5500 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5501     rights, transformer, r, reducer)).fork();
5502     }
5503     for (Node<K,V> p; (p = advance()) != null; )
5504 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5505 dl 1.149 result = r;
5506     CountedCompleter<?> c;
5507     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5508 dl 1.222 @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V>
5509 dl 1.149 t = (MapReduceKeysToDoubleTask<K,V>)c,
5510     s = t.rights;
5511     while (s != null) {
5512 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5513 dl 1.149 s = t.rights = s.nextRight;
5514     }
5515 dl 1.119 }
5516 dl 1.138 }
5517 dl 1.79 }
5518 dl 1.119 }
5519 dl 1.79
5520 dl 1.222 @SuppressWarnings("serial")
5521 dl 1.210 static final class MapReduceValuesToDoubleTask<K,V>
5522     extends BulkTask<K,V,Double> {
5523 dl 1.171 final ToDoubleFunction<? super V> transformer;
5524 dl 1.153 final DoubleBinaryOperator reducer;
5525 dl 1.119 final double basis;
5526     double result;
5527 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5528 dl 1.119 MapReduceValuesToDoubleTask
5529 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5530 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
5531 dl 1.171 ToDoubleFunction<? super V> transformer,
5532 dl 1.119 double basis,
5533 dl 1.153 DoubleBinaryOperator reducer) {
5534 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5535 dl 1.119 this.transformer = transformer;
5536     this.basis = basis; this.reducer = reducer;
5537     }
5538 dl 1.146 public final Double getRawResult() { return result; }
5539 dl 1.210 public final void compute() {
5540 dl 1.171 final ToDoubleFunction<? super V> transformer;
5541 dl 1.153 final DoubleBinaryOperator reducer;
5542 dl 1.149 if ((transformer = this.transformer) != null &&
5543     (reducer = this.reducer) != null) {
5544     double r = this.basis;
5545 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5546     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5547     addToPendingCount(1);
5548 dl 1.149 (rights = new MapReduceValuesToDoubleTask<K,V>
5549 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5550     rights, transformer, r, reducer)).fork();
5551     }
5552     for (Node<K,V> p; (p = advance()) != null; )
5553     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5554 dl 1.149 result = r;
5555     CountedCompleter<?> c;
5556     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5557 dl 1.222 @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
5558 dl 1.149 t = (MapReduceValuesToDoubleTask<K,V>)c,
5559     s = t.rights;
5560     while (s != null) {
5561 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5562 dl 1.149 s = t.rights = s.nextRight;
5563     }
5564 dl 1.119 }
5565     }
5566 dl 1.30 }
5567 dl 1.79 }
5568 dl 1.30
5569 dl 1.222 @SuppressWarnings("serial")
5570 dl 1.210 static final class MapReduceEntriesToDoubleTask<K,V>
5571     extends BulkTask<K,V,Double> {
5572 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5573 dl 1.153 final DoubleBinaryOperator reducer;
5574 dl 1.119 final double basis;
5575     double result;
5576 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5577 dl 1.119 MapReduceEntriesToDoubleTask
5578 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5579 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
5580 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5581 dl 1.119 double basis,
5582 dl 1.153 DoubleBinaryOperator reducer) {
5583 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5584 dl 1.119 this.transformer = transformer;
5585     this.basis = basis; this.reducer = reducer;
5586     }
5587 dl 1.146 public final Double getRawResult() { return result; }
5588 dl 1.210 public final void compute() {
5589 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5590 dl 1.153 final DoubleBinaryOperator reducer;
5591 dl 1.149 if ((transformer = this.transformer) != null &&
5592     (reducer = this.reducer) != null) {
5593     double r = this.basis;
5594 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5595     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5596     addToPendingCount(1);
5597 dl 1.149 (rights = new MapReduceEntriesToDoubleTask<K,V>
5598 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5599     rights, transformer, r, reducer)).fork();
5600     }
5601     for (Node<K,V> p; (p = advance()) != null; )
5602     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5603 dl 1.149 result = r;
5604     CountedCompleter<?> c;
5605     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5606 dl 1.222 @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V>
5607 dl 1.149 t = (MapReduceEntriesToDoubleTask<K,V>)c,
5608     s = t.rights;
5609     while (s != null) {
5610 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5611 dl 1.149 s = t.rights = s.nextRight;
5612     }
5613 dl 1.119 }
5614 dl 1.138 }
5615 dl 1.30 }
5616 tim 1.1 }
5617    
5618 dl 1.222 @SuppressWarnings("serial")
5619 dl 1.210 static final class MapReduceMappingsToDoubleTask<K,V>
5620     extends BulkTask<K,V,Double> {
5621 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5622 dl 1.153 final DoubleBinaryOperator reducer;
5623 dl 1.119 final double basis;
5624     double result;
5625 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5626 dl 1.119 MapReduceMappingsToDoubleTask
5627 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5628 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
5629 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
5630 dl 1.119 double basis,
5631 dl 1.153 DoubleBinaryOperator reducer) {
5632 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5633 dl 1.119 this.transformer = transformer;
5634     this.basis = basis; this.reducer = reducer;
5635     }
5636 dl 1.146 public final Double getRawResult() { return result; }
5637 dl 1.210 public final void compute() {
5638 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5639 dl 1.153 final DoubleBinaryOperator reducer;
5640 dl 1.149 if ((transformer = this.transformer) != null &&
5641     (reducer = this.reducer) != null) {
5642     double r = this.basis;
5643 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5644     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5645     addToPendingCount(1);
5646 dl 1.149 (rights = new MapReduceMappingsToDoubleTask<K,V>
5647 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5648     rights, transformer, r, reducer)).fork();
5649     }
5650     for (Node<K,V> p; (p = advance()) != null; )
5651 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5652 dl 1.149 result = r;
5653     CountedCompleter<?> c;
5654     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5655 dl 1.222 @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask<K,V>
5656 dl 1.149 t = (MapReduceMappingsToDoubleTask<K,V>)c,
5657     s = t.rights;
5658     while (s != null) {
5659 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5660 dl 1.149 s = t.rights = s.nextRight;
5661     }
5662 dl 1.119 }
5663     }
5664 dl 1.4 }
5665 dl 1.119 }
5666    
5667 dl 1.222 @SuppressWarnings("serial")
5668 dl 1.210 static final class MapReduceKeysToLongTask<K,V>
5669     extends BulkTask<K,V,Long> {
5670 dl 1.171 final ToLongFunction<? super K> transformer;
5671 dl 1.153 final LongBinaryOperator reducer;
5672 dl 1.119 final long basis;
5673     long result;
5674 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
5675 dl 1.119 MapReduceKeysToLongTask
5676 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5677 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
5678 dl 1.171 ToLongFunction<? super K> transformer,
5679 dl 1.119 long basis,
5680 dl 1.153 LongBinaryOperator reducer) {
5681 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5682 dl 1.119 this.transformer = transformer;
5683     this.basis = basis; this.reducer = reducer;
5684     }
5685 dl 1.146 public final Long getRawResult() { return result; }
5686 dl 1.210 public final void compute() {
5687 dl 1.171 final ToLongFunction<? super K> transformer;
5688 dl 1.153 final LongBinaryOperator reducer;
5689 dl 1.149 if ((transformer = this.transformer) != null &&
5690     (reducer = this.reducer) != null) {
5691     long r = this.basis;
5692 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5693     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5694     addToPendingCount(1);
5695 dl 1.149 (rights = new MapReduceKeysToLongTask<K,V>
5696 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5697     rights, transformer, r, reducer)).fork();
5698     }
5699     for (Node<K,V> p; (p = advance()) != null; )
5700 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5701 dl 1.149 result = r;
5702     CountedCompleter<?> c;
5703     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5704 dl 1.222 @SuppressWarnings("unchecked") MapReduceKeysToLongTask<K,V>
5705 dl 1.149 t = (MapReduceKeysToLongTask<K,V>)c,
5706     s = t.rights;
5707     while (s != null) {
5708 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5709 dl 1.149 s = t.rights = s.nextRight;
5710     }
5711 dl 1.119 }
5712 dl 1.138 }
5713 dl 1.4 }
5714 dl 1.119 }
5715    
5716 dl 1.222 @SuppressWarnings("serial")
5717 dl 1.210 static final class MapReduceValuesToLongTask<K,V>
5718     extends BulkTask<K,V,Long> {
5719 dl 1.171 final ToLongFunction<? super V> transformer;
5720 dl 1.153 final LongBinaryOperator reducer;
5721 dl 1.119 final long basis;
5722     long result;
5723 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
5724 dl 1.119 MapReduceValuesToLongTask
5725 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5726 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
5727 dl 1.171 ToLongFunction<? super V> transformer,
5728 dl 1.119 long basis,
5729 dl 1.153 LongBinaryOperator reducer) {
5730 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5731 dl 1.119 this.transformer = transformer;
5732     this.basis = basis; this.reducer = reducer;
5733     }
5734 dl 1.146 public final Long getRawResult() { return result; }
5735 dl 1.210 public final void compute() {
5736 dl 1.171 final ToLongFunction<? super V> transformer;
5737 dl 1.153 final LongBinaryOperator reducer;
5738 dl 1.149 if ((transformer = this.transformer) != null &&
5739     (reducer = this.reducer) != null) {
5740     long r = this.basis;
5741 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5742     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5743     addToPendingCount(1);
5744 dl 1.149 (rights = new MapReduceValuesToLongTask<K,V>
5745 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5746     rights, transformer, r, reducer)).fork();
5747     }
5748     for (Node<K,V> p; (p = advance()) != null; )
5749     r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5750 dl 1.149 result = r;
5751     CountedCompleter<?> c;
5752     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5753 dl 1.222 @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V>
5754 dl 1.149 t = (MapReduceValuesToLongTask<K,V>)c,
5755     s = t.rights;
5756     while (s != null) {
5757 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5758 dl 1.149 s = t.rights = s.nextRight;
5759     }
5760 dl 1.119 }
5761     }
5762 jsr166 1.95 }
5763 dl 1.119 }
5764    
5765 dl 1.222 @SuppressWarnings("serial")
5766 dl 1.210 static final class MapReduceEntriesToLongTask<K,V>
5767     extends BulkTask<K,V,Long> {
5768 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5769 dl 1.153 final LongBinaryOperator reducer;
5770 dl 1.119 final long basis;
5771     long result;
5772 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
5773 dl 1.119 MapReduceEntriesToLongTask
5774 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5775 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
5776 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
5777 dl 1.119 long basis,
5778 dl 1.153 LongBinaryOperator reducer) {
5779 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5780 dl 1.119 this.transformer = transformer;
5781     this.basis = basis; this.reducer = reducer;
5782     }
5783 dl 1.146 public final Long getRawResult() { return result; }
5784 dl 1.210 public final void compute() {
5785 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5786 dl 1.153 final LongBinaryOperator reducer;
5787 dl 1.149 if ((transformer = this.transformer) != null &&
5788     (reducer = this.reducer) != null) {
5789     long r = this.basis;
5790 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5791     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5792     addToPendingCount(1);
5793 dl 1.149 (rights = new MapReduceEntriesToLongTask<K,V>
5794 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5795     rights, transformer, r, reducer)).fork();
5796     }
5797     for (Node<K,V> p; (p = advance()) != null; )
5798     r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5799 dl 1.149 result = r;
5800     CountedCompleter<?> c;
5801     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5802 dl 1.222 @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V>
5803 dl 1.149 t = (MapReduceEntriesToLongTask<K,V>)c,
5804     s = t.rights;
5805     while (s != null) {
5806 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5807 dl 1.149 s = t.rights = s.nextRight;
5808     }
5809 dl 1.119 }
5810 dl 1.138 }
5811 dl 1.4 }
5812 tim 1.1 }
5813    
5814 dl 1.222 @SuppressWarnings("serial")
5815 dl 1.210 static final class MapReduceMappingsToLongTask<K,V>
5816     extends BulkTask<K,V,Long> {
5817 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
5818 dl 1.153 final LongBinaryOperator reducer;
5819 dl 1.119 final long basis;
5820     long result;
5821 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
5822 dl 1.119 MapReduceMappingsToLongTask
5823 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5824 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
5825 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
5826 dl 1.119 long basis,
5827 dl 1.153 LongBinaryOperator reducer) {
5828 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5829 dl 1.119 this.transformer = transformer;
5830     this.basis = basis; this.reducer = reducer;
5831     }
5832 dl 1.146 public final Long getRawResult() { return result; }
5833 dl 1.210 public final void compute() {
5834 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
5835 dl 1.153 final LongBinaryOperator reducer;
5836 dl 1.149 if ((transformer = this.transformer) != null &&
5837     (reducer = this.reducer) != null) {
5838     long r = this.basis;
5839 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5840     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5841     addToPendingCount(1);
5842 dl 1.149 (rights = new MapReduceMappingsToLongTask<K,V>
5843 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5844     rights, transformer, r, reducer)).fork();
5845     }
5846     for (Node<K,V> p; (p = advance()) != null; )
5847 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
5848 dl 1.149 result = r;
5849     CountedCompleter<?> c;
5850     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5851 dl 1.222 @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V>
5852 dl 1.149 t = (MapReduceMappingsToLongTask<K,V>)c,
5853     s = t.rights;
5854     while (s != null) {
5855 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5856 dl 1.149 s = t.rights = s.nextRight;
5857     }
5858 dl 1.119 }
5859     }
5860 dl 1.4 }
5861 tim 1.1 }
5862    
5863 dl 1.222 @SuppressWarnings("serial")
5864 dl 1.210 static final class MapReduceKeysToIntTask<K,V>
5865     extends BulkTask<K,V,Integer> {
5866 dl 1.171 final ToIntFunction<? super K> transformer;
5867 dl 1.153 final IntBinaryOperator reducer;
5868 dl 1.119 final int basis;
5869     int result;
5870 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
5871 dl 1.119 MapReduceKeysToIntTask
5872 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5873 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
5874 dl 1.171 ToIntFunction<? super K> transformer,
5875 dl 1.119 int basis,
5876 dl 1.153 IntBinaryOperator reducer) {
5877 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5878 dl 1.119 this.transformer = transformer;
5879     this.basis = basis; this.reducer = reducer;
5880     }
5881 dl 1.146 public final Integer getRawResult() { return result; }
5882 dl 1.210 public final void compute() {
5883 dl 1.171 final ToIntFunction<? super K> transformer;
5884 dl 1.153 final IntBinaryOperator reducer;
5885 dl 1.149 if ((transformer = this.transformer) != null &&
5886     (reducer = this.reducer) != null) {
5887     int r = this.basis;
5888 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5889     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5890     addToPendingCount(1);
5891 dl 1.149 (rights = new MapReduceKeysToIntTask<K,V>
5892 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5893     rights, transformer, r, reducer)).fork();
5894     }
5895     for (Node<K,V> p; (p = advance()) != null; )
5896 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
5897 dl 1.149 result = r;
5898     CountedCompleter<?> c;
5899     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5900 dl 1.222 @SuppressWarnings("unchecked") MapReduceKeysToIntTask<K,V>
5901 dl 1.149 t = (MapReduceKeysToIntTask<K,V>)c,
5902     s = t.rights;
5903     while (s != null) {
5904 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5905 dl 1.149 s = t.rights = s.nextRight;
5906     }
5907 dl 1.119 }
5908 dl 1.138 }
5909 dl 1.30 }
5910     }
5911    
5912 dl 1.222 @SuppressWarnings("serial")
5913 dl 1.210 static final class MapReduceValuesToIntTask<K,V>
5914     extends BulkTask<K,V,Integer> {
5915 dl 1.171 final ToIntFunction<? super V> transformer;
5916 dl 1.153 final IntBinaryOperator reducer;
5917 dl 1.119 final int basis;
5918     int result;
5919 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
5920 dl 1.119 MapReduceValuesToIntTask
5921 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5922 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
5923 dl 1.171 ToIntFunction<? super V> transformer,
5924 dl 1.119 int basis,
5925 dl 1.153 IntBinaryOperator reducer) {
5926 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5927 dl 1.119 this.transformer = transformer;
5928     this.basis = basis; this.reducer = reducer;
5929     }
5930 dl 1.146 public final Integer getRawResult() { return result; }
5931 dl 1.210 public final void compute() {
5932 dl 1.171 final ToIntFunction<? super V> transformer;
5933 dl 1.153 final IntBinaryOperator reducer;
5934 dl 1.149 if ((transformer = this.transformer) != null &&
5935     (reducer = this.reducer) != null) {
5936     int r = this.basis;
5937 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5938     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5939     addToPendingCount(1);
5940 dl 1.149 (rights = new MapReduceValuesToIntTask<K,V>
5941 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5942     rights, transformer, r, reducer)).fork();
5943     }
5944     for (Node<K,V> p; (p = advance()) != null; )
5945     r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5946 dl 1.149 result = r;
5947     CountedCompleter<?> c;
5948     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5949 dl 1.222 @SuppressWarnings("unchecked") MapReduceValuesToIntTask<K,V>
5950 dl 1.149 t = (MapReduceValuesToIntTask<K,V>)c,
5951     s = t.rights;
5952     while (s != null) {
5953 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5954 dl 1.149 s = t.rights = s.nextRight;
5955     }
5956 dl 1.119 }
5957 dl 1.2 }
5958 tim 1.1 }
5959     }
5960    
5961 dl 1.222 @SuppressWarnings("serial")
5962 dl 1.210 static final class MapReduceEntriesToIntTask<K,V>
5963     extends BulkTask<K,V,Integer> {
5964 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
5965 dl 1.153 final IntBinaryOperator reducer;
5966 dl 1.119 final int basis;
5967     int result;
5968 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
5969 dl 1.119 MapReduceEntriesToIntTask
5970 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5971 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
5972 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
5973 dl 1.119 int basis,
5974 dl 1.153 IntBinaryOperator reducer) {
5975 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5976 dl 1.119 this.transformer = transformer;
5977     this.basis = basis; this.reducer = reducer;
5978     }
5979 dl 1.146 public final Integer getRawResult() { return result; }
5980 dl 1.210 public final void compute() {
5981 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
5982 dl 1.153 final IntBinaryOperator reducer;
5983 dl 1.149 if ((transformer = this.transformer) != null &&
5984     (reducer = this.reducer) != null) {
5985     int r = this.basis;
5986 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5987     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5988     addToPendingCount(1);
5989 dl 1.149 (rights = new MapReduceEntriesToIntTask<K,V>
5990 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5991     rights, transformer, r, reducer)).fork();
5992     }
5993     for (Node<K,V> p; (p = advance()) != null; )
5994     r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5995 dl 1.149 result = r;
5996     CountedCompleter<?> c;
5997     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5998 dl 1.222 @SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
5999 dl 1.149 t = (MapReduceEntriesToIntTask<K,V>)c,
6000     s = t.rights;
6001     while (s != null) {
6002 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6003 dl 1.149 s = t.rights = s.nextRight;
6004     }
6005 dl 1.119 }
6006 dl 1.138 }
6007 dl 1.4 }
6008 dl 1.119 }
6009 tim 1.1
6010 dl 1.222 @SuppressWarnings("serial")
6011 dl 1.210 static final class MapReduceMappingsToIntTask<K,V>
6012     extends BulkTask<K,V,Integer> {
6013 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6014 dl 1.153 final IntBinaryOperator reducer;
6015 dl 1.119 final int basis;
6016     int result;
6017 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6018 dl 1.119 MapReduceMappingsToIntTask
6019 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6020 dl 1.146 MapReduceMappingsToIntTask<K,V> nextRight,
6021 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
6022 dl 1.119 int basis,
6023 dl 1.153 IntBinaryOperator reducer) {
6024 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6025 dl 1.119 this.transformer = transformer;
6026     this.basis = basis; this.reducer = reducer;
6027     }
6028 dl 1.146 public final Integer getRawResult() { return result; }
6029 dl 1.210 public final void compute() {
6030 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6031 dl 1.153 final IntBinaryOperator reducer;
6032 dl 1.149 if ((transformer = this.transformer) != null &&
6033     (reducer = this.reducer) != null) {
6034     int r = this.basis;
6035 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6036     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6037     addToPendingCount(1);
6038 dl 1.149 (rights = new MapReduceMappingsToIntTask<K,V>
6039 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6040     rights, transformer, r, reducer)).fork();
6041     }
6042     for (Node<K,V> p; (p = advance()) != null; )
6043 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6044 dl 1.149 result = r;
6045     CountedCompleter<?> c;
6046     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6047 dl 1.222 @SuppressWarnings("unchecked") MapReduceMappingsToIntTask<K,V>
6048 dl 1.149 t = (MapReduceMappingsToIntTask<K,V>)c,
6049     s = t.rights;
6050     while (s != null) {
6051 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6052 dl 1.149 s = t.rights = s.nextRight;
6053     }
6054 dl 1.119 }
6055 dl 1.138 }
6056 tim 1.1 }
6057     }
6058 dl 1.99
6059     // Unsafe mechanics
6060 dl 1.149 private static final sun.misc.Unsafe U;
6061     private static final long SIZECTL;
6062     private static final long TRANSFERINDEX;
6063     private static final long TRANSFERORIGIN;
6064     private static final long BASECOUNT;
6065 dl 1.153 private static final long CELLSBUSY;
6066 dl 1.149 private static final long CELLVALUE;
6067 dl 1.119 private static final long ABASE;
6068     private static final int ASHIFT;
6069 dl 1.99
6070     static {
6071     try {
6072 dl 1.149 U = sun.misc.Unsafe.getUnsafe();
6073 dl 1.119 Class<?> k = ConcurrentHashMap.class;
6074 dl 1.149 SIZECTL = U.objectFieldOffset
6075 dl 1.119 (k.getDeclaredField("sizeCtl"));
6076 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
6077     (k.getDeclaredField("transferIndex"));
6078     TRANSFERORIGIN = U.objectFieldOffset
6079     (k.getDeclaredField("transferOrigin"));
6080     BASECOUNT = U.objectFieldOffset
6081     (k.getDeclaredField("baseCount"));
6082 dl 1.153 CELLSBUSY = U.objectFieldOffset
6083     (k.getDeclaredField("cellsBusy"));
6084 dl 1.222 Class<?> ck = CounterCell.class;
6085 dl 1.149 CELLVALUE = U.objectFieldOffset
6086     (ck.getDeclaredField("value"));
6087 jsr166 1.226 Class<?> ak = Node[].class;
6088     ABASE = U.arrayBaseOffset(ak);
6089     int scale = U.arrayIndexScale(ak);
6090 jsr166 1.167 if ((scale & (scale - 1)) != 0)
6091     throw new Error("data type scale not a power of two");
6092     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6093 dl 1.99 } catch (Exception e) {
6094     throw new Error(e);
6095     }
6096     }
6097 jsr166 1.152 }