ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.241
Committed: Thu Aug 8 18:25:06 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.240: +34 -26 lines
Log Message:
document "weakly consistent" properties of spliterators

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