ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.252
Committed: Sun Dec 1 13:38:58 2013 UTC (10 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.251: +78 -35 lines
Log Message:
avoid overlapping resize generations; fix RW mask

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     return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
2192     }
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     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     (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 dl 1.252 int rs = resizeStamp(tab.length);
2276     while (nextTab == nextTable && table == tab &&
2277     (sc = sizeCtl) < 0) {
2278     if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
2279     sc == rs + MAX_RESIZERS || transferIndex <= 0)
2280     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     Node<K,V>[] nt;
2323     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     (rs << RESIZE_STAMP_SHIFT) + 2))
2332     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     if ((sc - 2) != resizeStamp(n))
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     do {
2657     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     for (Node<K,V> e = first; e != null; e = e.next) {
2813     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     }
2819     else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2820     s + READER)) {
2821     TreeNode<K,V> r, p;
2822     try {
2823     p = ((r = root) == null ? null :
2824     r.findTreeNode(h, k, null));
2825     } finally {
2826     Thread w;
2827     if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
2828     (READER|WAITER) && (w = waiter) != null)
2829     LockSupport.unpark(w);
2830     }
2831     return p;
2832     }
2833     }
2834     }
2835     return null;
2836 dl 1.192 }
2837    
2838 dl 1.222 /**
2839     * Finds or adds a node.
2840     * @return null if added
2841     */
2842     final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2843     Class<?> kc = null;
2844 dl 1.240 boolean searched = false;
2845 dl 1.224 for (TreeNode<K,V> p = root;;) {
2846 dl 1.240 int dir, ph; K pk;
2847 dl 1.224 if (p == null) {
2848     first = root = new TreeNode<K,V>(h, k, v, null, null);
2849     break;
2850     }
2851     else if ((ph = p.hash) > h)
2852 dl 1.222 dir = -1;
2853     else if (ph < h)
2854     dir = 1;
2855     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2856     return p;
2857     else if ((kc == null &&
2858     (kc = comparableClassFor(k)) == null) ||
2859     (dir = compareComparables(kc, k, pk)) == 0) {
2860 dl 1.240 if (!searched) {
2861     TreeNode<K,V> q, ch;
2862     searched = true;
2863     if (((ch = p.left) != null &&
2864     (q = ch.findTreeNode(h, k, kc)) != null) ||
2865     ((ch = p.right) != null &&
2866     (q = ch.findTreeNode(h, k, kc)) != null))
2867     return q;
2868     }
2869     dir = tieBreakOrder(k, pk);
2870 dl 1.222 }
2871 dl 1.240
2872 dl 1.222 TreeNode<K,V> xp = p;
2873 dl 1.240 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2874 dl 1.222 TreeNode<K,V> x, f = first;
2875     first = x = new TreeNode<K,V>(h, k, v, f, xp);
2876     if (f != null)
2877     f.prev = x;
2878 dl 1.240 if (dir <= 0)
2879 dl 1.222 xp.left = x;
2880     else
2881     xp.right = x;
2882     if (!xp.red)
2883     x.red = true;
2884     else {
2885     lockRoot();
2886     try {
2887     root = balanceInsertion(root, x);
2888     } finally {
2889     unlockRoot();
2890     }
2891     }
2892 dl 1.224 break;
2893 dl 1.222 }
2894     }
2895 dl 1.224 assert checkInvariants(root);
2896     return null;
2897 dl 1.192 }
2898    
2899 dl 1.222 /**
2900     * Removes the given node, that must be present before this
2901     * call. This is messier than typical red-black deletion code
2902     * because we cannot swap the contents of an interior node
2903     * with a leaf successor that is pinned by "next" pointers
2904     * that are accessible independently of lock. So instead we
2905     * swap the tree linkages.
2906     *
2907 jsr166 1.230 * @return true if now too small, so should be untreeified
2908 dl 1.222 */
2909     final boolean removeTreeNode(TreeNode<K,V> p) {
2910     TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2911     TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2912     TreeNode<K,V> r, rl;
2913     if (pred == null)
2914     first = next;
2915     else
2916     pred.next = next;
2917     if (next != null)
2918     next.prev = pred;
2919     if (first == null) {
2920     root = null;
2921     return true;
2922     }
2923 dl 1.224 if ((r = root) == null || r.right == null || // too small
2924 dl 1.222 (rl = r.left) == null || rl.left == null)
2925     return true;
2926     lockRoot();
2927     try {
2928     TreeNode<K,V> replacement;
2929     TreeNode<K,V> pl = p.left;
2930     TreeNode<K,V> pr = p.right;
2931     if (pl != null && pr != null) {
2932     TreeNode<K,V> s = pr, sl;
2933     while ((sl = s.left) != null) // find successor
2934     s = sl;
2935     boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2936     TreeNode<K,V> sr = s.right;
2937     TreeNode<K,V> pp = p.parent;
2938     if (s == pr) { // p was s's direct parent
2939     p.parent = s;
2940     s.right = p;
2941     }
2942     else {
2943     TreeNode<K,V> sp = s.parent;
2944     if ((p.parent = sp) != null) {
2945     if (s == sp.left)
2946     sp.left = p;
2947     else
2948     sp.right = p;
2949     }
2950     if ((s.right = pr) != null)
2951     pr.parent = s;
2952     }
2953     p.left = null;
2954     if ((p.right = sr) != null)
2955     sr.parent = p;
2956     if ((s.left = pl) != null)
2957     pl.parent = s;
2958     if ((s.parent = pp) == null)
2959     r = s;
2960     else if (p == pp.left)
2961     pp.left = s;
2962     else
2963     pp.right = s;
2964     if (sr != null)
2965     replacement = sr;
2966     else
2967     replacement = p;
2968     }
2969     else if (pl != null)
2970     replacement = pl;
2971     else if (pr != null)
2972     replacement = pr;
2973     else
2974     replacement = p;
2975     if (replacement != p) {
2976     TreeNode<K,V> pp = replacement.parent = p.parent;
2977     if (pp == null)
2978     r = replacement;
2979     else if (p == pp.left)
2980     pp.left = replacement;
2981     else
2982     pp.right = replacement;
2983     p.left = p.right = p.parent = null;
2984     }
2985    
2986     root = (p.red) ? r : balanceDeletion(r, replacement);
2987    
2988     if (p == replacement) { // detach pointers
2989     TreeNode<K,V> pp;
2990     if ((pp = p.parent) != null) {
2991     if (p == pp.left)
2992     pp.left = null;
2993     else if (p == pp.right)
2994     pp.right = null;
2995     p.parent = null;
2996     }
2997     }
2998     } finally {
2999     unlockRoot();
3000     }
3001 dl 1.224 assert checkInvariants(root);
3002 dl 1.222 return false;
3003 dl 1.210 }
3004    
3005 dl 1.222 /* ------------------------------------------------------------ */
3006     // Red-black tree methods, all adapted from CLR
3007 dl 1.210
3008 dl 1.222 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
3009     TreeNode<K,V> p) {
3010 dl 1.224 TreeNode<K,V> r, pp, rl;
3011     if (p != null && (r = p.right) != null) {
3012 dl 1.222 if ((rl = p.right = r.left) != null)
3013     rl.parent = p;
3014     if ((pp = r.parent = p.parent) == null)
3015     (root = r).red = false;
3016     else if (pp.left == p)
3017     pp.left = r;
3018     else
3019     pp.right = r;
3020     r.left = p;
3021     p.parent = r;
3022     }
3023     return root;
3024 dl 1.119 }
3025    
3026 dl 1.222 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
3027     TreeNode<K,V> p) {
3028 dl 1.224 TreeNode<K,V> l, pp, lr;
3029     if (p != null && (l = p.left) != null) {
3030 dl 1.222 if ((lr = p.left = l.right) != null)
3031     lr.parent = p;
3032     if ((pp = l.parent = p.parent) == null)
3033     (root = l).red = false;
3034     else if (pp.right == p)
3035     pp.right = l;
3036     else
3037     pp.left = l;
3038     l.right = p;
3039     p.parent = l;
3040     }
3041     return root;
3042 dl 1.119 }
3043    
3044 dl 1.222 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
3045     TreeNode<K,V> x) {
3046     x.red = true;
3047     for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
3048     if ((xp = x.parent) == null) {
3049     x.red = false;
3050     return x;
3051     }
3052     else if (!xp.red || (xpp = xp.parent) == null)
3053     return root;
3054     if (xp == (xppl = xpp.left)) {
3055     if ((xppr = xpp.right) != null && xppr.red) {
3056     xppr.red = false;
3057     xp.red = false;
3058     xpp.red = true;
3059     x = xpp;
3060     }
3061     else {
3062     if (x == xp.right) {
3063     root = rotateLeft(root, x = xp);
3064     xpp = (xp = x.parent) == null ? null : xp.parent;
3065     }
3066     if (xp != null) {
3067     xp.red = false;
3068     if (xpp != null) {
3069     xpp.red = true;
3070     root = rotateRight(root, xpp);
3071     }
3072     }
3073     }
3074     }
3075     else {
3076     if (xppl != null && xppl.red) {
3077     xppl.red = false;
3078     xp.red = false;
3079     xpp.red = true;
3080     x = xpp;
3081     }
3082     else {
3083     if (x == xp.left) {
3084     root = rotateRight(root, x = xp);
3085     xpp = (xp = x.parent) == null ? null : xp.parent;
3086     }
3087     if (xp != null) {
3088     xp.red = false;
3089     if (xpp != null) {
3090     xpp.red = true;
3091     root = rotateLeft(root, xpp);
3092     }
3093     }
3094     }
3095     }
3096     }
3097 dl 1.119 }
3098    
3099 dl 1.222 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
3100     TreeNode<K,V> x) {
3101     for (TreeNode<K,V> xp, xpl, xpr;;) {
3102     if (x == null || x == root)
3103     return root;
3104     else if ((xp = x.parent) == null) {
3105     x.red = false;
3106     return x;
3107     }
3108     else if (x.red) {
3109     x.red = false;
3110     return root;
3111     }
3112     else if ((xpl = xp.left) == x) {
3113     if ((xpr = xp.right) != null && xpr.red) {
3114     xpr.red = false;
3115     xp.red = true;
3116     root = rotateLeft(root, xp);
3117     xpr = (xp = x.parent) == null ? null : xp.right;
3118     }
3119     if (xpr == null)
3120     x = xp;
3121     else {
3122     TreeNode<K,V> sl = xpr.left, sr = xpr.right;
3123     if ((sr == null || !sr.red) &&
3124     (sl == null || !sl.red)) {
3125     xpr.red = true;
3126     x = xp;
3127     }
3128     else {
3129     if (sr == null || !sr.red) {
3130     if (sl != null)
3131     sl.red = false;
3132     xpr.red = true;
3133     root = rotateRight(root, xpr);
3134     xpr = (xp = x.parent) == null ?
3135     null : xp.right;
3136     }
3137     if (xpr != null) {
3138     xpr.red = (xp == null) ? false : xp.red;
3139     if ((sr = xpr.right) != null)
3140     sr.red = false;
3141     }
3142     if (xp != null) {
3143     xp.red = false;
3144     root = rotateLeft(root, xp);
3145     }
3146     x = root;
3147     }
3148     }
3149     }
3150     else { // symmetric
3151     if (xpl != null && xpl.red) {
3152     xpl.red = false;
3153     xp.red = true;
3154     root = rotateRight(root, xp);
3155     xpl = (xp = x.parent) == null ? null : xp.left;
3156     }
3157     if (xpl == null)
3158     x = xp;
3159     else {
3160     TreeNode<K,V> sl = xpl.left, sr = xpl.right;
3161     if ((sl == null || !sl.red) &&
3162     (sr == null || !sr.red)) {
3163     xpl.red = true;
3164     x = xp;
3165     }
3166     else {
3167     if (sl == null || !sl.red) {
3168     if (sr != null)
3169     sr.red = false;
3170     xpl.red = true;
3171     root = rotateLeft(root, xpl);
3172     xpl = (xp = x.parent) == null ?
3173     null : xp.left;
3174     }
3175     if (xpl != null) {
3176     xpl.red = (xp == null) ? false : xp.red;
3177     if ((sl = xpl.left) != null)
3178     sl.red = false;
3179     }
3180     if (xp != null) {
3181     xp.red = false;
3182     root = rotateRight(root, xp);
3183     }
3184     x = root;
3185     }
3186     }
3187     }
3188     }
3189 dl 1.210 }
3190 jsr166 1.225
3191 dl 1.222 /**
3192     * Recursive invariant check
3193     */
3194 dl 1.224 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
3195 dl 1.222 TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
3196     tb = t.prev, tn = (TreeNode<K,V>)t.next;
3197     if (tb != null && tb.next != t)
3198     return false;
3199     if (tn != null && tn.prev != t)
3200     return false;
3201     if (tp != null && t != tp.left && t != tp.right)
3202     return false;
3203     if (tl != null && (tl.parent != t || tl.hash > t.hash))
3204     return false;
3205     if (tr != null && (tr.parent != t || tr.hash < t.hash))
3206     return false;
3207     if (t.red && tl != null && tl.red && tr != null && tr.red)
3208     return false;
3209 dl 1.224 if (tl != null && !checkInvariants(tl))
3210 dl 1.222 return false;
3211 dl 1.224 if (tr != null && !checkInvariants(tr))
3212 dl 1.210 return false;
3213     return true;
3214     }
3215 dl 1.146
3216 dl 1.222 private static final sun.misc.Unsafe U;
3217     private static final long LOCKSTATE;
3218     static {
3219     try {
3220     U = sun.misc.Unsafe.getUnsafe();
3221     Class<?> k = TreeBin.class;
3222     LOCKSTATE = U.objectFieldOffset
3223     (k.getDeclaredField("lockState"));
3224     } catch (Exception e) {
3225     throw new Error(e);
3226     }
3227 dl 1.146 }
3228 dl 1.119 }
3229    
3230 dl 1.222 /* ----------------Table Traversal -------------- */
3231    
3232 jsr166 1.247 /**
3233     * Records the table, its length, and current traversal index for a
3234     * traverser that must process a region of a forwarded table before
3235     * proceeding with current table.
3236     */
3237     static final class TableStack<K,V> {
3238 dl 1.246 int length;
3239     int index;
3240     Node<K,V>[] tab;
3241 jsr166 1.247 TableStack<K,V> next;
3242 dl 1.246 }
3243    
3244 dl 1.222 /**
3245     * Encapsulates traversal for methods such as containsValue; also
3246     * serves as a base class for other iterators and spliterators.
3247     *
3248     * Method advance visits once each still-valid node that was
3249     * reachable upon iterator construction. It might miss some that
3250     * were added to a bin after the bin was visited, which is OK wrt
3251     * consistency guarantees. Maintaining this property in the face
3252     * of possible ongoing resizes requires a fair amount of
3253     * bookkeeping state that is difficult to optimize away amidst
3254     * volatile accesses. Even so, traversal maintains reasonable
3255     * throughput.
3256     *
3257     * Normally, iteration proceeds bin-by-bin traversing lists.
3258     * However, if the table has been resized, then all future steps
3259     * must traverse both the bin at the current index as well as at
3260     * (index + baseSize); and so on for further resizings. To
3261     * paranoically cope with potential sharing by users of iterators
3262     * across threads, iteration terminates if a bounds checks fails
3263     * for a table read.
3264     */
3265     static class Traverser<K,V> {
3266     Node<K,V>[] tab; // current table; updated if resized
3267     Node<K,V> next; // the next entry to use
3268 dl 1.246 TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
3269 dl 1.222 int index; // index of bin to use next
3270     int baseIndex; // current index of initial table
3271     int baseLimit; // index bound for initial table
3272     final int baseSize; // initial table size
3273    
3274     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
3275     this.tab = tab;
3276     this.baseSize = size;
3277     this.baseIndex = this.index = index;
3278     this.baseLimit = limit;
3279     this.next = null;
3280     }
3281    
3282     /**
3283     * Advances if possible, returning next valid node, or null if none.
3284     */
3285     final Node<K,V> advance() {
3286     Node<K,V> e;
3287     if ((e = next) != null)
3288     e = e.next;
3289     for (;;) {
3290 dl 1.246 Node<K,V>[] t; int i, n; // must use locals in checks
3291 dl 1.222 if (e != null)
3292     return next = e;
3293     if (baseIndex >= baseLimit || (t = tab) == null ||
3294     (n = t.length) <= (i = index) || i < 0)
3295     return next = null;
3296 dl 1.246 if ((e = tabAt(t, i)) != null && e.hash < 0) {
3297 dl 1.222 if (e instanceof ForwardingNode) {
3298     tab = ((ForwardingNode<K,V>)e).nextTable;
3299     e = null;
3300 dl 1.246 pushState(t, i, n);
3301 dl 1.222 continue;
3302     }
3303     else if (e instanceof TreeBin)
3304     e = ((TreeBin<K,V>)e).first;
3305     else
3306     e = null;
3307     }
3308 dl 1.246 if (stack != null)
3309     recoverState(n);
3310     else if ((index = i + baseSize) >= n)
3311     index = ++baseIndex; // visit upper slots if present
3312 dl 1.222 }
3313     }
3314 dl 1.246
3315     /**
3316 jsr166 1.249 * Saves traversal state upon encountering a forwarding node.
3317 dl 1.246 */
3318     private void pushState(Node<K,V>[] t, int i, int n) {
3319     TableStack<K,V> s = spare; // reuse if possible
3320     if (s != null)
3321     spare = s.next;
3322     else
3323     s = new TableStack<K,V>();
3324     s.tab = t;
3325     s.length = n;
3326     s.index = i;
3327     s.next = stack;
3328     stack = s;
3329     }
3330    
3331     /**
3332 jsr166 1.249 * Possibly pops traversal state.
3333 dl 1.246 *
3334     * @param n length of current table
3335     */
3336     private void recoverState(int n) {
3337     TableStack<K,V> s; int len;
3338     while ((s = stack) != null && (index += (len = s.length)) >= n) {
3339     n = len;
3340     index = s.index;
3341     tab = s.tab;
3342     s.tab = null;
3343     TableStack<K,V> next = s.next;
3344     s.next = spare; // save for reuse
3345     stack = next;
3346     spare = s;
3347     }
3348     if (s == null && (index += baseSize) >= n)
3349     index = ++baseIndex;
3350     }
3351 dl 1.222 }
3352    
3353     /**
3354     * Base of key, value, and entry Iterators. Adds fields to
3355 jsr166 1.229 * Traverser to support iterator.remove.
3356 dl 1.222 */
3357     static class BaseIterator<K,V> extends Traverser<K,V> {
3358     final ConcurrentHashMap<K,V> map;
3359     Node<K,V> lastReturned;
3360     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
3361     ConcurrentHashMap<K,V> map) {
3362 dl 1.210 super(tab, size, index, limit);
3363     this.map = map;
3364 dl 1.222 advance();
3365 dl 1.210 }
3366    
3367 dl 1.222 public final boolean hasNext() { return next != null; }
3368     public final boolean hasMoreElements() { return next != null; }
3369    
3370     public final void remove() {
3371     Node<K,V> p;
3372     if ((p = lastReturned) == null)
3373     throw new IllegalStateException();
3374     lastReturned = null;
3375     map.replaceNode(p.key, null, null);
3376 dl 1.210 }
3377 dl 1.222 }
3378 dl 1.210
3379 dl 1.222 static final class KeyIterator<K,V> extends BaseIterator<K,V>
3380     implements Iterator<K>, Enumeration<K> {
3381     KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
3382     ConcurrentHashMap<K,V> map) {
3383     super(tab, index, size, limit, map);
3384 dl 1.210 }
3385    
3386 dl 1.222 public final K next() {
3387 dl 1.210 Node<K,V> p;
3388 dl 1.222 if ((p = next) == null)
3389     throw new NoSuchElementException();
3390     K k = p.key;
3391     lastReturned = p;
3392     advance();
3393     return k;
3394 dl 1.210 }
3395    
3396 dl 1.222 public final K nextElement() { return next(); }
3397     }
3398    
3399     static final class ValueIterator<K,V> extends BaseIterator<K,V>
3400     implements Iterator<V>, Enumeration<V> {
3401     ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
3402     ConcurrentHashMap<K,V> map) {
3403     super(tab, index, size, limit, map);
3404     }
3405 dl 1.210
3406 dl 1.222 public final V next() {
3407     Node<K,V> p;
3408     if ((p = next) == null)
3409     throw new NoSuchElementException();
3410     V v = p.val;
3411     lastReturned = p;
3412     advance();
3413     return v;
3414 dl 1.210 }
3415 dl 1.222
3416     public final V nextElement() { return next(); }
3417 dl 1.210 }
3418    
3419 dl 1.222 static final class EntryIterator<K,V> extends BaseIterator<K,V>
3420     implements Iterator<Map.Entry<K,V>> {
3421     EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
3422     ConcurrentHashMap<K,V> map) {
3423     super(tab, index, size, limit, map);
3424     }
3425 dl 1.210
3426 dl 1.222 public final Map.Entry<K,V> next() {
3427     Node<K,V> p;
3428     if ((p = next) == null)
3429     throw new NoSuchElementException();
3430     K k = p.key;
3431     V v = p.val;
3432     lastReturned = p;
3433     advance();
3434     return new MapEntry<K,V>(k, v, map);
3435     }
3436     }
3437 dl 1.119
3438     /**
3439 dl 1.222 * Exported Entry for EntryIterator
3440 dl 1.119 */
3441 dl 1.222 static final class MapEntry<K,V> implements Map.Entry<K,V> {
3442     final K key; // non-null
3443     V val; // non-null
3444     final ConcurrentHashMap<K,V> map;
3445     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3446     this.key = key;
3447     this.val = val;
3448     this.map = map;
3449     }
3450     public K getKey() { return key; }
3451     public V getValue() { return val; }
3452     public int hashCode() { return key.hashCode() ^ val.hashCode(); }
3453     public String toString() { return key + "=" + val; }
3454 dl 1.119
3455 dl 1.222 public boolean equals(Object o) {
3456     Object k, v; Map.Entry<?,?> e;
3457     return ((o instanceof Map.Entry) &&
3458     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3459     (v = e.getValue()) != null &&
3460     (k == key || k.equals(key)) &&
3461     (v == val || v.equals(val)));
3462     }
3463 dl 1.119
3464 dl 1.222 /**
3465     * Sets our entry's value and writes through to the map. The
3466     * value to return is somewhat arbitrary here. Since we do not
3467     * necessarily track asynchronous changes, the most recent
3468     * "previous" value could be different from what we return (or
3469     * could even have been removed, in which case the put will
3470     * re-establish). We do not and cannot guarantee more.
3471     */
3472     public V setValue(V value) {
3473     if (value == null) throw new NullPointerException();
3474     V v = val;
3475     val = value;
3476     map.put(key, value);
3477     return v;
3478     }
3479 dl 1.119 }
3480    
3481 dl 1.222 static final class KeySpliterator<K,V> extends Traverser<K,V>
3482     implements Spliterator<K> {
3483     long est; // size estimate
3484     KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3485     long est) {
3486     super(tab, size, index, limit);
3487     this.est = est;
3488     }
3489 dl 1.119
3490 dl 1.222 public Spliterator<K> trySplit() {
3491     int i, f, h;
3492     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3493     new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
3494     f, est >>>= 1);
3495 dl 1.119 }
3496    
3497 dl 1.222 public void forEachRemaining(Consumer<? super K> action) {
3498     if (action == null) throw new NullPointerException();
3499     for (Node<K,V> p; (p = advance()) != null;)
3500     action.accept(p.key);
3501 dl 1.119 }
3502    
3503 dl 1.222 public boolean tryAdvance(Consumer<? super K> action) {
3504     if (action == null) throw new NullPointerException();
3505     Node<K,V> p;
3506     if ((p = advance()) == null)
3507 dl 1.119 return false;
3508 dl 1.222 action.accept(p.key);
3509     return true;
3510 dl 1.119 }
3511    
3512 dl 1.222 public long estimateSize() { return est; }
3513 dl 1.119
3514 dl 1.222 public int characteristics() {
3515     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3516     Spliterator.NONNULL;
3517     }
3518 dl 1.142 }
3519 dl 1.119
3520 dl 1.222 static final class ValueSpliterator<K,V> extends Traverser<K,V>
3521     implements Spliterator<V> {
3522     long est; // size estimate
3523     ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
3524     long est) {
3525     super(tab, size, index, limit);
3526     this.est = est;
3527 dl 1.209 }
3528    
3529 dl 1.222 public Spliterator<V> trySplit() {
3530     int i, f, h;
3531     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3532     new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
3533     f, est >>>= 1);
3534 dl 1.142 }
3535 dl 1.119
3536 dl 1.222 public void forEachRemaining(Consumer<? super V> action) {
3537     if (action == null) throw new NullPointerException();
3538     for (Node<K,V> p; (p = advance()) != null;)
3539     action.accept(p.val);
3540     }
3541 dl 1.119
3542 dl 1.222 public boolean tryAdvance(Consumer<? super V> action) {
3543     if (action == null) throw new NullPointerException();
3544     Node<K,V> p;
3545     if ((p = advance()) == null)
3546     return false;
3547     action.accept(p.val);
3548     return true;
3549 dl 1.119 }
3550 dl 1.222
3551     public long estimateSize() { return est; }
3552    
3553     public int characteristics() {
3554     return Spliterator.CONCURRENT | Spliterator.NONNULL;
3555 dl 1.119 }
3556 dl 1.142 }
3557 dl 1.119
3558 dl 1.222 static final class EntrySpliterator<K,V> extends Traverser<K,V>
3559     implements Spliterator<Map.Entry<K,V>> {
3560     final ConcurrentHashMap<K,V> map; // To export MapEntry
3561     long est; // size estimate
3562     EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
3563     long est, ConcurrentHashMap<K,V> map) {
3564     super(tab, size, index, limit);
3565     this.map = map;
3566     this.est = est;
3567     }
3568    
3569     public Spliterator<Map.Entry<K,V>> trySplit() {
3570     int i, f, h;
3571     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
3572     new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
3573     f, est >>>= 1, map);
3574     }
3575 dl 1.142
3576 dl 1.222 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3577     if (action == null) throw new NullPointerException();
3578     for (Node<K,V> p; (p = advance()) != null; )
3579     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3580     }
3581 dl 1.210
3582 dl 1.222 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3583     if (action == null) throw new NullPointerException();
3584     Node<K,V> p;
3585     if ((p = advance()) == null)
3586     return false;
3587     action.accept(new MapEntry<K,V>(p.key, p.val, map));
3588     return true;
3589 dl 1.210 }
3590    
3591 dl 1.222 public long estimateSize() { return est; }
3592    
3593     public int characteristics() {
3594     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3595     Spliterator.NONNULL;
3596 dl 1.210 }
3597     }
3598    
3599     // Parallel bulk operations
3600    
3601     /**
3602     * Computes initial batch value for bulk tasks. The returned value
3603     * is approximately exp2 of the number of times (minus one) to
3604     * split task by two before executing leaf action. This value is
3605     * faster to compute and more convenient to use as a guide to
3606     * splitting than is the depth, since it is used while dividing by
3607     * two anyway.
3608     */
3609     final int batchFor(long b) {
3610     long n;
3611     if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3612     return 0;
3613     int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3614     return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3615     }
3616 dl 1.151
3617 dl 1.119 /**
3618 dl 1.137 * Performs the given action for each (key, value).
3619 dl 1.119 *
3620 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3621 jsr166 1.213 * needed for this operation to be executed in parallel
3622 dl 1.137 * @param action the action
3623 jsr166 1.220 * @since 1.8
3624 dl 1.119 */
3625 dl 1.210 public void forEach(long parallelismThreshold,
3626     BiConsumer<? super K,? super V> action) {
3627 dl 1.151 if (action == null) throw new NullPointerException();
3628 dl 1.210 new ForEachMappingTask<K,V>
3629     (null, batchFor(parallelismThreshold), 0, 0, table,
3630     action).invoke();
3631 dl 1.119 }
3632    
3633     /**
3634 dl 1.137 * Performs the given action for each non-null transformation
3635     * of each (key, value).
3636     *
3637 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3638 jsr166 1.213 * needed for this operation to be executed in parallel
3639 dl 1.137 * @param transformer a function returning the transformation
3640 jsr166 1.169 * for an element, or null if there is no transformation (in
3641 jsr166 1.172 * which case the action is not applied)
3642 dl 1.137 * @param action the action
3643 jsr166 1.237 * @param <U> the return type of the transformer
3644 jsr166 1.220 * @since 1.8
3645 dl 1.119 */
3646 dl 1.210 public <U> void forEach(long parallelismThreshold,
3647     BiFunction<? super K, ? super V, ? extends U> transformer,
3648     Consumer<? super U> action) {
3649 dl 1.151 if (transformer == null || action == null)
3650     throw new NullPointerException();
3651 dl 1.210 new ForEachTransformedMappingTask<K,V,U>
3652     (null, batchFor(parallelismThreshold), 0, 0, table,
3653     transformer, action).invoke();
3654 dl 1.137 }
3655    
3656     /**
3657     * Returns a non-null result from applying the given search
3658 dl 1.210 * function on each (key, value), or null if none. Upon
3659     * success, further element processing is suppressed and the
3660     * results of any other parallel invocations of the search
3661     * function are ignored.
3662 dl 1.137 *
3663 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3664 jsr166 1.213 * needed for this operation to be executed in parallel
3665 dl 1.137 * @param searchFunction a function returning a non-null
3666     * result on success, else null
3667 jsr166 1.237 * @param <U> the return type of the search function
3668 dl 1.137 * @return a non-null result from applying the given search
3669     * function on each (key, value), or null if none
3670 jsr166 1.220 * @since 1.8
3671 dl 1.137 */
3672 dl 1.210 public <U> U search(long parallelismThreshold,
3673     BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3674 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3675 dl 1.210 return new SearchMappingsTask<K,V,U>
3676     (null, batchFor(parallelismThreshold), 0, 0, table,
3677     searchFunction, new AtomicReference<U>()).invoke();
3678 dl 1.137 }
3679    
3680     /**
3681     * Returns the result of accumulating the given transformation
3682     * of all (key, value) pairs using the given reducer to
3683     * combine values, or null if none.
3684     *
3685 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3686 jsr166 1.213 * needed for this operation to be executed in parallel
3687 dl 1.137 * @param transformer a function returning the transformation
3688 jsr166 1.169 * for an element, or null if there is no transformation (in
3689 jsr166 1.172 * which case it is not combined)
3690 dl 1.137 * @param reducer a commutative associative combining function
3691 jsr166 1.237 * @param <U> the return type of the transformer
3692 dl 1.137 * @return the result of accumulating the given transformation
3693     * of all (key, value) pairs
3694 jsr166 1.220 * @since 1.8
3695 dl 1.137 */
3696 dl 1.210 public <U> U reduce(long parallelismThreshold,
3697     BiFunction<? super K, ? super V, ? extends U> transformer,
3698     BiFunction<? super U, ? super U, ? extends U> reducer) {
3699 dl 1.151 if (transformer == null || reducer == null)
3700     throw new NullPointerException();
3701 dl 1.210 return new MapReduceMappingsTask<K,V,U>
3702     (null, batchFor(parallelismThreshold), 0, 0, table,
3703     null, transformer, reducer).invoke();
3704 dl 1.137 }
3705    
3706     /**
3707     * Returns the result of accumulating the given transformation
3708     * of all (key, value) pairs using the given reducer to
3709     * combine values, and the given basis as an identity value.
3710     *
3711 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3712 jsr166 1.213 * needed for this operation to be executed in parallel
3713 dl 1.137 * @param transformer a function returning the transformation
3714     * for an element
3715     * @param basis the identity (initial default value) for the reduction
3716     * @param reducer a commutative associative combining function
3717     * @return the result of accumulating the given transformation
3718     * of all (key, value) pairs
3719 jsr166 1.220 * @since 1.8
3720 dl 1.137 */
3721 dl 1.231 public double reduceToDouble(long parallelismThreshold,
3722     ToDoubleBiFunction<? super K, ? super V> transformer,
3723     double basis,
3724     DoubleBinaryOperator reducer) {
3725 dl 1.151 if (transformer == null || reducer == null)
3726     throw new NullPointerException();
3727 dl 1.210 return new MapReduceMappingsToDoubleTask<K,V>
3728     (null, batchFor(parallelismThreshold), 0, 0, table,
3729     null, transformer, basis, reducer).invoke();
3730 dl 1.137 }
3731 dl 1.119
3732 dl 1.137 /**
3733     * Returns the result of accumulating the given transformation
3734     * of all (key, value) pairs using the given reducer to
3735     * combine values, and the given basis as an identity value.
3736     *
3737 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3738 jsr166 1.213 * needed for this operation to be executed in parallel
3739 dl 1.137 * @param transformer a function returning the transformation
3740     * for an element
3741     * @param basis the identity (initial default value) for the reduction
3742     * @param reducer a commutative associative combining function
3743     * @return the result of accumulating the given transformation
3744     * of all (key, value) pairs
3745 jsr166 1.220 * @since 1.8
3746 dl 1.137 */
3747 dl 1.210 public long reduceToLong(long parallelismThreshold,
3748     ToLongBiFunction<? super K, ? super V> transformer,
3749     long basis,
3750     LongBinaryOperator reducer) {
3751 dl 1.151 if (transformer == null || reducer == null)
3752     throw new NullPointerException();
3753 dl 1.210 return new MapReduceMappingsToLongTask<K,V>
3754     (null, batchFor(parallelismThreshold), 0, 0, table,
3755     null, transformer, basis, reducer).invoke();
3756 dl 1.137 }
3757    
3758     /**
3759     * Returns the result of accumulating the given transformation
3760     * of all (key, value) pairs using the given reducer to
3761     * combine values, and the given basis as an identity value.
3762     *
3763 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3764 jsr166 1.213 * needed for this operation to be executed in parallel
3765 dl 1.137 * @param transformer a function returning the transformation
3766     * for an element
3767     * @param basis the identity (initial default value) for the reduction
3768     * @param reducer a commutative associative combining function
3769     * @return the result of accumulating the given transformation
3770     * of all (key, value) pairs
3771 jsr166 1.220 * @since 1.8
3772 dl 1.137 */
3773 dl 1.210 public int reduceToInt(long parallelismThreshold,
3774     ToIntBiFunction<? super K, ? super V> transformer,
3775     int basis,
3776     IntBinaryOperator reducer) {
3777 dl 1.151 if (transformer == null || reducer == null)
3778     throw new NullPointerException();
3779 dl 1.210 return new MapReduceMappingsToIntTask<K,V>
3780     (null, batchFor(parallelismThreshold), 0, 0, table,
3781     null, transformer, basis, reducer).invoke();
3782 dl 1.137 }
3783    
3784     /**
3785     * Performs the given action for each key.
3786     *
3787 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3788 jsr166 1.213 * needed for this operation to be executed in parallel
3789 dl 1.137 * @param action the action
3790 jsr166 1.220 * @since 1.8
3791 dl 1.137 */
3792 dl 1.210 public void forEachKey(long parallelismThreshold,
3793     Consumer<? super K> action) {
3794     if (action == null) throw new NullPointerException();
3795     new ForEachKeyTask<K,V>
3796     (null, batchFor(parallelismThreshold), 0, 0, table,
3797     action).invoke();
3798 dl 1.137 }
3799 dl 1.119
3800 dl 1.137 /**
3801     * Performs the given action for each non-null transformation
3802     * of each key.
3803     *
3804 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3805 jsr166 1.213 * needed for this operation to be executed in parallel
3806 dl 1.137 * @param transformer a function returning the transformation
3807 jsr166 1.169 * for an element, or null if there is no transformation (in
3808 jsr166 1.172 * which case the action is not applied)
3809 dl 1.137 * @param action the action
3810 jsr166 1.237 * @param <U> the return type of the transformer
3811 jsr166 1.220 * @since 1.8
3812 dl 1.137 */
3813 dl 1.210 public <U> void forEachKey(long parallelismThreshold,
3814     Function<? super K, ? extends U> transformer,
3815     Consumer<? super U> action) {
3816 dl 1.151 if (transformer == null || action == null)
3817     throw new NullPointerException();
3818 dl 1.210 new ForEachTransformedKeyTask<K,V,U>
3819     (null, batchFor(parallelismThreshold), 0, 0, table,
3820     transformer, action).invoke();
3821 dl 1.137 }
3822 dl 1.119
3823 dl 1.137 /**
3824     * Returns a non-null result from applying the given search
3825 dl 1.210 * function on each key, or null if none. Upon success,
3826     * further element processing is suppressed and the results of
3827     * any other parallel invocations of the search function are
3828     * ignored.
3829 dl 1.137 *
3830 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3831 jsr166 1.213 * needed for this operation to be executed in parallel
3832 dl 1.137 * @param searchFunction a function returning a non-null
3833     * result on success, else null
3834 jsr166 1.237 * @param <U> the return type of the search function
3835 dl 1.137 * @return a non-null result from applying the given search
3836     * function on each key, or null if none
3837 jsr166 1.220 * @since 1.8
3838 dl 1.137 */
3839 dl 1.210 public <U> U searchKeys(long parallelismThreshold,
3840     Function<? super K, ? extends U> searchFunction) {
3841     if (searchFunction == null) throw new NullPointerException();
3842     return new SearchKeysTask<K,V,U>
3843     (null, batchFor(parallelismThreshold), 0, 0, table,
3844     searchFunction, new AtomicReference<U>()).invoke();
3845 dl 1.137 }
3846 dl 1.119
3847 dl 1.137 /**
3848     * Returns the result of accumulating all keys using the given
3849     * reducer to combine values, or null if none.
3850     *
3851 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3852 jsr166 1.213 * needed for this operation to be executed in parallel
3853 dl 1.137 * @param reducer a commutative associative combining function
3854     * @return the result of accumulating all keys using the given
3855     * reducer to combine values, or null if none
3856 jsr166 1.220 * @since 1.8
3857 dl 1.137 */
3858 dl 1.210 public K reduceKeys(long parallelismThreshold,
3859     BiFunction<? super K, ? super K, ? extends K> reducer) {
3860 dl 1.151 if (reducer == null) throw new NullPointerException();
3861 dl 1.210 return new ReduceKeysTask<K,V>
3862     (null, batchFor(parallelismThreshold), 0, 0, table,
3863     null, reducer).invoke();
3864 dl 1.137 }
3865 dl 1.119
3866 dl 1.137 /**
3867     * Returns the result of accumulating the given transformation
3868     * of all keys using the given reducer to combine values, or
3869     * null if none.
3870     *
3871 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3872 jsr166 1.213 * needed for this operation to be executed in parallel
3873 dl 1.137 * @param transformer a function returning the transformation
3874 jsr166 1.169 * for an element, or null if there is no transformation (in
3875 jsr166 1.172 * which case it is not combined)
3876 dl 1.137 * @param reducer a commutative associative combining function
3877 jsr166 1.237 * @param <U> the return type of the transformer
3878 dl 1.137 * @return the result of accumulating the given transformation
3879     * of all keys
3880 jsr166 1.220 * @since 1.8
3881 dl 1.137 */
3882 dl 1.210 public <U> U reduceKeys(long parallelismThreshold,
3883     Function<? super K, ? extends U> transformer,
3884 dl 1.153 BiFunction<? super U, ? super U, ? extends U> reducer) {
3885 dl 1.151 if (transformer == null || reducer == null)
3886     throw new NullPointerException();
3887 dl 1.210 return new MapReduceKeysTask<K,V,U>
3888     (null, batchFor(parallelismThreshold), 0, 0, table,
3889     null, transformer, reducer).invoke();
3890 dl 1.137 }
3891 dl 1.119
3892 dl 1.137 /**
3893     * Returns the result of accumulating the given transformation
3894     * of all keys using the given reducer to combine values, and
3895     * the given basis as an identity value.
3896     *
3897 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3898 jsr166 1.213 * needed for this operation to be executed in parallel
3899 dl 1.137 * @param transformer a function returning the transformation
3900     * for an element
3901     * @param basis the identity (initial default value) for the reduction
3902     * @param reducer a commutative associative combining function
3903 jsr166 1.157 * @return the result of accumulating the given transformation
3904 dl 1.137 * of all keys
3905 jsr166 1.220 * @since 1.8
3906 dl 1.137 */
3907 dl 1.210 public double reduceKeysToDouble(long parallelismThreshold,
3908     ToDoubleFunction<? super K> transformer,
3909     double basis,
3910     DoubleBinaryOperator reducer) {
3911 dl 1.151 if (transformer == null || reducer == null)
3912     throw new NullPointerException();
3913 dl 1.210 return new MapReduceKeysToDoubleTask<K,V>
3914     (null, batchFor(parallelismThreshold), 0, 0, table,
3915     null, transformer, basis, reducer).invoke();
3916 dl 1.137 }
3917 dl 1.119
3918 dl 1.137 /**
3919     * Returns the result of accumulating the given transformation
3920     * of all keys using the given reducer to combine values, and
3921     * the given basis as an identity value.
3922     *
3923 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3924 jsr166 1.213 * needed for this operation to be executed in parallel
3925 dl 1.137 * @param transformer a function returning the transformation
3926     * for an element
3927     * @param basis the identity (initial default value) for the reduction
3928     * @param reducer a commutative associative combining function
3929     * @return the result of accumulating the given transformation
3930     * of all keys
3931 jsr166 1.220 * @since 1.8
3932 dl 1.137 */
3933 dl 1.210 public long reduceKeysToLong(long parallelismThreshold,
3934     ToLongFunction<? super K> transformer,
3935     long basis,
3936     LongBinaryOperator reducer) {
3937 dl 1.151 if (transformer == null || reducer == null)
3938     throw new NullPointerException();
3939 dl 1.210 return new MapReduceKeysToLongTask<K,V>
3940     (null, batchFor(parallelismThreshold), 0, 0, table,
3941     null, transformer, basis, reducer).invoke();
3942 dl 1.137 }
3943 dl 1.119
3944 dl 1.137 /**
3945     * Returns the result of accumulating the given transformation
3946     * of all keys using the given reducer to combine values, and
3947     * the given basis as an identity value.
3948     *
3949 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3950 jsr166 1.213 * needed for this operation to be executed in parallel
3951 dl 1.137 * @param transformer a function returning the transformation
3952     * for an element
3953     * @param basis the identity (initial default value) for the reduction
3954     * @param reducer a commutative associative combining function
3955     * @return the result of accumulating the given transformation
3956     * of all keys
3957 jsr166 1.220 * @since 1.8
3958 dl 1.137 */
3959 dl 1.210 public int reduceKeysToInt(long parallelismThreshold,
3960     ToIntFunction<? super K> transformer,
3961     int basis,
3962     IntBinaryOperator reducer) {
3963 dl 1.151 if (transformer == null || reducer == null)
3964     throw new NullPointerException();
3965 dl 1.210 return new MapReduceKeysToIntTask<K,V>
3966     (null, batchFor(parallelismThreshold), 0, 0, table,
3967     null, transformer, basis, reducer).invoke();
3968 dl 1.137 }
3969 dl 1.119
3970 dl 1.137 /**
3971     * Performs the given action for each value.
3972     *
3973 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3974 jsr166 1.213 * needed for this operation to be executed in parallel
3975 dl 1.137 * @param action the action
3976 jsr166 1.220 * @since 1.8
3977 dl 1.137 */
3978 dl 1.210 public void forEachValue(long parallelismThreshold,
3979     Consumer<? super V> action) {
3980     if (action == null)
3981     throw new NullPointerException();
3982     new ForEachValueTask<K,V>
3983     (null, batchFor(parallelismThreshold), 0, 0, table,
3984     action).invoke();
3985 dl 1.137 }
3986 dl 1.119
3987 dl 1.137 /**
3988     * Performs the given action for each non-null transformation
3989     * of each value.
3990     *
3991 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3992 jsr166 1.213 * needed for this operation to be executed in parallel
3993 dl 1.137 * @param transformer a function returning the transformation
3994 jsr166 1.169 * for an element, or null if there is no transformation (in
3995 jsr166 1.172 * which case the action is not applied)
3996 jsr166 1.179 * @param action the action
3997 jsr166 1.237 * @param <U> the return type of the transformer
3998 jsr166 1.220 * @since 1.8
3999 dl 1.137 */
4000 dl 1.210 public <U> void forEachValue(long parallelismThreshold,
4001     Function<? super V, ? extends U> transformer,
4002     Consumer<? super U> action) {
4003 dl 1.151 if (transformer == null || action == null)
4004     throw new NullPointerException();
4005 dl 1.210 new ForEachTransformedValueTask<K,V,U>
4006     (null, batchFor(parallelismThreshold), 0, 0, table,
4007     transformer, action).invoke();
4008 dl 1.137 }
4009 dl 1.119
4010 dl 1.137 /**
4011     * Returns a non-null result from applying the given search
4012 dl 1.210 * function on each value, or null if none. Upon success,
4013     * further element processing is suppressed and the results of
4014     * any other parallel invocations of the search function are
4015     * ignored.
4016 dl 1.137 *
4017 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4018 jsr166 1.213 * needed for this operation to be executed in parallel
4019 dl 1.137 * @param searchFunction a function returning a non-null
4020     * result on success, else null
4021 jsr166 1.237 * @param <U> the return type of the search function
4022 dl 1.137 * @return a non-null result from applying the given search
4023     * function on each value, or null if none
4024 jsr166 1.220 * @since 1.8
4025 dl 1.137 */
4026 dl 1.210 public <U> U searchValues(long parallelismThreshold,
4027     Function<? super V, ? extends U> searchFunction) {
4028 dl 1.151 if (searchFunction == null) throw new NullPointerException();
4029 dl 1.210 return new SearchValuesTask<K,V,U>
4030     (null, batchFor(parallelismThreshold), 0, 0, table,
4031     searchFunction, new AtomicReference<U>()).invoke();
4032 dl 1.137 }
4033 dl 1.119
4034 dl 1.137 /**
4035     * Returns the result of accumulating all values using the
4036     * given reducer to combine values, or null if none.
4037     *
4038 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4039 jsr166 1.213 * needed for this operation to be executed in parallel
4040 dl 1.137 * @param reducer a commutative associative combining function
4041 jsr166 1.157 * @return the result of accumulating all values
4042 jsr166 1.220 * @since 1.8
4043 dl 1.137 */
4044 dl 1.210 public V reduceValues(long parallelismThreshold,
4045     BiFunction<? super V, ? super V, ? extends V> reducer) {
4046 dl 1.151 if (reducer == null) throw new NullPointerException();
4047 dl 1.210 return new ReduceValuesTask<K,V>
4048     (null, batchFor(parallelismThreshold), 0, 0, table,
4049     null, reducer).invoke();
4050 dl 1.137 }
4051 dl 1.119
4052 dl 1.137 /**
4053     * Returns the result of accumulating the given transformation
4054     * of all values using the given reducer to combine values, or
4055     * null if none.
4056     *
4057 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4058 jsr166 1.213 * needed for this operation to be executed in parallel
4059 dl 1.137 * @param transformer a function returning the transformation
4060 jsr166 1.169 * for an element, or null if there is no transformation (in
4061 jsr166 1.172 * which case it is not combined)
4062 dl 1.137 * @param reducer a commutative associative combining function
4063 jsr166 1.237 * @param <U> the return type of the transformer
4064 dl 1.137 * @return the result of accumulating the given transformation
4065     * of all values
4066 jsr166 1.220 * @since 1.8
4067 dl 1.137 */
4068 dl 1.210 public <U> U reduceValues(long parallelismThreshold,
4069     Function<? super V, ? extends U> transformer,
4070     BiFunction<? super U, ? super U, ? extends U> reducer) {
4071 dl 1.151 if (transformer == null || reducer == null)
4072     throw new NullPointerException();
4073 dl 1.210 return new MapReduceValuesTask<K,V,U>
4074     (null, batchFor(parallelismThreshold), 0, 0, table,
4075     null, transformer, reducer).invoke();
4076 dl 1.137 }
4077 dl 1.119
4078 dl 1.137 /**
4079     * Returns the result of accumulating the given transformation
4080     * of all values using the given reducer to combine values,
4081     * and the given basis as an identity value.
4082     *
4083 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4084 jsr166 1.213 * needed for this operation to be executed in parallel
4085 dl 1.137 * @param transformer a function returning the transformation
4086     * for an element
4087     * @param basis the identity (initial default value) for the reduction
4088     * @param reducer a commutative associative combining function
4089     * @return the result of accumulating the given transformation
4090     * of all values
4091 jsr166 1.220 * @since 1.8
4092 dl 1.137 */
4093 dl 1.210 public double reduceValuesToDouble(long parallelismThreshold,
4094     ToDoubleFunction<? super V> transformer,
4095     double basis,
4096     DoubleBinaryOperator reducer) {
4097 dl 1.151 if (transformer == null || reducer == null)
4098     throw new NullPointerException();
4099 dl 1.210 return new MapReduceValuesToDoubleTask<K,V>
4100     (null, batchFor(parallelismThreshold), 0, 0, table,
4101     null, transformer, basis, reducer).invoke();
4102 dl 1.137 }
4103 dl 1.119
4104 dl 1.137 /**
4105     * Returns the result of accumulating the given transformation
4106     * of all values using the given reducer to combine values,
4107     * and the given basis as an identity value.
4108     *
4109 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4110 jsr166 1.213 * needed for this operation to be executed in parallel
4111 dl 1.137 * @param transformer a function returning the transformation
4112     * for an element
4113     * @param basis the identity (initial default value) for the reduction
4114     * @param reducer a commutative associative combining function
4115     * @return the result of accumulating the given transformation
4116     * of all values
4117 jsr166 1.220 * @since 1.8
4118 dl 1.137 */
4119 dl 1.210 public long reduceValuesToLong(long parallelismThreshold,
4120     ToLongFunction<? super V> transformer,
4121     long basis,
4122     LongBinaryOperator reducer) {
4123 dl 1.151 if (transformer == null || reducer == null)
4124     throw new NullPointerException();
4125 dl 1.210 return new MapReduceValuesToLongTask<K,V>
4126     (null, batchFor(parallelismThreshold), 0, 0, table,
4127     null, transformer, basis, reducer).invoke();
4128 dl 1.137 }
4129 dl 1.119
4130 dl 1.137 /**
4131     * Returns the result of accumulating the given transformation
4132     * of all values using the given reducer to combine values,
4133     * and the given basis as an identity value.
4134     *
4135 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4136 jsr166 1.213 * needed for this operation to be executed in parallel
4137 dl 1.137 * @param transformer a function returning the transformation
4138     * for an element
4139     * @param basis the identity (initial default value) for the reduction
4140     * @param reducer a commutative associative combining function
4141     * @return the result of accumulating the given transformation
4142     * of all values
4143 jsr166 1.220 * @since 1.8
4144 dl 1.137 */
4145 dl 1.210 public int reduceValuesToInt(long parallelismThreshold,
4146     ToIntFunction<? super V> transformer,
4147     int basis,
4148     IntBinaryOperator reducer) {
4149 dl 1.151 if (transformer == null || reducer == null)
4150     throw new NullPointerException();
4151 dl 1.210 return new MapReduceValuesToIntTask<K,V>
4152     (null, batchFor(parallelismThreshold), 0, 0, table,
4153     null, transformer, basis, reducer).invoke();
4154 dl 1.137 }
4155 dl 1.119
4156 dl 1.137 /**
4157     * Performs the given action for each entry.
4158     *
4159 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4160 jsr166 1.213 * needed for this operation to be executed in parallel
4161 dl 1.137 * @param action the action
4162 jsr166 1.220 * @since 1.8
4163 dl 1.137 */
4164 dl 1.210 public void forEachEntry(long parallelismThreshold,
4165     Consumer<? super Map.Entry<K,V>> action) {
4166 dl 1.151 if (action == null) throw new NullPointerException();
4167 dl 1.210 new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
4168     action).invoke();
4169 dl 1.137 }
4170 dl 1.119
4171 dl 1.137 /**
4172     * Performs the given action for each non-null transformation
4173     * of each entry.
4174     *
4175 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4176 jsr166 1.213 * needed for this operation to be executed in parallel
4177 dl 1.137 * @param transformer a function returning the transformation
4178 jsr166 1.169 * for an element, or null if there is no transformation (in
4179 jsr166 1.172 * which case the action is not applied)
4180 dl 1.137 * @param action the action
4181 jsr166 1.237 * @param <U> the return type of the transformer
4182 jsr166 1.220 * @since 1.8
4183 dl 1.137 */
4184 dl 1.210 public <U> void forEachEntry(long parallelismThreshold,
4185     Function<Map.Entry<K,V>, ? extends U> transformer,
4186     Consumer<? super U> action) {
4187 dl 1.151 if (transformer == null || action == null)
4188     throw new NullPointerException();
4189 dl 1.210 new ForEachTransformedEntryTask<K,V,U>
4190     (null, batchFor(parallelismThreshold), 0, 0, table,
4191     transformer, action).invoke();
4192 dl 1.137 }
4193 dl 1.119
4194 dl 1.137 /**
4195     * Returns a non-null result from applying the given search
4196 dl 1.210 * function on each entry, or null if none. Upon success,
4197     * further element processing is suppressed and the results of
4198     * any other parallel invocations of the search function are
4199     * ignored.
4200 dl 1.137 *
4201 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4202 jsr166 1.213 * needed for this operation to be executed in parallel
4203 dl 1.137 * @param searchFunction a function returning a non-null
4204     * result on success, else null
4205 jsr166 1.237 * @param <U> the return type of the search function
4206 dl 1.137 * @return a non-null result from applying the given search
4207     * function on each entry, or null if none
4208 jsr166 1.220 * @since 1.8
4209 dl 1.137 */
4210 dl 1.210 public <U> U searchEntries(long parallelismThreshold,
4211     Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4212 dl 1.151 if (searchFunction == null) throw new NullPointerException();
4213 dl 1.210 return new SearchEntriesTask<K,V,U>
4214     (null, batchFor(parallelismThreshold), 0, 0, table,
4215     searchFunction, new AtomicReference<U>()).invoke();
4216 dl 1.137 }
4217 dl 1.119
4218 dl 1.137 /**
4219     * Returns the result of accumulating all entries using the
4220     * given reducer to combine values, or null if none.
4221     *
4222 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4223 jsr166 1.213 * needed for this operation to be executed in parallel
4224 dl 1.137 * @param reducer a commutative associative combining function
4225     * @return the result of accumulating all entries
4226 jsr166 1.220 * @since 1.8
4227 dl 1.137 */
4228 dl 1.210 public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
4229     BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4230 dl 1.151 if (reducer == null) throw new NullPointerException();
4231 dl 1.210 return new ReduceEntriesTask<K,V>
4232     (null, batchFor(parallelismThreshold), 0, 0, table,
4233     null, reducer).invoke();
4234 dl 1.137 }
4235 dl 1.119
4236 dl 1.137 /**
4237     * Returns the result of accumulating the given transformation
4238     * of all entries using the given reducer to combine values,
4239     * or null if none.
4240     *
4241 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4242 jsr166 1.213 * needed for this operation to be executed in parallel
4243 dl 1.137 * @param transformer a function returning the transformation
4244 jsr166 1.169 * for an element, or null if there is no transformation (in
4245 jsr166 1.172 * which case it is not combined)
4246 dl 1.137 * @param reducer a commutative associative combining function
4247 jsr166 1.237 * @param <U> the return type of the transformer
4248 dl 1.137 * @return the result of accumulating the given transformation
4249     * of all entries
4250 jsr166 1.220 * @since 1.8
4251 dl 1.137 */
4252 dl 1.210 public <U> U reduceEntries(long parallelismThreshold,
4253     Function<Map.Entry<K,V>, ? extends U> transformer,
4254     BiFunction<? super U, ? super U, ? extends U> reducer) {
4255 dl 1.151 if (transformer == null || reducer == null)
4256     throw new NullPointerException();
4257 dl 1.210 return new MapReduceEntriesTask<K,V,U>
4258     (null, batchFor(parallelismThreshold), 0, 0, table,
4259     null, transformer, reducer).invoke();
4260 dl 1.137 }
4261 dl 1.119
4262 dl 1.137 /**
4263     * Returns the result of accumulating the given transformation
4264     * of all entries using the given reducer to combine values,
4265     * and the given basis as an identity value.
4266     *
4267 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4268 jsr166 1.213 * needed for this operation to be executed in parallel
4269 dl 1.137 * @param transformer a function returning the transformation
4270     * for an element
4271     * @param basis the identity (initial default value) for the reduction
4272     * @param reducer a commutative associative combining function
4273     * @return the result of accumulating the given transformation
4274     * of all entries
4275 jsr166 1.220 * @since 1.8
4276 dl 1.137 */
4277 dl 1.210 public double reduceEntriesToDouble(long parallelismThreshold,
4278     ToDoubleFunction<Map.Entry<K,V>> transformer,
4279     double basis,
4280     DoubleBinaryOperator reducer) {
4281 dl 1.151 if (transformer == null || reducer == null)
4282     throw new NullPointerException();
4283 dl 1.210 return new MapReduceEntriesToDoubleTask<K,V>
4284     (null, batchFor(parallelismThreshold), 0, 0, table,
4285     null, transformer, basis, reducer).invoke();
4286 dl 1.137 }
4287 dl 1.119
4288 dl 1.137 /**
4289     * Returns the result of accumulating the given transformation
4290     * of all entries using the given reducer to combine values,
4291     * and the given basis as an identity value.
4292     *
4293 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4294 jsr166 1.213 * needed for this operation to be executed in parallel
4295 dl 1.137 * @param transformer a function returning the transformation
4296     * for an element
4297     * @param basis the identity (initial default value) for the reduction
4298     * @param reducer a commutative associative combining function
4299 jsr166 1.157 * @return the result of accumulating the given transformation
4300 dl 1.137 * of all entries
4301 jsr166 1.221 * @since 1.8
4302 dl 1.137 */
4303 dl 1.210 public long reduceEntriesToLong(long parallelismThreshold,
4304     ToLongFunction<Map.Entry<K,V>> transformer,
4305     long basis,
4306     LongBinaryOperator reducer) {
4307 dl 1.151 if (transformer == null || reducer == null)
4308     throw new NullPointerException();
4309 dl 1.210 return new MapReduceEntriesToLongTask<K,V>
4310     (null, batchFor(parallelismThreshold), 0, 0, table,
4311     null, transformer, basis, reducer).invoke();
4312 dl 1.137 }
4313 dl 1.119
4314 dl 1.137 /**
4315     * Returns the result of accumulating the given transformation
4316     * of all entries using the given reducer to combine values,
4317     * and the given basis as an identity value.
4318     *
4319 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
4320 jsr166 1.213 * needed for this operation to be executed in parallel
4321 dl 1.137 * @param transformer a function returning the transformation
4322     * for an element
4323     * @param basis the identity (initial default value) for the reduction
4324     * @param reducer a commutative associative combining function
4325     * @return the result of accumulating the given transformation
4326     * of all entries
4327 jsr166 1.221 * @since 1.8
4328 dl 1.137 */
4329 dl 1.210 public int reduceEntriesToInt(long parallelismThreshold,
4330     ToIntFunction<Map.Entry<K,V>> transformer,
4331     int basis,
4332     IntBinaryOperator reducer) {
4333 dl 1.151 if (transformer == null || reducer == null)
4334     throw new NullPointerException();
4335 dl 1.210 return new MapReduceEntriesToIntTask<K,V>
4336     (null, batchFor(parallelismThreshold), 0, 0, table,
4337     null, transformer, basis, reducer).invoke();
4338 dl 1.119 }
4339    
4340 dl 1.209
4341 dl 1.210 /* ----------------Views -------------- */
4342 dl 1.142
4343     /**
4344 dl 1.210 * Base class for views.
4345 dl 1.142 */
4346 dl 1.210 abstract static class CollectionView<K,V,E>
4347     implements Collection<E>, java.io.Serializable {
4348     private static final long serialVersionUID = 7249069246763182397L;
4349     final ConcurrentHashMap<K,V> map;
4350     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4351    
4352     /**
4353     * Returns the map backing this view.
4354     *
4355     * @return the map backing this view
4356     */
4357     public ConcurrentHashMap<K,V> getMap() { return map; }
4358 dl 1.142
4359 dl 1.210 /**
4360     * Removes all of the elements from this view, by removing all
4361     * the mappings from the map backing this view.
4362 jsr166 1.184 */
4363     public final void clear() { map.clear(); }
4364     public final int size() { return map.size(); }
4365     public final boolean isEmpty() { return map.isEmpty(); }
4366 dl 1.151
4367     // implementations below rely on concrete classes supplying these
4368 jsr166 1.184 // abstract methods
4369     /**
4370 jsr166 1.242 * Returns an iterator over the elements in this collection.
4371     *
4372     * <p>The returned iterator is
4373     * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
4374     *
4375     * @return an iterator over the elements in this collection
4376 jsr166 1.184 */
4377     public abstract Iterator<E> iterator();
4378 jsr166 1.165 public abstract boolean contains(Object o);
4379     public abstract boolean remove(Object o);
4380 dl 1.151
4381     private static final String oomeMsg = "Required array size too large";
4382 dl 1.142
4383     public final Object[] toArray() {
4384     long sz = map.mappingCount();
4385 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4386 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4387     int n = (int)sz;
4388     Object[] r = new Object[n];
4389     int i = 0;
4390 jsr166 1.184 for (E e : this) {
4391 dl 1.142 if (i == n) {
4392     if (n >= MAX_ARRAY_SIZE)
4393     throw new OutOfMemoryError(oomeMsg);
4394     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4395     n = MAX_ARRAY_SIZE;
4396     else
4397     n += (n >>> 1) + 1;
4398     r = Arrays.copyOf(r, n);
4399     }
4400 jsr166 1.184 r[i++] = e;
4401 dl 1.142 }
4402     return (i == n) ? r : Arrays.copyOf(r, i);
4403     }
4404    
4405 dl 1.222 @SuppressWarnings("unchecked")
4406 jsr166 1.184 public final <T> T[] toArray(T[] a) {
4407 dl 1.142 long sz = map.mappingCount();
4408 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4409 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4410     int m = (int)sz;
4411     T[] r = (a.length >= m) ? a :
4412     (T[])java.lang.reflect.Array
4413     .newInstance(a.getClass().getComponentType(), m);
4414     int n = r.length;
4415     int i = 0;
4416 jsr166 1.184 for (E e : this) {
4417 dl 1.142 if (i == n) {
4418     if (n >= MAX_ARRAY_SIZE)
4419     throw new OutOfMemoryError(oomeMsg);
4420     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4421     n = MAX_ARRAY_SIZE;
4422     else
4423     n += (n >>> 1) + 1;
4424     r = Arrays.copyOf(r, n);
4425     }
4426 jsr166 1.184 r[i++] = (T)e;
4427 dl 1.142 }
4428     if (a == r && i < n) {
4429     r[i] = null; // null-terminate
4430     return r;
4431     }
4432     return (i == n) ? r : Arrays.copyOf(r, i);
4433     }
4434    
4435 jsr166 1.184 /**
4436     * Returns a string representation of this collection.
4437     * The string representation consists of the string representations
4438     * of the collection's elements in the order they are returned by
4439     * its iterator, enclosed in square brackets ({@code "[]"}).
4440     * Adjacent elements are separated by the characters {@code ", "}
4441     * (comma and space). Elements are converted to strings as by
4442     * {@link String#valueOf(Object)}.
4443     *
4444     * @return a string representation of this collection
4445     */
4446 dl 1.142 public final String toString() {
4447     StringBuilder sb = new StringBuilder();
4448     sb.append('[');
4449 jsr166 1.184 Iterator<E> it = iterator();
4450 dl 1.142 if (it.hasNext()) {
4451     for (;;) {
4452     Object e = it.next();
4453     sb.append(e == this ? "(this Collection)" : e);
4454     if (!it.hasNext())
4455     break;
4456     sb.append(',').append(' ');
4457     }
4458     }
4459     return sb.append(']').toString();
4460     }
4461    
4462     public final boolean containsAll(Collection<?> c) {
4463     if (c != this) {
4464 jsr166 1.184 for (Object e : c) {
4465 dl 1.142 if (e == null || !contains(e))
4466     return false;
4467     }
4468     }
4469     return true;
4470     }
4471    
4472     public final boolean removeAll(Collection<?> c) {
4473 dl 1.251 if (c == null) throw new NullPointerException();
4474 dl 1.142 boolean modified = false;
4475 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4476 dl 1.142 if (c.contains(it.next())) {
4477     it.remove();
4478     modified = true;
4479     }
4480     }
4481     return modified;
4482     }
4483    
4484     public final boolean retainAll(Collection<?> c) {
4485 dl 1.251 if (c == null) throw new NullPointerException();
4486 dl 1.142 boolean modified = false;
4487 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4488 dl 1.142 if (!c.contains(it.next())) {
4489     it.remove();
4490     modified = true;
4491     }
4492     }
4493     return modified;
4494     }
4495    
4496     }
4497    
4498     /**
4499     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4500     * which additions may optionally be enabled by mapping to a
4501 jsr166 1.185 * common value. This class cannot be directly instantiated.
4502     * See {@link #keySet() keySet()},
4503     * {@link #keySet(Object) keySet(V)},
4504     * {@link #newKeySet() newKeySet()},
4505     * {@link #newKeySet(int) newKeySet(int)}.
4506 jsr166 1.221 *
4507     * @since 1.8
4508 dl 1.142 */
4509 dl 1.210 public static class KeySetView<K,V> extends CollectionView<K,V,K>
4510     implements Set<K>, java.io.Serializable {
4511 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4512     private final V value;
4513 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4514 dl 1.142 super(map);
4515     this.value = value;
4516     }
4517    
4518     /**
4519     * Returns the default mapped value for additions,
4520     * or {@code null} if additions are not supported.
4521     *
4522     * @return the default mapped value for additions, or {@code null}
4523 jsr166 1.172 * if not supported
4524 dl 1.142 */
4525     public V getMappedValue() { return value; }
4526    
4527 jsr166 1.184 /**
4528     * {@inheritDoc}
4529     * @throws NullPointerException if the specified key is null
4530     */
4531     public boolean contains(Object o) { return map.containsKey(o); }
4532 dl 1.142
4533 jsr166 1.184 /**
4534     * Removes the key from this map view, by removing the key (and its
4535     * corresponding value) from the backing map. This method does
4536     * nothing if the key is not in the map.
4537     *
4538     * @param o the key to be removed from the backing map
4539     * @return {@code true} if the backing map contained the specified key
4540     * @throws NullPointerException if the specified key is null
4541     */
4542     public boolean remove(Object o) { return map.remove(o) != null; }
4543    
4544     /**
4545     * @return an iterator over the keys of the backing map
4546     */
4547 dl 1.210 public Iterator<K> iterator() {
4548     Node<K,V>[] t;
4549     ConcurrentHashMap<K,V> m = map;
4550     int f = (t = m.table) == null ? 0 : t.length;
4551     return new KeyIterator<K,V>(t, f, 0, f, m);
4552     }
4553 dl 1.142
4554     /**
4555 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4556     * the default mapped value in the backing map, if defined.
4557 dl 1.142 *
4558 jsr166 1.184 * @param e key to be added
4559     * @return {@code true} if this set changed as a result of the call
4560     * @throws NullPointerException if the specified key is null
4561     * @throws UnsupportedOperationException if no default mapped value
4562     * for additions was provided
4563 dl 1.142 */
4564     public boolean add(K e) {
4565     V v;
4566     if ((v = value) == null)
4567     throw new UnsupportedOperationException();
4568 dl 1.222 return map.putVal(e, v, true) == null;
4569 dl 1.142 }
4570 jsr166 1.184
4571     /**
4572     * Adds all of the elements in the specified collection to this set,
4573     * as if by calling {@link #add} on each one.
4574     *
4575     * @param c the elements to be inserted into this set
4576     * @return {@code true} if this set changed as a result of the call
4577     * @throws NullPointerException if the collection or any of its
4578     * elements are {@code null}
4579     * @throws UnsupportedOperationException if no default mapped value
4580     * for additions was provided
4581     */
4582 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4583     boolean added = false;
4584     V v;
4585     if ((v = value) == null)
4586     throw new UnsupportedOperationException();
4587     for (K e : c) {
4588 dl 1.222 if (map.putVal(e, v, true) == null)
4589 dl 1.142 added = true;
4590     }
4591     return added;
4592     }
4593 dl 1.153
4594 dl 1.210 public int hashCode() {
4595     int h = 0;
4596     for (K e : this)
4597     h += e.hashCode();
4598     return h;
4599 dl 1.191 }
4600    
4601 dl 1.210 public boolean equals(Object o) {
4602     Set<?> c;
4603     return ((o instanceof Set) &&
4604     ((c = (Set<?>)o) == this ||
4605     (containsAll(c) && c.containsAll(this))));
4606 dl 1.119 }
4607 jsr166 1.125
4608 dl 1.210 public Spliterator<K> spliterator() {
4609     Node<K,V>[] t;
4610     ConcurrentHashMap<K,V> m = map;
4611     long n = m.sumCount();
4612     int f = (t = m.table) == null ? 0 : t.length;
4613     return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4614 dl 1.119 }
4615    
4616 dl 1.210 public void forEach(Consumer<? super K> action) {
4617     if (action == null) throw new NullPointerException();
4618     Node<K,V>[] t;
4619     if ((t = map.table) != null) {
4620     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4621     for (Node<K,V> p; (p = it.advance()) != null; )
4622 dl 1.222 action.accept(p.key);
4623 dl 1.210 }
4624 dl 1.119 }
4625 dl 1.210 }
4626 dl 1.119
4627 dl 1.210 /**
4628     * A view of a ConcurrentHashMap as a {@link Collection} of
4629     * values, in which additions are disabled. This class cannot be
4630     * directly instantiated. See {@link #values()}.
4631     */
4632     static final class ValuesView<K,V> extends CollectionView<K,V,V>
4633     implements Collection<V>, java.io.Serializable {
4634     private static final long serialVersionUID = 2249069246763182397L;
4635     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4636     public final boolean contains(Object o) {
4637     return map.containsValue(o);
4638 dl 1.119 }
4639    
4640 dl 1.210 public final boolean remove(Object o) {
4641     if (o != null) {
4642     for (Iterator<V> it = iterator(); it.hasNext();) {
4643     if (o.equals(it.next())) {
4644     it.remove();
4645     return true;
4646     }
4647     }
4648     }
4649     return false;
4650 dl 1.119 }
4651    
4652 dl 1.210 public final Iterator<V> iterator() {
4653     ConcurrentHashMap<K,V> m = map;
4654     Node<K,V>[] t;
4655     int f = (t = m.table) == null ? 0 : t.length;
4656     return new ValueIterator<K,V>(t, f, 0, f, m);
4657 dl 1.119 }
4658    
4659 dl 1.210 public final boolean add(V e) {
4660     throw new UnsupportedOperationException();
4661     }
4662     public final boolean addAll(Collection<? extends V> c) {
4663     throw new UnsupportedOperationException();
4664 dl 1.119 }
4665    
4666 dl 1.210 public Spliterator<V> spliterator() {
4667     Node<K,V>[] t;
4668     ConcurrentHashMap<K,V> m = map;
4669     long n = m.sumCount();
4670     int f = (t = m.table) == null ? 0 : t.length;
4671     return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4672 dl 1.119 }
4673    
4674 dl 1.210 public void forEach(Consumer<? super V> action) {
4675     if (action == null) throw new NullPointerException();
4676     Node<K,V>[] t;
4677     if ((t = map.table) != null) {
4678     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4679     for (Node<K,V> p; (p = it.advance()) != null; )
4680     action.accept(p.val);
4681     }
4682 dl 1.119 }
4683 dl 1.210 }
4684    
4685     /**
4686     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4687     * entries. This class cannot be directly instantiated. See
4688     * {@link #entrySet()}.
4689     */
4690     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4691     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4692     private static final long serialVersionUID = 2249069246763182397L;
4693     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4694 dl 1.119
4695 dl 1.210 public boolean contains(Object o) {
4696     Object k, v, r; Map.Entry<?,?> e;
4697     return ((o instanceof Map.Entry) &&
4698     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4699     (r = map.get(k)) != null &&
4700     (v = e.getValue()) != null &&
4701     (v == r || v.equals(r)));
4702 dl 1.119 }
4703    
4704 dl 1.210 public boolean remove(Object o) {
4705     Object k, v; Map.Entry<?,?> e;
4706     return ((o instanceof Map.Entry) &&
4707     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4708     (v = e.getValue()) != null &&
4709     map.remove(k, v));
4710 dl 1.119 }
4711    
4712     /**
4713 dl 1.210 * @return an iterator over the entries of the backing map
4714 dl 1.119 */
4715 dl 1.210 public Iterator<Map.Entry<K,V>> iterator() {
4716     ConcurrentHashMap<K,V> m = map;
4717     Node<K,V>[] t;
4718     int f = (t = m.table) == null ? 0 : t.length;
4719     return new EntryIterator<K,V>(t, f, 0, f, m);
4720 dl 1.119 }
4721    
4722 dl 1.210 public boolean add(Entry<K,V> e) {
4723 dl 1.222 return map.putVal(e.getKey(), e.getValue(), false) == null;
4724 dl 1.119 }
4725    
4726 dl 1.210 public boolean addAll(Collection<? extends Entry<K,V>> c) {
4727     boolean added = false;
4728     for (Entry<K,V> e : c) {
4729     if (add(e))
4730     added = true;
4731     }
4732     return added;
4733 dl 1.119 }
4734    
4735 dl 1.210 public final int hashCode() {
4736     int h = 0;
4737     Node<K,V>[] t;
4738     if ((t = map.table) != null) {
4739     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4740     for (Node<K,V> p; (p = it.advance()) != null; ) {
4741     h += p.hashCode();
4742     }
4743     }
4744     return h;
4745 dl 1.119 }
4746    
4747 dl 1.210 public final boolean equals(Object o) {
4748     Set<?> c;
4749     return ((o instanceof Set) &&
4750     ((c = (Set<?>)o) == this ||
4751     (containsAll(c) && c.containsAll(this))));
4752 dl 1.119 }
4753    
4754 dl 1.210 public Spliterator<Map.Entry<K,V>> spliterator() {
4755     Node<K,V>[] t;
4756     ConcurrentHashMap<K,V> m = map;
4757     long n = m.sumCount();
4758     int f = (t = m.table) == null ? 0 : t.length;
4759     return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4760 dl 1.119 }
4761    
4762 dl 1.210 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4763     if (action == null) throw new NullPointerException();
4764     Node<K,V>[] t;
4765     if ((t = map.table) != null) {
4766     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4767     for (Node<K,V> p; (p = it.advance()) != null; )
4768 dl 1.222 action.accept(new MapEntry<K,V>(p.key, p.val, map));
4769 dl 1.210 }
4770 dl 1.119 }
4771    
4772 dl 1.210 }
4773    
4774     // -------------------------------------------------------
4775 dl 1.119
4776 dl 1.210 /**
4777     * Base class for bulk tasks. Repeats some fields and code from
4778     * class Traverser, because we need to subclass CountedCompleter.
4779     */
4780 dl 1.243 @SuppressWarnings("serial")
4781 jsr166 1.211 abstract static class BulkTask<K,V,R> extends CountedCompleter<R> {
4782 dl 1.210 Node<K,V>[] tab; // same as Traverser
4783     Node<K,V> next;
4784 dl 1.246 TableStack<K,V> stack, spare;
4785 dl 1.210 int index;
4786     int baseIndex;
4787     int baseLimit;
4788     final int baseSize;
4789     int batch; // split control
4790    
4791     BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4792     super(par);
4793     this.batch = b;
4794     this.index = this.baseIndex = i;
4795     if ((this.tab = t) == null)
4796     this.baseSize = this.baseLimit = 0;
4797     else if (par == null)
4798     this.baseSize = this.baseLimit = t.length;
4799     else {
4800     this.baseLimit = f;
4801     this.baseSize = par.baseSize;
4802     }
4803 dl 1.119 }
4804    
4805     /**
4806 dl 1.210 * Same as Traverser version
4807 dl 1.119 */
4808 dl 1.210 final Node<K,V> advance() {
4809     Node<K,V> e;
4810     if ((e = next) != null)
4811     e = e.next;
4812     for (;;) {
4813 dl 1.246 Node<K,V>[] t; int i, n;
4814 dl 1.210 if (e != null)
4815     return next = e;
4816     if (baseIndex >= baseLimit || (t = tab) == null ||
4817     (n = t.length) <= (i = index) || i < 0)
4818     return next = null;
4819 dl 1.246 if ((e = tabAt(t, i)) != null && e.hash < 0) {
4820 dl 1.222 if (e instanceof ForwardingNode) {
4821     tab = ((ForwardingNode<K,V>)e).nextTable;
4822 dl 1.210 e = null;
4823 dl 1.246 pushState(t, i, n);
4824 dl 1.210 continue;
4825     }
4826 dl 1.222 else if (e instanceof TreeBin)
4827     e = ((TreeBin<K,V>)e).first;
4828     else
4829     e = null;
4830 dl 1.210 }
4831 dl 1.246 if (stack != null)
4832     recoverState(n);
4833     else if ((index = i + baseSize) >= n)
4834     index = ++baseIndex;
4835     }
4836     }
4837    
4838     private void pushState(Node<K,V>[] t, int i, int n) {
4839     TableStack<K,V> s = spare;
4840     if (s != null)
4841     spare = s.next;
4842     else
4843     s = new TableStack<K,V>();
4844     s.tab = t;
4845     s.length = n;
4846     s.index = i;
4847     s.next = stack;
4848     stack = s;
4849     }
4850    
4851     private void recoverState(int n) {
4852     TableStack<K,V> s; int len;
4853     while ((s = stack) != null && (index += (len = s.length)) >= n) {
4854     n = len;
4855     index = s.index;
4856     tab = s.tab;
4857     s.tab = null;
4858     TableStack<K,V> next = s.next;
4859     s.next = spare; // save for reuse
4860     stack = next;
4861     spare = s;
4862 dl 1.210 }
4863 dl 1.246 if (s == null && (index += baseSize) >= n)
4864     index = ++baseIndex;
4865 dl 1.119 }
4866     }
4867    
4868     /*
4869     * Task classes. Coded in a regular but ugly format/style to
4870     * simplify checks that each variant differs in the right way from
4871 dl 1.149 * others. The null screenings exist because compilers cannot tell
4872     * that we've already null-checked task arguments, so we force
4873     * simplest hoisted bypass to help avoid convoluted traps.
4874 dl 1.119 */
4875 dl 1.222 @SuppressWarnings("serial")
4876 dl 1.210 static final class ForEachKeyTask<K,V>
4877     extends BulkTask<K,V,Void> {
4878 dl 1.171 final Consumer<? super K> action;
4879 dl 1.119 ForEachKeyTask
4880 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4881 dl 1.171 Consumer<? super K> action) {
4882 dl 1.210 super(p, b, i, f, t);
4883 dl 1.119 this.action = action;
4884     }
4885 jsr166 1.168 public final void compute() {
4886 dl 1.171 final Consumer<? super K> action;
4887 dl 1.149 if ((action = this.action) != null) {
4888 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4889     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4890     addToPendingCount(1);
4891     new ForEachKeyTask<K,V>
4892     (this, batch >>>= 1, baseLimit = h, f, tab,
4893     action).fork();
4894     }
4895     for (Node<K,V> p; (p = advance()) != null;)
4896 dl 1.222 action.accept(p.key);
4897 dl 1.149 propagateCompletion();
4898     }
4899 dl 1.119 }
4900     }
4901    
4902 dl 1.222 @SuppressWarnings("serial")
4903 dl 1.210 static final class ForEachValueTask<K,V>
4904     extends BulkTask<K,V,Void> {
4905 dl 1.171 final Consumer<? super V> action;
4906 dl 1.119 ForEachValueTask
4907 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4908 dl 1.171 Consumer<? super V> action) {
4909 dl 1.210 super(p, b, i, f, t);
4910 dl 1.119 this.action = action;
4911     }
4912 jsr166 1.168 public final void compute() {
4913 dl 1.171 final Consumer<? super V> action;
4914 dl 1.149 if ((action = this.action) != null) {
4915 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4916     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4917     addToPendingCount(1);
4918     new ForEachValueTask<K,V>
4919     (this, batch >>>= 1, baseLimit = h, f, tab,
4920     action).fork();
4921     }
4922     for (Node<K,V> p; (p = advance()) != null;)
4923     action.accept(p.val);
4924 dl 1.149 propagateCompletion();
4925     }
4926 dl 1.119 }
4927     }
4928    
4929 dl 1.222 @SuppressWarnings("serial")
4930 dl 1.210 static final class ForEachEntryTask<K,V>
4931     extends BulkTask<K,V,Void> {
4932 dl 1.171 final Consumer<? super Entry<K,V>> action;
4933 dl 1.119 ForEachEntryTask
4934 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4935 dl 1.171 Consumer<? super Entry<K,V>> action) {
4936 dl 1.210 super(p, b, i, f, t);
4937 dl 1.119 this.action = action;
4938     }
4939 jsr166 1.168 public final void compute() {
4940 dl 1.171 final Consumer<? super Entry<K,V>> action;
4941 dl 1.149 if ((action = this.action) != null) {
4942 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4943     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4944     addToPendingCount(1);
4945     new ForEachEntryTask<K,V>
4946     (this, batch >>>= 1, baseLimit = h, f, tab,
4947     action).fork();
4948     }
4949     for (Node<K,V> p; (p = advance()) != null; )
4950     action.accept(p);
4951 dl 1.149 propagateCompletion();
4952     }
4953 dl 1.119 }
4954     }
4955    
4956 dl 1.222 @SuppressWarnings("serial")
4957 dl 1.210 static final class ForEachMappingTask<K,V>
4958     extends BulkTask<K,V,Void> {
4959 dl 1.171 final BiConsumer<? super K, ? super V> action;
4960 dl 1.119 ForEachMappingTask
4961 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4962 dl 1.171 BiConsumer<? super K,? super V> action) {
4963 dl 1.210 super(p, b, i, f, t);
4964 dl 1.119 this.action = action;
4965     }
4966 jsr166 1.168 public final void compute() {
4967 dl 1.171 final BiConsumer<? super K, ? super V> action;
4968 dl 1.149 if ((action = this.action) != null) {
4969 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4970     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4971     addToPendingCount(1);
4972     new ForEachMappingTask<K,V>
4973     (this, batch >>>= 1, baseLimit = h, f, tab,
4974     action).fork();
4975     }
4976     for (Node<K,V> p; (p = advance()) != null; )
4977 dl 1.222 action.accept(p.key, p.val);
4978 dl 1.149 propagateCompletion();
4979     }
4980 dl 1.119 }
4981     }
4982    
4983 dl 1.222 @SuppressWarnings("serial")
4984 dl 1.210 static final class ForEachTransformedKeyTask<K,V,U>
4985     extends BulkTask<K,V,Void> {
4986 dl 1.153 final Function<? super K, ? extends U> transformer;
4987 dl 1.171 final Consumer<? super U> action;
4988 dl 1.119 ForEachTransformedKeyTask
4989 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4990 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4991 dl 1.210 super(p, b, i, f, t);
4992 dl 1.146 this.transformer = transformer; this.action = action;
4993     }
4994 jsr166 1.168 public final void compute() {
4995 dl 1.153 final Function<? super K, ? extends U> transformer;
4996 dl 1.171 final Consumer<? super U> action;
4997 dl 1.149 if ((transformer = this.transformer) != null &&
4998     (action = this.action) != null) {
4999 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5000     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5001     addToPendingCount(1);
5002 dl 1.149 new ForEachTransformedKeyTask<K,V,U>
5003 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5004     transformer, action).fork();
5005     }
5006     for (Node<K,V> p; (p = advance()) != null; ) {
5007     U u;
5008 dl 1.222 if ((u = transformer.apply(p.key)) != null)
5009 dl 1.153 action.accept(u);
5010 dl 1.149 }
5011     propagateCompletion();
5012 dl 1.119 }
5013     }
5014     }
5015    
5016 dl 1.222 @SuppressWarnings("serial")
5017 dl 1.210 static final class ForEachTransformedValueTask<K,V,U>
5018     extends BulkTask<K,V,Void> {
5019 dl 1.153 final Function<? super V, ? extends U> transformer;
5020 dl 1.171 final Consumer<? super U> action;
5021 dl 1.119 ForEachTransformedValueTask
5022 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5023 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5024 dl 1.210 super(p, b, i, f, t);
5025 dl 1.146 this.transformer = transformer; this.action = action;
5026     }
5027 jsr166 1.168 public final void compute() {
5028 dl 1.153 final Function<? super V, ? extends U> transformer;
5029 dl 1.171 final Consumer<? super U> action;
5030 dl 1.149 if ((transformer = this.transformer) != null &&
5031     (action = this.action) != null) {
5032 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5033     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5034     addToPendingCount(1);
5035 dl 1.149 new ForEachTransformedValueTask<K,V,U>
5036 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5037     transformer, action).fork();
5038     }
5039     for (Node<K,V> p; (p = advance()) != null; ) {
5040     U u;
5041     if ((u = transformer.apply(p.val)) != null)
5042 dl 1.153 action.accept(u);
5043 dl 1.149 }
5044     propagateCompletion();
5045 dl 1.119 }
5046     }
5047 tim 1.1 }
5048    
5049 dl 1.222 @SuppressWarnings("serial")
5050 dl 1.210 static final class ForEachTransformedEntryTask<K,V,U>
5051     extends BulkTask<K,V,Void> {
5052 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5053 dl 1.171 final Consumer<? super U> action;
5054 dl 1.119 ForEachTransformedEntryTask
5055 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5056 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5057 dl 1.210 super(p, b, i, f, t);
5058 dl 1.146 this.transformer = transformer; this.action = action;
5059     }
5060 jsr166 1.168 public final void compute() {
5061 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5062 dl 1.171 final Consumer<? super U> action;
5063 dl 1.149 if ((transformer = this.transformer) != null &&
5064     (action = this.action) != null) {
5065 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5066     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5067     addToPendingCount(1);
5068 dl 1.149 new ForEachTransformedEntryTask<K,V,U>
5069 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5070     transformer, action).fork();
5071     }
5072     for (Node<K,V> p; (p = advance()) != null; ) {
5073     U u;
5074     if ((u = transformer.apply(p)) != null)
5075 dl 1.153 action.accept(u);
5076 dl 1.149 }
5077     propagateCompletion();
5078 dl 1.119 }
5079     }
5080 tim 1.1 }
5081    
5082 dl 1.222 @SuppressWarnings("serial")
5083 dl 1.210 static final class ForEachTransformedMappingTask<K,V,U>
5084     extends BulkTask<K,V,Void> {
5085 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5086 dl 1.171 final Consumer<? super U> action;
5087 dl 1.119 ForEachTransformedMappingTask
5088 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5089 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5090 dl 1.171 Consumer<? super U> action) {
5091 dl 1.210 super(p, b, i, f, t);
5092 dl 1.146 this.transformer = transformer; this.action = action;
5093 dl 1.119 }
5094 jsr166 1.168 public final void compute() {
5095 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5096 dl 1.171 final Consumer<? super U> action;
5097 dl 1.149 if ((transformer = this.transformer) != null &&
5098     (action = this.action) != null) {
5099 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5100     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5101     addToPendingCount(1);
5102 dl 1.149 new ForEachTransformedMappingTask<K,V,U>
5103 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5104     transformer, action).fork();
5105     }
5106     for (Node<K,V> p; (p = advance()) != null; ) {
5107     U u;
5108 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
5109 dl 1.153 action.accept(u);
5110 dl 1.149 }
5111     propagateCompletion();
5112 dl 1.119 }
5113     }
5114 tim 1.1 }
5115    
5116 dl 1.222 @SuppressWarnings("serial")
5117 dl 1.210 static final class SearchKeysTask<K,V,U>
5118     extends BulkTask<K,V,U> {
5119 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5120 dl 1.119 final AtomicReference<U> result;
5121     SearchKeysTask
5122 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5123 dl 1.153 Function<? super K, ? extends U> searchFunction,
5124 dl 1.119 AtomicReference<U> result) {
5125 dl 1.210 super(p, b, i, f, t);
5126 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5127     }
5128 dl 1.146 public final U getRawResult() { return result.get(); }
5129 jsr166 1.168 public final void compute() {
5130 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5131 dl 1.146 final AtomicReference<U> result;
5132 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5133     (result = this.result) != null) {
5134 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5135     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5136 dl 1.149 if (result.get() != null)
5137     return;
5138 dl 1.210 addToPendingCount(1);
5139 dl 1.149 new SearchKeysTask<K,V,U>
5140 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5141     searchFunction, result).fork();
5142 dl 1.128 }
5143 dl 1.149 while (result.get() == null) {
5144 dl 1.210 U u;
5145     Node<K,V> p;
5146     if ((p = advance()) == null) {
5147 dl 1.149 propagateCompletion();
5148     break;
5149     }
5150 dl 1.222 if ((u = searchFunction.apply(p.key)) != null) {
5151 dl 1.149 if (result.compareAndSet(null, u))
5152     quietlyCompleteRoot();
5153     break;
5154     }
5155 dl 1.119 }
5156     }
5157     }
5158 tim 1.1 }
5159    
5160 dl 1.222 @SuppressWarnings("serial")
5161 dl 1.210 static final class SearchValuesTask<K,V,U>
5162     extends BulkTask<K,V,U> {
5163 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5164 dl 1.119 final AtomicReference<U> result;
5165     SearchValuesTask
5166 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5167 dl 1.153 Function<? super V, ? extends U> searchFunction,
5168 dl 1.119 AtomicReference<U> result) {
5169 dl 1.210 super(p, b, i, f, t);
5170 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5171     }
5172 dl 1.146 public final U getRawResult() { return result.get(); }
5173 jsr166 1.168 public final void compute() {
5174 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5175 dl 1.146 final AtomicReference<U> result;
5176 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5177     (result = this.result) != null) {
5178 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5179     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5180 dl 1.149 if (result.get() != null)
5181     return;
5182 dl 1.210 addToPendingCount(1);
5183 dl 1.149 new SearchValuesTask<K,V,U>
5184 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5185     searchFunction, result).fork();
5186 dl 1.128 }
5187 dl 1.149 while (result.get() == null) {
5188 dl 1.210 U u;
5189     Node<K,V> p;
5190     if ((p = advance()) == null) {
5191 dl 1.149 propagateCompletion();
5192     break;
5193     }
5194 dl 1.210 if ((u = searchFunction.apply(p.val)) != null) {
5195 dl 1.149 if (result.compareAndSet(null, u))
5196     quietlyCompleteRoot();
5197     break;
5198     }
5199 dl 1.119 }
5200     }
5201     }
5202     }
5203 tim 1.11
5204 dl 1.222 @SuppressWarnings("serial")
5205 dl 1.210 static final class SearchEntriesTask<K,V,U>
5206     extends BulkTask<K,V,U> {
5207 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5208 dl 1.119 final AtomicReference<U> result;
5209     SearchEntriesTask
5210 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5211 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
5212 dl 1.119 AtomicReference<U> result) {
5213 dl 1.210 super(p, b, i, f, t);
5214 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5215     }
5216 dl 1.146 public final U getRawResult() { return result.get(); }
5217 jsr166 1.168 public final void compute() {
5218 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5219 dl 1.146 final AtomicReference<U> result;
5220 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5221     (result = this.result) != null) {
5222 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5223     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5224 dl 1.149 if (result.get() != null)
5225     return;
5226 dl 1.210 addToPendingCount(1);
5227 dl 1.149 new SearchEntriesTask<K,V,U>
5228 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5229     searchFunction, result).fork();
5230 dl 1.128 }
5231 dl 1.149 while (result.get() == null) {
5232 dl 1.210 U u;
5233     Node<K,V> p;
5234     if ((p = advance()) == null) {
5235 dl 1.149 propagateCompletion();
5236     break;
5237     }
5238 dl 1.210 if ((u = searchFunction.apply(p)) != null) {
5239 dl 1.149 if (result.compareAndSet(null, u))
5240     quietlyCompleteRoot();
5241     return;
5242     }
5243 dl 1.119 }
5244     }
5245     }
5246     }
5247 tim 1.1
5248 dl 1.222 @SuppressWarnings("serial")
5249 dl 1.210 static final class SearchMappingsTask<K,V,U>
5250     extends BulkTask<K,V,U> {
5251 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5252 dl 1.119 final AtomicReference<U> result;
5253     SearchMappingsTask
5254 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5255 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
5256 dl 1.119 AtomicReference<U> result) {
5257 dl 1.210 super(p, b, i, f, t);
5258 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5259     }
5260 dl 1.146 public final U getRawResult() { return result.get(); }
5261 jsr166 1.168 public final void compute() {
5262 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5263 dl 1.146 final AtomicReference<U> result;
5264 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5265     (result = this.result) != null) {
5266 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5267     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5268 dl 1.149 if (result.get() != null)
5269     return;
5270 dl 1.210 addToPendingCount(1);
5271 dl 1.149 new SearchMappingsTask<K,V,U>
5272 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5273     searchFunction, result).fork();
5274 dl 1.128 }
5275 dl 1.149 while (result.get() == null) {
5276 dl 1.210 U u;
5277     Node<K,V> p;
5278     if ((p = advance()) == null) {
5279 dl 1.149 propagateCompletion();
5280     break;
5281     }
5282 dl 1.222 if ((u = searchFunction.apply(p.key, p.val)) != null) {
5283 dl 1.149 if (result.compareAndSet(null, u))
5284     quietlyCompleteRoot();
5285     break;
5286     }
5287 dl 1.119 }
5288     }
5289 tim 1.1 }
5290 dl 1.119 }
5291 tim 1.1
5292 dl 1.222 @SuppressWarnings("serial")
5293 dl 1.210 static final class ReduceKeysTask<K,V>
5294     extends BulkTask<K,V,K> {
5295 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5296 dl 1.119 K result;
5297 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
5298 dl 1.119 ReduceKeysTask
5299 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5300 dl 1.128 ReduceKeysTask<K,V> nextRight,
5301 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5302 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5303 dl 1.119 this.reducer = reducer;
5304     }
5305 dl 1.146 public final K getRawResult() { return result; }
5306 dl 1.210 public final void compute() {
5307 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5308 dl 1.149 if ((reducer = this.reducer) != null) {
5309 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5310     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5311     addToPendingCount(1);
5312 dl 1.149 (rights = new ReduceKeysTask<K,V>
5313 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5314     rights, reducer)).fork();
5315     }
5316     K r = null;
5317     for (Node<K,V> p; (p = advance()) != null; ) {
5318 dl 1.222 K u = p.key;
5319 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5320 dl 1.149 }
5321     result = r;
5322     CountedCompleter<?> c;
5323     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5324 dl 1.246 @SuppressWarnings("unchecked")
5325     ReduceKeysTask<K,V>
5326 dl 1.149 t = (ReduceKeysTask<K,V>)c,
5327     s = t.rights;
5328     while (s != null) {
5329     K tr, sr;
5330     if ((sr = s.result) != null)
5331     t.result = (((tr = t.result) == null) ? sr :
5332     reducer.apply(tr, sr));
5333     s = t.rights = s.nextRight;
5334     }
5335 dl 1.99 }
5336 dl 1.138 }
5337 tim 1.1 }
5338 dl 1.119 }
5339 tim 1.1
5340 dl 1.222 @SuppressWarnings("serial")
5341 dl 1.210 static final class ReduceValuesTask<K,V>
5342     extends BulkTask<K,V,V> {
5343 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5344 dl 1.119 V result;
5345 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
5346 dl 1.119 ReduceValuesTask
5347 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5348 dl 1.128 ReduceValuesTask<K,V> nextRight,
5349 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5350 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5351 dl 1.119 this.reducer = reducer;
5352     }
5353 dl 1.146 public final V getRawResult() { return result; }
5354 dl 1.210 public final void compute() {
5355 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5356 dl 1.149 if ((reducer = this.reducer) != null) {
5357 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5358     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5359     addToPendingCount(1);
5360 dl 1.149 (rights = new ReduceValuesTask<K,V>
5361 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5362     rights, reducer)).fork();
5363     }
5364     V r = null;
5365     for (Node<K,V> p; (p = advance()) != null; ) {
5366     V v = p.val;
5367 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
5368 dl 1.210 }
5369 dl 1.149 result = r;
5370     CountedCompleter<?> c;
5371     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5372 dl 1.246 @SuppressWarnings("unchecked")
5373     ReduceValuesTask<K,V>
5374 dl 1.149 t = (ReduceValuesTask<K,V>)c,
5375     s = t.rights;
5376     while (s != null) {
5377     V tr, sr;
5378     if ((sr = s.result) != null)
5379     t.result = (((tr = t.result) == null) ? sr :
5380     reducer.apply(tr, sr));
5381     s = t.rights = s.nextRight;
5382     }
5383 dl 1.119 }
5384     }
5385 tim 1.1 }
5386 dl 1.119 }
5387 tim 1.1
5388 dl 1.222 @SuppressWarnings("serial")
5389 dl 1.210 static final class ReduceEntriesTask<K,V>
5390     extends BulkTask<K,V,Map.Entry<K,V>> {
5391 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5392 dl 1.119 Map.Entry<K,V> result;
5393 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
5394 dl 1.119 ReduceEntriesTask
5395 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5396 dl 1.130 ReduceEntriesTask<K,V> nextRight,
5397 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5398 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5399 dl 1.119 this.reducer = reducer;
5400     }
5401 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
5402 dl 1.210 public final void compute() {
5403 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
5404 dl 1.149 if ((reducer = this.reducer) != null) {
5405 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5406     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5407     addToPendingCount(1);
5408 dl 1.149 (rights = new ReduceEntriesTask<K,V>
5409 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5410     rights, reducer)).fork();
5411     }
5412 dl 1.149 Map.Entry<K,V> r = null;
5413 dl 1.210 for (Node<K,V> p; (p = advance()) != null; )
5414     r = (r == null) ? p : reducer.apply(r, p);
5415 dl 1.149 result = r;
5416     CountedCompleter<?> c;
5417     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5418 dl 1.246 @SuppressWarnings("unchecked")
5419     ReduceEntriesTask<K,V>
5420 dl 1.149 t = (ReduceEntriesTask<K,V>)c,
5421     s = t.rights;
5422     while (s != null) {
5423     Map.Entry<K,V> tr, sr;
5424     if ((sr = s.result) != null)
5425     t.result = (((tr = t.result) == null) ? sr :
5426     reducer.apply(tr, sr));
5427     s = t.rights = s.nextRight;
5428     }
5429 dl 1.119 }
5430 dl 1.138 }
5431 dl 1.119 }
5432     }
5433 dl 1.99
5434 dl 1.222 @SuppressWarnings("serial")
5435 dl 1.210 static final class MapReduceKeysTask<K,V,U>
5436     extends BulkTask<K,V,U> {
5437 dl 1.153 final Function<? super K, ? extends U> transformer;
5438     final BiFunction<? super U, ? super U, ? extends U> reducer;
5439 dl 1.119 U result;
5440 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
5441 dl 1.119 MapReduceKeysTask
5442 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5443 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
5444 dl 1.153 Function<? super K, ? extends U> transformer,
5445     BiFunction<? super U, ? super U, ? extends U> reducer) {
5446 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5447 dl 1.119 this.transformer = transformer;
5448     this.reducer = reducer;
5449     }
5450 dl 1.146 public final U getRawResult() { return result; }
5451 dl 1.210 public final void compute() {
5452 dl 1.153 final Function<? super K, ? extends U> transformer;
5453     final BiFunction<? super U, ? super U, ? extends U> reducer;
5454 dl 1.149 if ((transformer = this.transformer) != null &&
5455     (reducer = this.reducer) != null) {
5456 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5457     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5458     addToPendingCount(1);
5459 dl 1.149 (rights = new MapReduceKeysTask<K,V,U>
5460 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5461     rights, transformer, reducer)).fork();
5462     }
5463     U r = null;
5464     for (Node<K,V> p; (p = advance()) != null; ) {
5465     U u;
5466 dl 1.222 if ((u = transformer.apply(p.key)) != null)
5467 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5468     }
5469     result = r;
5470     CountedCompleter<?> c;
5471     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5472 dl 1.246 @SuppressWarnings("unchecked")
5473     MapReduceKeysTask<K,V,U>
5474 dl 1.149 t = (MapReduceKeysTask<K,V,U>)c,
5475     s = t.rights;
5476     while (s != null) {
5477     U tr, sr;
5478     if ((sr = s.result) != null)
5479     t.result = (((tr = t.result) == null) ? sr :
5480     reducer.apply(tr, sr));
5481     s = t.rights = s.nextRight;
5482     }
5483 dl 1.119 }
5484 dl 1.138 }
5485 tim 1.1 }
5486 dl 1.4 }
5487    
5488 dl 1.222 @SuppressWarnings("serial")
5489 dl 1.210 static final class MapReduceValuesTask<K,V,U>
5490     extends BulkTask<K,V,U> {
5491 dl 1.153 final Function<? super V, ? extends U> transformer;
5492     final BiFunction<? super U, ? super U, ? extends U> reducer;
5493 dl 1.119 U result;
5494 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
5495 dl 1.119 MapReduceValuesTask
5496 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5497 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
5498 dl 1.153 Function<? super V, ? extends U> transformer,
5499     BiFunction<? super U, ? super U, ? extends U> reducer) {
5500 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5501 dl 1.119 this.transformer = transformer;
5502     this.reducer = reducer;
5503     }
5504 dl 1.146 public final U getRawResult() { return result; }
5505 dl 1.210 public final void compute() {
5506 dl 1.153 final Function<? super V, ? extends U> transformer;
5507     final BiFunction<? super U, ? super U, ? extends U> reducer;
5508 dl 1.149 if ((transformer = this.transformer) != null &&
5509     (reducer = this.reducer) != null) {
5510 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5511     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5512     addToPendingCount(1);
5513 dl 1.149 (rights = new MapReduceValuesTask<K,V,U>
5514 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5515     rights, transformer, reducer)).fork();
5516     }
5517     U r = null;
5518     for (Node<K,V> p; (p = advance()) != null; ) {
5519     U u;
5520     if ((u = transformer.apply(p.val)) != null)
5521 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5522     }
5523     result = r;
5524     CountedCompleter<?> c;
5525     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5526 dl 1.246 @SuppressWarnings("unchecked")
5527     MapReduceValuesTask<K,V,U>
5528 dl 1.149 t = (MapReduceValuesTask<K,V,U>)c,
5529     s = t.rights;
5530     while (s != null) {
5531     U tr, sr;
5532     if ((sr = s.result) != null)
5533     t.result = (((tr = t.result) == null) ? sr :
5534     reducer.apply(tr, sr));
5535     s = t.rights = s.nextRight;
5536     }
5537 dl 1.119 }
5538     }
5539     }
5540 dl 1.4 }
5541    
5542 dl 1.222 @SuppressWarnings("serial")
5543 dl 1.210 static final class MapReduceEntriesTask<K,V,U>
5544     extends BulkTask<K,V,U> {
5545 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5546     final BiFunction<? super U, ? super U, ? extends U> reducer;
5547 dl 1.119 U result;
5548 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
5549 dl 1.119 MapReduceEntriesTask
5550 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5551 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
5552 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5553     BiFunction<? super U, ? super U, ? extends U> reducer) {
5554 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5555 dl 1.119 this.transformer = transformer;
5556     this.reducer = reducer;
5557     }
5558 dl 1.146 public final U getRawResult() { return result; }
5559 dl 1.210 public final void compute() {
5560 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5561     final BiFunction<? super U, ? super U, ? extends U> reducer;
5562 dl 1.149 if ((transformer = this.transformer) != null &&
5563     (reducer = this.reducer) != null) {
5564 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5565     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5566     addToPendingCount(1);
5567 dl 1.149 (rights = new MapReduceEntriesTask<K,V,U>
5568 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5569     rights, transformer, reducer)).fork();
5570     }
5571     U r = null;
5572     for (Node<K,V> p; (p = advance()) != null; ) {
5573     U u;
5574     if ((u = transformer.apply(p)) != null)
5575 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5576     }
5577     result = r;
5578     CountedCompleter<?> c;
5579     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5580 dl 1.246 @SuppressWarnings("unchecked")
5581     MapReduceEntriesTask<K,V,U>
5582 dl 1.149 t = (MapReduceEntriesTask<K,V,U>)c,
5583     s = t.rights;
5584     while (s != null) {
5585     U tr, sr;
5586     if ((sr = s.result) != null)
5587     t.result = (((tr = t.result) == null) ? sr :
5588     reducer.apply(tr, sr));
5589     s = t.rights = s.nextRight;
5590     }
5591 dl 1.119 }
5592 dl 1.138 }
5593 dl 1.119 }
5594 dl 1.4 }
5595 tim 1.1
5596 dl 1.222 @SuppressWarnings("serial")
5597 dl 1.210 static final class MapReduceMappingsTask<K,V,U>
5598     extends BulkTask<K,V,U> {
5599 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5600     final BiFunction<? super U, ? super U, ? extends U> reducer;
5601 dl 1.119 U result;
5602 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
5603 dl 1.119 MapReduceMappingsTask
5604 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5605 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
5606 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5607     BiFunction<? super U, ? super U, ? extends U> reducer) {
5608 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5609 dl 1.119 this.transformer = transformer;
5610     this.reducer = reducer;
5611     }
5612 dl 1.146 public final U getRawResult() { return result; }
5613 dl 1.210 public final void compute() {
5614 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5615     final BiFunction<? super U, ? super U, ? extends U> reducer;
5616 dl 1.149 if ((transformer = this.transformer) != null &&
5617     (reducer = this.reducer) != null) {
5618 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5619     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5620     addToPendingCount(1);
5621 dl 1.149 (rights = new MapReduceMappingsTask<K,V,U>
5622 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5623     rights, transformer, reducer)).fork();
5624     }
5625     U r = null;
5626     for (Node<K,V> p; (p = advance()) != null; ) {
5627     U u;
5628 dl 1.222 if ((u = transformer.apply(p.key, p.val)) != null)
5629 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5630     }
5631     result = r;
5632     CountedCompleter<?> c;
5633     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5634 dl 1.246 @SuppressWarnings("unchecked")
5635     MapReduceMappingsTask<K,V,U>
5636 dl 1.149 t = (MapReduceMappingsTask<K,V,U>)c,
5637     s = t.rights;
5638     while (s != null) {
5639     U tr, sr;
5640     if ((sr = s.result) != null)
5641     t.result = (((tr = t.result) == null) ? sr :
5642     reducer.apply(tr, sr));
5643     s = t.rights = s.nextRight;
5644     }
5645 dl 1.119 }
5646     }
5647     }
5648     }
5649 jsr166 1.114
5650 dl 1.222 @SuppressWarnings("serial")
5651 dl 1.210 static final class MapReduceKeysToDoubleTask<K,V>
5652     extends BulkTask<K,V,Double> {
5653 dl 1.171 final ToDoubleFunction<? super K> transformer;
5654 dl 1.153 final DoubleBinaryOperator reducer;
5655 dl 1.119 final double basis;
5656     double result;
5657 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5658 dl 1.119 MapReduceKeysToDoubleTask
5659 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5660 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
5661 dl 1.171 ToDoubleFunction<? super K> transformer,
5662 dl 1.119 double basis,
5663 dl 1.153 DoubleBinaryOperator reducer) {
5664 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5665 dl 1.119 this.transformer = transformer;
5666     this.basis = basis; this.reducer = reducer;
5667     }
5668 dl 1.146 public final Double getRawResult() { return result; }
5669 dl 1.210 public final void compute() {
5670 dl 1.171 final ToDoubleFunction<? super K> transformer;
5671 dl 1.153 final DoubleBinaryOperator reducer;
5672 dl 1.149 if ((transformer = this.transformer) != null &&
5673     (reducer = this.reducer) != null) {
5674     double r = this.basis;
5675 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5676     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5677     addToPendingCount(1);
5678 dl 1.149 (rights = new MapReduceKeysToDoubleTask<K,V>
5679 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5680     rights, transformer, r, reducer)).fork();
5681     }
5682     for (Node<K,V> p; (p = advance()) != null; )
5683 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key));
5684 dl 1.149 result = r;
5685     CountedCompleter<?> c;
5686     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5687 dl 1.246 @SuppressWarnings("unchecked")
5688     MapReduceKeysToDoubleTask<K,V>
5689 dl 1.149 t = (MapReduceKeysToDoubleTask<K,V>)c,
5690     s = t.rights;
5691     while (s != null) {
5692 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5693 dl 1.149 s = t.rights = s.nextRight;
5694     }
5695 dl 1.119 }
5696 dl 1.138 }
5697 dl 1.79 }
5698 dl 1.119 }
5699 dl 1.79
5700 dl 1.222 @SuppressWarnings("serial")
5701 dl 1.210 static final class MapReduceValuesToDoubleTask<K,V>
5702     extends BulkTask<K,V,Double> {
5703 dl 1.171 final ToDoubleFunction<? super V> transformer;
5704 dl 1.153 final DoubleBinaryOperator reducer;
5705 dl 1.119 final double basis;
5706     double result;
5707 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5708 dl 1.119 MapReduceValuesToDoubleTask
5709 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5710 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
5711 dl 1.171 ToDoubleFunction<? super V> transformer,
5712 dl 1.119 double basis,
5713 dl 1.153 DoubleBinaryOperator reducer) {
5714 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5715 dl 1.119 this.transformer = transformer;
5716     this.basis = basis; this.reducer = reducer;
5717     }
5718 dl 1.146 public final Double getRawResult() { return result; }
5719 dl 1.210 public final void compute() {
5720 dl 1.171 final ToDoubleFunction<? super V> transformer;
5721 dl 1.153 final DoubleBinaryOperator reducer;
5722 dl 1.149 if ((transformer = this.transformer) != null &&
5723     (reducer = this.reducer) != null) {
5724     double r = this.basis;
5725 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5726     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5727     addToPendingCount(1);
5728 dl 1.149 (rights = new MapReduceValuesToDoubleTask<K,V>
5729 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5730     rights, transformer, r, reducer)).fork();
5731     }
5732     for (Node<K,V> p; (p = advance()) != null; )
5733     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5734 dl 1.149 result = r;
5735     CountedCompleter<?> c;
5736     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5737 dl 1.246 @SuppressWarnings("unchecked")
5738     MapReduceValuesToDoubleTask<K,V>
5739 dl 1.149 t = (MapReduceValuesToDoubleTask<K,V>)c,
5740     s = t.rights;
5741     while (s != null) {
5742 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5743 dl 1.149 s = t.rights = s.nextRight;
5744     }
5745 dl 1.119 }
5746     }
5747 dl 1.30 }
5748 dl 1.79 }
5749 dl 1.30
5750 dl 1.222 @SuppressWarnings("serial")
5751 dl 1.210 static final class MapReduceEntriesToDoubleTask<K,V>
5752     extends BulkTask<K,V,Double> {
5753 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5754 dl 1.153 final DoubleBinaryOperator reducer;
5755 dl 1.119 final double basis;
5756     double result;
5757 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5758 dl 1.119 MapReduceEntriesToDoubleTask
5759 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5760 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
5761 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5762 dl 1.119 double basis,
5763 dl 1.153 DoubleBinaryOperator reducer) {
5764 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5765 dl 1.119 this.transformer = transformer;
5766     this.basis = basis; this.reducer = reducer;
5767     }
5768 dl 1.146 public final Double getRawResult() { return result; }
5769 dl 1.210 public final void compute() {
5770 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5771 dl 1.153 final DoubleBinaryOperator reducer;
5772 dl 1.149 if ((transformer = this.transformer) != null &&
5773     (reducer = this.reducer) != null) {
5774     double r = this.basis;
5775 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5776     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5777     addToPendingCount(1);
5778 dl 1.149 (rights = new MapReduceEntriesToDoubleTask<K,V>
5779 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5780     rights, transformer, r, reducer)).fork();
5781     }
5782     for (Node<K,V> p; (p = advance()) != null; )
5783     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5784 dl 1.149 result = r;
5785     CountedCompleter<?> c;
5786     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5787 dl 1.246 @SuppressWarnings("unchecked")
5788     MapReduceEntriesToDoubleTask<K,V>
5789 dl 1.149 t = (MapReduceEntriesToDoubleTask<K,V>)c,
5790     s = t.rights;
5791     while (s != null) {
5792 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5793 dl 1.149 s = t.rights = s.nextRight;
5794     }
5795 dl 1.119 }
5796 dl 1.138 }
5797 dl 1.30 }
5798 tim 1.1 }
5799    
5800 dl 1.222 @SuppressWarnings("serial")
5801 dl 1.210 static final class MapReduceMappingsToDoubleTask<K,V>
5802     extends BulkTask<K,V,Double> {
5803 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5804 dl 1.153 final DoubleBinaryOperator reducer;
5805 dl 1.119 final double basis;
5806     double result;
5807 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5808 dl 1.119 MapReduceMappingsToDoubleTask
5809 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5810 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
5811 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
5812 dl 1.119 double basis,
5813 dl 1.153 DoubleBinaryOperator reducer) {
5814 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5815 dl 1.119 this.transformer = transformer;
5816     this.basis = basis; this.reducer = reducer;
5817     }
5818 dl 1.146 public final Double getRawResult() { return result; }
5819 dl 1.210 public final void compute() {
5820 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5821 dl 1.153 final DoubleBinaryOperator reducer;
5822 dl 1.149 if ((transformer = this.transformer) != null &&
5823     (reducer = this.reducer) != null) {
5824     double r = this.basis;
5825 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5826     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5827     addToPendingCount(1);
5828 dl 1.149 (rights = new MapReduceMappingsToDoubleTask<K,V>
5829 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5830     rights, transformer, r, reducer)).fork();
5831     }
5832     for (Node<K,V> p; (p = advance()) != null; )
5833 dl 1.222 r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val));
5834 dl 1.149 result = r;
5835     CountedCompleter<?> c;
5836     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5837 dl 1.246 @SuppressWarnings("unchecked")
5838     MapReduceMappingsToDoubleTask<K,V>
5839 dl 1.149 t = (MapReduceMappingsToDoubleTask<K,V>)c,
5840     s = t.rights;
5841     while (s != null) {
5842 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5843 dl 1.149 s = t.rights = s.nextRight;
5844     }
5845 dl 1.119 }
5846     }
5847 dl 1.4 }
5848 dl 1.119 }
5849    
5850 dl 1.222 @SuppressWarnings("serial")
5851 dl 1.210 static final class MapReduceKeysToLongTask<K,V>
5852     extends BulkTask<K,V,Long> {
5853 dl 1.171 final ToLongFunction<? super K> transformer;
5854 dl 1.153 final LongBinaryOperator reducer;
5855 dl 1.119 final long basis;
5856     long result;
5857 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
5858 dl 1.119 MapReduceKeysToLongTask
5859 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5860 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
5861 dl 1.171 ToLongFunction<? super K> transformer,
5862 dl 1.119 long basis,
5863 dl 1.153 LongBinaryOperator reducer) {
5864 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5865 dl 1.119 this.transformer = transformer;
5866     this.basis = basis; this.reducer = reducer;
5867     }
5868 dl 1.146 public final Long getRawResult() { return result; }
5869 dl 1.210 public final void compute() {
5870 dl 1.171 final ToLongFunction<? super K> transformer;
5871 dl 1.153 final LongBinaryOperator reducer;
5872 dl 1.149 if ((transformer = this.transformer) != null &&
5873     (reducer = this.reducer) != null) {
5874     long r = this.basis;
5875 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5876     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5877     addToPendingCount(1);
5878 dl 1.149 (rights = new MapReduceKeysToLongTask<K,V>
5879 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5880     rights, transformer, r, reducer)).fork();
5881     }
5882     for (Node<K,V> p; (p = advance()) != null; )
5883 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key));
5884 dl 1.149 result = r;
5885     CountedCompleter<?> c;
5886     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5887 dl 1.246 @SuppressWarnings("unchecked")
5888     MapReduceKeysToLongTask<K,V>
5889 dl 1.149 t = (MapReduceKeysToLongTask<K,V>)c,
5890     s = t.rights;
5891     while (s != null) {
5892 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5893 dl 1.149 s = t.rights = s.nextRight;
5894     }
5895 dl 1.119 }
5896 dl 1.138 }
5897 dl 1.4 }
5898 dl 1.119 }
5899    
5900 dl 1.222 @SuppressWarnings("serial")
5901 dl 1.210 static final class MapReduceValuesToLongTask<K,V>
5902     extends BulkTask<K,V,Long> {
5903 dl 1.171 final ToLongFunction<? super V> transformer;
5904 dl 1.153 final LongBinaryOperator reducer;
5905 dl 1.119 final long basis;
5906     long result;
5907 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
5908 dl 1.119 MapReduceValuesToLongTask
5909 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5910 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
5911 dl 1.171 ToLongFunction<? super V> transformer,
5912 dl 1.119 long basis,
5913 dl 1.153 LongBinaryOperator reducer) {
5914 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5915 dl 1.119 this.transformer = transformer;
5916     this.basis = basis; this.reducer = reducer;
5917     }
5918 dl 1.146 public final Long getRawResult() { return result; }
5919 dl 1.210 public final void compute() {
5920 dl 1.171 final ToLongFunction<? super V> transformer;
5921 dl 1.153 final LongBinaryOperator reducer;
5922 dl 1.149 if ((transformer = this.transformer) != null &&
5923     (reducer = this.reducer) != null) {
5924     long r = this.basis;
5925 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5926     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5927     addToPendingCount(1);
5928 dl 1.149 (rights = new MapReduceValuesToLongTask<K,V>
5929 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5930     rights, transformer, r, reducer)).fork();
5931     }
5932     for (Node<K,V> p; (p = advance()) != null; )
5933     r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5934 dl 1.149 result = r;
5935     CountedCompleter<?> c;
5936     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5937 dl 1.246 @SuppressWarnings("unchecked")
5938     MapReduceValuesToLongTask<K,V>
5939 dl 1.149 t = (MapReduceValuesToLongTask<K,V>)c,
5940     s = t.rights;
5941     while (s != null) {
5942 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5943 dl 1.149 s = t.rights = s.nextRight;
5944     }
5945 dl 1.119 }
5946     }
5947 jsr166 1.95 }
5948 dl 1.119 }
5949    
5950 dl 1.222 @SuppressWarnings("serial")
5951 dl 1.210 static final class MapReduceEntriesToLongTask<K,V>
5952     extends BulkTask<K,V,Long> {
5953 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5954 dl 1.153 final LongBinaryOperator reducer;
5955 dl 1.119 final long basis;
5956     long result;
5957 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
5958 dl 1.119 MapReduceEntriesToLongTask
5959 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5960 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
5961 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
5962 dl 1.119 long basis,
5963 dl 1.153 LongBinaryOperator reducer) {
5964 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5965 dl 1.119 this.transformer = transformer;
5966     this.basis = basis; this.reducer = reducer;
5967     }
5968 dl 1.146 public final Long getRawResult() { return result; }
5969 dl 1.210 public final void compute() {
5970 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5971 dl 1.153 final LongBinaryOperator reducer;
5972 dl 1.149 if ((transformer = this.transformer) != null &&
5973     (reducer = this.reducer) != null) {
5974     long r = this.basis;
5975 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5976     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5977     addToPendingCount(1);
5978 dl 1.149 (rights = new MapReduceEntriesToLongTask<K,V>
5979 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5980     rights, transformer, r, reducer)).fork();
5981     }
5982     for (Node<K,V> p; (p = advance()) != null; )
5983     r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5984 dl 1.149 result = r;
5985     CountedCompleter<?> c;
5986     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5987 dl 1.246 @SuppressWarnings("unchecked")
5988     MapReduceEntriesToLongTask<K,V>
5989 dl 1.149 t = (MapReduceEntriesToLongTask<K,V>)c,
5990     s = t.rights;
5991     while (s != null) {
5992 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5993 dl 1.149 s = t.rights = s.nextRight;
5994     }
5995 dl 1.119 }
5996 dl 1.138 }
5997 dl 1.4 }
5998 tim 1.1 }
5999    
6000 dl 1.222 @SuppressWarnings("serial")
6001 dl 1.210 static final class MapReduceMappingsToLongTask<K,V>
6002     extends BulkTask<K,V,Long> {
6003 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6004 dl 1.153 final LongBinaryOperator reducer;
6005 dl 1.119 final long basis;
6006     long result;
6007 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6008 dl 1.119 MapReduceMappingsToLongTask
6009 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6010 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
6011 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
6012 dl 1.119 long basis,
6013 dl 1.153 LongBinaryOperator reducer) {
6014 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6015 dl 1.119 this.transformer = transformer;
6016     this.basis = basis; this.reducer = reducer;
6017     }
6018 dl 1.146 public final Long getRawResult() { return result; }
6019 dl 1.210 public final void compute() {
6020 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6021 dl 1.153 final LongBinaryOperator reducer;
6022 dl 1.149 if ((transformer = this.transformer) != null &&
6023     (reducer = this.reducer) != null) {
6024     long r = this.basis;
6025 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6026     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6027     addToPendingCount(1);
6028 dl 1.149 (rights = new MapReduceMappingsToLongTask<K,V>
6029 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6030     rights, transformer, r, reducer)).fork();
6031     }
6032     for (Node<K,V> p; (p = advance()) != null; )
6033 dl 1.222 r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val));
6034 dl 1.149 result = r;
6035     CountedCompleter<?> c;
6036     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6037 dl 1.246 @SuppressWarnings("unchecked")
6038     MapReduceMappingsToLongTask<K,V>
6039 dl 1.149 t = (MapReduceMappingsToLongTask<K,V>)c,
6040     s = t.rights;
6041     while (s != null) {
6042 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6043 dl 1.149 s = t.rights = s.nextRight;
6044     }
6045 dl 1.119 }
6046     }
6047 dl 1.4 }
6048 tim 1.1 }
6049    
6050 dl 1.222 @SuppressWarnings("serial")
6051 dl 1.210 static final class MapReduceKeysToIntTask<K,V>
6052     extends BulkTask<K,V,Integer> {
6053 dl 1.171 final ToIntFunction<? super K> transformer;
6054 dl 1.153 final IntBinaryOperator reducer;
6055 dl 1.119 final int basis;
6056     int result;
6057 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
6058 dl 1.119 MapReduceKeysToIntTask
6059 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6060 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
6061 dl 1.171 ToIntFunction<? super K> transformer,
6062 dl 1.119 int basis,
6063 dl 1.153 IntBinaryOperator reducer) {
6064 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6065 dl 1.119 this.transformer = transformer;
6066     this.basis = basis; this.reducer = reducer;
6067     }
6068 dl 1.146 public final Integer getRawResult() { return result; }
6069 dl 1.210 public final void compute() {
6070 dl 1.171 final ToIntFunction<? super K> transformer;
6071 dl 1.153 final IntBinaryOperator reducer;
6072 dl 1.149 if ((transformer = this.transformer) != null &&
6073     (reducer = this.reducer) != null) {
6074     int r = this.basis;
6075 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6076     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6077     addToPendingCount(1);
6078 dl 1.149 (rights = new MapReduceKeysToIntTask<K,V>
6079 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6080     rights, transformer, r, reducer)).fork();
6081     }
6082     for (Node<K,V> p; (p = advance()) != null; )
6083 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key));
6084 dl 1.149 result = r;
6085     CountedCompleter<?> c;
6086     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6087 dl 1.246 @SuppressWarnings("unchecked")
6088     MapReduceKeysToIntTask<K,V>
6089 dl 1.149 t = (MapReduceKeysToIntTask<K,V>)c,
6090     s = t.rights;
6091     while (s != null) {
6092 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6093 dl 1.149 s = t.rights = s.nextRight;
6094     }
6095 dl 1.119 }
6096 dl 1.138 }
6097 dl 1.30 }
6098     }
6099    
6100 dl 1.222 @SuppressWarnings("serial")
6101 dl 1.210 static final class MapReduceValuesToIntTask<K,V>
6102     extends BulkTask<K,V,Integer> {
6103 dl 1.171 final ToIntFunction<? super V> transformer;
6104 dl 1.153 final IntBinaryOperator reducer;
6105 dl 1.119 final int basis;
6106     int result;
6107 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
6108 dl 1.119 MapReduceValuesToIntTask
6109 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6110 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
6111 dl 1.171 ToIntFunction<? super V> transformer,
6112 dl 1.119 int basis,
6113 dl 1.153 IntBinaryOperator reducer) {
6114 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6115 dl 1.119 this.transformer = transformer;
6116     this.basis = basis; this.reducer = reducer;
6117     }
6118 dl 1.146 public final Integer getRawResult() { return result; }
6119 dl 1.210 public final void compute() {
6120 dl 1.171 final ToIntFunction<? super V> transformer;
6121 dl 1.153 final IntBinaryOperator reducer;
6122 dl 1.149 if ((transformer = this.transformer) != null &&
6123     (reducer = this.reducer) != null) {
6124     int r = this.basis;
6125 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6126     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6127     addToPendingCount(1);
6128 dl 1.149 (rights = new MapReduceValuesToIntTask<K,V>
6129 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6130     rights, transformer, r, reducer)).fork();
6131     }
6132     for (Node<K,V> p; (p = advance()) != null; )
6133     r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
6134 dl 1.149 result = r;
6135     CountedCompleter<?> c;
6136     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6137 dl 1.246 @SuppressWarnings("unchecked")
6138     MapReduceValuesToIntTask<K,V>
6139 dl 1.149 t = (MapReduceValuesToIntTask<K,V>)c,
6140     s = t.rights;
6141     while (s != null) {
6142 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6143 dl 1.149 s = t.rights = s.nextRight;
6144     }
6145 dl 1.119 }
6146 dl 1.2 }
6147 tim 1.1 }
6148     }
6149    
6150 dl 1.222 @SuppressWarnings("serial")
6151 dl 1.210 static final class MapReduceEntriesToIntTask<K,V>
6152     extends BulkTask<K,V,Integer> {
6153 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6154 dl 1.153 final IntBinaryOperator reducer;
6155 dl 1.119 final int basis;
6156     int result;
6157 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6158 dl 1.119 MapReduceEntriesToIntTask
6159 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6160 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
6161 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
6162 dl 1.119 int basis,
6163 dl 1.153 IntBinaryOperator reducer) {
6164 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6165 dl 1.119 this.transformer = transformer;
6166     this.basis = basis; this.reducer = reducer;
6167     }
6168 dl 1.146 public final Integer getRawResult() { return result; }
6169 dl 1.210 public final void compute() {
6170 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6171 dl 1.153 final IntBinaryOperator reducer;
6172 dl 1.149 if ((transformer = this.transformer) != null &&
6173     (reducer = this.reducer) != null) {
6174     int r = this.basis;
6175 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6176     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6177     addToPendingCount(1);
6178 dl 1.149 (rights = new MapReduceEntriesToIntTask<K,V>
6179 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6180     rights, transformer, r, reducer)).fork();
6181     }
6182     for (Node<K,V> p; (p = advance()) != null; )
6183     r = reducer.applyAsInt(r, transformer.applyAsInt(p));
6184 dl 1.149 result = r;
6185     CountedCompleter<?> c;
6186     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6187 dl 1.246 @SuppressWarnings("unchecked")
6188     MapReduceEntriesToIntTask<K,V>
6189 dl 1.149 t = (MapReduceEntriesToIntTask<K,V>)c,
6190     s = t.rights;
6191     while (s != null) {
6192 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6193 dl 1.149 s = t.rights = s.nextRight;
6194     }
6195 dl 1.119 }
6196 dl 1.138 }
6197 dl 1.4 }
6198 dl 1.119 }
6199 tim 1.1
6200 dl 1.222 @SuppressWarnings("serial")
6201 dl 1.210 static final class MapReduceMappingsToIntTask<K,V>
6202     extends BulkTask<K,V,Integer> {
6203 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6204 dl 1.153 final IntBinaryOperator reducer;
6205 dl 1.119 final int basis;
6206     int result;
6207 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6208 dl 1.119 MapReduceMappingsToIntTask
6209 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
6210 dl 1.146 MapReduceMappingsToIntTask<K,V> nextRight,
6211 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
6212 dl 1.119 int basis,
6213 dl 1.153 IntBinaryOperator reducer) {
6214 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
6215 dl 1.119 this.transformer = transformer;
6216     this.basis = basis; this.reducer = reducer;
6217     }
6218 dl 1.146 public final Integer getRawResult() { return result; }
6219 dl 1.210 public final void compute() {
6220 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6221 dl 1.153 final IntBinaryOperator reducer;
6222 dl 1.149 if ((transformer = this.transformer) != null &&
6223     (reducer = this.reducer) != null) {
6224     int r = this.basis;
6225 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
6226     (h = ((f = baseLimit) + i) >>> 1) > i;) {
6227     addToPendingCount(1);
6228 dl 1.149 (rights = new MapReduceMappingsToIntTask<K,V>
6229 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
6230     rights, transformer, r, reducer)).fork();
6231     }
6232     for (Node<K,V> p; (p = advance()) != null; )
6233 dl 1.222 r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val));
6234 dl 1.149 result = r;
6235     CountedCompleter<?> c;
6236     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6237 dl 1.246 @SuppressWarnings("unchecked")
6238     MapReduceMappingsToIntTask<K,V>
6239 dl 1.149 t = (MapReduceMappingsToIntTask<K,V>)c,
6240     s = t.rights;
6241     while (s != null) {
6242 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6243 dl 1.149 s = t.rights = s.nextRight;
6244     }
6245 dl 1.119 }
6246 dl 1.138 }
6247 tim 1.1 }
6248     }
6249 dl 1.99
6250     // Unsafe mechanics
6251 dl 1.149 private static final sun.misc.Unsafe U;
6252     private static final long SIZECTL;
6253     private static final long TRANSFERINDEX;
6254     private static final long BASECOUNT;
6255 dl 1.153 private static final long CELLSBUSY;
6256 dl 1.149 private static final long CELLVALUE;
6257 dl 1.119 private static final long ABASE;
6258     private static final int ASHIFT;
6259 dl 1.99
6260     static {
6261     try {
6262 dl 1.149 U = sun.misc.Unsafe.getUnsafe();
6263 dl 1.119 Class<?> k = ConcurrentHashMap.class;
6264 dl 1.149 SIZECTL = U.objectFieldOffset
6265 dl 1.119 (k.getDeclaredField("sizeCtl"));
6266 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
6267     (k.getDeclaredField("transferIndex"));
6268     BASECOUNT = U.objectFieldOffset
6269     (k.getDeclaredField("baseCount"));
6270 dl 1.153 CELLSBUSY = U.objectFieldOffset
6271     (k.getDeclaredField("cellsBusy"));
6272 dl 1.222 Class<?> ck = CounterCell.class;
6273 dl 1.149 CELLVALUE = U.objectFieldOffset
6274     (ck.getDeclaredField("value"));
6275 jsr166 1.226 Class<?> ak = Node[].class;
6276     ABASE = U.arrayBaseOffset(ak);
6277     int scale = U.arrayIndexScale(ak);
6278 jsr166 1.167 if ((scale & (scale - 1)) != 0)
6279     throw new Error("data type scale not a power of two");
6280     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6281 dl 1.99 } catch (Exception e) {
6282     throw new Error(e);
6283     }
6284     }
6285 jsr166 1.152 }