ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.259
Committed: Mon Dec 22 12:58:17 2014 UTC (9 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.258: +16 -0 lines
Log Message:
Improve detection of recursive usage errors

File Contents

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