ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.270
Committed: Tue Mar 24 22:30:53 2015 UTC (9 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.269: +4 -3 lines
Log Message:
refactor calls to putFields

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