ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.274
Committed: Sun Sep 6 00:57:56 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.273: +1 -1 lines
Log Message:
spelling

File Contents

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