ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.262
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.261: +2 -2 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

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