ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.210
Committed: Tue May 21 19:10:43 2013 UTC (11 years ago) by dl
Branch: MAIN
Changes since 1.209: +1643 -2863 lines
Log Message:
API changes to mesh better with lambda/streams

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