ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.271
Committed: Tue Apr 28 23:06:53 2015 UTC (9 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.270: +25 -0 lines
Log Message:
Override default removeIf for ConcurrentMap EntrySets

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