ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.164
Committed: Thu Jan 17 14:21:02 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.163: +3 -1 lines
Log Message:
correct putAll counts

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