ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.241
Committed: Thu Aug 8 18:25:06 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.240: +34 -26 lines
Log Message:
document "weakly consistent" properties of spliterators

File Contents

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