ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.219
Committed: Sat Jun 1 18:19:08 2013 UTC (11 years ago) by dl
Branch: MAIN
Changes since 1.218: +26 -22 lines
Log Message:
Improve specs; reparamterize comparableClassFor

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