ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.258
Committed: Sat Oct 25 18:04:44 2014 UTC (9 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.257: +2 -11 lines
Log Message:
Remove dead code

File Contents

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