ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.237
Committed: Thu Jul 18 17:13:42 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.236: +14 -0 lines
Log Message:
doclint warning fixes

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