ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.204
Committed: Thu Apr 11 18:43:33 2013 UTC (11 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.203: +5 -6 lines
Log Message:
Improve cccompare

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