ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.202
Committed: Thu Apr 11 17:50:12 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.201: +1 -1 lines
Log Message:
whitespace

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