ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.243
Committed: Fri Aug 9 13:02:57 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.242: +1 -0 lines
Log Message:
Suppress warnings

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