ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.238
Committed: Thu Jul 18 18:21:22 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.237: +4 -0 lines
Log Message:
javadoc warning fixes: add serialization method @throws

File Contents

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