ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.293
Committed: Sat Jun 4 20:29:20 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.292: +3 -2 lines
Log Message:
import jdk.internal.misc.Unsafe

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