ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.293
Committed: Sat Jun 4 20:29:20 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.292: +3 -2 lines
Log Message:
import jdk.internal.misc.Unsafe

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