ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.292
Committed: Sat Apr 23 20:13:21 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.291: +6 -3 lines
Log Message:
standardize on slightly better lazy init code for views

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