ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.269
Committed: Mon Mar 23 18:48:19 2015 UTC (9 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.268: +4 -0 lines
Log Message:
JDK-8074773: Reduce the risk of rare disastrous classloading in first call to LockSupport.park

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