ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.236
Committed: Thu Jul 11 10:38:10 2013 UTC (10 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.235: +2 -1 lines
Log Message:
Avoid backarward-compatibility problems by needlessly extending AbstractMap

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