ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.240
Committed: Sat Jul 20 16:50:01 2013 UTC (10 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.239: +68 -39 lines
Log Message:
Ensure consistent insertion

File Contents

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