ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.299
Committed: Sat Mar 18 19:19:04 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.298: +7 -6 lines
Log Message:
errorprone [OperatorPrecedence]

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