ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.310
Committed: Wed May 23 06:11:41 2018 UTC (6 years ago) by jsr166
Branch: MAIN
Changes since 1.309: +1 -6 lines
Log Message:
tableSizeFor: optimize and add whitebox tests

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