ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.271
Committed: Tue Apr 28 23:06:53 2015 UTC (9 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.270: +25 -0 lines
Log Message:
Override default removeIf for ConcurrentMap EntrySets

File Contents

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