ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.256
Committed: Sat Dec 21 21:32:34 2013 UTC (10 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.255: +2 -2 lines
Log Message:
whitespace

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