ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.197
Committed: Mon Mar 18 19:35:09 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.196: +1 -1 lines
Log Message:
key param specs

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