ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.236
Committed: Thu Jul 11 10:38:10 2013 UTC (10 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.235: +2 -1 lines
Log Message:
Avoid backarward-compatibility problems by needlessly extending AbstractMap

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