ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.308
Committed: Mon Mar 12 03:29:09 2018 UTC (6 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.307: +1 -1 lines
Log Message:
prefer throwing ExceptionInInitializerError from <clinit> to throwing Error

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