ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.210
Committed: Tue May 21 19:10:43 2013 UTC (11 years ago) by dl
Branch: MAIN
Changes since 1.209: +1643 -2863 lines
Log Message:
API changes to mesh better with lambda/streams

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     * in curom bulk tasks. Nodes with a hash field of MOVED are
585     * special, and do not contain user keys or values (and are never
586     * 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     * could even have been removed in which case the put will
651     * 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     */
2192 dl 1.210 static class Traverser<K,V> {
2193     Node<K,V>[] tab; // current table; updated if resized
2194     Node<K,V> next; // the next entry to use
2195     int index; // index of bin to use next
2196     int baseIndex; // current index of initial table
2197     int baseLimit; // index bound for initial table
2198     final int baseSize; // initial table size
2199    
2200     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
2201     this.tab = tab;
2202     this.baseSize = size;
2203     this.baseIndex = this.index = index;
2204     this.baseLimit = limit;
2205     this.next = null;
2206     }
2207    
2208     /**
2209     * Advances if possible, returning next valid node, or null if none.
2210     */
2211     final Node<K,V> advance() {
2212     Node<K,V> e;
2213     if ((e = next) != null)
2214     e = e.next;
2215     for (;;) {
2216     Node<K,V>[] t; int i, n; Object ek; // must use locals in checks
2217     if (e != null)
2218     return next = e;
2219     if (baseIndex >= baseLimit || (t = tab) == null ||
2220     (n = t.length) <= (i = index) || i < 0)
2221     return next = null;
2222     if ((e = tabAt(t, index)) != null && e.hash < 0) {
2223     if ((ek = e.key) instanceof TreeBin)
2224     e = ((TreeBin<K,V>)ek).first;
2225     else {
2226     tab = (Node<K,V>[])ek;
2227     e = null;
2228     continue;
2229     }
2230     }
2231     if ((index += baseSize) >= n)
2232     index = ++baseIndex; // visit upper slots if present
2233     }
2234     }
2235     }
2236    
2237     /**
2238     * Base of key, value, and entry Iterators. Adds fields to
2239     * Traverser to support iterator.remove
2240     */
2241     static class BaseIterator<K,V> extends Traverser<K,V> {
2242 jsr166 1.186 final ConcurrentHashMap<K,V> map;
2243 dl 1.210 Node<K,V> lastReturned;
2244     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
2245     ConcurrentHashMap<K,V> map) {
2246     super(tab, size, index, limit);
2247     this.map = map;
2248     advance();
2249     }
2250    
2251     public final boolean hasNext() { return next != null; }
2252     public final boolean hasMoreElements() { return next != null; }
2253    
2254     public final void remove() {
2255     Node<K,V> p;
2256     if ((p = lastReturned) == null)
2257     throw new IllegalStateException();
2258     lastReturned = null;
2259     map.internalReplace((K)p.key, null, null);
2260     }
2261     }
2262    
2263     static final class KeyIterator<K,V> extends BaseIterator<K,V>
2264     implements Iterator<K>, Enumeration<K> {
2265     KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
2266     ConcurrentHashMap<K,V> map) {
2267     super(tab, index, size, limit, map);
2268     }
2269    
2270     public final K next() {
2271     Node<K,V> p;
2272     if ((p = next) == null)
2273     throw new NoSuchElementException();
2274     K k = (K)p.key;
2275     lastReturned = p;
2276     advance();
2277     return k;
2278     }
2279    
2280     public final K nextElement() { return next(); }
2281     }
2282 dl 1.192
2283 dl 1.210 static final class ValueIterator<K,V> extends BaseIterator<K,V>
2284     implements Iterator<V>, Enumeration<V> {
2285     ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
2286     ConcurrentHashMap<K,V> map) {
2287     super(tab, index, size, limit, map);
2288 dl 1.119 }
2289    
2290 dl 1.210 public final V next() {
2291     Node<K,V> p;
2292     if ((p = next) == null)
2293     throw new NoSuchElementException();
2294     V v = p.val;
2295     lastReturned = p;
2296     advance();
2297     return v;
2298 dl 1.119 }
2299    
2300 dl 1.210 public final V nextElement() { return next(); }
2301     }
2302    
2303     static final class EntryIterator<K,V> extends BaseIterator<K,V>
2304     implements Iterator<Map.Entry<K,V>> {
2305     EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
2306     ConcurrentHashMap<K,V> map) {
2307     super(tab, index, size, limit, map);
2308 dl 1.153 }
2309    
2310 dl 1.210 public final Map.Entry<K,V> next() {
2311     Node<K,V> p;
2312     if ((p = next) == null)
2313     throw new NoSuchElementException();
2314     K k = (K)p.key;
2315     V v = p.val;
2316     lastReturned = p;
2317     advance();
2318     return new MapEntry<K,V>(k, v, map);
2319 dl 1.191 }
2320 dl 1.210 }
2321 dl 1.191
2322 dl 1.210 static final class KeySpliterator<K,V> extends Traverser<K,V>
2323     implements Spliterator<K> {
2324     long est; // size estimate
2325     KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2326     long est) {
2327     super(tab, size, index, limit);
2328     this.est = est;
2329 dl 1.192 }
2330    
2331 dl 1.210 public Spliterator<K> trySplit() {
2332     int i, f, h;
2333     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2334     new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
2335     f, est >>>= 1);
2336 dl 1.192 }
2337    
2338 dl 1.210 public void forEachRemaining(Consumer<? super K> action) {
2339 dl 1.192 if (action == null) throw new NullPointerException();
2340 dl 1.210 for (Node<K,V> p; (p = advance()) != null;)
2341     action.accept((K)p.key);
2342 dl 1.192 }
2343    
2344 dl 1.210 public boolean tryAdvance(Consumer<? super K> action) {
2345 dl 1.192 if (action == null) throw new NullPointerException();
2346 dl 1.210 Node<K,V> p;
2347     if ((p = advance()) == null)
2348     return false;
2349     action.accept((K)p.key);
2350     return true;
2351     }
2352    
2353     public long estimateSize() { return est; }
2354    
2355     public int characteristics() {
2356     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2357     Spliterator.NONNULL;
2358 dl 1.119 }
2359 dl 1.210 }
2360 dl 1.119
2361 dl 1.210 static final class ValueSpliterator<K,V> extends Traverser<K,V>
2362     implements Spliterator<V> {
2363     long est; // size estimate
2364     ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
2365     long est) {
2366     super(tab, size, index, limit);
2367     this.est = est;
2368 dl 1.119 }
2369    
2370 dl 1.210 public Spliterator<V> trySplit() {
2371     int i, f, h;
2372     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2373     new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
2374     f, est >>>= 1);
2375 dl 1.119 }
2376    
2377 dl 1.210 public void forEachRemaining(Consumer<? super V> action) {
2378     if (action == null) throw new NullPointerException();
2379     for (Node<K,V> p; (p = advance()) != null;)
2380     action.accept(p.val);
2381     }
2382 dl 1.146
2383 dl 1.210 public boolean tryAdvance(Consumer<? super V> action) {
2384     if (action == null) throw new NullPointerException();
2385     Node<K,V> p;
2386     if ((p = advance()) == null)
2387     return false;
2388     action.accept(p.val);
2389     return true;
2390     }
2391 dl 1.146
2392 dl 1.210 public long estimateSize() { return est; }
2393 dl 1.192
2394 dl 1.210 public int characteristics() {
2395     return Spliterator.CONCURRENT | Spliterator.NONNULL;
2396 dl 1.146 }
2397 dl 1.119 }
2398    
2399 dl 1.210 static final class EntrySpliterator<K,V> extends Traverser<K,V>
2400     implements Spliterator<Map.Entry<K,V>> {
2401     final ConcurrentHashMap<K,V> map; // To export MapEntry
2402     long est; // size estimate
2403     EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
2404     long est, ConcurrentHashMap<K,V> map) {
2405     super(tab, size, index, limit);
2406     this.map = map;
2407     this.est = est;
2408     }
2409    
2410     public Spliterator<Map.Entry<K,V>> trySplit() {
2411     int i, f, h;
2412     return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
2413     new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
2414     f, est >>>= 1, map);
2415     }
2416    
2417     public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
2418     if (action == null) throw new NullPointerException();
2419     for (Node<K,V> p; (p = advance()) != null; )
2420     action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2421     }
2422    
2423     public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
2424     if (action == null) throw new NullPointerException();
2425     Node<K,V> p;
2426     if ((p = advance()) == null)
2427     return false;
2428     action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
2429     return true;
2430     }
2431    
2432     public long estimateSize() { return est; }
2433    
2434     public int characteristics() {
2435     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2436     Spliterator.NONNULL;
2437     }
2438     }
2439    
2440    
2441 dl 1.119 /* ---------------- Public operations -------------- */
2442    
2443     /**
2444     * Creates a new, empty map with the default initial table size (16).
2445     */
2446     public ConcurrentHashMap() {
2447     }
2448    
2449     /**
2450     * Creates a new, empty map with an initial table size
2451     * accommodating the specified number of elements without the need
2452     * to dynamically resize.
2453     *
2454     * @param initialCapacity The implementation performs internal
2455     * sizing to accommodate this many elements.
2456     * @throws IllegalArgumentException if the initial capacity of
2457     * elements is negative
2458     */
2459     public ConcurrentHashMap(int initialCapacity) {
2460     if (initialCapacity < 0)
2461     throw new IllegalArgumentException();
2462     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2463     MAXIMUM_CAPACITY :
2464     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2465     this.sizeCtl = cap;
2466     }
2467    
2468     /**
2469     * Creates a new map with the same mappings as the given map.
2470     *
2471     * @param m the map
2472     */
2473     public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2474     this.sizeCtl = DEFAULT_CAPACITY;
2475     internalPutAll(m);
2476     }
2477    
2478     /**
2479     * Creates a new, empty map with an initial table size based on
2480     * the given number of elements ({@code initialCapacity}) and
2481     * initial table density ({@code loadFactor}).
2482     *
2483     * @param initialCapacity the initial capacity. The implementation
2484     * performs internal sizing to accommodate this many elements,
2485     * given the specified load factor.
2486     * @param loadFactor the load factor (table density) for
2487     * establishing the initial table size
2488     * @throws IllegalArgumentException if the initial capacity of
2489     * elements is negative or the load factor is nonpositive
2490     *
2491     * @since 1.6
2492     */
2493     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2494     this(initialCapacity, loadFactor, 1);
2495     }
2496    
2497     /**
2498     * Creates a new, empty map with an initial table size based on
2499     * the given number of elements ({@code initialCapacity}), table
2500     * density ({@code loadFactor}), and number of concurrently
2501     * updating threads ({@code concurrencyLevel}).
2502     *
2503     * @param initialCapacity the initial capacity. The implementation
2504     * performs internal sizing to accommodate this many elements,
2505     * given the specified load factor.
2506     * @param loadFactor the load factor (table density) for
2507     * establishing the initial table size
2508     * @param concurrencyLevel the estimated number of concurrently
2509     * updating threads. The implementation may use this value as
2510     * a sizing hint.
2511     * @throws IllegalArgumentException if the initial capacity is
2512     * negative or the load factor or concurrencyLevel are
2513     * nonpositive
2514     */
2515     public ConcurrentHashMap(int initialCapacity,
2516 dl 1.210 float loadFactor, int concurrencyLevel) {
2517 dl 1.119 if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2518     throw new IllegalArgumentException();
2519     if (initialCapacity < concurrencyLevel) // Use at least as many bins
2520     initialCapacity = concurrencyLevel; // as estimated threads
2521     long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2522     int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2523     MAXIMUM_CAPACITY : tableSizeFor((int)size);
2524     this.sizeCtl = cap;
2525     }
2526    
2527     /**
2528 dl 1.137 * Creates a new {@link Set} backed by a ConcurrentHashMap
2529     * from the given type to {@code Boolean.TRUE}.
2530     *
2531     * @return the new set
2532     */
2533     public static <K> KeySetView<K,Boolean> newKeySet() {
2534 jsr166 1.184 return new KeySetView<K,Boolean>
2535     (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2536 dl 1.137 }
2537    
2538     /**
2539     * Creates a new {@link Set} backed by a ConcurrentHashMap
2540     * from the given type to {@code Boolean.TRUE}.
2541     *
2542     * @param initialCapacity The implementation performs internal
2543     * sizing to accommodate this many elements.
2544     * @throws IllegalArgumentException if the initial capacity of
2545     * elements is negative
2546     * @return the new set
2547     */
2548     public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2549 dl 1.149 return new KeySetView<K,Boolean>
2550     (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2551 dl 1.137 }
2552    
2553     /**
2554 dl 1.119 * {@inheritDoc}
2555     */
2556     public boolean isEmpty() {
2557 dl 1.149 return sumCount() <= 0L; // ignore transient negative values
2558 dl 1.119 }
2559    
2560     /**
2561     * {@inheritDoc}
2562     */
2563     public int size() {
2564 dl 1.149 long n = sumCount();
2565 dl 1.119 return ((n < 0L) ? 0 :
2566     (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2567     (int)n);
2568     }
2569    
2570     /**
2571     * Returns the number of mappings. This method should be used
2572     * instead of {@link #size} because a ConcurrentHashMap may
2573     * contain more mappings than can be represented as an int. The
2574 dl 1.146 * value returned is an estimate; the actual count may differ if
2575     * there are concurrent insertions or removals.
2576 dl 1.119 *
2577     * @return the number of mappings
2578     */
2579     public long mappingCount() {
2580 dl 1.149 long n = sumCount();
2581 dl 1.126 return (n < 0L) ? 0L : n; // ignore transient negative values
2582 dl 1.119 }
2583    
2584     /**
2585     * Returns the value to which the specified key is mapped,
2586     * or {@code null} if this map contains no mapping for the key.
2587     *
2588     * <p>More formally, if this map contains a mapping from a key
2589     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2590     * then this method returns {@code v}; otherwise it returns
2591     * {@code null}. (There can be at most one such mapping.)
2592     *
2593     * @throws NullPointerException if the specified key is null
2594     */
2595 dl 1.149 public V get(Object key) {
2596     return internalGet(key);
2597 dl 1.119 }
2598    
2599     /**
2600 dl 1.129 * Returns the value to which the specified key is mapped,
2601 jsr166 1.133 * or the given defaultValue if this map contains no mapping for the key.
2602 dl 1.129 *
2603     * @param key the key
2604     * @param defaultValue the value to return if this map contains
2605 jsr166 1.134 * no mapping for the given key
2606 dl 1.129 * @return the mapping for the key, if present; else the defaultValue
2607     * @throws NullPointerException if the specified key is null
2608     */
2609 dl 1.195 public V getOrDefault(Object key, V defaultValue) {
2610 dl 1.149 V v;
2611     return (v = internalGet(key)) == null ? defaultValue : v;
2612 dl 1.129 }
2613    
2614     /**
2615 dl 1.119 * Tests if the specified object is a key in this table.
2616     *
2617 jsr166 1.190 * @param key possible key
2618 dl 1.119 * @return {@code true} if and only if the specified object
2619     * is a key in this table, as determined by the
2620     * {@code equals} method; {@code false} otherwise
2621     * @throws NullPointerException if the specified key is null
2622     */
2623     public boolean containsKey(Object key) {
2624     return internalGet(key) != null;
2625     }
2626    
2627     /**
2628     * Returns {@code true} if this map maps one or more keys to the
2629     * specified value. Note: This method may require a full traversal
2630     * of the map, and is much slower than method {@code containsKey}.
2631     *
2632     * @param value value whose presence in this map is to be tested
2633     * @return {@code true} if this map maps one or more keys to the
2634     * specified value
2635     * @throws NullPointerException if the specified value is null
2636     */
2637     public boolean containsValue(Object value) {
2638     if (value == null)
2639     throw new NullPointerException();
2640 dl 1.210 Node<K,V>[] t;
2641     if ((t = table) != null) {
2642     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
2643     for (Node<K,V> p; (p = it.advance()) != null; ) {
2644     V v;
2645     if ((v = p.val) == value || value.equals(v))
2646     return true;
2647     }
2648 dl 1.119 }
2649     return false;
2650     }
2651    
2652     /**
2653     * Legacy method testing if some key maps into the specified value
2654     * in this table. This method is identical in functionality to
2655 jsr166 1.176 * {@link #containsValue(Object)}, and exists solely to ensure
2656 dl 1.119 * full compatibility with class {@link java.util.Hashtable},
2657     * which supported this method prior to introduction of the
2658     * Java Collections framework.
2659     *
2660     * @param value a value to search for
2661     * @return {@code true} if and only if some key maps to the
2662     * {@code value} argument in this table as
2663     * determined by the {@code equals} method;
2664     * {@code false} otherwise
2665     * @throws NullPointerException if the specified value is null
2666     */
2667 dl 1.151 @Deprecated public boolean contains(Object value) {
2668 dl 1.119 return containsValue(value);
2669     }
2670    
2671     /**
2672     * Maps the specified key to the specified value in this table.
2673     * Neither the key nor the value can be null.
2674     *
2675 jsr166 1.145 * <p>The value can be retrieved by calling the {@code get} method
2676 dl 1.119 * with a key that is equal to the original key.
2677     *
2678     * @param key key with which the specified value is to be associated
2679     * @param value value to be associated with the specified key
2680     * @return the previous value associated with {@code key}, or
2681     * {@code null} if there was no mapping for {@code key}
2682     * @throws NullPointerException if the specified key or value is null
2683     */
2684 dl 1.149 public V put(K key, V value) {
2685     return internalPut(key, value, false);
2686 dl 1.119 }
2687    
2688     /**
2689     * {@inheritDoc}
2690     *
2691     * @return the previous value associated with the specified key,
2692     * or {@code null} if there was no mapping for the key
2693     * @throws NullPointerException if the specified key or value is null
2694     */
2695 dl 1.149 public V putIfAbsent(K key, V value) {
2696     return internalPut(key, value, true);
2697 dl 1.119 }
2698    
2699     /**
2700     * Copies all of the mappings from the specified map to this one.
2701     * These mappings replace any mappings that this map had for any of the
2702     * keys currently in the specified map.
2703     *
2704     * @param m mappings to be stored in this map
2705     */
2706     public void putAll(Map<? extends K, ? extends V> m) {
2707     internalPutAll(m);
2708     }
2709    
2710     /**
2711 dl 1.153 * If the specified key is not already associated with a value (or
2712     * is mapped to {@code null}), attempts to compute its value using
2713     * the given mapping function and enters it into this map unless
2714     * {@code null}. The entire method invocation is performed
2715     * atomically, so the function is applied at most once per key.
2716     * Some attempted update operations on this map by other threads
2717     * may be blocked while computation is in progress, so the
2718     * computation should be short and simple, and must not attempt to
2719     * update any other mappings of this Map.
2720 dl 1.119 *
2721     * @param key key with which the specified value is to be associated
2722     * @param mappingFunction the function to compute a value
2723     * @return the current (existing or computed) value associated with
2724 jsr166 1.134 * the specified key, or null if the computed value is null
2725 dl 1.119 * @throws NullPointerException if the specified key or mappingFunction
2726     * is null
2727     * @throws IllegalStateException if the computation detectably
2728     * attempts a recursive update to this map that would
2729     * otherwise never complete
2730     * @throws RuntimeException or Error if the mappingFunction does so,
2731     * in which case the mapping is left unestablished
2732     */
2733 dl 1.210 public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
2734 dl 1.149 return internalComputeIfAbsent(key, mappingFunction);
2735 dl 1.119 }
2736    
2737     /**
2738 dl 1.153 * If the value for the specified key is present and non-null,
2739     * attempts to compute a new mapping given the key and its current
2740     * mapped value. The entire method invocation is performed
2741     * atomically. Some attempted update operations on this map by
2742 dl 1.119 * other threads may be blocked while computation is in progress,
2743     * so the computation should be short and simple, and must not
2744 dl 1.153 * attempt to update any other mappings of this Map.
2745 dl 1.119 *
2746 dl 1.197 * @param key key with which a value may be associated
2747 dl 1.119 * @param remappingFunction the function to compute a value
2748 jsr166 1.123 * @return the new value associated with the specified key, or null if none
2749 dl 1.119 * @throws NullPointerException if the specified key or remappingFunction
2750     * is null
2751     * @throws IllegalStateException if the computation detectably
2752     * attempts a recursive update to this map that would
2753     * otherwise never complete
2754     * @throws RuntimeException or Error if the remappingFunction does so,
2755     * in which case the mapping is unchanged
2756     */
2757 dl 1.210 public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2758 dl 1.149 return internalCompute(key, true, remappingFunction);
2759 dl 1.119 }
2760    
2761     /**
2762 dl 1.153 * Attempts to compute a mapping for the specified key and its
2763     * current mapped value (or {@code null} if there is no current
2764     * mapping). The entire method invocation is performed atomically.
2765     * Some attempted update operations on this map by other threads
2766     * may be blocked while computation is in progress, so the
2767     * computation should be short and simple, and must not attempt to
2768     * update any other mappings of this Map.
2769 dl 1.119 *
2770     * @param key key with which the specified value is to be associated
2771     * @param remappingFunction the function to compute a value
2772 jsr166 1.123 * @return the new value associated with the specified key, or null if none
2773 dl 1.119 * @throws NullPointerException if the specified key or remappingFunction
2774     * is null
2775     * @throws IllegalStateException if the computation detectably
2776     * attempts a recursive update to this map that would
2777     * otherwise never complete
2778     * @throws RuntimeException or Error if the remappingFunction does so,
2779     * in which case the mapping is unchanged
2780     */
2781 dl 1.210 public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2782 dl 1.149 return internalCompute(key, false, remappingFunction);
2783 dl 1.119 }
2784    
2785     /**
2786 dl 1.153 * If the specified key is not already associated with a
2787     * (non-null) value, associates it with the given value.
2788     * Otherwise, replaces the value with the results of the given
2789     * remapping function, or removes if {@code null}. The entire
2790     * method invocation is performed atomically. Some attempted
2791     * update operations on this map by other threads may be blocked
2792     * while computation is in progress, so the computation should be
2793     * short and simple, and must not attempt to update any other
2794     * mappings of this Map.
2795     *
2796     * @param key key with which the specified value is to be associated
2797     * @param value the value to use if absent
2798     * @param remappingFunction the function to recompute a value if present
2799     * @return the new value associated with the specified key, or null if none
2800     * @throws NullPointerException if the specified key or the
2801     * remappingFunction is null
2802     * @throws RuntimeException or Error if the remappingFunction does so,
2803     * in which case the mapping is unchanged
2804 dl 1.119 */
2805 dl 1.210 public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2806 dl 1.149 return internalMerge(key, value, remappingFunction);
2807 dl 1.119 }
2808    
2809     /**
2810     * Removes the key (and its corresponding value) from this map.
2811     * This method does nothing if the key is not in the map.
2812     *
2813     * @param key the key that needs to be removed
2814     * @return the previous value associated with {@code key}, or
2815     * {@code null} if there was no mapping for {@code key}
2816     * @throws NullPointerException if the specified key is null
2817     */
2818 dl 1.149 public V remove(Object key) {
2819     return internalReplace(key, null, null);
2820 dl 1.119 }
2821    
2822     /**
2823     * {@inheritDoc}
2824     *
2825     * @throws NullPointerException if the specified key is null
2826     */
2827     public boolean remove(Object key, Object value) {
2828 dl 1.163 if (key == null)
2829     throw new NullPointerException();
2830 dl 1.149 return value != null && internalReplace(key, null, value) != null;
2831 tim 1.1 }
2832 dl 1.31
2833     /**
2834 jsr166 1.68 * {@inheritDoc}
2835     *
2836     * @throws NullPointerException if any of the arguments are null
2837 dl 1.31 */
2838     public boolean replace(K key, V oldValue, V newValue) {
2839 dl 1.119 if (key == null || oldValue == null || newValue == null)
2840 dl 1.31 throw new NullPointerException();
2841 dl 1.119 return internalReplace(key, newValue, oldValue) != null;
2842 dl 1.32 }
2843    
2844     /**
2845 jsr166 1.68 * {@inheritDoc}
2846     *
2847     * @return the previous value associated with the specified key,
2848 dl 1.119 * or {@code null} if there was no mapping for the key
2849 jsr166 1.68 * @throws NullPointerException if the specified key or value is null
2850 dl 1.32 */
2851 dl 1.149 public V replace(K key, V value) {
2852 dl 1.119 if (key == null || value == null)
2853 dl 1.32 throw new NullPointerException();
2854 dl 1.149 return internalReplace(key, value, null);
2855 dl 1.31 }
2856    
2857 tim 1.1 /**
2858 jsr166 1.68 * Removes all of the mappings from this map.
2859 tim 1.1 */
2860     public void clear() {
2861 dl 1.119 internalClear();
2862 tim 1.1 }
2863    
2864     /**
2865 jsr166 1.68 * Returns a {@link Set} view of the keys contained in this map.
2866     * The set is backed by the map, so changes to the map are
2867 dl 1.210 * reflected in the set, and vice-versa. The set supports element
2868     * removal, which removes the corresponding mapping from this map,
2869     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
2870     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
2871     * operations. It does not support the <tt>add</tt> or
2872     * <tt>addAll</tt> operations.
2873     *
2874     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2875     * that will never throw {@link ConcurrentModificationException},
2876     * and guarantees to traverse elements as they existed upon
2877     * construction of the iterator, and may (but is not guaranteed to)
2878     * reflect any modifications subsequent to construction.
2879 dl 1.137 *
2880     * @return the set view
2881     */
2882     public KeySetView<K,V> keySet() {
2883     KeySetView<K,V> ks = keySet;
2884     return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2885     }
2886    
2887     /**
2888     * Returns a {@link Set} view of the keys in this map, using the
2889     * given common mapped value for any additions (i.e., {@link
2890 jsr166 1.174 * Collection#add} and {@link Collection#addAll(Collection)}).
2891     * This is of course only appropriate if it is acceptable to use
2892     * the same value for all additions from this view.
2893 jsr166 1.68 *
2894 jsr166 1.172 * @param mappedValue the mapped value to use for any additions
2895 dl 1.137 * @return the set view
2896     * @throws NullPointerException if the mappedValue is null
2897 tim 1.1 */
2898 dl 1.137 public KeySetView<K,V> keySet(V mappedValue) {
2899     if (mappedValue == null)
2900     throw new NullPointerException();
2901     return new KeySetView<K,V>(this, mappedValue);
2902 tim 1.1 }
2903    
2904     /**
2905 jsr166 1.68 * Returns a {@link Collection} view of the values contained in this map.
2906     * The collection is backed by the map, so changes to the map are
2907 dl 1.210 * reflected in the collection, and vice-versa. The collection
2908     * supports element removal, which removes the corresponding
2909     * mapping from this map, via the <tt>Iterator.remove</tt>,
2910     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
2911     * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
2912     * support the <tt>add</tt> or <tt>addAll</tt> operations.
2913     *
2914     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2915     * that will never throw {@link ConcurrentModificationException},
2916     * and guarantees to traverse elements as they existed upon
2917     * construction of the iterator, and may (but is not guaranteed to)
2918     * reflect any modifications subsequent to construction.
2919 jsr166 1.184 *
2920     * @return the collection view
2921 tim 1.1 */
2922 dl 1.210 public Collection<V> values() {
2923 dl 1.142 ValuesView<K,V> vs = values;
2924     return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2925 dl 1.119 }
2926    
2927     /**
2928     * Returns a {@link Set} view of the mappings contained in this map.
2929     * The set is backed by the map, so changes to the map are
2930     * reflected in the set, and vice-versa. The set supports element
2931     * removal, which removes the corresponding mapping from the map,
2932     * via the {@code Iterator.remove}, {@code Set.remove},
2933     * {@code removeAll}, {@code retainAll}, and {@code clear}
2934 dl 1.210 * operations.
2935 dl 1.119 *
2936     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2937     * that will never throw {@link ConcurrentModificationException},
2938     * and guarantees to traverse elements as they existed upon
2939     * construction of the iterator, and may (but is not guaranteed to)
2940     * reflect any modifications subsequent to construction.
2941 jsr166 1.184 *
2942     * @return the set view
2943 dl 1.119 */
2944     public Set<Map.Entry<K,V>> entrySet() {
2945 dl 1.142 EntrySetView<K,V> es = entrySet;
2946     return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2947 dl 1.119 }
2948    
2949     /**
2950     * Returns an enumeration of the keys in this table.
2951     *
2952     * @return an enumeration of the keys in this table
2953     * @see #keySet()
2954     */
2955     public Enumeration<K> keys() {
2956 dl 1.210 Node<K,V>[] t;
2957     int f = (t = table) == null ? 0 : t.length;
2958     return new KeyIterator<K,V>(t, f, 0, f, this);
2959 dl 1.119 }
2960    
2961     /**
2962     * Returns an enumeration of the values in this table.
2963     *
2964     * @return an enumeration of the values in this table
2965     * @see #values()
2966     */
2967     public Enumeration<V> elements() {
2968 dl 1.210 Node<K,V>[] t;
2969     int f = (t = table) == null ? 0 : t.length;
2970     return new ValueIterator<K,V>(t, f, 0, f, this);
2971 dl 1.119 }
2972    
2973     /**
2974     * Returns the hash code value for this {@link Map}, i.e.,
2975     * the sum of, for each key-value pair in the map,
2976     * {@code key.hashCode() ^ value.hashCode()}.
2977     *
2978     * @return the hash code value for this map
2979     */
2980     public int hashCode() {
2981     int h = 0;
2982 dl 1.210 Node<K,V>[] t;
2983     if ((t = table) != null) {
2984     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
2985     for (Node<K,V> p; (p = it.advance()) != null; )
2986     h += p.key.hashCode() ^ p.val.hashCode();
2987 dl 1.119 }
2988     return h;
2989     }
2990    
2991     /**
2992     * Returns a string representation of this map. The string
2993     * representation consists of a list of key-value mappings (in no
2994     * particular order) enclosed in braces ("{@code {}}"). Adjacent
2995     * mappings are separated by the characters {@code ", "} (comma
2996     * and space). Each key-value mapping is rendered as the key
2997     * followed by an equals sign ("{@code =}") followed by the
2998     * associated value.
2999     *
3000     * @return a string representation of this map
3001     */
3002     public String toString() {
3003 dl 1.210 Node<K,V>[] t;
3004     int f = (t = table) == null ? 0 : t.length;
3005     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3006 dl 1.119 StringBuilder sb = new StringBuilder();
3007     sb.append('{');
3008 dl 1.210 Node<K,V> p;
3009     if ((p = it.advance()) != null) {
3010 dl 1.119 for (;;) {
3011 dl 1.210 K k = (K)p.key;
3012     V v = p.val;
3013 dl 1.119 sb.append(k == this ? "(this Map)" : k);
3014     sb.append('=');
3015     sb.append(v == this ? "(this Map)" : v);
3016 dl 1.210 if ((p = it.advance()) == null)
3017 dl 1.119 break;
3018     sb.append(',').append(' ');
3019     }
3020     }
3021     return sb.append('}').toString();
3022     }
3023    
3024     /**
3025     * Compares the specified object with this map for equality.
3026     * Returns {@code true} if the given object is a map with the same
3027     * mappings as this map. This operation may return misleading
3028     * results if either map is concurrently modified during execution
3029     * of this method.
3030     *
3031     * @param o object to be compared for equality with this map
3032     * @return {@code true} if the specified object is equal to this map
3033     */
3034     public boolean equals(Object o) {
3035     if (o != this) {
3036     if (!(o instanceof Map))
3037     return false;
3038     Map<?,?> m = (Map<?,?>) o;
3039 dl 1.210 Node<K,V>[] t;
3040     int f = (t = table) == null ? 0 : t.length;
3041     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
3042     for (Node<K,V> p; (p = it.advance()) != null; ) {
3043     V val = p.val;
3044     Object v = m.get(p.key);
3045 dl 1.119 if (v == null || (v != val && !v.equals(val)))
3046     return false;
3047     }
3048     for (Map.Entry<?,?> e : m.entrySet()) {
3049     Object mk, mv, v;
3050     if ((mk = e.getKey()) == null ||
3051     (mv = e.getValue()) == null ||
3052     (v = internalGet(mk)) == null ||
3053     (mv != v && !mv.equals(v)))
3054     return false;
3055     }
3056     }
3057     return true;
3058     }
3059    
3060 dl 1.142 /* ---------------- Serialization Support -------------- */
3061 dl 1.119
3062     /**
3063 dl 1.142 * Stripped-down version of helper class used in previous version,
3064     * declared for the sake of serialization compatibility
3065 dl 1.119 */
3066 dl 1.208 static class Segment<K,V> extends ReentrantLock implements Serializable {
3067 dl 1.142 private static final long serialVersionUID = 2249069246763182397L;
3068     final float loadFactor;
3069     Segment(float lf) { this.loadFactor = lf; }
3070     }
3071 dl 1.119
3072 dl 1.142 /**
3073     * Saves the state of the {@code ConcurrentHashMap} instance to a
3074     * stream (i.e., serializes it).
3075     * @param s the stream
3076     * @serialData
3077     * the key (Object) and value (Object)
3078     * for each key-value mapping, followed by a null pair.
3079     * The key-value mappings are emitted in no particular order.
3080     */
3081 dl 1.210 private void writeObject(java.io.ObjectOutputStream s)
3082 dl 1.142 throws java.io.IOException {
3083 dl 1.208 // For serialization compatibility
3084 dl 1.209 // Emulate segment calculation from previous version of this class
3085     int sshift = 0;
3086     int ssize = 1;
3087     while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
3088     ++sshift;
3089     ssize <<= 1;
3090     }
3091     int segmentShift = 32 - sshift;
3092     int segmentMask = ssize - 1;
3093 dl 1.208 Segment<K,V>[] segments = (Segment<K,V>[])
3094     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3095     for (int i = 0; i < segments.length; ++i)
3096     segments[i] = new Segment<K,V>(LOAD_FACTOR);
3097     s.putFields().put("segments", segments);
3098 dl 1.209 s.putFields().put("segmentShift", segmentShift);
3099     s.putFields().put("segmentMask", segmentMask);
3100 dl 1.210 s.writeFields();
3101 dl 1.209
3102 dl 1.210 Node<K,V>[] t;
3103     if ((t = table) != null) {
3104     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3105     for (Node<K,V> p; (p = it.advance()) != null; ) {
3106     s.writeObject(p.key);
3107     s.writeObject(p.val);
3108     }
3109 dl 1.142 }
3110     s.writeObject(null);
3111     s.writeObject(null);
3112     segments = null; // throw away
3113     }
3114 dl 1.119
3115 dl 1.142 /**
3116     * Reconstitutes the instance from a stream (that is, deserializes it).
3117     * @param s the stream
3118     */
3119 dl 1.210 private void readObject(java.io.ObjectInputStream s)
3120 dl 1.142 throws java.io.IOException, ClassNotFoundException {
3121     s.defaultReadObject();
3122 dl 1.119
3123 dl 1.142 // Create all nodes, then place in table once size is known
3124     long size = 0L;
3125 dl 1.210 Node<K,V> p = null;
3126 dl 1.142 for (;;) {
3127     K k = (K) s.readObject();
3128     V v = (V) s.readObject();
3129     if (k != null && v != null) {
3130     int h = spread(k.hashCode());
3131 dl 1.210 p = new Node<K,V>(h, k, v, p);
3132 dl 1.142 ++size;
3133 dl 1.119 }
3134 dl 1.142 else
3135     break;
3136 dl 1.119 }
3137 dl 1.142 if (p != null) {
3138     boolean init = false;
3139     int n;
3140     if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3141     n = MAXIMUM_CAPACITY;
3142     else {
3143     int sz = (int)size;
3144     n = tableSizeFor(sz + (sz >>> 1) + 1);
3145     }
3146     int sc = sizeCtl;
3147     boolean collide = false;
3148     if (n > sc &&
3149 dl 1.149 U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3150 dl 1.142 try {
3151     if (table == null) {
3152     init = true;
3153 dl 1.210 Node<K,V>[] tab = (Node<K,V>[])new Node[n];
3154 dl 1.142 int mask = n - 1;
3155     while (p != null) {
3156     int j = p.hash & mask;
3157 dl 1.210 Node<K,V> next = p.next;
3158     Node<K,V> q = p.next = tabAt(tab, j);
3159 dl 1.142 setTabAt(tab, j, p);
3160     if (!collide && q != null && q.hash == p.hash)
3161     collide = true;
3162     p = next;
3163     }
3164     table = tab;
3165 dl 1.149 addCount(size, -1);
3166 dl 1.142 sc = n - (n >>> 2);
3167     }
3168     } finally {
3169     sizeCtl = sc;
3170     }
3171     if (collide) { // rescan and convert to TreeBins
3172 dl 1.210 Node<K,V>[] tab = table;
3173 dl 1.142 for (int i = 0; i < tab.length; ++i) {
3174     int c = 0;
3175 dl 1.210 for (Node<K,V> e = tabAt(tab, i); e != null; e = e.next) {
3176 dl 1.142 if (++c > TREE_THRESHOLD &&
3177     (e.key instanceof Comparable)) {
3178     replaceWithTreeBin(tab, i, e.key);
3179     break;
3180     }
3181     }
3182     }
3183 dl 1.119 }
3184     }
3185 dl 1.142 if (!init) { // Can only happen if unsafely published.
3186     while (p != null) {
3187 dl 1.151 internalPut((K)p.key, p.val, false);
3188 dl 1.142 p = p.next;
3189     }
3190 dl 1.119 }
3191     }
3192 dl 1.142 }
3193 dl 1.119
3194 dl 1.142 // -------------------------------------------------------
3195    
3196 dl 1.210 // Overrides of other default Map methods
3197    
3198     public void forEach(BiConsumer<? super K, ? super V> action) {
3199     if (action == null) throw new NullPointerException();
3200     Node<K,V>[] t;
3201     if ((t = table) != null) {
3202     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3203     for (Node<K,V> p; (p = it.advance()) != null; ) {
3204     action.accept((K)p.key, p.val);
3205     }
3206     }
3207     }
3208    
3209     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3210     if (function == null) throw new NullPointerException();
3211     Node<K,V>[] t;
3212     if ((t = table) != null) {
3213     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3214     for (Node<K,V> p; (p = it.advance()) != null; ) {
3215     K k = (K)p.key;
3216     internalPut(k, function.apply(k, p.val), false);
3217     }
3218     }
3219     }
3220    
3221     // -------------------------------------------------------
3222    
3223     // Parallel bulk operations
3224    
3225     /**
3226     * Computes initial batch value for bulk tasks. The returned value
3227     * is approximately exp2 of the number of times (minus one) to
3228     * split task by two before executing leaf action. This value is
3229     * faster to compute and more convenient to use as a guide to
3230     * splitting than is the depth, since it is used while dividing by
3231     * two anyway.
3232     */
3233     final int batchFor(long b) {
3234     long n;
3235     if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b)
3236     return 0;
3237     int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4
3238     return (b <= 0L || (n /= b) >= sp) ? sp : (int)n;
3239     }
3240 dl 1.151
3241 dl 1.119 /**
3242 dl 1.137 * Performs the given action for each (key, value).
3243 dl 1.119 *
3244 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3245     * needed for this operation to be executed in parallel.
3246 dl 1.137 * @param action the action
3247 dl 1.119 */
3248 dl 1.210 public void forEach(long parallelismThreshold,
3249     BiConsumer<? super K,? super V> action) {
3250 dl 1.151 if (action == null) throw new NullPointerException();
3251 dl 1.210 new ForEachMappingTask<K,V>
3252     (null, batchFor(parallelismThreshold), 0, 0, table,
3253     action).invoke();
3254 dl 1.119 }
3255    
3256     /**
3257 dl 1.137 * Performs the given action for each non-null transformation
3258     * of each (key, value).
3259     *
3260 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3261     * needed for this operation to be executed in parallel.
3262 dl 1.137 * @param transformer a function returning the transformation
3263 jsr166 1.169 * for an element, or null if there is no transformation (in
3264 jsr166 1.172 * which case the action is not applied)
3265 dl 1.137 * @param action the action
3266 dl 1.119 */
3267 dl 1.210 public <U> void forEach(long parallelismThreshold,
3268     BiFunction<? super K, ? super V, ? extends U> transformer,
3269     Consumer<? super U> action) {
3270 dl 1.151 if (transformer == null || action == null)
3271     throw new NullPointerException();
3272 dl 1.210 new ForEachTransformedMappingTask<K,V,U>
3273     (null, batchFor(parallelismThreshold), 0, 0, table,
3274     transformer, action).invoke();
3275 dl 1.137 }
3276    
3277     /**
3278     * Returns a non-null result from applying the given search
3279 dl 1.210 * function on each (key, value), or null if none. Upon
3280     * success, further element processing is suppressed and the
3281     * results of any other parallel invocations of the search
3282     * function are ignored.
3283 dl 1.137 *
3284 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3285     * needed for this operation to be executed in parallel.
3286 dl 1.137 * @param searchFunction a function returning a non-null
3287     * result on success, else null
3288     * @return a non-null result from applying the given search
3289     * function on each (key, value), or null if none
3290     */
3291 dl 1.210 public <U> U search(long parallelismThreshold,
3292     BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3293 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3294 dl 1.210 return new SearchMappingsTask<K,V,U>
3295     (null, batchFor(parallelismThreshold), 0, 0, table,
3296     searchFunction, new AtomicReference<U>()).invoke();
3297 dl 1.137 }
3298    
3299     /**
3300     * Returns the result of accumulating the given transformation
3301     * of all (key, value) pairs using the given reducer to
3302     * combine values, or null if none.
3303     *
3304 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3305     * needed for this operation to be executed in parallel.
3306 dl 1.137 * @param transformer a function returning the transformation
3307 jsr166 1.169 * for an element, or null if there is no transformation (in
3308 jsr166 1.172 * which case it is not combined)
3309 dl 1.137 * @param reducer a commutative associative combining function
3310     * @return the result of accumulating the given transformation
3311     * of all (key, value) pairs
3312     */
3313 dl 1.210 public <U> U reduce(long parallelismThreshold,
3314     BiFunction<? super K, ? super V, ? extends U> transformer,
3315     BiFunction<? super U, ? super U, ? extends U> reducer) {
3316 dl 1.151 if (transformer == null || reducer == null)
3317     throw new NullPointerException();
3318 dl 1.210 return new MapReduceMappingsTask<K,V,U>
3319     (null, batchFor(parallelismThreshold), 0, 0, table,
3320     null, transformer, reducer).invoke();
3321 dl 1.137 }
3322    
3323     /**
3324     * Returns the result of accumulating the given transformation
3325     * of all (key, value) pairs using the given reducer to
3326     * combine values, and the given basis as an identity value.
3327     *
3328 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3329     * needed for this operation to be executed in parallel.
3330 dl 1.137 * @param transformer a function returning the transformation
3331     * for an element
3332     * @param basis the identity (initial default value) for the reduction
3333     * @param reducer a commutative associative combining function
3334     * @return the result of accumulating the given transformation
3335     * of all (key, value) pairs
3336     */
3337 dl 1.210 public double reduceToDoubleIn(long parallelismThreshold,
3338     ToDoubleBiFunction<? super K, ? super V> transformer,
3339     double basis,
3340     DoubleBinaryOperator reducer) {
3341 dl 1.151 if (transformer == null || reducer == null)
3342     throw new NullPointerException();
3343 dl 1.210 return new MapReduceMappingsToDoubleTask<K,V>
3344     (null, batchFor(parallelismThreshold), 0, 0, table,
3345     null, transformer, basis, reducer).invoke();
3346 dl 1.137 }
3347 dl 1.119
3348 dl 1.137 /**
3349     * Returns the result of accumulating the given transformation
3350     * of all (key, value) pairs using the given reducer to
3351     * combine values, and the given basis as an identity value.
3352     *
3353 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3354     * needed for this operation to be executed in parallel.
3355 dl 1.137 * @param transformer a function returning the transformation
3356     * for an element
3357     * @param basis the identity (initial default value) for the reduction
3358     * @param reducer a commutative associative combining function
3359     * @return the result of accumulating the given transformation
3360     * of all (key, value) pairs
3361     */
3362 dl 1.210 public long reduceToLong(long parallelismThreshold,
3363     ToLongBiFunction<? super K, ? super V> transformer,
3364     long basis,
3365     LongBinaryOperator reducer) {
3366 dl 1.151 if (transformer == null || reducer == null)
3367     throw new NullPointerException();
3368 dl 1.210 return new MapReduceMappingsToLongTask<K,V>
3369     (null, batchFor(parallelismThreshold), 0, 0, table,
3370     null, transformer, basis, reducer).invoke();
3371 dl 1.137 }
3372    
3373     /**
3374     * Returns the result of accumulating the given transformation
3375     * of all (key, value) pairs using the given reducer to
3376     * combine values, and the given basis as an identity value.
3377     *
3378 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3379     * needed for this operation to be executed in parallel.
3380 dl 1.137 * @param transformer a function returning the transformation
3381     * for an element
3382     * @param basis the identity (initial default value) for the reduction
3383     * @param reducer a commutative associative combining function
3384     * @return the result of accumulating the given transformation
3385     * of all (key, value) pairs
3386     */
3387 dl 1.210 public int reduceToInt(long parallelismThreshold,
3388     ToIntBiFunction<? super K, ? super V> transformer,
3389     int basis,
3390     IntBinaryOperator reducer) {
3391 dl 1.151 if (transformer == null || reducer == null)
3392     throw new NullPointerException();
3393 dl 1.210 return new MapReduceMappingsToIntTask<K,V>
3394     (null, batchFor(parallelismThreshold), 0, 0, table,
3395     null, transformer, basis, reducer).invoke();
3396 dl 1.137 }
3397    
3398     /**
3399     * Performs the given action for each key.
3400     *
3401 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3402     * needed for this operation to be executed in parallel.
3403 dl 1.137 * @param action the action
3404     */
3405 dl 1.210 public void forEachKey(long parallelismThreshold,
3406     Consumer<? super K> action) {
3407     if (action == null) throw new NullPointerException();
3408     new ForEachKeyTask<K,V>
3409     (null, batchFor(parallelismThreshold), 0, 0, table,
3410     action).invoke();
3411 dl 1.137 }
3412 dl 1.119
3413 dl 1.137 /**
3414     * Performs the given action for each non-null transformation
3415     * of each key.
3416     *
3417 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3418     * needed for this operation to be executed in parallel.
3419 dl 1.137 * @param transformer a function returning the transformation
3420 jsr166 1.169 * for an element, or null if there is no transformation (in
3421 jsr166 1.172 * which case the action is not applied)
3422 dl 1.137 * @param action the action
3423     */
3424 dl 1.210 public <U> void forEachKey(long parallelismThreshold,
3425     Function<? super K, ? extends U> transformer,
3426     Consumer<? super U> action) {
3427 dl 1.151 if (transformer == null || action == null)
3428     throw new NullPointerException();
3429 dl 1.210 new ForEachTransformedKeyTask<K,V,U>
3430     (null, batchFor(parallelismThreshold), 0, 0, table,
3431     transformer, action).invoke();
3432 dl 1.137 }
3433 dl 1.119
3434 dl 1.137 /**
3435     * Returns a non-null result from applying the given search
3436 dl 1.210 * function on each key, or null if none. Upon success,
3437     * further element processing is suppressed and the results of
3438     * any other parallel invocations of the search function are
3439     * ignored.
3440 dl 1.137 *
3441 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3442     * needed for this operation to be executed in parallel.
3443 dl 1.137 * @param searchFunction a function returning a non-null
3444     * result on success, else null
3445     * @return a non-null result from applying the given search
3446     * function on each key, or null if none
3447     */
3448 dl 1.210 public <U> U searchKeys(long parallelismThreshold,
3449     Function<? super K, ? extends U> searchFunction) {
3450     if (searchFunction == null) throw new NullPointerException();
3451     return new SearchKeysTask<K,V,U>
3452     (null, batchFor(parallelismThreshold), 0, 0, table,
3453     searchFunction, new AtomicReference<U>()).invoke();
3454 dl 1.137 }
3455 dl 1.119
3456 dl 1.137 /**
3457     * Returns the result of accumulating all keys using the given
3458     * reducer to combine values, or null if none.
3459     *
3460 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3461     * needed for this operation to be executed in parallel.
3462 dl 1.137 * @param reducer a commutative associative combining function
3463     * @return the result of accumulating all keys using the given
3464     * reducer to combine values, or null if none
3465     */
3466 dl 1.210 public K reduceKeys(long parallelismThreshold,
3467     BiFunction<? super K, ? super K, ? extends K> reducer) {
3468 dl 1.151 if (reducer == null) throw new NullPointerException();
3469 dl 1.210 return new ReduceKeysTask<K,V>
3470     (null, batchFor(parallelismThreshold), 0, 0, table,
3471     null, reducer).invoke();
3472 dl 1.137 }
3473 dl 1.119
3474 dl 1.137 /**
3475     * Returns the result of accumulating the given transformation
3476     * of all keys using the given reducer to combine values, or
3477     * null if none.
3478     *
3479 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3480     * needed for this operation to be executed in parallel.
3481 dl 1.137 * @param transformer a function returning the transformation
3482 jsr166 1.169 * for an element, or null if there is no transformation (in
3483 jsr166 1.172 * which case it is not combined)
3484 dl 1.137 * @param reducer a commutative associative combining function
3485     * @return the result of accumulating the given transformation
3486     * of all keys
3487     */
3488 dl 1.210 public <U> U reduceKeys(long parallelismThreshold,
3489     Function<? super K, ? extends U> transformer,
3490 dl 1.153 BiFunction<? super U, ? super U, ? extends U> reducer) {
3491 dl 1.151 if (transformer == null || reducer == null)
3492     throw new NullPointerException();
3493 dl 1.210 return new MapReduceKeysTask<K,V,U>
3494     (null, batchFor(parallelismThreshold), 0, 0, table,
3495     null, transformer, reducer).invoke();
3496 dl 1.137 }
3497 dl 1.119
3498 dl 1.137 /**
3499     * Returns the result of accumulating the given transformation
3500     * of all keys using the given reducer to combine values, and
3501     * the given basis as an identity value.
3502     *
3503 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3504     * needed for this operation to be executed in parallel.
3505 dl 1.137 * @param transformer a function returning the transformation
3506     * for an element
3507     * @param basis the identity (initial default value) for the reduction
3508     * @param reducer a commutative associative combining function
3509 jsr166 1.157 * @return the result of accumulating the given transformation
3510 dl 1.137 * of all keys
3511     */
3512 dl 1.210 public double reduceKeysToDouble(long parallelismThreshold,
3513     ToDoubleFunction<? super K> transformer,
3514     double basis,
3515     DoubleBinaryOperator reducer) {
3516 dl 1.151 if (transformer == null || reducer == null)
3517     throw new NullPointerException();
3518 dl 1.210 return new MapReduceKeysToDoubleTask<K,V>
3519     (null, batchFor(parallelismThreshold), 0, 0, table,
3520     null, transformer, basis, reducer).invoke();
3521 dl 1.137 }
3522 dl 1.119
3523 dl 1.137 /**
3524     * Returns the result of accumulating the given transformation
3525     * of all keys using the given reducer to combine values, and
3526     * the given basis as an identity value.
3527     *
3528 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3529     * needed for this operation to be executed in parallel.
3530 dl 1.137 * @param transformer a function returning the transformation
3531     * for an element
3532     * @param basis the identity (initial default value) for the reduction
3533     * @param reducer a commutative associative combining function
3534     * @return the result of accumulating the given transformation
3535     * of all keys
3536     */
3537 dl 1.210 public long reduceKeysToLong(long parallelismThreshold,
3538     ToLongFunction<? super K> transformer,
3539     long basis,
3540     LongBinaryOperator reducer) {
3541 dl 1.151 if (transformer == null || reducer == null)
3542     throw new NullPointerException();
3543 dl 1.210 return new MapReduceKeysToLongTask<K,V>
3544     (null, batchFor(parallelismThreshold), 0, 0, table,
3545     null, transformer, basis, reducer).invoke();
3546 dl 1.137 }
3547 dl 1.119
3548 dl 1.137 /**
3549     * Returns the result of accumulating the given transformation
3550     * of all keys using the given reducer to combine values, and
3551     * the given basis as an identity value.
3552     *
3553 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3554     * needed for this operation to be executed in parallel.
3555 dl 1.137 * @param transformer a function returning the transformation
3556     * for an element
3557     * @param basis the identity (initial default value) for the reduction
3558     * @param reducer a commutative associative combining function
3559     * @return the result of accumulating the given transformation
3560     * of all keys
3561     */
3562 dl 1.210 public int reduceKeysToInt(long parallelismThreshold,
3563     ToIntFunction<? super K> transformer,
3564     int basis,
3565     IntBinaryOperator reducer) {
3566 dl 1.151 if (transformer == null || reducer == null)
3567     throw new NullPointerException();
3568 dl 1.210 return new MapReduceKeysToIntTask<K,V>
3569     (null, batchFor(parallelismThreshold), 0, 0, table,
3570     null, transformer, basis, reducer).invoke();
3571 dl 1.137 }
3572 dl 1.119
3573 dl 1.137 /**
3574     * Performs the given action for each value.
3575     *
3576 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3577     * needed for this operation to be executed in parallel.
3578 dl 1.137 * @param action the action
3579     */
3580 dl 1.210 public void forEachValue(long parallelismThreshold,
3581     Consumer<? super V> action) {
3582     if (action == null)
3583     throw new NullPointerException();
3584     new ForEachValueTask<K,V>
3585     (null, batchFor(parallelismThreshold), 0, 0, table,
3586     action).invoke();
3587 dl 1.137 }
3588 dl 1.119
3589 dl 1.137 /**
3590     * Performs the given action for each non-null transformation
3591     * of each value.
3592     *
3593 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3594     * needed for this operation to be executed in parallel.
3595 dl 1.137 * @param transformer a function returning the transformation
3596 jsr166 1.169 * for an element, or null if there is no transformation (in
3597 jsr166 1.172 * which case the action is not applied)
3598 jsr166 1.179 * @param action the action
3599 dl 1.137 */
3600 dl 1.210 public <U> void forEachValue(long parallelismThreshold,
3601     Function<? super V, ? extends U> transformer,
3602     Consumer<? super U> action) {
3603 dl 1.151 if (transformer == null || action == null)
3604     throw new NullPointerException();
3605 dl 1.210 new ForEachTransformedValueTask<K,V,U>
3606     (null, batchFor(parallelismThreshold), 0, 0, table,
3607     transformer, action).invoke();
3608 dl 1.137 }
3609 dl 1.119
3610 dl 1.137 /**
3611     * Returns a non-null result from applying the given search
3612 dl 1.210 * function on each value, or null if none. Upon success,
3613     * further element processing is suppressed and the results of
3614     * any other parallel invocations of the search function are
3615     * ignored.
3616 dl 1.137 *
3617 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3618     * needed for this operation to be executed in parallel.
3619 dl 1.137 * @param searchFunction a function returning a non-null
3620     * result on success, else null
3621     * @return a non-null result from applying the given search
3622     * function on each value, or null if none
3623     */
3624 dl 1.210 public <U> U searchValues(long parallelismThreshold,
3625     Function<? super V, ? extends U> searchFunction) {
3626 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3627 dl 1.210 return new SearchValuesTask<K,V,U>
3628     (null, batchFor(parallelismThreshold), 0, 0, table,
3629     searchFunction, new AtomicReference<U>()).invoke();
3630 dl 1.137 }
3631 dl 1.119
3632 dl 1.137 /**
3633     * Returns the result of accumulating all values using the
3634     * given reducer to combine values, or null if none.
3635     *
3636 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3637     * needed for this operation to be executed in parallel.
3638 dl 1.137 * @param reducer a commutative associative combining function
3639 jsr166 1.157 * @return the result of accumulating all values
3640 dl 1.137 */
3641 dl 1.210 public V reduceValues(long parallelismThreshold,
3642     BiFunction<? super V, ? super V, ? extends V> reducer) {
3643 dl 1.151 if (reducer == null) throw new NullPointerException();
3644 dl 1.210 return new ReduceValuesTask<K,V>
3645     (null, batchFor(parallelismThreshold), 0, 0, table,
3646     null, reducer).invoke();
3647 dl 1.137 }
3648 dl 1.119
3649 dl 1.137 /**
3650     * Returns the result of accumulating the given transformation
3651     * of all values using the given reducer to combine values, or
3652     * null if none.
3653     *
3654 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3655     * needed for this operation to be executed in parallel.
3656 dl 1.137 * @param transformer a function returning the transformation
3657 jsr166 1.169 * for an element, or null if there is no transformation (in
3658 jsr166 1.172 * which case it is not combined)
3659 dl 1.137 * @param reducer a commutative associative combining function
3660     * @return the result of accumulating the given transformation
3661     * of all values
3662     */
3663 dl 1.210 public <U> U reduceValues(long parallelismThreshold,
3664     Function<? super V, ? extends U> transformer,
3665     BiFunction<? super U, ? super U, ? extends U> reducer) {
3666 dl 1.151 if (transformer == null || reducer == null)
3667     throw new NullPointerException();
3668 dl 1.210 return new MapReduceValuesTask<K,V,U>
3669     (null, batchFor(parallelismThreshold), 0, 0, table,
3670     null, transformer, reducer).invoke();
3671 dl 1.137 }
3672 dl 1.119
3673 dl 1.137 /**
3674     * Returns the result of accumulating the given transformation
3675     * of all values using the given reducer to combine values,
3676     * and the given basis as an identity value.
3677     *
3678 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3679     * needed for this operation to be executed in parallel.
3680 dl 1.137 * @param transformer a function returning the transformation
3681     * for an element
3682     * @param basis the identity (initial default value) for the reduction
3683     * @param reducer a commutative associative combining function
3684     * @return the result of accumulating the given transformation
3685     * of all values
3686     */
3687 dl 1.210 public double reduceValuesToDouble(long parallelismThreshold,
3688     ToDoubleFunction<? super V> transformer,
3689     double basis,
3690     DoubleBinaryOperator reducer) {
3691 dl 1.151 if (transformer == null || reducer == null)
3692     throw new NullPointerException();
3693 dl 1.210 return new MapReduceValuesToDoubleTask<K,V>
3694     (null, batchFor(parallelismThreshold), 0, 0, table,
3695     null, transformer, basis, reducer).invoke();
3696 dl 1.137 }
3697 dl 1.119
3698 dl 1.137 /**
3699     * Returns the result of accumulating the given transformation
3700     * of all values using the given reducer to combine values,
3701     * and the given basis as an identity value.
3702     *
3703 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3704     * needed for this operation to be executed in parallel.
3705 dl 1.137 * @param transformer a function returning the transformation
3706     * for an element
3707     * @param basis the identity (initial default value) for the reduction
3708     * @param reducer a commutative associative combining function
3709     * @return the result of accumulating the given transformation
3710     * of all values
3711     */
3712 dl 1.210 public long reduceValuesToLong(long parallelismThreshold,
3713     ToLongFunction<? super V> transformer,
3714     long basis,
3715     LongBinaryOperator reducer) {
3716 dl 1.151 if (transformer == null || reducer == null)
3717     throw new NullPointerException();
3718 dl 1.210 return new MapReduceValuesToLongTask<K,V>
3719     (null, batchFor(parallelismThreshold), 0, 0, table,
3720     null, transformer, basis, reducer).invoke();
3721 dl 1.137 }
3722 dl 1.119
3723 dl 1.137 /**
3724     * Returns the result of accumulating the given transformation
3725     * of all values using the given reducer to combine values,
3726     * and the given basis as an identity value.
3727     *
3728 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3729     * needed for this operation to be executed in parallel.
3730 dl 1.137 * @param transformer a function returning the transformation
3731     * for an element
3732     * @param basis the identity (initial default value) for the reduction
3733     * @param reducer a commutative associative combining function
3734     * @return the result of accumulating the given transformation
3735     * of all values
3736     */
3737 dl 1.210 public int reduceValuesToInt(long parallelismThreshold,
3738     ToIntFunction<? super V> transformer,
3739     int basis,
3740     IntBinaryOperator reducer) {
3741 dl 1.151 if (transformer == null || reducer == null)
3742     throw new NullPointerException();
3743 dl 1.210 return new MapReduceValuesToIntTask<K,V>
3744     (null, batchFor(parallelismThreshold), 0, 0, table,
3745     null, transformer, basis, reducer).invoke();
3746 dl 1.137 }
3747 dl 1.119
3748 dl 1.137 /**
3749     * Performs the given action for each entry.
3750     *
3751 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3752     * needed for this operation to be executed in parallel.
3753 dl 1.137 * @param action the action
3754     */
3755 dl 1.210 public void forEachEntry(long parallelismThreshold,
3756     Consumer<? super Map.Entry<K,V>> action) {
3757 dl 1.151 if (action == null) throw new NullPointerException();
3758 dl 1.210 new ForEachEntryTask<K,V>(null, batchFor(parallelismThreshold), 0, 0, table,
3759     action).invoke();
3760 dl 1.137 }
3761 dl 1.119
3762 dl 1.137 /**
3763     * Performs the given action for each non-null transformation
3764     * of each entry.
3765     *
3766 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3767     * needed for this operation to be executed in parallel.
3768 dl 1.137 * @param transformer a function returning the transformation
3769 jsr166 1.169 * for an element, or null if there is no transformation (in
3770 jsr166 1.172 * which case the action is not applied)
3771 dl 1.137 * @param action the action
3772     */
3773 dl 1.210 public <U> void forEachEntry(long parallelismThreshold,
3774     Function<Map.Entry<K,V>, ? extends U> transformer,
3775     Consumer<? super U> action) {
3776 dl 1.151 if (transformer == null || action == null)
3777     throw new NullPointerException();
3778 dl 1.210 new ForEachTransformedEntryTask<K,V,U>
3779     (null, batchFor(parallelismThreshold), 0, 0, table,
3780     transformer, action).invoke();
3781 dl 1.137 }
3782 dl 1.119
3783 dl 1.137 /**
3784     * Returns a non-null result from applying the given search
3785 dl 1.210 * function on each entry, or null if none. Upon success,
3786     * further element processing is suppressed and the results of
3787     * any other parallel invocations of the search function are
3788     * ignored.
3789 dl 1.137 *
3790 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3791     * needed for this operation to be executed in parallel.
3792 dl 1.137 * @param searchFunction a function returning a non-null
3793     * result on success, else null
3794     * @return a non-null result from applying the given search
3795     * function on each entry, or null if none
3796     */
3797 dl 1.210 public <U> U searchEntries(long parallelismThreshold,
3798     Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3799 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3800 dl 1.210 return new SearchEntriesTask<K,V,U>
3801     (null, batchFor(parallelismThreshold), 0, 0, table,
3802     searchFunction, new AtomicReference<U>()).invoke();
3803 dl 1.137 }
3804 dl 1.119
3805 dl 1.137 /**
3806     * Returns the result of accumulating all entries using the
3807     * given reducer to combine values, or null if none.
3808     *
3809 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3810     * needed for this operation to be executed in parallel.
3811 dl 1.137 * @param reducer a commutative associative combining function
3812     * @return the result of accumulating all entries
3813     */
3814 dl 1.210 public Map.Entry<K,V> reduceEntries(long parallelismThreshold,
3815     BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3816 dl 1.151 if (reducer == null) throw new NullPointerException();
3817 dl 1.210 return new ReduceEntriesTask<K,V>
3818     (null, batchFor(parallelismThreshold), 0, 0, table,
3819     null, reducer).invoke();
3820 dl 1.137 }
3821 dl 1.119
3822 dl 1.137 /**
3823     * Returns the result of accumulating the given transformation
3824     * of all entries using the given reducer to combine values,
3825     * or null if none.
3826     *
3827 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3828     * needed for this operation to be executed in parallel.
3829 dl 1.137 * @param transformer a function returning the transformation
3830 jsr166 1.169 * for an element, or null if there is no transformation (in
3831 jsr166 1.172 * which case it is not combined)
3832 dl 1.137 * @param reducer a commutative associative combining function
3833     * @return the result of accumulating the given transformation
3834     * of all entries
3835     */
3836 dl 1.210 public <U> U reduceEntries(long parallelismThreshold,
3837     Function<Map.Entry<K,V>, ? extends U> transformer,
3838     BiFunction<? super U, ? super U, ? extends U> reducer) {
3839 dl 1.151 if (transformer == null || reducer == null)
3840     throw new NullPointerException();
3841 dl 1.210 return new MapReduceEntriesTask<K,V,U>
3842     (null, batchFor(parallelismThreshold), 0, 0, table,
3843     null, transformer, reducer).invoke();
3844 dl 1.137 }
3845 dl 1.119
3846 dl 1.137 /**
3847     * Returns the result of accumulating the given transformation
3848     * of all entries using the given reducer to combine values,
3849     * and the given basis as an identity value.
3850     *
3851 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3852     * needed for this operation to be executed in parallel.
3853 dl 1.137 * @param transformer a function returning the transformation
3854     * for an element
3855     * @param basis the identity (initial default value) for the reduction
3856     * @param reducer a commutative associative combining function
3857     * @return the result of accumulating the given transformation
3858     * of all entries
3859     */
3860 dl 1.210 public double reduceEntriesToDouble(long parallelismThreshold,
3861     ToDoubleFunction<Map.Entry<K,V>> transformer,
3862     double basis,
3863     DoubleBinaryOperator reducer) {
3864 dl 1.151 if (transformer == null || reducer == null)
3865     throw new NullPointerException();
3866 dl 1.210 return new MapReduceEntriesToDoubleTask<K,V>
3867     (null, batchFor(parallelismThreshold), 0, 0, table,
3868     null, transformer, basis, reducer).invoke();
3869 dl 1.137 }
3870 dl 1.119
3871 dl 1.137 /**
3872     * Returns the result of accumulating the given transformation
3873     * of all entries using the given reducer to combine values,
3874     * and the given basis as an identity value.
3875     *
3876 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3877     * needed for this operation to be executed in parallel.
3878 dl 1.137 * @param transformer a function returning the transformation
3879     * for an element
3880     * @param basis the identity (initial default value) for the reduction
3881     * @param reducer a commutative associative combining function
3882 jsr166 1.157 * @return the result of accumulating the given transformation
3883 dl 1.137 * of all entries
3884     */
3885 dl 1.210 public long reduceEntriesToLong(long parallelismThreshold,
3886     ToLongFunction<Map.Entry<K,V>> transformer,
3887     long basis,
3888     LongBinaryOperator reducer) {
3889 dl 1.151 if (transformer == null || reducer == null)
3890     throw new NullPointerException();
3891 dl 1.210 return new MapReduceEntriesToLongTask<K,V>
3892     (null, batchFor(parallelismThreshold), 0, 0, table,
3893     null, transformer, basis, reducer).invoke();
3894 dl 1.137 }
3895 dl 1.119
3896 dl 1.137 /**
3897     * Returns the result of accumulating the given transformation
3898     * of all entries using the given reducer to combine values,
3899     * and the given basis as an identity value.
3900     *
3901 dl 1.210 * @param parallelismThreshold the (estimated) number of elements
3902     * needed for this operation to be executed in parallel.
3903 dl 1.137 * @param transformer a function returning the transformation
3904     * for an element
3905     * @param basis the identity (initial default value) for the reduction
3906     * @param reducer a commutative associative combining function
3907     * @return the result of accumulating the given transformation
3908     * of all entries
3909     */
3910 dl 1.210 public int reduceEntriesToInt(long parallelismThreshold,
3911     ToIntFunction<Map.Entry<K,V>> transformer,
3912     int basis,
3913     IntBinaryOperator reducer) {
3914 dl 1.151 if (transformer == null || reducer == null)
3915     throw new NullPointerException();
3916 dl 1.210 return new MapReduceEntriesToIntTask<K,V>
3917     (null, batchFor(parallelismThreshold), 0, 0, table,
3918     null, transformer, basis, reducer).invoke();
3919 dl 1.119 }
3920    
3921 dl 1.209
3922 dl 1.210 /* ----------------Views -------------- */
3923 dl 1.142
3924     /**
3925 dl 1.210 * Base class for views.
3926 dl 1.142 */
3927 dl 1.210 abstract static class CollectionView<K,V,E>
3928     implements Collection<E>, java.io.Serializable {
3929     private static final long serialVersionUID = 7249069246763182397L;
3930     final ConcurrentHashMap<K,V> map;
3931     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
3932    
3933     /**
3934     * Returns the map backing this view.
3935     *
3936     * @return the map backing this view
3937     */
3938     public ConcurrentHashMap<K,V> getMap() { return map; }
3939 dl 1.142
3940 dl 1.210 /**
3941     * Removes all of the elements from this view, by removing all
3942     * the mappings from the map backing this view.
3943 jsr166 1.184 */
3944     public final void clear() { map.clear(); }
3945     public final int size() { return map.size(); }
3946     public final boolean isEmpty() { return map.isEmpty(); }
3947 dl 1.151
3948     // implementations below rely on concrete classes supplying these
3949 jsr166 1.184 // abstract methods
3950     /**
3951     * Returns a "weakly consistent" iterator that will never
3952     * throw {@link ConcurrentModificationException}, and
3953     * guarantees to traverse elements as they existed upon
3954     * construction of the iterator, and may (but is not
3955     * guaranteed to) reflect any modifications subsequent to
3956     * construction.
3957     */
3958     public abstract Iterator<E> iterator();
3959 jsr166 1.165 public abstract boolean contains(Object o);
3960     public abstract boolean remove(Object o);
3961 dl 1.151
3962     private static final String oomeMsg = "Required array size too large";
3963 dl 1.142
3964     public final Object[] toArray() {
3965     long sz = map.mappingCount();
3966 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
3967 dl 1.142 throw new OutOfMemoryError(oomeMsg);
3968     int n = (int)sz;
3969     Object[] r = new Object[n];
3970     int i = 0;
3971 jsr166 1.184 for (E e : this) {
3972 dl 1.142 if (i == n) {
3973     if (n >= MAX_ARRAY_SIZE)
3974     throw new OutOfMemoryError(oomeMsg);
3975     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
3976     n = MAX_ARRAY_SIZE;
3977     else
3978     n += (n >>> 1) + 1;
3979     r = Arrays.copyOf(r, n);
3980     }
3981 jsr166 1.184 r[i++] = e;
3982 dl 1.142 }
3983     return (i == n) ? r : Arrays.copyOf(r, i);
3984     }
3985    
3986 jsr166 1.184 public final <T> T[] toArray(T[] a) {
3987 dl 1.142 long sz = map.mappingCount();
3988 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
3989 dl 1.142 throw new OutOfMemoryError(oomeMsg);
3990     int m = (int)sz;
3991     T[] r = (a.length >= m) ? a :
3992     (T[])java.lang.reflect.Array
3993     .newInstance(a.getClass().getComponentType(), m);
3994     int n = r.length;
3995     int i = 0;
3996 jsr166 1.184 for (E e : this) {
3997 dl 1.142 if (i == n) {
3998     if (n >= MAX_ARRAY_SIZE)
3999     throw new OutOfMemoryError(oomeMsg);
4000     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4001     n = MAX_ARRAY_SIZE;
4002     else
4003     n += (n >>> 1) + 1;
4004     r = Arrays.copyOf(r, n);
4005     }
4006 jsr166 1.184 r[i++] = (T)e;
4007 dl 1.142 }
4008     if (a == r && i < n) {
4009     r[i] = null; // null-terminate
4010     return r;
4011     }
4012     return (i == n) ? r : Arrays.copyOf(r, i);
4013     }
4014    
4015 jsr166 1.184 /**
4016     * Returns a string representation of this collection.
4017     * The string representation consists of the string representations
4018     * of the collection's elements in the order they are returned by
4019     * its iterator, enclosed in square brackets ({@code "[]"}).
4020     * Adjacent elements are separated by the characters {@code ", "}
4021     * (comma and space). Elements are converted to strings as by
4022     * {@link String#valueOf(Object)}.
4023     *
4024     * @return a string representation of this collection
4025     */
4026 dl 1.142 public final String toString() {
4027     StringBuilder sb = new StringBuilder();
4028     sb.append('[');
4029 jsr166 1.184 Iterator<E> it = iterator();
4030 dl 1.142 if (it.hasNext()) {
4031     for (;;) {
4032     Object e = it.next();
4033     sb.append(e == this ? "(this Collection)" : e);
4034     if (!it.hasNext())
4035     break;
4036     sb.append(',').append(' ');
4037     }
4038     }
4039     return sb.append(']').toString();
4040     }
4041    
4042     public final boolean containsAll(Collection<?> c) {
4043     if (c != this) {
4044 jsr166 1.184 for (Object e : c) {
4045 dl 1.142 if (e == null || !contains(e))
4046     return false;
4047     }
4048     }
4049     return true;
4050     }
4051    
4052     public final boolean removeAll(Collection<?> c) {
4053     boolean modified = false;
4054 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4055 dl 1.142 if (c.contains(it.next())) {
4056     it.remove();
4057     modified = true;
4058     }
4059     }
4060     return modified;
4061     }
4062    
4063     public final boolean retainAll(Collection<?> c) {
4064     boolean modified = false;
4065 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4066 dl 1.142 if (!c.contains(it.next())) {
4067     it.remove();
4068     modified = true;
4069     }
4070     }
4071     return modified;
4072     }
4073    
4074     }
4075    
4076     /**
4077     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4078     * which additions may optionally be enabled by mapping to a
4079 jsr166 1.185 * common value. This class cannot be directly instantiated.
4080     * See {@link #keySet() keySet()},
4081     * {@link #keySet(Object) keySet(V)},
4082     * {@link #newKeySet() newKeySet()},
4083     * {@link #newKeySet(int) newKeySet(int)}.
4084 dl 1.142 */
4085 dl 1.210 public static class KeySetView<K,V> extends CollectionView<K,V,K>
4086     implements Set<K>, java.io.Serializable {
4087 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4088     private final V value;
4089 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4090 dl 1.142 super(map);
4091     this.value = value;
4092     }
4093    
4094     /**
4095     * Returns the default mapped value for additions,
4096     * or {@code null} if additions are not supported.
4097     *
4098     * @return the default mapped value for additions, or {@code null}
4099 jsr166 1.172 * if not supported
4100 dl 1.142 */
4101     public V getMappedValue() { return value; }
4102    
4103 jsr166 1.184 /**
4104     * {@inheritDoc}
4105     * @throws NullPointerException if the specified key is null
4106     */
4107     public boolean contains(Object o) { return map.containsKey(o); }
4108 dl 1.142
4109 jsr166 1.184 /**
4110     * Removes the key from this map view, by removing the key (and its
4111     * corresponding value) from the backing map. This method does
4112     * nothing if the key is not in the map.
4113     *
4114     * @param o the key to be removed from the backing map
4115     * @return {@code true} if the backing map contained the specified key
4116     * @throws NullPointerException if the specified key is null
4117     */
4118     public boolean remove(Object o) { return map.remove(o) != null; }
4119    
4120     /**
4121     * @return an iterator over the keys of the backing map
4122     */
4123 dl 1.210 public Iterator<K> iterator() {
4124     Node<K,V>[] t;
4125     ConcurrentHashMap<K,V> m = map;
4126     int f = (t = m.table) == null ? 0 : t.length;
4127     return new KeyIterator<K,V>(t, f, 0, f, m);
4128     }
4129 dl 1.142
4130     /**
4131 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4132     * the default mapped value in the backing map, if defined.
4133 dl 1.142 *
4134 jsr166 1.184 * @param e key to be added
4135     * @return {@code true} if this set changed as a result of the call
4136     * @throws NullPointerException if the specified key is null
4137     * @throws UnsupportedOperationException if no default mapped value
4138     * for additions was provided
4139 dl 1.142 */
4140     public boolean add(K e) {
4141     V v;
4142     if ((v = value) == null)
4143     throw new UnsupportedOperationException();
4144 dl 1.149 return map.internalPut(e, v, true) == null;
4145 dl 1.142 }
4146 jsr166 1.184
4147     /**
4148     * Adds all of the elements in the specified collection to this set,
4149     * as if by calling {@link #add} on each one.
4150     *
4151     * @param c the elements to be inserted into this set
4152     * @return {@code true} if this set changed as a result of the call
4153     * @throws NullPointerException if the collection or any of its
4154     * elements are {@code null}
4155     * @throws UnsupportedOperationException if no default mapped value
4156     * for additions was provided
4157     */
4158 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4159     boolean added = false;
4160     V v;
4161     if ((v = value) == null)
4162     throw new UnsupportedOperationException();
4163     for (K e : c) {
4164 dl 1.149 if (map.internalPut(e, v, true) == null)
4165 dl 1.142 added = true;
4166     }
4167     return added;
4168     }
4169 dl 1.153
4170 dl 1.210 public int hashCode() {
4171     int h = 0;
4172     for (K e : this)
4173     h += e.hashCode();
4174     return h;
4175 dl 1.191 }
4176    
4177 dl 1.210 public boolean equals(Object o) {
4178     Set<?> c;
4179     return ((o instanceof Set) &&
4180     ((c = (Set<?>)o) == this ||
4181     (containsAll(c) && c.containsAll(this))));
4182 dl 1.119 }
4183 jsr166 1.125
4184 dl 1.210 public Spliterator<K> spliterator() {
4185     Node<K,V>[] t;
4186     ConcurrentHashMap<K,V> m = map;
4187     long n = m.sumCount();
4188     int f = (t = m.table) == null ? 0 : t.length;
4189     return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4190 dl 1.119 }
4191    
4192 dl 1.210 public void forEach(Consumer<? super K> action) {
4193     if (action == null) throw new NullPointerException();
4194     Node<K,V>[] t;
4195     if ((t = map.table) != null) {
4196     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4197     for (Node<K,V> p; (p = it.advance()) != null; )
4198     action.accept((K)p.key);
4199     }
4200 dl 1.119 }
4201 dl 1.210 }
4202 dl 1.119
4203 dl 1.210 /**
4204     * A view of a ConcurrentHashMap as a {@link Collection} of
4205     * values, in which additions are disabled. This class cannot be
4206     * directly instantiated. See {@link #values()}.
4207     */
4208     static final class ValuesView<K,V> extends CollectionView<K,V,V>
4209     implements Collection<V>, java.io.Serializable {
4210     private static final long serialVersionUID = 2249069246763182397L;
4211     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4212     public final boolean contains(Object o) {
4213     return map.containsValue(o);
4214 dl 1.119 }
4215    
4216 dl 1.210 public final boolean remove(Object o) {
4217     if (o != null) {
4218     for (Iterator<V> it = iterator(); it.hasNext();) {
4219     if (o.equals(it.next())) {
4220     it.remove();
4221     return true;
4222     }
4223     }
4224     }
4225     return false;
4226 dl 1.119 }
4227    
4228 dl 1.210 public final Iterator<V> iterator() {
4229     ConcurrentHashMap<K,V> m = map;
4230     Node<K,V>[] t;
4231     int f = (t = m.table) == null ? 0 : t.length;
4232     return new ValueIterator<K,V>(t, f, 0, f, m);
4233 dl 1.119 }
4234    
4235 dl 1.210 public final boolean add(V e) {
4236     throw new UnsupportedOperationException();
4237     }
4238     public final boolean addAll(Collection<? extends V> c) {
4239     throw new UnsupportedOperationException();
4240 dl 1.119 }
4241    
4242 dl 1.210 public Spliterator<V> spliterator() {
4243     Node<K,V>[] t;
4244     ConcurrentHashMap<K,V> m = map;
4245     long n = m.sumCount();
4246     int f = (t = m.table) == null ? 0 : t.length;
4247     return new ValueSpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
4248 dl 1.119 }
4249    
4250 dl 1.210 public void forEach(Consumer<? super V> action) {
4251     if (action == null) throw new NullPointerException();
4252     Node<K,V>[] t;
4253     if ((t = map.table) != null) {
4254     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4255     for (Node<K,V> p; (p = it.advance()) != null; )
4256     action.accept(p.val);
4257     }
4258 dl 1.119 }
4259 dl 1.210 }
4260    
4261     /**
4262     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4263     * entries. This class cannot be directly instantiated. See
4264     * {@link #entrySet()}.
4265     */
4266     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
4267     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4268     private static final long serialVersionUID = 2249069246763182397L;
4269     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4270 dl 1.119
4271 dl 1.210 public boolean contains(Object o) {
4272     Object k, v, r; Map.Entry<?,?> e;
4273     return ((o instanceof Map.Entry) &&
4274     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4275     (r = map.get(k)) != null &&
4276     (v = e.getValue()) != null &&
4277     (v == r || v.equals(r)));
4278 dl 1.119 }
4279    
4280 dl 1.210 public boolean remove(Object o) {
4281     Object k, v; Map.Entry<?,?> e;
4282     return ((o instanceof Map.Entry) &&
4283     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4284     (v = e.getValue()) != null &&
4285     map.remove(k, v));
4286 dl 1.119 }
4287    
4288     /**
4289 dl 1.210 * @return an iterator over the entries of the backing map
4290 dl 1.119 */
4291 dl 1.210 public Iterator<Map.Entry<K,V>> iterator() {
4292     ConcurrentHashMap<K,V> m = map;
4293     Node<K,V>[] t;
4294     int f = (t = m.table) == null ? 0 : t.length;
4295     return new EntryIterator<K,V>(t, f, 0, f, m);
4296 dl 1.119 }
4297    
4298 dl 1.210 public boolean add(Entry<K,V> e) {
4299     return map.internalPut(e.getKey(), e.getValue(), false) == null;
4300 dl 1.119 }
4301    
4302 dl 1.210 public boolean addAll(Collection<? extends Entry<K,V>> c) {
4303     boolean added = false;
4304     for (Entry<K,V> e : c) {
4305     if (add(e))
4306     added = true;
4307     }
4308     return added;
4309 dl 1.119 }
4310    
4311 dl 1.210 public final int hashCode() {
4312     int h = 0;
4313     Node<K,V>[] t;
4314     if ((t = map.table) != null) {
4315     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4316     for (Node<K,V> p; (p = it.advance()) != null; ) {
4317     h += p.hashCode();
4318     }
4319     }
4320     return h;
4321 dl 1.119 }
4322    
4323 dl 1.210 public final boolean equals(Object o) {
4324     Set<?> c;
4325     return ((o instanceof Set) &&
4326     ((c = (Set<?>)o) == this ||
4327     (containsAll(c) && c.containsAll(this))));
4328 dl 1.119 }
4329    
4330 dl 1.210 public Spliterator<Map.Entry<K,V>> spliterator() {
4331     Node<K,V>[] t;
4332     ConcurrentHashMap<K,V> m = map;
4333     long n = m.sumCount();
4334     int f = (t = m.table) == null ? 0 : t.length;
4335     return new EntrySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n, m);
4336 dl 1.119 }
4337    
4338 dl 1.210 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
4339     if (action == null) throw new NullPointerException();
4340     Node<K,V>[] t;
4341     if ((t = map.table) != null) {
4342     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
4343     for (Node<K,V> p; (p = it.advance()) != null; )
4344     action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
4345     }
4346 dl 1.119 }
4347    
4348 dl 1.210 }
4349    
4350     // -------------------------------------------------------
4351 dl 1.119
4352 dl 1.210 /**
4353     * Base class for bulk tasks. Repeats some fields and code from
4354     * class Traverser, because we need to subclass CountedCompleter.
4355     */
4356     static abstract class BulkTask<K,V,R> extends CountedCompleter<R> {
4357     Node<K,V>[] tab; // same as Traverser
4358     Node<K,V> next;
4359     int index;
4360     int baseIndex;
4361     int baseLimit;
4362     final int baseSize;
4363     int batch; // split control
4364    
4365     BulkTask(BulkTask<K,V,?> par, int b, int i, int f, Node<K,V>[] t) {
4366     super(par);
4367     this.batch = b;
4368     this.index = this.baseIndex = i;
4369     if ((this.tab = t) == null)
4370     this.baseSize = this.baseLimit = 0;
4371     else if (par == null)
4372     this.baseSize = this.baseLimit = t.length;
4373     else {
4374     this.baseLimit = f;
4375     this.baseSize = par.baseSize;
4376     }
4377 dl 1.119 }
4378    
4379     /**
4380 dl 1.210 * Same as Traverser version
4381 dl 1.119 */
4382 dl 1.210 final Node<K,V> advance() {
4383     Node<K,V> e;
4384     if ((e = next) != null)
4385     e = e.next;
4386     for (;;) {
4387     Node<K,V>[] t; int i, n; Object ek;
4388     if (e != null)
4389     return next = e;
4390     if (baseIndex >= baseLimit || (t = tab) == null ||
4391     (n = t.length) <= (i = index) || i < 0)
4392     return next = null;
4393     if ((e = tabAt(t, index)) != null && e.hash < 0) {
4394     if ((ek = e.key) instanceof TreeBin)
4395     e = ((TreeBin<K,V>)ek).first;
4396     else {
4397     tab = (Node<K,V>[])ek;
4398     e = null;
4399     continue;
4400     }
4401     }
4402     if ((index += baseSize) >= n)
4403     index = ++baseIndex;
4404     }
4405 dl 1.119 }
4406     }
4407    
4408     /*
4409     * Task classes. Coded in a regular but ugly format/style to
4410     * simplify checks that each variant differs in the right way from
4411 dl 1.149 * others. The null screenings exist because compilers cannot tell
4412     * that we've already null-checked task arguments, so we force
4413     * simplest hoisted bypass to help avoid convoluted traps.
4414 dl 1.119 */
4415    
4416 dl 1.210 static final class ForEachKeyTask<K,V>
4417     extends BulkTask<K,V,Void> {
4418 dl 1.171 final Consumer<? super K> action;
4419 dl 1.119 ForEachKeyTask
4420 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4421 dl 1.171 Consumer<? super K> action) {
4422 dl 1.210 super(p, b, i, f, t);
4423 dl 1.119 this.action = action;
4424     }
4425 jsr166 1.168 public final void compute() {
4426 dl 1.171 final Consumer<? super K> action;
4427 dl 1.149 if ((action = this.action) != null) {
4428 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4429     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4430     addToPendingCount(1);
4431     new ForEachKeyTask<K,V>
4432     (this, batch >>>= 1, baseLimit = h, f, tab,
4433     action).fork();
4434     }
4435     for (Node<K,V> p; (p = advance()) != null;)
4436     action.accept((K)p.key);
4437 dl 1.149 propagateCompletion();
4438     }
4439 dl 1.119 }
4440     }
4441    
4442 dl 1.210 static final class ForEachValueTask<K,V>
4443     extends BulkTask<K,V,Void> {
4444 dl 1.171 final Consumer<? super V> action;
4445 dl 1.119 ForEachValueTask
4446 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4447 dl 1.171 Consumer<? super V> action) {
4448 dl 1.210 super(p, b, i, f, t);
4449 dl 1.119 this.action = action;
4450     }
4451 jsr166 1.168 public final void compute() {
4452 dl 1.171 final Consumer<? super V> action;
4453 dl 1.149 if ((action = this.action) != null) {
4454 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4455     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4456     addToPendingCount(1);
4457     new ForEachValueTask<K,V>
4458     (this, batch >>>= 1, baseLimit = h, f, tab,
4459     action).fork();
4460     }
4461     for (Node<K,V> p; (p = advance()) != null;)
4462     action.accept(p.val);
4463 dl 1.149 propagateCompletion();
4464     }
4465 dl 1.119 }
4466     }
4467    
4468 dl 1.210 static final class ForEachEntryTask<K,V>
4469     extends BulkTask<K,V,Void> {
4470 dl 1.171 final Consumer<? super Entry<K,V>> action;
4471 dl 1.119 ForEachEntryTask
4472 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4473 dl 1.171 Consumer<? super Entry<K,V>> action) {
4474 dl 1.210 super(p, b, i, f, t);
4475 dl 1.119 this.action = action;
4476     }
4477 jsr166 1.168 public final void compute() {
4478 dl 1.171 final Consumer<? super Entry<K,V>> action;
4479 dl 1.149 if ((action = this.action) != null) {
4480 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4481     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4482     addToPendingCount(1);
4483     new ForEachEntryTask<K,V>
4484     (this, batch >>>= 1, baseLimit = h, f, tab,
4485     action).fork();
4486     }
4487     for (Node<K,V> p; (p = advance()) != null; )
4488     action.accept(p);
4489 dl 1.149 propagateCompletion();
4490     }
4491 dl 1.119 }
4492     }
4493    
4494 dl 1.210 static final class ForEachMappingTask<K,V>
4495     extends BulkTask<K,V,Void> {
4496 dl 1.171 final BiConsumer<? super K, ? super V> action;
4497 dl 1.119 ForEachMappingTask
4498 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4499 dl 1.171 BiConsumer<? super K,? super V> action) {
4500 dl 1.210 super(p, b, i, f, t);
4501 dl 1.119 this.action = action;
4502     }
4503 jsr166 1.168 public final void compute() {
4504 dl 1.171 final BiConsumer<? super K, ? super V> action;
4505 dl 1.149 if ((action = this.action) != null) {
4506 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4507     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4508     addToPendingCount(1);
4509     new ForEachMappingTask<K,V>
4510     (this, batch >>>= 1, baseLimit = h, f, tab,
4511     action).fork();
4512     }
4513     for (Node<K,V> p; (p = advance()) != null; )
4514     action.accept((K)p.key, p.val);
4515 dl 1.149 propagateCompletion();
4516     }
4517 dl 1.119 }
4518     }
4519    
4520 dl 1.210 static final class ForEachTransformedKeyTask<K,V,U>
4521     extends BulkTask<K,V,Void> {
4522 dl 1.153 final Function<? super K, ? extends U> transformer;
4523 dl 1.171 final Consumer<? super U> action;
4524 dl 1.119 ForEachTransformedKeyTask
4525 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4526 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
4527 dl 1.210 super(p, b, i, f, t);
4528 dl 1.146 this.transformer = transformer; this.action = action;
4529     }
4530 jsr166 1.168 public final void compute() {
4531 dl 1.153 final Function<? super K, ? extends U> transformer;
4532 dl 1.171 final Consumer<? super U> action;
4533 dl 1.149 if ((transformer = this.transformer) != null &&
4534     (action = this.action) != null) {
4535 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4536     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4537     addToPendingCount(1);
4538 dl 1.149 new ForEachTransformedKeyTask<K,V,U>
4539 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4540     transformer, action).fork();
4541     }
4542     for (Node<K,V> p; (p = advance()) != null; ) {
4543     U u;
4544     if ((u = transformer.apply((K)p.key)) != null)
4545 dl 1.153 action.accept(u);
4546 dl 1.149 }
4547     propagateCompletion();
4548 dl 1.119 }
4549     }
4550     }
4551    
4552 dl 1.210 static final class ForEachTransformedValueTask<K,V,U>
4553     extends BulkTask<K,V,Void> {
4554 dl 1.153 final Function<? super V, ? extends U> transformer;
4555 dl 1.171 final Consumer<? super U> action;
4556 dl 1.119 ForEachTransformedValueTask
4557 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4558 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
4559 dl 1.210 super(p, b, i, f, t);
4560 dl 1.146 this.transformer = transformer; this.action = action;
4561     }
4562 jsr166 1.168 public final void compute() {
4563 dl 1.153 final Function<? super V, ? extends U> transformer;
4564 dl 1.171 final Consumer<? super U> action;
4565 dl 1.149 if ((transformer = this.transformer) != null &&
4566     (action = this.action) != null) {
4567 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4568     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4569     addToPendingCount(1);
4570 dl 1.149 new ForEachTransformedValueTask<K,V,U>
4571 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4572     transformer, action).fork();
4573     }
4574     for (Node<K,V> p; (p = advance()) != null; ) {
4575     U u;
4576     if ((u = transformer.apply(p.val)) != null)
4577 dl 1.153 action.accept(u);
4578 dl 1.149 }
4579     propagateCompletion();
4580 dl 1.119 }
4581     }
4582 tim 1.1 }
4583    
4584 dl 1.210 static final class ForEachTransformedEntryTask<K,V,U>
4585     extends BulkTask<K,V,Void> {
4586 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
4587 dl 1.171 final Consumer<? super U> action;
4588 dl 1.119 ForEachTransformedEntryTask
4589 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4590 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
4591 dl 1.210 super(p, b, i, f, t);
4592 dl 1.146 this.transformer = transformer; this.action = action;
4593     }
4594 jsr166 1.168 public final void compute() {
4595 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
4596 dl 1.171 final Consumer<? super U> action;
4597 dl 1.149 if ((transformer = this.transformer) != null &&
4598     (action = this.action) != null) {
4599 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4600     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4601     addToPendingCount(1);
4602 dl 1.149 new ForEachTransformedEntryTask<K,V,U>
4603 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4604     transformer, action).fork();
4605     }
4606     for (Node<K,V> p; (p = advance()) != null; ) {
4607     U u;
4608     if ((u = transformer.apply(p)) != null)
4609 dl 1.153 action.accept(u);
4610 dl 1.149 }
4611     propagateCompletion();
4612 dl 1.119 }
4613     }
4614 tim 1.1 }
4615    
4616 dl 1.210 static final class ForEachTransformedMappingTask<K,V,U>
4617     extends BulkTask<K,V,Void> {
4618 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
4619 dl 1.171 final Consumer<? super U> action;
4620 dl 1.119 ForEachTransformedMappingTask
4621 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4622 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
4623 dl 1.171 Consumer<? super U> action) {
4624 dl 1.210 super(p, b, i, f, t);
4625 dl 1.146 this.transformer = transformer; this.action = action;
4626 dl 1.119 }
4627 jsr166 1.168 public final void compute() {
4628 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
4629 dl 1.171 final Consumer<? super U> action;
4630 dl 1.149 if ((transformer = this.transformer) != null &&
4631     (action = this.action) != null) {
4632 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4633     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4634     addToPendingCount(1);
4635 dl 1.149 new ForEachTransformedMappingTask<K,V,U>
4636 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4637     transformer, action).fork();
4638     }
4639     for (Node<K,V> p; (p = advance()) != null; ) {
4640     U u;
4641     if ((u = transformer.apply((K)p.key, p.val)) != null)
4642 dl 1.153 action.accept(u);
4643 dl 1.149 }
4644     propagateCompletion();
4645 dl 1.119 }
4646     }
4647 tim 1.1 }
4648    
4649 dl 1.210 static final class SearchKeysTask<K,V,U>
4650     extends BulkTask<K,V,U> {
4651 dl 1.153 final Function<? super K, ? extends U> searchFunction;
4652 dl 1.119 final AtomicReference<U> result;
4653     SearchKeysTask
4654 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4655 dl 1.153 Function<? super K, ? extends U> searchFunction,
4656 dl 1.119 AtomicReference<U> result) {
4657 dl 1.210 super(p, b, i, f, t);
4658 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4659     }
4660 dl 1.146 public final U getRawResult() { return result.get(); }
4661 jsr166 1.168 public final void compute() {
4662 dl 1.153 final Function<? super K, ? extends U> searchFunction;
4663 dl 1.146 final AtomicReference<U> result;
4664 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
4665     (result = this.result) != null) {
4666 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4667     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4668 dl 1.149 if (result.get() != null)
4669     return;
4670 dl 1.210 addToPendingCount(1);
4671 dl 1.149 new SearchKeysTask<K,V,U>
4672 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4673     searchFunction, result).fork();
4674 dl 1.128 }
4675 dl 1.149 while (result.get() == null) {
4676 dl 1.210 U u;
4677     Node<K,V> p;
4678     if ((p = advance()) == null) {
4679 dl 1.149 propagateCompletion();
4680     break;
4681     }
4682 dl 1.210 if ((u = searchFunction.apply((K)p.key)) != null) {
4683 dl 1.149 if (result.compareAndSet(null, u))
4684     quietlyCompleteRoot();
4685     break;
4686     }
4687 dl 1.119 }
4688     }
4689     }
4690 tim 1.1 }
4691    
4692 dl 1.210 static final class SearchValuesTask<K,V,U>
4693     extends BulkTask<K,V,U> {
4694 dl 1.153 final Function<? super V, ? extends U> searchFunction;
4695 dl 1.119 final AtomicReference<U> result;
4696     SearchValuesTask
4697 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4698 dl 1.153 Function<? super V, ? extends U> searchFunction,
4699 dl 1.119 AtomicReference<U> result) {
4700 dl 1.210 super(p, b, i, f, t);
4701 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4702     }
4703 dl 1.146 public final U getRawResult() { return result.get(); }
4704 jsr166 1.168 public final void compute() {
4705 dl 1.153 final Function<? super V, ? extends U> searchFunction;
4706 dl 1.146 final AtomicReference<U> result;
4707 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
4708     (result = this.result) != null) {
4709 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4710     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4711 dl 1.149 if (result.get() != null)
4712     return;
4713 dl 1.210 addToPendingCount(1);
4714 dl 1.149 new SearchValuesTask<K,V,U>
4715 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4716     searchFunction, result).fork();
4717 dl 1.128 }
4718 dl 1.149 while (result.get() == null) {
4719 dl 1.210 U u;
4720     Node<K,V> p;
4721     if ((p = advance()) == null) {
4722 dl 1.149 propagateCompletion();
4723     break;
4724     }
4725 dl 1.210 if ((u = searchFunction.apply(p.val)) != null) {
4726 dl 1.149 if (result.compareAndSet(null, u))
4727     quietlyCompleteRoot();
4728     break;
4729     }
4730 dl 1.119 }
4731     }
4732     }
4733     }
4734 tim 1.11
4735 dl 1.210 static final class SearchEntriesTask<K,V,U>
4736     extends BulkTask<K,V,U> {
4737 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
4738 dl 1.119 final AtomicReference<U> result;
4739     SearchEntriesTask
4740 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4741 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
4742 dl 1.119 AtomicReference<U> result) {
4743 dl 1.210 super(p, b, i, f, t);
4744 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4745     }
4746 dl 1.146 public final U getRawResult() { return result.get(); }
4747 jsr166 1.168 public final void compute() {
4748 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
4749 dl 1.146 final AtomicReference<U> result;
4750 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
4751     (result = this.result) != null) {
4752 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4753     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4754 dl 1.149 if (result.get() != null)
4755     return;
4756 dl 1.210 addToPendingCount(1);
4757 dl 1.149 new SearchEntriesTask<K,V,U>
4758 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4759     searchFunction, result).fork();
4760 dl 1.128 }
4761 dl 1.149 while (result.get() == null) {
4762 dl 1.210 U u;
4763     Node<K,V> p;
4764     if ((p = advance()) == null) {
4765 dl 1.149 propagateCompletion();
4766     break;
4767     }
4768 dl 1.210 if ((u = searchFunction.apply(p)) != null) {
4769 dl 1.149 if (result.compareAndSet(null, u))
4770     quietlyCompleteRoot();
4771     return;
4772     }
4773 dl 1.119 }
4774     }
4775     }
4776     }
4777 tim 1.1
4778 dl 1.210 static final class SearchMappingsTask<K,V,U>
4779     extends BulkTask<K,V,U> {
4780 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4781 dl 1.119 final AtomicReference<U> result;
4782     SearchMappingsTask
4783 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4784 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
4785 dl 1.119 AtomicReference<U> result) {
4786 dl 1.210 super(p, b, i, f, t);
4787 dl 1.119 this.searchFunction = searchFunction; this.result = result;
4788     }
4789 dl 1.146 public final U getRawResult() { return result.get(); }
4790 jsr166 1.168 public final void compute() {
4791 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
4792 dl 1.146 final AtomicReference<U> result;
4793 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
4794     (result = this.result) != null) {
4795 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4796     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4797 dl 1.149 if (result.get() != null)
4798     return;
4799 dl 1.210 addToPendingCount(1);
4800 dl 1.149 new SearchMappingsTask<K,V,U>
4801 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4802     searchFunction, result).fork();
4803 dl 1.128 }
4804 dl 1.149 while (result.get() == null) {
4805 dl 1.210 U u;
4806     Node<K,V> p;
4807     if ((p = advance()) == null) {
4808 dl 1.149 propagateCompletion();
4809     break;
4810     }
4811 dl 1.210 if ((u = searchFunction.apply((K)p.key, p.val)) != null) {
4812 dl 1.149 if (result.compareAndSet(null, u))
4813     quietlyCompleteRoot();
4814     break;
4815     }
4816 dl 1.119 }
4817     }
4818 tim 1.1 }
4819 dl 1.119 }
4820 tim 1.1
4821 dl 1.210 static final class ReduceKeysTask<K,V>
4822     extends BulkTask<K,V,K> {
4823 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
4824 dl 1.119 K result;
4825 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
4826 dl 1.119 ReduceKeysTask
4827 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4828 dl 1.128 ReduceKeysTask<K,V> nextRight,
4829 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
4830 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
4831 dl 1.119 this.reducer = reducer;
4832     }
4833 dl 1.146 public final K getRawResult() { return result; }
4834 dl 1.210 public final void compute() {
4835 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
4836 dl 1.149 if ((reducer = this.reducer) != null) {
4837 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4838     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4839     addToPendingCount(1);
4840 dl 1.149 (rights = new ReduceKeysTask<K,V>
4841 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4842     rights, reducer)).fork();
4843     }
4844     K r = null;
4845     for (Node<K,V> p; (p = advance()) != null; ) {
4846     K u = (K)p.key;
4847 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
4848 dl 1.149 }
4849     result = r;
4850     CountedCompleter<?> c;
4851     for (c = firstComplete(); c != null; c = c.nextComplete()) {
4852     ReduceKeysTask<K,V>
4853     t = (ReduceKeysTask<K,V>)c,
4854     s = t.rights;
4855     while (s != null) {
4856     K tr, sr;
4857     if ((sr = s.result) != null)
4858     t.result = (((tr = t.result) == null) ? sr :
4859     reducer.apply(tr, sr));
4860     s = t.rights = s.nextRight;
4861     }
4862 dl 1.99 }
4863 dl 1.138 }
4864 tim 1.1 }
4865 dl 1.119 }
4866 tim 1.1
4867 dl 1.210 static final class ReduceValuesTask<K,V>
4868     extends BulkTask<K,V,V> {
4869 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
4870 dl 1.119 V result;
4871 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
4872 dl 1.119 ReduceValuesTask
4873 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4874 dl 1.128 ReduceValuesTask<K,V> nextRight,
4875 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
4876 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
4877 dl 1.119 this.reducer = reducer;
4878     }
4879 dl 1.146 public final V getRawResult() { return result; }
4880 dl 1.210 public final void compute() {
4881 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
4882 dl 1.149 if ((reducer = this.reducer) != null) {
4883 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4884     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4885     addToPendingCount(1);
4886 dl 1.149 (rights = new ReduceValuesTask<K,V>
4887 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4888     rights, reducer)).fork();
4889     }
4890     V r = null;
4891     for (Node<K,V> p; (p = advance()) != null; ) {
4892     V v = p.val;
4893 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
4894 dl 1.210 }
4895 dl 1.149 result = r;
4896     CountedCompleter<?> c;
4897     for (c = firstComplete(); c != null; c = c.nextComplete()) {
4898     ReduceValuesTask<K,V>
4899     t = (ReduceValuesTask<K,V>)c,
4900     s = t.rights;
4901     while (s != null) {
4902     V tr, sr;
4903     if ((sr = s.result) != null)
4904     t.result = (((tr = t.result) == null) ? sr :
4905     reducer.apply(tr, sr));
4906     s = t.rights = s.nextRight;
4907     }
4908 dl 1.119 }
4909     }
4910 tim 1.1 }
4911 dl 1.119 }
4912 tim 1.1
4913 dl 1.210 static final class ReduceEntriesTask<K,V>
4914     extends BulkTask<K,V,Map.Entry<K,V>> {
4915 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4916 dl 1.119 Map.Entry<K,V> result;
4917 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
4918 dl 1.119 ReduceEntriesTask
4919 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4920 dl 1.130 ReduceEntriesTask<K,V> nextRight,
4921 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4922 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
4923 dl 1.119 this.reducer = reducer;
4924     }
4925 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
4926 dl 1.210 public final void compute() {
4927 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
4928 dl 1.149 if ((reducer = this.reducer) != null) {
4929 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4930     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4931     addToPendingCount(1);
4932 dl 1.149 (rights = new ReduceEntriesTask<K,V>
4933 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4934     rights, reducer)).fork();
4935     }
4936 dl 1.149 Map.Entry<K,V> r = null;
4937 dl 1.210 for (Node<K,V> p; (p = advance()) != null; )
4938     r = (r == null) ? p : reducer.apply(r, p);
4939 dl 1.149 result = r;
4940     CountedCompleter<?> c;
4941     for (c = firstComplete(); c != null; c = c.nextComplete()) {
4942     ReduceEntriesTask<K,V>
4943     t = (ReduceEntriesTask<K,V>)c,
4944     s = t.rights;
4945     while (s != null) {
4946     Map.Entry<K,V> tr, sr;
4947     if ((sr = s.result) != null)
4948     t.result = (((tr = t.result) == null) ? sr :
4949     reducer.apply(tr, sr));
4950     s = t.rights = s.nextRight;
4951     }
4952 dl 1.119 }
4953 dl 1.138 }
4954 dl 1.119 }
4955     }
4956 dl 1.99
4957 dl 1.210 static final class MapReduceKeysTask<K,V,U>
4958     extends BulkTask<K,V,U> {
4959 dl 1.153 final Function<? super K, ? extends U> transformer;
4960     final BiFunction<? super U, ? super U, ? extends U> reducer;
4961 dl 1.119 U result;
4962 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
4963 dl 1.119 MapReduceKeysTask
4964 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
4965 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
4966 dl 1.153 Function<? super K, ? extends U> transformer,
4967     BiFunction<? super U, ? super U, ? extends U> reducer) {
4968 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
4969 dl 1.119 this.transformer = transformer;
4970     this.reducer = reducer;
4971     }
4972 dl 1.146 public final U getRawResult() { return result; }
4973 dl 1.210 public final void compute() {
4974 dl 1.153 final Function<? super K, ? extends U> transformer;
4975     final BiFunction<? super U, ? super U, ? extends U> reducer;
4976 dl 1.149 if ((transformer = this.transformer) != null &&
4977     (reducer = this.reducer) != null) {
4978 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
4979     (h = ((f = baseLimit) + i) >>> 1) > i;) {
4980     addToPendingCount(1);
4981 dl 1.149 (rights = new MapReduceKeysTask<K,V,U>
4982 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
4983     rights, transformer, reducer)).fork();
4984     }
4985     U r = null;
4986     for (Node<K,V> p; (p = advance()) != null; ) {
4987     U u;
4988     if ((u = transformer.apply((K)p.key)) != null)
4989 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
4990     }
4991     result = r;
4992     CountedCompleter<?> c;
4993     for (c = firstComplete(); c != null; c = c.nextComplete()) {
4994     MapReduceKeysTask<K,V,U>
4995     t = (MapReduceKeysTask<K,V,U>)c,
4996     s = t.rights;
4997     while (s != null) {
4998     U tr, sr;
4999     if ((sr = s.result) != null)
5000     t.result = (((tr = t.result) == null) ? sr :
5001     reducer.apply(tr, sr));
5002     s = t.rights = s.nextRight;
5003     }
5004 dl 1.119 }
5005 dl 1.138 }
5006 tim 1.1 }
5007 dl 1.4 }
5008    
5009 dl 1.210 static final class MapReduceValuesTask<K,V,U>
5010     extends BulkTask<K,V,U> {
5011 dl 1.153 final Function<? super V, ? extends U> transformer;
5012     final BiFunction<? super U, ? super U, ? extends U> reducer;
5013 dl 1.119 U result;
5014 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
5015 dl 1.119 MapReduceValuesTask
5016 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5017 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
5018 dl 1.153 Function<? super V, ? extends U> transformer,
5019     BiFunction<? super U, ? super U, ? extends U> reducer) {
5020 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5021 dl 1.119 this.transformer = transformer;
5022     this.reducer = reducer;
5023     }
5024 dl 1.146 public final U getRawResult() { return result; }
5025 dl 1.210 public final void compute() {
5026 dl 1.153 final Function<? super V, ? extends U> transformer;
5027     final BiFunction<? super U, ? super U, ? extends U> reducer;
5028 dl 1.149 if ((transformer = this.transformer) != null &&
5029     (reducer = this.reducer) != null) {
5030 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5031     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5032     addToPendingCount(1);
5033 dl 1.149 (rights = new MapReduceValuesTask<K,V,U>
5034 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5035     rights, transformer, reducer)).fork();
5036     }
5037     U r = null;
5038     for (Node<K,V> p; (p = advance()) != null; ) {
5039     U u;
5040     if ((u = transformer.apply(p.val)) != null)
5041 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5042     }
5043     result = r;
5044     CountedCompleter<?> c;
5045     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5046     MapReduceValuesTask<K,V,U>
5047     t = (MapReduceValuesTask<K,V,U>)c,
5048     s = t.rights;
5049     while (s != null) {
5050     U tr, sr;
5051     if ((sr = s.result) != null)
5052     t.result = (((tr = t.result) == null) ? sr :
5053     reducer.apply(tr, sr));
5054     s = t.rights = s.nextRight;
5055     }
5056 dl 1.119 }
5057     }
5058     }
5059 dl 1.4 }
5060    
5061 dl 1.210 static final class MapReduceEntriesTask<K,V,U>
5062     extends BulkTask<K,V,U> {
5063 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5064     final BiFunction<? super U, ? super U, ? extends U> reducer;
5065 dl 1.119 U result;
5066 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
5067 dl 1.119 MapReduceEntriesTask
5068 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5069 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
5070 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5071     BiFunction<? super U, ? super U, ? extends U> reducer) {
5072 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5073 dl 1.119 this.transformer = transformer;
5074     this.reducer = reducer;
5075     }
5076 dl 1.146 public final U getRawResult() { return result; }
5077 dl 1.210 public final void compute() {
5078 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5079     final BiFunction<? super U, ? super U, ? extends U> reducer;
5080 dl 1.149 if ((transformer = this.transformer) != null &&
5081     (reducer = this.reducer) != null) {
5082 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5083     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5084     addToPendingCount(1);
5085 dl 1.149 (rights = new MapReduceEntriesTask<K,V,U>
5086 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5087     rights, transformer, reducer)).fork();
5088     }
5089     U r = null;
5090     for (Node<K,V> p; (p = advance()) != null; ) {
5091     U u;
5092     if ((u = transformer.apply(p)) != null)
5093 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5094     }
5095     result = r;
5096     CountedCompleter<?> c;
5097     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5098     MapReduceEntriesTask<K,V,U>
5099     t = (MapReduceEntriesTask<K,V,U>)c,
5100     s = t.rights;
5101     while (s != null) {
5102     U tr, sr;
5103     if ((sr = s.result) != null)
5104     t.result = (((tr = t.result) == null) ? sr :
5105     reducer.apply(tr, sr));
5106     s = t.rights = s.nextRight;
5107     }
5108 dl 1.119 }
5109 dl 1.138 }
5110 dl 1.119 }
5111 dl 1.4 }
5112 tim 1.1
5113 dl 1.210 static final class MapReduceMappingsTask<K,V,U>
5114     extends BulkTask<K,V,U> {
5115 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5116     final BiFunction<? super U, ? super U, ? extends U> reducer;
5117 dl 1.119 U result;
5118 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
5119 dl 1.119 MapReduceMappingsTask
5120 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5121 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
5122 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5123     BiFunction<? super U, ? super U, ? extends U> reducer) {
5124 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5125 dl 1.119 this.transformer = transformer;
5126     this.reducer = reducer;
5127     }
5128 dl 1.146 public final U getRawResult() { return result; }
5129 dl 1.210 public final void compute() {
5130 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5131     final BiFunction<? super U, ? super U, ? extends U> reducer;
5132 dl 1.149 if ((transformer = this.transformer) != null &&
5133     (reducer = this.reducer) != null) {
5134 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5135     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5136     addToPendingCount(1);
5137 dl 1.149 (rights = new MapReduceMappingsTask<K,V,U>
5138 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5139     rights, transformer, reducer)).fork();
5140     }
5141     U r = null;
5142     for (Node<K,V> p; (p = advance()) != null; ) {
5143     U u;
5144     if ((u = transformer.apply((K)p.key, p.val)) != null)
5145 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
5146     }
5147     result = r;
5148     CountedCompleter<?> c;
5149     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5150     MapReduceMappingsTask<K,V,U>
5151     t = (MapReduceMappingsTask<K,V,U>)c,
5152     s = t.rights;
5153     while (s != null) {
5154     U tr, sr;
5155     if ((sr = s.result) != null)
5156     t.result = (((tr = t.result) == null) ? sr :
5157     reducer.apply(tr, sr));
5158     s = t.rights = s.nextRight;
5159     }
5160 dl 1.119 }
5161     }
5162     }
5163     }
5164 jsr166 1.114
5165 dl 1.210 static final class MapReduceKeysToDoubleTask<K,V>
5166     extends BulkTask<K,V,Double> {
5167 dl 1.171 final ToDoubleFunction<? super K> transformer;
5168 dl 1.153 final DoubleBinaryOperator reducer;
5169 dl 1.119 final double basis;
5170     double result;
5171 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
5172 dl 1.119 MapReduceKeysToDoubleTask
5173 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5174 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
5175 dl 1.171 ToDoubleFunction<? super K> transformer,
5176 dl 1.119 double basis,
5177 dl 1.153 DoubleBinaryOperator reducer) {
5178 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5179 dl 1.119 this.transformer = transformer;
5180     this.basis = basis; this.reducer = reducer;
5181     }
5182 dl 1.146 public final Double getRawResult() { return result; }
5183 dl 1.210 public final void compute() {
5184 dl 1.171 final ToDoubleFunction<? super K> transformer;
5185 dl 1.153 final DoubleBinaryOperator reducer;
5186 dl 1.149 if ((transformer = this.transformer) != null &&
5187     (reducer = this.reducer) != null) {
5188     double r = this.basis;
5189 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5190     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5191     addToPendingCount(1);
5192 dl 1.149 (rights = new MapReduceKeysToDoubleTask<K,V>
5193 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5194     rights, transformer, r, reducer)).fork();
5195     }
5196     for (Node<K,V> p; (p = advance()) != null; )
5197     r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key));
5198 dl 1.149 result = r;
5199     CountedCompleter<?> c;
5200     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5201     MapReduceKeysToDoubleTask<K,V>
5202     t = (MapReduceKeysToDoubleTask<K,V>)c,
5203     s = t.rights;
5204     while (s != null) {
5205 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5206 dl 1.149 s = t.rights = s.nextRight;
5207     }
5208 dl 1.119 }
5209 dl 1.138 }
5210 dl 1.79 }
5211 dl 1.119 }
5212 dl 1.79
5213 dl 1.210 static final class MapReduceValuesToDoubleTask<K,V>
5214     extends BulkTask<K,V,Double> {
5215 dl 1.171 final ToDoubleFunction<? super V> transformer;
5216 dl 1.153 final DoubleBinaryOperator reducer;
5217 dl 1.119 final double basis;
5218     double result;
5219 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
5220 dl 1.119 MapReduceValuesToDoubleTask
5221 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5222 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
5223 dl 1.171 ToDoubleFunction<? super V> transformer,
5224 dl 1.119 double basis,
5225 dl 1.153 DoubleBinaryOperator reducer) {
5226 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5227 dl 1.119 this.transformer = transformer;
5228     this.basis = basis; this.reducer = reducer;
5229     }
5230 dl 1.146 public final Double getRawResult() { return result; }
5231 dl 1.210 public final void compute() {
5232 dl 1.171 final ToDoubleFunction<? super V> transformer;
5233 dl 1.153 final DoubleBinaryOperator reducer;
5234 dl 1.149 if ((transformer = this.transformer) != null &&
5235     (reducer = this.reducer) != null) {
5236     double r = this.basis;
5237 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5238     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5239     addToPendingCount(1);
5240 dl 1.149 (rights = new MapReduceValuesToDoubleTask<K,V>
5241 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5242     rights, transformer, r, reducer)).fork();
5243     }
5244     for (Node<K,V> p; (p = advance()) != null; )
5245     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val));
5246 dl 1.149 result = r;
5247     CountedCompleter<?> c;
5248     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5249     MapReduceValuesToDoubleTask<K,V>
5250     t = (MapReduceValuesToDoubleTask<K,V>)c,
5251     s = t.rights;
5252     while (s != null) {
5253 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5254 dl 1.149 s = t.rights = s.nextRight;
5255     }
5256 dl 1.119 }
5257     }
5258 dl 1.30 }
5259 dl 1.79 }
5260 dl 1.30
5261 dl 1.210 static final class MapReduceEntriesToDoubleTask<K,V>
5262     extends BulkTask<K,V,Double> {
5263 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5264 dl 1.153 final DoubleBinaryOperator reducer;
5265 dl 1.119 final double basis;
5266     double result;
5267 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
5268 dl 1.119 MapReduceEntriesToDoubleTask
5269 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5270 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
5271 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5272 dl 1.119 double basis,
5273 dl 1.153 DoubleBinaryOperator reducer) {
5274 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5275 dl 1.119 this.transformer = transformer;
5276     this.basis = basis; this.reducer = reducer;
5277     }
5278 dl 1.146 public final Double getRawResult() { return result; }
5279 dl 1.210 public final void compute() {
5280 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
5281 dl 1.153 final DoubleBinaryOperator reducer;
5282 dl 1.149 if ((transformer = this.transformer) != null &&
5283     (reducer = this.reducer) != null) {
5284     double r = this.basis;
5285 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5286     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5287     addToPendingCount(1);
5288 dl 1.149 (rights = new MapReduceEntriesToDoubleTask<K,V>
5289 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5290     rights, transformer, r, reducer)).fork();
5291     }
5292     for (Node<K,V> p; (p = advance()) != null; )
5293     r = reducer.applyAsDouble(r, transformer.applyAsDouble(p));
5294 dl 1.149 result = r;
5295     CountedCompleter<?> c;
5296     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5297     MapReduceEntriesToDoubleTask<K,V>
5298     t = (MapReduceEntriesToDoubleTask<K,V>)c,
5299     s = t.rights;
5300     while (s != null) {
5301 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5302 dl 1.149 s = t.rights = s.nextRight;
5303     }
5304 dl 1.119 }
5305 dl 1.138 }
5306 dl 1.30 }
5307 tim 1.1 }
5308    
5309 dl 1.210 static final class MapReduceMappingsToDoubleTask<K,V>
5310     extends BulkTask<K,V,Double> {
5311 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5312 dl 1.153 final DoubleBinaryOperator reducer;
5313 dl 1.119 final double basis;
5314     double result;
5315 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
5316 dl 1.119 MapReduceMappingsToDoubleTask
5317 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5318 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
5319 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
5320 dl 1.119 double basis,
5321 dl 1.153 DoubleBinaryOperator reducer) {
5322 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5323 dl 1.119 this.transformer = transformer;
5324     this.basis = basis; this.reducer = reducer;
5325     }
5326 dl 1.146 public final Double getRawResult() { return result; }
5327 dl 1.210 public final void compute() {
5328 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
5329 dl 1.153 final DoubleBinaryOperator reducer;
5330 dl 1.149 if ((transformer = this.transformer) != null &&
5331     (reducer = this.reducer) != null) {
5332     double r = this.basis;
5333 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5334     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5335     addToPendingCount(1);
5336 dl 1.149 (rights = new MapReduceMappingsToDoubleTask<K,V>
5337 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5338     rights, transformer, r, reducer)).fork();
5339     }
5340     for (Node<K,V> p; (p = advance()) != null; )
5341     r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key, p.val));
5342 dl 1.149 result = r;
5343     CountedCompleter<?> c;
5344     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5345     MapReduceMappingsToDoubleTask<K,V>
5346     t = (MapReduceMappingsToDoubleTask<K,V>)c,
5347     s = t.rights;
5348     while (s != null) {
5349 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
5350 dl 1.149 s = t.rights = s.nextRight;
5351     }
5352 dl 1.119 }
5353     }
5354 dl 1.4 }
5355 dl 1.119 }
5356    
5357 dl 1.210 static final class MapReduceKeysToLongTask<K,V>
5358     extends BulkTask<K,V,Long> {
5359 dl 1.171 final ToLongFunction<? super K> transformer;
5360 dl 1.153 final LongBinaryOperator reducer;
5361 dl 1.119 final long basis;
5362     long result;
5363 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
5364 dl 1.119 MapReduceKeysToLongTask
5365 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5366 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
5367 dl 1.171 ToLongFunction<? super K> transformer,
5368 dl 1.119 long basis,
5369 dl 1.153 LongBinaryOperator reducer) {
5370 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5371 dl 1.119 this.transformer = transformer;
5372     this.basis = basis; this.reducer = reducer;
5373     }
5374 dl 1.146 public final Long getRawResult() { return result; }
5375 dl 1.210 public final void compute() {
5376 dl 1.171 final ToLongFunction<? super K> transformer;
5377 dl 1.153 final LongBinaryOperator reducer;
5378 dl 1.149 if ((transformer = this.transformer) != null &&
5379     (reducer = this.reducer) != null) {
5380     long r = this.basis;
5381 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5382     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5383     addToPendingCount(1);
5384 dl 1.149 (rights = new MapReduceKeysToLongTask<K,V>
5385 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5386     rights, transformer, r, reducer)).fork();
5387     }
5388     for (Node<K,V> p; (p = advance()) != null; )
5389     r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key));
5390 dl 1.149 result = r;
5391     CountedCompleter<?> c;
5392     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5393     MapReduceKeysToLongTask<K,V>
5394     t = (MapReduceKeysToLongTask<K,V>)c,
5395     s = t.rights;
5396     while (s != null) {
5397 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5398 dl 1.149 s = t.rights = s.nextRight;
5399     }
5400 dl 1.119 }
5401 dl 1.138 }
5402 dl 1.4 }
5403 dl 1.119 }
5404    
5405 dl 1.210 static final class MapReduceValuesToLongTask<K,V>
5406     extends BulkTask<K,V,Long> {
5407 dl 1.171 final ToLongFunction<? super V> transformer;
5408 dl 1.153 final LongBinaryOperator reducer;
5409 dl 1.119 final long basis;
5410     long result;
5411 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
5412 dl 1.119 MapReduceValuesToLongTask
5413 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5414 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
5415 dl 1.171 ToLongFunction<? super V> transformer,
5416 dl 1.119 long basis,
5417 dl 1.153 LongBinaryOperator reducer) {
5418 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5419 dl 1.119 this.transformer = transformer;
5420     this.basis = basis; this.reducer = reducer;
5421     }
5422 dl 1.146 public final Long getRawResult() { return result; }
5423 dl 1.210 public final void compute() {
5424 dl 1.171 final ToLongFunction<? super V> transformer;
5425 dl 1.153 final LongBinaryOperator reducer;
5426 dl 1.149 if ((transformer = this.transformer) != null &&
5427     (reducer = this.reducer) != null) {
5428     long r = this.basis;
5429 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5430     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5431     addToPendingCount(1);
5432 dl 1.149 (rights = new MapReduceValuesToLongTask<K,V>
5433 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5434     rights, transformer, r, reducer)).fork();
5435     }
5436     for (Node<K,V> p; (p = advance()) != null; )
5437     r = reducer.applyAsLong(r, transformer.applyAsLong(p.val));
5438 dl 1.149 result = r;
5439     CountedCompleter<?> c;
5440     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5441     MapReduceValuesToLongTask<K,V>
5442     t = (MapReduceValuesToLongTask<K,V>)c,
5443     s = t.rights;
5444     while (s != null) {
5445 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5446 dl 1.149 s = t.rights = s.nextRight;
5447     }
5448 dl 1.119 }
5449     }
5450 jsr166 1.95 }
5451 dl 1.119 }
5452    
5453 dl 1.210 static final class MapReduceEntriesToLongTask<K,V>
5454     extends BulkTask<K,V,Long> {
5455 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5456 dl 1.153 final LongBinaryOperator reducer;
5457 dl 1.119 final long basis;
5458     long result;
5459 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
5460 dl 1.119 MapReduceEntriesToLongTask
5461 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5462 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
5463 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
5464 dl 1.119 long basis,
5465 dl 1.153 LongBinaryOperator reducer) {
5466 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5467 dl 1.119 this.transformer = transformer;
5468     this.basis = basis; this.reducer = reducer;
5469     }
5470 dl 1.146 public final Long getRawResult() { return result; }
5471 dl 1.210 public final void compute() {
5472 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
5473 dl 1.153 final LongBinaryOperator reducer;
5474 dl 1.149 if ((transformer = this.transformer) != null &&
5475     (reducer = this.reducer) != null) {
5476     long r = this.basis;
5477 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5478     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5479     addToPendingCount(1);
5480 dl 1.149 (rights = new MapReduceEntriesToLongTask<K,V>
5481 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5482     rights, transformer, r, reducer)).fork();
5483     }
5484     for (Node<K,V> p; (p = advance()) != null; )
5485     r = reducer.applyAsLong(r, transformer.applyAsLong(p));
5486 dl 1.149 result = r;
5487     CountedCompleter<?> c;
5488     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5489     MapReduceEntriesToLongTask<K,V>
5490     t = (MapReduceEntriesToLongTask<K,V>)c,
5491     s = t.rights;
5492     while (s != null) {
5493 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5494 dl 1.149 s = t.rights = s.nextRight;
5495     }
5496 dl 1.119 }
5497 dl 1.138 }
5498 dl 1.4 }
5499 tim 1.1 }
5500    
5501 dl 1.210 static final class MapReduceMappingsToLongTask<K,V>
5502     extends BulkTask<K,V,Long> {
5503 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
5504 dl 1.153 final LongBinaryOperator reducer;
5505 dl 1.119 final long basis;
5506     long result;
5507 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
5508 dl 1.119 MapReduceMappingsToLongTask
5509 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5510 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
5511 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
5512 dl 1.119 long basis,
5513 dl 1.153 LongBinaryOperator reducer) {
5514 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5515 dl 1.119 this.transformer = transformer;
5516     this.basis = basis; this.reducer = reducer;
5517     }
5518 dl 1.146 public final Long getRawResult() { return result; }
5519 dl 1.210 public final void compute() {
5520 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
5521 dl 1.153 final LongBinaryOperator reducer;
5522 dl 1.149 if ((transformer = this.transformer) != null &&
5523     (reducer = this.reducer) != null) {
5524     long r = this.basis;
5525 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5526     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5527     addToPendingCount(1);
5528 dl 1.149 (rights = new MapReduceMappingsToLongTask<K,V>
5529 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5530     rights, transformer, r, reducer)).fork();
5531     }
5532     for (Node<K,V> p; (p = advance()) != null; )
5533     r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key, p.val));
5534 dl 1.149 result = r;
5535     CountedCompleter<?> c;
5536     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5537     MapReduceMappingsToLongTask<K,V>
5538     t = (MapReduceMappingsToLongTask<K,V>)c,
5539     s = t.rights;
5540     while (s != null) {
5541 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
5542 dl 1.149 s = t.rights = s.nextRight;
5543     }
5544 dl 1.119 }
5545     }
5546 dl 1.4 }
5547 tim 1.1 }
5548    
5549 dl 1.210 static final class MapReduceKeysToIntTask<K,V>
5550     extends BulkTask<K,V,Integer> {
5551 dl 1.171 final ToIntFunction<? super K> transformer;
5552 dl 1.153 final IntBinaryOperator reducer;
5553 dl 1.119 final int basis;
5554     int result;
5555 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
5556 dl 1.119 MapReduceKeysToIntTask
5557 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5558 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
5559 dl 1.171 ToIntFunction<? super K> transformer,
5560 dl 1.119 int basis,
5561 dl 1.153 IntBinaryOperator reducer) {
5562 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5563 dl 1.119 this.transformer = transformer;
5564     this.basis = basis; this.reducer = reducer;
5565     }
5566 dl 1.146 public final Integer getRawResult() { return result; }
5567 dl 1.210 public final void compute() {
5568 dl 1.171 final ToIntFunction<? super K> transformer;
5569 dl 1.153 final IntBinaryOperator reducer;
5570 dl 1.149 if ((transformer = this.transformer) != null &&
5571     (reducer = this.reducer) != null) {
5572     int r = this.basis;
5573 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5574     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5575     addToPendingCount(1);
5576 dl 1.149 (rights = new MapReduceKeysToIntTask<K,V>
5577 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5578     rights, transformer, r, reducer)).fork();
5579     }
5580     for (Node<K,V> p; (p = advance()) != null; )
5581     r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key));
5582 dl 1.149 result = r;
5583     CountedCompleter<?> c;
5584     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5585     MapReduceKeysToIntTask<K,V>
5586     t = (MapReduceKeysToIntTask<K,V>)c,
5587     s = t.rights;
5588     while (s != null) {
5589 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5590 dl 1.149 s = t.rights = s.nextRight;
5591     }
5592 dl 1.119 }
5593 dl 1.138 }
5594 dl 1.30 }
5595     }
5596    
5597 dl 1.210 static final class MapReduceValuesToIntTask<K,V>
5598     extends BulkTask<K,V,Integer> {
5599 dl 1.171 final ToIntFunction<? super V> transformer;
5600 dl 1.153 final IntBinaryOperator reducer;
5601 dl 1.119 final int basis;
5602     int result;
5603 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
5604 dl 1.119 MapReduceValuesToIntTask
5605 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5606 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
5607 dl 1.171 ToIntFunction<? super V> transformer,
5608 dl 1.119 int basis,
5609 dl 1.153 IntBinaryOperator reducer) {
5610 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5611 dl 1.119 this.transformer = transformer;
5612     this.basis = basis; this.reducer = reducer;
5613     }
5614 dl 1.146 public final Integer getRawResult() { return result; }
5615 dl 1.210 public final void compute() {
5616 dl 1.171 final ToIntFunction<? super V> transformer;
5617 dl 1.153 final IntBinaryOperator reducer;
5618 dl 1.149 if ((transformer = this.transformer) != null &&
5619     (reducer = this.reducer) != null) {
5620     int r = this.basis;
5621 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5622     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5623     addToPendingCount(1);
5624 dl 1.149 (rights = new MapReduceValuesToIntTask<K,V>
5625 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5626     rights, transformer, r, reducer)).fork();
5627     }
5628     for (Node<K,V> p; (p = advance()) != null; )
5629     r = reducer.applyAsInt(r, transformer.applyAsInt(p.val));
5630 dl 1.149 result = r;
5631     CountedCompleter<?> c;
5632     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5633     MapReduceValuesToIntTask<K,V>
5634     t = (MapReduceValuesToIntTask<K,V>)c,
5635     s = t.rights;
5636     while (s != null) {
5637 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5638 dl 1.149 s = t.rights = s.nextRight;
5639     }
5640 dl 1.119 }
5641 dl 1.2 }
5642 tim 1.1 }
5643     }
5644    
5645 dl 1.210 static final class MapReduceEntriesToIntTask<K,V>
5646     extends BulkTask<K,V,Integer> {
5647 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
5648 dl 1.153 final IntBinaryOperator reducer;
5649 dl 1.119 final int basis;
5650     int result;
5651 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
5652 dl 1.119 MapReduceEntriesToIntTask
5653 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5654 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
5655 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
5656 dl 1.119 int basis,
5657 dl 1.153 IntBinaryOperator reducer) {
5658 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5659 dl 1.119 this.transformer = transformer;
5660     this.basis = basis; this.reducer = reducer;
5661     }
5662 dl 1.146 public final Integer getRawResult() { return result; }
5663 dl 1.210 public final void compute() {
5664 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
5665 dl 1.153 final IntBinaryOperator reducer;
5666 dl 1.149 if ((transformer = this.transformer) != null &&
5667     (reducer = this.reducer) != null) {
5668     int r = this.basis;
5669 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5670     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5671     addToPendingCount(1);
5672 dl 1.149 (rights = new MapReduceEntriesToIntTask<K,V>
5673 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5674     rights, transformer, r, reducer)).fork();
5675     }
5676     for (Node<K,V> p; (p = advance()) != null; )
5677     r = reducer.applyAsInt(r, transformer.applyAsInt(p));
5678 dl 1.149 result = r;
5679     CountedCompleter<?> c;
5680     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5681     MapReduceEntriesToIntTask<K,V>
5682     t = (MapReduceEntriesToIntTask<K,V>)c,
5683     s = t.rights;
5684     while (s != null) {
5685 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5686 dl 1.149 s = t.rights = s.nextRight;
5687     }
5688 dl 1.119 }
5689 dl 1.138 }
5690 dl 1.4 }
5691 dl 1.119 }
5692 tim 1.1
5693 dl 1.210 static final class MapReduceMappingsToIntTask<K,V>
5694     extends BulkTask<K,V,Integer> {
5695 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
5696 dl 1.153 final IntBinaryOperator reducer;
5697 dl 1.119 final int basis;
5698     int result;
5699 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
5700 dl 1.119 MapReduceMappingsToIntTask
5701 dl 1.210 (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
5702 dl 1.146 MapReduceMappingsToIntTask<K,V> nextRight,
5703 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
5704 dl 1.119 int basis,
5705 dl 1.153 IntBinaryOperator reducer) {
5706 dl 1.210 super(p, b, i, f, t); this.nextRight = nextRight;
5707 dl 1.119 this.transformer = transformer;
5708     this.basis = basis; this.reducer = reducer;
5709     }
5710 dl 1.146 public final Integer getRawResult() { return result; }
5711 dl 1.210 public final void compute() {
5712 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
5713 dl 1.153 final IntBinaryOperator reducer;
5714 dl 1.149 if ((transformer = this.transformer) != null &&
5715     (reducer = this.reducer) != null) {
5716     int r = this.basis;
5717 dl 1.210 for (int i = baseIndex, f, h; batch > 0 &&
5718     (h = ((f = baseLimit) + i) >>> 1) > i;) {
5719     addToPendingCount(1);
5720 dl 1.149 (rights = new MapReduceMappingsToIntTask<K,V>
5721 dl 1.210 (this, batch >>>= 1, baseLimit = h, f, tab,
5722     rights, transformer, r, reducer)).fork();
5723     }
5724     for (Node<K,V> p; (p = advance()) != null; )
5725     r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key, p.val));
5726 dl 1.149 result = r;
5727     CountedCompleter<?> c;
5728     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5729     MapReduceMappingsToIntTask<K,V>
5730     t = (MapReduceMappingsToIntTask<K,V>)c,
5731     s = t.rights;
5732     while (s != null) {
5733 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
5734 dl 1.149 s = t.rights = s.nextRight;
5735     }
5736 dl 1.119 }
5737 dl 1.138 }
5738 tim 1.1 }
5739     }
5740 dl 1.99
5741     // Unsafe mechanics
5742 dl 1.149 private static final sun.misc.Unsafe U;
5743     private static final long SIZECTL;
5744     private static final long TRANSFERINDEX;
5745     private static final long TRANSFERORIGIN;
5746     private static final long BASECOUNT;
5747 dl 1.153 private static final long CELLSBUSY;
5748 dl 1.149 private static final long CELLVALUE;
5749 dl 1.119 private static final long ABASE;
5750     private static final int ASHIFT;
5751 dl 1.99
5752     static {
5753     try {
5754 dl 1.149 U = sun.misc.Unsafe.getUnsafe();
5755 dl 1.119 Class<?> k = ConcurrentHashMap.class;
5756 dl 1.149 SIZECTL = U.objectFieldOffset
5757 dl 1.119 (k.getDeclaredField("sizeCtl"));
5758 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
5759     (k.getDeclaredField("transferIndex"));
5760     TRANSFERORIGIN = U.objectFieldOffset
5761     (k.getDeclaredField("transferOrigin"));
5762     BASECOUNT = U.objectFieldOffset
5763     (k.getDeclaredField("baseCount"));
5764 dl 1.153 CELLSBUSY = U.objectFieldOffset
5765     (k.getDeclaredField("cellsBusy"));
5766     Class<?> ck = Cell.class;
5767 dl 1.149 CELLVALUE = U.objectFieldOffset
5768     (ck.getDeclaredField("value"));
5769 dl 1.119 Class<?> sc = Node[].class;
5770 dl 1.149 ABASE = U.arrayBaseOffset(sc);
5771 jsr166 1.167 int scale = U.arrayIndexScale(sc);
5772     if ((scale & (scale - 1)) != 0)
5773     throw new Error("data type scale not a power of two");
5774     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
5775 dl 1.99 } catch (Exception e) {
5776     throw new Error(e);
5777     }
5778     }
5779 jsr166 1.152 }