ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.216
Committed: Fri May 24 03:27:47 2013 UTC (11 years ago) by jsr166
Branch: MAIN
Changes since 1.215: +15 -16 lines
Log Message:
remove references to null values in javadoc

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