ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.193
Committed: Tue Feb 26 17:33:53 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.192: +2 -2 lines
Log Message:
promote comments to actual javadoc

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 computeIfAbsent}. For example, to add a count
99 * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
100 * {@code 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 * </ul>
153 * </li>
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 * Exported iterators must track whether the iterator has advanced
2148 * (in hasNext vs next) (by setting/checking/nulling field
2149 * nextVal), and then extract key, value, or key-value pairs as
2150 * return values of next().
2151 *
2152 * Method advance visits once each still-valid node that was
2153 * reachable upon iterator construction. It might miss some that
2154 * were added to a bin after the bin was visited, which is OK wrt
2155 * consistency guarantees. Maintaining this property in the face
2156 * of possible ongoing resizes requires a fair amount of
2157 * bookkeeping state that is difficult to optimize away amidst
2158 * volatile accesses. Even so, traversal maintains reasonable
2159 * throughput.
2160 *
2161 * Normally, iteration proceeds bin-by-bin traversing lists.
2162 * However, if the table has been resized, then all future steps
2163 * must traverse both the bin at the current index as well as at
2164 * (index + baseSize); and so on for further resizings. To
2165 * paranoically cope with potential sharing by users of iterators
2166 * across threads, iteration terminates if a bounds checks fails
2167 * for a table read.
2168 *
2169 * Methods advanceKey and advanceValue are specializations of the
2170 * common cases of advance, relaying to the full version
2171 * otherwise. The forEachKey and forEachValue methods further
2172 * specialize, bypassing all incremental field updates in most cases.
2173 *
2174 * This class supports both Spliterator-based traversal and
2175 * CountedCompleter-based bulk tasks. The same "batch" field is
2176 * used, but in slightly different ways, in the two cases. For
2177 * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2178 * estimate of element coverage. For CHM tasks, it is a pre-scaled
2179 * size that halves down to zero for leaf tasks, that is only
2180 * computed upon execution of the task. (Tasks can be submitted to
2181 * any pool, of any size, so we don't know scale factors until
2182 * running.)
2183 *
2184 * This class extends CountedCompleter to streamline parallel
2185 * iteration in bulk operations. This adds only a few fields of
2186 * space overhead, which is small enough in cases where it is not
2187 * needed to not worry about it. Because CountedCompleter is
2188 * Serializable, but iterators need not be, we need to add warning
2189 * suppressions.
2190 */
2191 @SuppressWarnings("serial") static class Traverser<K,V,R>
2192 extends CountedCompleter<R> {
2193 final ConcurrentHashMap<K,V> map;
2194 Node<V> next; // the next entry to use
2195 K nextKey; // cached key field of next
2196 V nextVal; // cached val field of next
2197 Node<V>[] tab; // current table; updated if resized
2198 int index; // index of bin to use next
2199 int baseIndex; // current index of initial table
2200 int baseLimit; // index bound for initial table
2201 final int baseSize; // initial table size
2202 int batch; // split control
2203
2204 /** Creates iterator for all entries in the table. */
2205 Traverser(ConcurrentHashMap<K,V> map) {
2206 this.map = map;
2207 Node<V>[] t = this.tab = map.table;
2208 baseLimit = baseSize = (t == null) ? 0 : t.length;
2209 }
2210
2211 /** Task constructor */
2212 Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2213 super(it);
2214 this.map = map;
2215 this.batch = batch; // -1 if unknown
2216 if (it == null) {
2217 Node<V>[] t = this.tab = map.table;
2218 baseLimit = baseSize = (t == null) ? 0 : t.length;
2219 }
2220 else { // split parent
2221 this.tab = it.tab;
2222 this.baseSize = it.baseSize;
2223 int hi = this.baseLimit = it.baseLimit;
2224 it.baseLimit = this.index = this.baseIndex =
2225 (hi + it.baseIndex + 1) >>> 1;
2226 }
2227 }
2228
2229 /** Spliterator constructor */
2230 Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2231 super(it);
2232 this.map = map;
2233 if (it == null) {
2234 Node<V>[] t = this.tab = map.table;
2235 baseLimit = baseSize = (t == null) ? 0 : 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 if possible, returning next valid value, or null if none.
2252 */
2253 @SuppressWarnings("unchecked") final V advance() {
2254 for (Node<V> e = next;;) {
2255 if (e != null) // advance past used/skipped node
2256 e = next = e.next;
2257 while (e == null) { // get to next non-null bin
2258 Node<V>[] t; int i, n; // must use locals in checks
2259 if (baseIndex >= baseLimit || (t = tab) == null ||
2260 (n = t.length) <= (i = index) || i < 0)
2261 return nextVal = null;
2262 if ((e = next = tabAt(t, index)) != null && e.hash < 0) {
2263 Object ek;
2264 if ((ek = e.key) instanceof TreeBin)
2265 e = ((TreeBin<V>)ek).first;
2266 else {
2267 tab = (Node<V>[])ek;
2268 continue; // restarts due to null val
2269 }
2270 }
2271 if ((index += baseSize) >= n)
2272 index = ++baseIndex; // visit upper slots if present
2273 }
2274 nextKey = (K)e.key;
2275 if ((nextVal = e.val) != null) // skip deleted or special nodes
2276 return nextVal;
2277 }
2278 }
2279
2280 /**
2281 * Common case version for value traversal
2282 */
2283 @SuppressWarnings("unchecked") final V advanceValue() {
2284 outer: for (Node<V> e = next;;) {
2285 if (e == null || (e = e.next) == null) {
2286 Node<V>[] t; int i, len, n; Object ek;
2287 if ((t = tab) == null ||
2288 baseSize != (len = t.length) ||
2289 len < (n = baseLimit) ||
2290 baseIndex != (i = index))
2291 break;
2292 do {
2293 if (i < 0 || i >= n) {
2294 index = baseIndex = n;
2295 next = null;
2296 return nextVal = null;
2297 }
2298 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2299 if ((ek = e.key) instanceof TreeBin)
2300 e = ((TreeBin<V>)ek).first;
2301 else {
2302 index = baseIndex = i;
2303 next = null;
2304 tab = (Node<V>[])ek;
2305 break outer;
2306 }
2307 }
2308 ++i;
2309 } while (e == null);
2310 index = baseIndex = i;
2311 }
2312 V v;
2313 K k = (K)e.key;
2314 if ((v = e.val) != null) {
2315 nextVal = v;
2316 nextKey = k;
2317 next = e;
2318 return v;
2319 }
2320 }
2321 return advance();
2322 }
2323
2324 /**
2325 * Common case version for key traversal
2326 */
2327 @SuppressWarnings("unchecked") final K advanceKey() {
2328 outer: for (Node<V> e = next;;) {
2329 if (e == null || (e = e.next) == null) {
2330 Node<V>[] t; int i, len, n; Object ek;
2331 if ((t = tab) == null ||
2332 baseSize != (len = t.length) ||
2333 len < (n = baseLimit) ||
2334 baseIndex != (i = index))
2335 break;
2336 do {
2337 if (i < 0 || i >= n) {
2338 index = baseIndex = n;
2339 next = null;
2340 nextVal = null;
2341 return null;
2342 }
2343 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2344 if ((ek = e.key) instanceof TreeBin)
2345 e = ((TreeBin<V>)ek).first;
2346 else {
2347 index = baseIndex = i;
2348 next = null;
2349 tab = (Node<V>[])ek;
2350 break outer;
2351 }
2352 }
2353 ++i;
2354 } while (e == null);
2355 index = baseIndex = i;
2356 }
2357 V v;
2358 K k = (K)e.key;
2359 if ((v = e.val) != null) {
2360 nextVal = v;
2361 nextKey = k;
2362 next = e;
2363 return k;
2364 }
2365 }
2366 return (advance() == null) ? null : nextKey;
2367 }
2368
2369 @SuppressWarnings("unchecked") final void forEachValue(Consumer<? super V> action) {
2370 if (action == null) throw new NullPointerException();
2371 Node<V>[] t; int i, len, n;
2372 if ((t = tab) != null && baseSize == (len = t.length) &&
2373 len >= (n = baseLimit) && baseIndex == (i = index)) {
2374 Node<V> e = next;
2375 index = baseIndex = n;
2376 next = null;
2377 nextVal = null;
2378 outer: for (;; e = e.next) {
2379 V v; Object ek;
2380 for (; e == null; ++i) {
2381 if (i < 0 || i >= n)
2382 return;
2383 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2384 if ((ek = e.key) instanceof TreeBin)
2385 e = ((TreeBin<V>)ek).first;
2386 else {
2387 index = baseIndex = i;
2388 tab = (Node<V>[])ek;
2389 break outer;
2390 }
2391 }
2392 }
2393 if ((v = e.val) != null)
2394 action.accept(v);
2395 }
2396 }
2397 V v;
2398 while ((v = advance()) != null)
2399 action.accept(v);
2400 }
2401
2402 @SuppressWarnings("unchecked") final void forEachKey(Consumer<? super K> action) {
2403 if (action == null) throw new NullPointerException();
2404 Node<V>[] t; int i, len, n;
2405 if ((t = tab) != null && baseSize == (len = t.length) &&
2406 len >= (n = baseLimit) && baseIndex == (i = index)) {
2407 Node<V> e = next;
2408 index = baseIndex = n;
2409 next = null;
2410 nextVal = null;
2411 outer: for (;; e = e.next) {
2412 for (; e == null; ++i) {
2413 if (i < 0 || i >= n)
2414 return;
2415 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2416 Object ek;
2417 if ((ek = e.key) instanceof TreeBin)
2418 e = ((TreeBin<V>)ek).first;
2419 else {
2420 index = baseIndex = i;
2421 tab = (Node<V>[])ek;
2422 break outer;
2423 }
2424 }
2425 }
2426 Object k = e.key;
2427 if (e.val != null)
2428 action.accept((K)k);
2429 }
2430 }
2431 while (advance() != null)
2432 action.accept(nextKey);
2433 }
2434
2435 public final void remove() {
2436 K k = nextKey;
2437 if (k == null && (advanceValue() == null || (k = nextKey) == null))
2438 throw new IllegalStateException();
2439 map.internalReplace(k, null, null);
2440 }
2441
2442 public final boolean hasNext() {
2443 return nextVal != null || advanceValue() != null;
2444 }
2445
2446 public final boolean hasMoreElements() { return hasNext(); }
2447
2448 public void compute() { } // default no-op CountedCompleter body
2449
2450 public long estimateSize() { return batch; }
2451
2452 /**
2453 * Returns a batch value > 0 if this task should (and must) be
2454 * split, if so, adding to pending count, and in any case
2455 * updating batch value. The initial batch value is approx
2456 * exp2 of the number of times (minus one) to split task by
2457 * two before executing leaf action. This value is faster to
2458 * compute and more convenient to use as a guide to splitting
2459 * than is the depth, since it is used while dividing by two
2460 * anyway.
2461 */
2462 final int preSplit() {
2463 int b; ForkJoinPool pool;
2464 if ((b = batch) < 0) { // force initialization
2465 int sp = (((pool = getPool()) == null) ?
2466 ForkJoinPool.getCommonPoolParallelism() :
2467 pool.getParallelism()) << 3; // slack of 8
2468 long n = map.sumCount();
2469 b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2470 }
2471 b = (b <= 1 || baseIndex >= baseLimit) ? 0 : (b >>> 1);
2472 if ((batch = b) > 0)
2473 addToPendingCount(1);
2474 return b;
2475 }
2476 }
2477
2478 /* ---------------- Public operations -------------- */
2479
2480 /**
2481 * Creates a new, empty map with the default initial table size (16).
2482 */
2483 public ConcurrentHashMap() {
2484 }
2485
2486 /**
2487 * Creates a new, empty map with an initial table size
2488 * accommodating the specified number of elements without the need
2489 * to dynamically resize.
2490 *
2491 * @param initialCapacity The implementation performs internal
2492 * sizing to accommodate this many elements.
2493 * @throws IllegalArgumentException if the initial capacity of
2494 * elements is negative
2495 */
2496 public ConcurrentHashMap(int initialCapacity) {
2497 if (initialCapacity < 0)
2498 throw new IllegalArgumentException();
2499 int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2500 MAXIMUM_CAPACITY :
2501 tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2502 this.sizeCtl = cap;
2503 }
2504
2505 /**
2506 * Creates a new map with the same mappings as the given map.
2507 *
2508 * @param m the map
2509 */
2510 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2511 this.sizeCtl = DEFAULT_CAPACITY;
2512 internalPutAll(m);
2513 }
2514
2515 /**
2516 * Creates a new, empty map with an initial table size based on
2517 * the given number of elements ({@code initialCapacity}) and
2518 * initial table density ({@code loadFactor}).
2519 *
2520 * @param initialCapacity the initial capacity. The implementation
2521 * performs internal sizing to accommodate this many elements,
2522 * given the specified load factor.
2523 * @param loadFactor the load factor (table density) for
2524 * establishing the initial table size
2525 * @throws IllegalArgumentException if the initial capacity of
2526 * elements is negative or the load factor is nonpositive
2527 *
2528 * @since 1.6
2529 */
2530 public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2531 this(initialCapacity, loadFactor, 1);
2532 }
2533
2534 /**
2535 * Creates a new, empty map with an initial table size based on
2536 * the given number of elements ({@code initialCapacity}), table
2537 * density ({@code loadFactor}), and number of concurrently
2538 * updating threads ({@code concurrencyLevel}).
2539 *
2540 * @param initialCapacity the initial capacity. The implementation
2541 * performs internal sizing to accommodate this many elements,
2542 * given the specified load factor.
2543 * @param loadFactor the load factor (table density) for
2544 * establishing the initial table size
2545 * @param concurrencyLevel the estimated number of concurrently
2546 * updating threads. The implementation may use this value as
2547 * a sizing hint.
2548 * @throws IllegalArgumentException if the initial capacity is
2549 * negative or the load factor or concurrencyLevel are
2550 * nonpositive
2551 */
2552 public ConcurrentHashMap(int initialCapacity,
2553 float loadFactor, int concurrencyLevel) {
2554 if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2555 throw new IllegalArgumentException();
2556 if (initialCapacity < concurrencyLevel) // Use at least as many bins
2557 initialCapacity = concurrencyLevel; // as estimated threads
2558 long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2559 int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2560 MAXIMUM_CAPACITY : tableSizeFor((int)size);
2561 this.sizeCtl = cap;
2562 }
2563
2564 /**
2565 * Creates a new {@link Set} backed by a ConcurrentHashMap
2566 * from the given type to {@code Boolean.TRUE}.
2567 *
2568 * @return the new set
2569 */
2570 public static <K> KeySetView<K,Boolean> newKeySet() {
2571 return new KeySetView<K,Boolean>
2572 (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2573 }
2574
2575 /**
2576 * Creates a new {@link Set} backed by a ConcurrentHashMap
2577 * from the given type to {@code Boolean.TRUE}.
2578 *
2579 * @param initialCapacity The implementation performs internal
2580 * sizing to accommodate this many elements.
2581 * @throws IllegalArgumentException if the initial capacity of
2582 * elements is negative
2583 * @return the new set
2584 */
2585 public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2586 return new KeySetView<K,Boolean>
2587 (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2588 }
2589
2590 /**
2591 * {@inheritDoc}
2592 */
2593 public boolean isEmpty() {
2594 return sumCount() <= 0L; // ignore transient negative values
2595 }
2596
2597 /**
2598 * {@inheritDoc}
2599 */
2600 public int size() {
2601 long n = sumCount();
2602 return ((n < 0L) ? 0 :
2603 (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2604 (int)n);
2605 }
2606
2607 /**
2608 * Returns the number of mappings. This method should be used
2609 * instead of {@link #size} because a ConcurrentHashMap may
2610 * contain more mappings than can be represented as an int. The
2611 * value returned is an estimate; the actual count may differ if
2612 * there are concurrent insertions or removals.
2613 *
2614 * @return the number of mappings
2615 */
2616 public long mappingCount() {
2617 long n = sumCount();
2618 return (n < 0L) ? 0L : n; // ignore transient negative values
2619 }
2620
2621 /**
2622 * Returns the value to which the specified key is mapped,
2623 * or {@code null} if this map contains no mapping for the key.
2624 *
2625 * <p>More formally, if this map contains a mapping from a key
2626 * {@code k} to a value {@code v} such that {@code key.equals(k)},
2627 * then this method returns {@code v}; otherwise it returns
2628 * {@code null}. (There can be at most one such mapping.)
2629 *
2630 * @throws NullPointerException if the specified key is null
2631 */
2632 public V get(Object key) {
2633 return internalGet(key);
2634 }
2635
2636 /**
2637 * Returns the value to which the specified key is mapped,
2638 * or the given defaultValue if this map contains no mapping for the key.
2639 *
2640 * @param key the key
2641 * @param defaultValue the value to return if this map contains
2642 * no mapping for the given key
2643 * @return the mapping for the key, if present; else the defaultValue
2644 * @throws NullPointerException if the specified key is null
2645 */
2646 public V getValueOrDefault(Object key, V defaultValue) {
2647 V v;
2648 return (v = internalGet(key)) == null ? defaultValue : v;
2649 }
2650
2651 /**
2652 * Tests if the specified object is a key in this table.
2653 *
2654 * @param key possible key
2655 * @return {@code true} if and only if the specified object
2656 * is a key in this table, as determined by the
2657 * {@code equals} method; {@code false} otherwise
2658 * @throws NullPointerException if the specified key is null
2659 */
2660 public boolean containsKey(Object key) {
2661 return internalGet(key) != null;
2662 }
2663
2664 /**
2665 * Returns {@code true} if this map maps one or more keys to the
2666 * specified value. Note: This method may require a full traversal
2667 * of the map, and is much slower than method {@code containsKey}.
2668 *
2669 * @param value value whose presence in this map is to be tested
2670 * @return {@code true} if this map maps one or more keys to the
2671 * specified value
2672 * @throws NullPointerException if the specified value is null
2673 */
2674 public boolean containsValue(Object value) {
2675 if (value == null)
2676 throw new NullPointerException();
2677 V v;
2678 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2679 while ((v = it.advanceValue()) != null) {
2680 if (v == value || value.equals(v))
2681 return true;
2682 }
2683 return false;
2684 }
2685
2686 /**
2687 * Legacy method testing if some key maps into the specified value
2688 * in this table. This method is identical in functionality to
2689 * {@link #containsValue(Object)}, and exists solely to ensure
2690 * full compatibility with class {@link java.util.Hashtable},
2691 * which supported this method prior to introduction of the
2692 * Java Collections framework.
2693 *
2694 * @param value a value to search for
2695 * @return {@code true} if and only if some key maps to the
2696 * {@code value} argument in this table as
2697 * determined by the {@code equals} method;
2698 * {@code false} otherwise
2699 * @throws NullPointerException if the specified value is null
2700 */
2701 @Deprecated public boolean contains(Object value) {
2702 return containsValue(value);
2703 }
2704
2705 /**
2706 * Maps the specified key to the specified value in this table.
2707 * Neither the key nor the value can be null.
2708 *
2709 * <p>The value can be retrieved by calling the {@code get} method
2710 * with a key that is equal to the original key.
2711 *
2712 * @param key key with which the specified value is to be associated
2713 * @param value value to be associated with the specified key
2714 * @return the previous value associated with {@code key}, or
2715 * {@code null} if there was no mapping for {@code key}
2716 * @throws NullPointerException if the specified key or value is null
2717 */
2718 public V put(K key, V value) {
2719 return internalPut(key, value, false);
2720 }
2721
2722 /**
2723 * {@inheritDoc}
2724 *
2725 * @return the previous value associated with the specified key,
2726 * or {@code null} if there was no mapping for the key
2727 * @throws NullPointerException if the specified key or value is null
2728 */
2729 public V putIfAbsent(K key, V value) {
2730 return internalPut(key, value, true);
2731 }
2732
2733 /**
2734 * Copies all of the mappings from the specified map to this one.
2735 * These mappings replace any mappings that this map had for any of the
2736 * keys currently in the specified map.
2737 *
2738 * @param m mappings to be stored in this map
2739 */
2740 public void putAll(Map<? extends K, ? extends V> m) {
2741 internalPutAll(m);
2742 }
2743
2744 /**
2745 * If the specified key is not already associated with a value (or
2746 * is mapped to {@code null}), attempts to compute its value using
2747 * the given mapping function and enters it into this map unless
2748 * {@code null}. The entire method invocation is performed
2749 * atomically, so the function is applied at most once per key.
2750 * Some attempted update operations on this map by other threads
2751 * may be blocked while computation is in progress, so the
2752 * computation should be short and simple, and must not attempt to
2753 * update any other mappings of this Map.
2754 *
2755 * @param key key with which the specified value is to be associated
2756 * @param mappingFunction the function to compute a value
2757 * @return the current (existing or computed) value associated with
2758 * the specified key, or null if the computed value is null
2759 * @throws NullPointerException if the specified key or mappingFunction
2760 * is null
2761 * @throws IllegalStateException if the computation detectably
2762 * attempts a recursive update to this map that would
2763 * otherwise never complete
2764 * @throws RuntimeException or Error if the mappingFunction does so,
2765 * in which case the mapping is left unestablished
2766 */
2767 public V computeIfAbsent
2768 (K key, Function<? super K, ? extends V> mappingFunction) {
2769 return internalComputeIfAbsent(key, mappingFunction);
2770 }
2771
2772 /**
2773 * If the value for the specified key is present and non-null,
2774 * attempts to compute a new mapping given the key and its current
2775 * mapped value. The entire method invocation is performed
2776 * atomically. Some attempted update operations on this map by
2777 * other threads may be blocked while computation is in progress,
2778 * so the computation should be short and simple, and must not
2779 * attempt to update any other mappings of this Map.
2780 *
2781 * @param key key with which the specified value is to be associated
2782 * @param remappingFunction the function to compute a value
2783 * @return the new value associated with the specified key, or null if none
2784 * @throws NullPointerException if the specified key or remappingFunction
2785 * is null
2786 * @throws IllegalStateException if the computation detectably
2787 * attempts a recursive update to this map that would
2788 * otherwise never complete
2789 * @throws RuntimeException or Error if the remappingFunction does so,
2790 * in which case the mapping is unchanged
2791 */
2792 public V computeIfPresent
2793 (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2794 return internalCompute(key, true, remappingFunction);
2795 }
2796
2797 /**
2798 * Attempts to compute a mapping for the specified key and its
2799 * current mapped value (or {@code null} if there is no current
2800 * mapping). The entire method invocation is performed atomically.
2801 * Some attempted update operations on this map by other threads
2802 * may be blocked while computation is in progress, so the
2803 * computation should be short and simple, and must not attempt to
2804 * update any other mappings of this Map.
2805 *
2806 * @param key key with which the specified value is to be associated
2807 * @param remappingFunction the function to compute a value
2808 * @return the new value associated with the specified key, or null if none
2809 * @throws NullPointerException if the specified key or remappingFunction
2810 * is null
2811 * @throws IllegalStateException if the computation detectably
2812 * attempts a recursive update to this map that would
2813 * otherwise never complete
2814 * @throws RuntimeException or Error if the remappingFunction does so,
2815 * in which case the mapping is unchanged
2816 */
2817 public V compute
2818 (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2819 return internalCompute(key, false, remappingFunction);
2820 }
2821
2822 /**
2823 * If the specified key is not already associated with a
2824 * (non-null) value, associates it with the given value.
2825 * Otherwise, replaces the value with the results of the given
2826 * remapping function, or removes if {@code null}. The entire
2827 * method invocation is performed atomically. Some attempted
2828 * update operations on this map by other threads may be blocked
2829 * while computation is in progress, so the computation should be
2830 * short and simple, and must not attempt to update any other
2831 * mappings of this Map.
2832 *
2833 * @param key key with which the specified value is to be associated
2834 * @param value the value to use if absent
2835 * @param remappingFunction the function to recompute a value if present
2836 * @return the new value associated with the specified key, or null if none
2837 * @throws NullPointerException if the specified key or the
2838 * remappingFunction is null
2839 * @throws RuntimeException or Error if the remappingFunction does so,
2840 * in which case the mapping is unchanged
2841 */
2842 public V merge
2843 (K key, V value,
2844 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2845 return internalMerge(key, value, remappingFunction);
2846 }
2847
2848 /**
2849 * Removes the key (and its corresponding value) from this map.
2850 * This method does nothing if the key is not in the map.
2851 *
2852 * @param key the key that needs to be removed
2853 * @return the previous value associated with {@code key}, or
2854 * {@code null} if there was no mapping for {@code key}
2855 * @throws NullPointerException if the specified key is null
2856 */
2857 public V remove(Object key) {
2858 return internalReplace(key, null, null);
2859 }
2860
2861 /**
2862 * {@inheritDoc}
2863 *
2864 * @throws NullPointerException if the specified key is null
2865 */
2866 public boolean remove(Object key, Object value) {
2867 if (key == null)
2868 throw new NullPointerException();
2869 return value != null && internalReplace(key, null, value) != null;
2870 }
2871
2872 /**
2873 * {@inheritDoc}
2874 *
2875 * @throws NullPointerException if any of the arguments are null
2876 */
2877 public boolean replace(K key, V oldValue, V newValue) {
2878 if (key == null || oldValue == null || newValue == null)
2879 throw new NullPointerException();
2880 return internalReplace(key, newValue, oldValue) != null;
2881 }
2882
2883 /**
2884 * {@inheritDoc}
2885 *
2886 * @return the previous value associated with the specified key,
2887 * or {@code null} if there was no mapping for the key
2888 * @throws NullPointerException if the specified key or value is null
2889 */
2890 public V replace(K key, V value) {
2891 if (key == null || value == null)
2892 throw new NullPointerException();
2893 return internalReplace(key, value, null);
2894 }
2895
2896 /**
2897 * Removes all of the mappings from this map.
2898 */
2899 public void clear() {
2900 internalClear();
2901 }
2902
2903 /**
2904 * Returns a {@link Set} view of the keys contained in this map.
2905 * The set is backed by the map, so changes to the map are
2906 * reflected in the set, and vice-versa.
2907 *
2908 * @return the set view
2909 */
2910 public KeySetView<K,V> keySet() {
2911 KeySetView<K,V> ks = keySet;
2912 return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2913 }
2914
2915 /**
2916 * Returns a {@link Set} view of the keys in this map, using the
2917 * given common mapped value for any additions (i.e., {@link
2918 * Collection#add} and {@link Collection#addAll(Collection)}).
2919 * This is of course only appropriate if it is acceptable to use
2920 * the same value for all additions from this view.
2921 *
2922 * @param mappedValue the mapped value to use for any additions
2923 * @return the set view
2924 * @throws NullPointerException if the mappedValue is null
2925 */
2926 public KeySetView<K,V> keySet(V mappedValue) {
2927 if (mappedValue == null)
2928 throw new NullPointerException();
2929 return new KeySetView<K,V>(this, mappedValue);
2930 }
2931
2932 /**
2933 * Returns a {@link Collection} view of the values contained in this map.
2934 * The collection is backed by the map, so changes to the map are
2935 * reflected in the collection, and vice-versa.
2936 *
2937 * @return the collection view
2938 */
2939 public ValuesView<K,V> values() {
2940 ValuesView<K,V> vs = values;
2941 return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2942 }
2943
2944 /**
2945 * Returns a {@link Set} view of the mappings contained in this map.
2946 * The set is backed by the map, so changes to the map are
2947 * reflected in the set, and vice-versa. The set supports element
2948 * removal, which removes the corresponding mapping from the map,
2949 * via the {@code Iterator.remove}, {@code Set.remove},
2950 * {@code removeAll}, {@code retainAll}, and {@code clear}
2951 * operations. It does not support the {@code add} or
2952 * {@code addAll} operations.
2953 *
2954 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2955 * that will never throw {@link ConcurrentModificationException},
2956 * and guarantees to traverse elements as they existed upon
2957 * construction of the iterator, and may (but is not guaranteed to)
2958 * reflect any modifications subsequent to construction.
2959 *
2960 * @return the set view
2961 */
2962 public Set<Map.Entry<K,V>> entrySet() {
2963 EntrySetView<K,V> es = entrySet;
2964 return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2965 }
2966
2967 /**
2968 * Returns an enumeration of the keys in this table.
2969 *
2970 * @return an enumeration of the keys in this table
2971 * @see #keySet()
2972 */
2973 public Enumeration<K> keys() {
2974 return new KeyIterator<K,V>(this);
2975 }
2976
2977 /**
2978 * Returns an enumeration of the values in this table.
2979 *
2980 * @return an enumeration of the values in this table
2981 * @see #values()
2982 */
2983 public Enumeration<V> elements() {
2984 return new ValueIterator<K,V>(this);
2985 }
2986
2987 /**
2988 * Returns the hash code value for this {@link Map}, i.e.,
2989 * the sum of, for each key-value pair in the map,
2990 * {@code key.hashCode() ^ value.hashCode()}.
2991 *
2992 * @return the hash code value for this map
2993 */
2994 public int hashCode() {
2995 int h = 0;
2996 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2997 V v;
2998 while ((v = it.advanceValue()) != null) {
2999 h += it.nextKey.hashCode() ^ v.hashCode();
3000 }
3001 return h;
3002 }
3003
3004 /**
3005 * Returns a string representation of this map. The string
3006 * representation consists of a list of key-value mappings (in no
3007 * particular order) enclosed in braces ("{@code {}}"). Adjacent
3008 * mappings are separated by the characters {@code ", "} (comma
3009 * and space). Each key-value mapping is rendered as the key
3010 * followed by an equals sign ("{@code =}") followed by the
3011 * associated value.
3012 *
3013 * @return a string representation of this map
3014 */
3015 public String toString() {
3016 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3017 StringBuilder sb = new StringBuilder();
3018 sb.append('{');
3019 V v;
3020 if ((v = it.advanceValue()) != null) {
3021 for (;;) {
3022 K k = it.nextKey;
3023 sb.append(k == this ? "(this Map)" : k);
3024 sb.append('=');
3025 sb.append(v == this ? "(this Map)" : v);
3026 if ((v = it.advanceValue()) == null)
3027 break;
3028 sb.append(',').append(' ');
3029 }
3030 }
3031 return sb.append('}').toString();
3032 }
3033
3034 /**
3035 * Compares the specified object with this map for equality.
3036 * Returns {@code true} if the given object is a map with the same
3037 * mappings as this map. This operation may return misleading
3038 * results if either map is concurrently modified during execution
3039 * of this method.
3040 *
3041 * @param o object to be compared for equality with this map
3042 * @return {@code true} if the specified object is equal to this map
3043 */
3044 public boolean equals(Object o) {
3045 if (o != this) {
3046 if (!(o instanceof Map))
3047 return false;
3048 Map<?,?> m = (Map<?,?>) o;
3049 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3050 V val;
3051 while ((val = it.advanceValue()) != null) {
3052 Object v = m.get(it.nextKey);
3053 if (v == null || (v != val && !v.equals(val)))
3054 return false;
3055 }
3056 for (Map.Entry<?,?> e : m.entrySet()) {
3057 Object mk, mv, v;
3058 if ((mk = e.getKey()) == null ||
3059 (mv = e.getValue()) == null ||
3060 (v = internalGet(mk)) == null ||
3061 (mv != v && !mv.equals(v)))
3062 return false;
3063 }
3064 }
3065 return true;
3066 }
3067
3068 /* ----------------Iterators -------------- */
3069
3070 @SuppressWarnings("serial") static final class KeyIterator<K,V>
3071 extends Traverser<K,V,Object>
3072 implements Spliterator<K>, Iterator<K>, Enumeration<K> {
3073 KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
3074 KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3075 super(map, it);
3076 }
3077 public Spliterator<K> trySplit() {
3078 return (baseIndex >= baseLimit) ? null :
3079 new KeyIterator<K,V>(map, this);
3080 }
3081 public final K next() {
3082 K k;
3083 if ((k = (nextVal == null) ? advanceKey() : nextKey) == null)
3084 throw new NoSuchElementException();
3085 nextVal = null;
3086 return k;
3087 }
3088
3089 public final K nextElement() { return next(); }
3090
3091 public Iterator<K> iterator() { return this; }
3092
3093 public void forEach(Consumer<? super K> action) {
3094 forEachKey(action);
3095 }
3096
3097 public boolean tryAdvance(Consumer<? super K> block) {
3098 if (block == null) throw new NullPointerException();
3099 K k;
3100 if ((k = advanceKey()) == null)
3101 return false;
3102 block.accept(k);
3103 return true;
3104 }
3105
3106 public int characteristics() {
3107 return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3108 Spliterator.NONNULL;
3109 }
3110
3111 }
3112
3113 @SuppressWarnings("serial") static final class ValueIterator<K,V>
3114 extends Traverser<K,V,Object>
3115 implements Spliterator<V>, Iterator<V>, Enumeration<V> {
3116 ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
3117 ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3118 super(map, it);
3119 }
3120 public Spliterator<V> trySplit() {
3121 return (baseIndex >= baseLimit) ? null :
3122 new ValueIterator<K,V>(map, this);
3123 }
3124
3125 public final V next() {
3126 V v;
3127 if ((v = nextVal) == null && (v = advanceValue()) == null)
3128 throw new NoSuchElementException();
3129 nextVal = null;
3130 return v;
3131 }
3132
3133 public final V nextElement() { return next(); }
3134
3135 public Iterator<V> iterator() { return this; }
3136
3137 public void forEach(Consumer<? super V> action) {
3138 forEachValue(action);
3139 }
3140
3141 public boolean tryAdvance(Consumer<? super V> block) {
3142 V v;
3143 if (block == null) throw new NullPointerException();
3144 if ((v = advanceValue()) == null)
3145 return false;
3146 block.accept(v);
3147 return true;
3148 }
3149
3150 public int characteristics() {
3151 return Spliterator.CONCURRENT | Spliterator.NONNULL;
3152 }
3153 }
3154
3155 @SuppressWarnings("serial") static final class EntryIterator<K,V>
3156 extends Traverser<K,V,Object>
3157 implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3158 EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3159 EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3160 super(map, it);
3161 }
3162 public Spliterator<Map.Entry<K,V>> trySplit() {
3163 return (baseIndex >= baseLimit) ? null :
3164 new EntryIterator<K,V>(map, this);
3165 }
3166
3167 public final Map.Entry<K,V> next() {
3168 V v;
3169 if ((v = nextVal) == null && (v = advanceValue()) == null)
3170 throw new NoSuchElementException();
3171 K k = nextKey;
3172 nextVal = null;
3173 return new MapEntry<K,V>(k, v, map);
3174 }
3175
3176 public Iterator<Map.Entry<K,V>> iterator() { return this; }
3177
3178 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
3179 if (action == null) throw new NullPointerException();
3180 V v;
3181 while ((v = advanceValue()) != null)
3182 action.accept(entryFor(nextKey, v));
3183 }
3184
3185 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3186 V v;
3187 if (block == null) throw new NullPointerException();
3188 if ((v = advanceValue()) == null)
3189 return false;
3190 block.accept(entryFor(nextKey, v));
3191 return true;
3192 }
3193
3194 public int characteristics() {
3195 return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3196 Spliterator.NONNULL;
3197 }
3198 }
3199
3200 /**
3201 * Exported Entry for iterators
3202 */
3203 static final class MapEntry<K,V> implements Map.Entry<K,V> {
3204 final K key; // non-null
3205 V val; // non-null
3206 final ConcurrentHashMap<K,V> map;
3207 MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3208 this.key = key;
3209 this.val = val;
3210 this.map = map;
3211 }
3212 public final K getKey() { return key; }
3213 public final V getValue() { return val; }
3214 public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
3215 public final String toString(){ return key + "=" + val; }
3216
3217 public final boolean equals(Object o) {
3218 Object k, v; Map.Entry<?,?> e;
3219 return ((o instanceof Map.Entry) &&
3220 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3221 (v = e.getValue()) != null &&
3222 (k == key || k.equals(key)) &&
3223 (v == val || v.equals(val)));
3224 }
3225
3226 /**
3227 * Sets our entry's value and writes through to the map. The
3228 * value to return is somewhat arbitrary here. Since we do not
3229 * necessarily track asynchronous changes, the most recent
3230 * "previous" value could be different from what we return (or
3231 * could even have been removed in which case the put will
3232 * re-establish). We do not and cannot guarantee more.
3233 */
3234 public final V setValue(V value) {
3235 if (value == null) throw new NullPointerException();
3236 V v = val;
3237 val = value;
3238 map.put(key, value);
3239 return v;
3240 }
3241 }
3242
3243 /**
3244 * Returns exportable snapshot entry for the given key and value
3245 * when write-through can't or shouldn't be used.
3246 */
3247 static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3248 return new AbstractMap.SimpleEntry<K,V>(k, v);
3249 }
3250
3251 /* ---------------- Serialization Support -------------- */
3252
3253 /**
3254 * Stripped-down version of helper class used in previous version,
3255 * declared for the sake of serialization compatibility
3256 */
3257 static class Segment<K,V> implements Serializable {
3258 private static final long serialVersionUID = 2249069246763182397L;
3259 final float loadFactor;
3260 Segment(float lf) { this.loadFactor = lf; }
3261 }
3262
3263 /**
3264 * Saves the state of the {@code ConcurrentHashMap} instance to a
3265 * stream (i.e., serializes it).
3266 * @param s the stream
3267 * @serialData
3268 * the key (Object) and value (Object)
3269 * for each key-value mapping, followed by a null pair.
3270 * The key-value mappings are emitted in no particular order.
3271 */
3272 @SuppressWarnings("unchecked") private void writeObject
3273 (java.io.ObjectOutputStream s)
3274 throws java.io.IOException {
3275 if (segments == null) { // for serialization compatibility
3276 segments = (Segment<K,V>[])
3277 new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3278 for (int i = 0; i < segments.length; ++i)
3279 segments[i] = new Segment<K,V>(LOAD_FACTOR);
3280 }
3281 s.defaultWriteObject();
3282 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3283 V v;
3284 while ((v = it.advanceValue()) != null) {
3285 s.writeObject(it.nextKey);
3286 s.writeObject(v);
3287 }
3288 s.writeObject(null);
3289 s.writeObject(null);
3290 segments = null; // throw away
3291 }
3292
3293 /**
3294 * Reconstitutes the instance from a stream (that is, deserializes it).
3295 * @param s the stream
3296 */
3297 @SuppressWarnings("unchecked") private void readObject
3298 (java.io.ObjectInputStream s)
3299 throws java.io.IOException, ClassNotFoundException {
3300 s.defaultReadObject();
3301 this.segments = null; // unneeded
3302
3303 // Create all nodes, then place in table once size is known
3304 long size = 0L;
3305 Node<V> p = null;
3306 for (;;) {
3307 K k = (K) s.readObject();
3308 V v = (V) s.readObject();
3309 if (k != null && v != null) {
3310 int h = spread(k.hashCode());
3311 p = new Node<V>(h, k, v, p);
3312 ++size;
3313 }
3314 else
3315 break;
3316 }
3317 if (p != null) {
3318 boolean init = false;
3319 int n;
3320 if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3321 n = MAXIMUM_CAPACITY;
3322 else {
3323 int sz = (int)size;
3324 n = tableSizeFor(sz + (sz >>> 1) + 1);
3325 }
3326 int sc = sizeCtl;
3327 boolean collide = false;
3328 if (n > sc &&
3329 U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3330 try {
3331 if (table == null) {
3332 init = true;
3333 @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3334 Node<V>[] tab = (Node<V>[])rt;
3335 int mask = n - 1;
3336 while (p != null) {
3337 int j = p.hash & mask;
3338 Node<V> next = p.next;
3339 Node<V> q = p.next = tabAt(tab, j);
3340 setTabAt(tab, j, p);
3341 if (!collide && q != null && q.hash == p.hash)
3342 collide = true;
3343 p = next;
3344 }
3345 table = tab;
3346 addCount(size, -1);
3347 sc = n - (n >>> 2);
3348 }
3349 } finally {
3350 sizeCtl = sc;
3351 }
3352 if (collide) { // rescan and convert to TreeBins
3353 Node<V>[] tab = table;
3354 for (int i = 0; i < tab.length; ++i) {
3355 int c = 0;
3356 for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3357 if (++c > TREE_THRESHOLD &&
3358 (e.key instanceof Comparable)) {
3359 replaceWithTreeBin(tab, i, e.key);
3360 break;
3361 }
3362 }
3363 }
3364 }
3365 }
3366 if (!init) { // Can only happen if unsafely published.
3367 while (p != null) {
3368 internalPut((K)p.key, p.val, false);
3369 p = p.next;
3370 }
3371 }
3372 }
3373 }
3374
3375 // -------------------------------------------------------
3376
3377 // Sequential bulk operations
3378
3379 /**
3380 * Performs the given action for each (key, value).
3381 *
3382 * @param action the action
3383 */
3384 public void forEachSequentially
3385 (BiConsumer<? super K, ? super V> action) {
3386 if (action == null) throw new NullPointerException();
3387 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3388 V v;
3389 while ((v = it.advanceValue()) != null)
3390 action.accept(it.nextKey, v);
3391 }
3392
3393 /**
3394 * Performs the given action for each non-null transformation
3395 * of each (key, value).
3396 *
3397 * @param transformer a function returning the transformation
3398 * for an element, or null if there is no transformation (in
3399 * which case the action is not applied)
3400 * @param action the action
3401 */
3402 public <U> void forEachSequentially
3403 (BiFunction<? super K, ? super V, ? extends U> transformer,
3404 Consumer<? super U> action) {
3405 if (transformer == null || action == null)
3406 throw new NullPointerException();
3407 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3408 V v; U u;
3409 while ((v = it.advanceValue()) != null) {
3410 if ((u = transformer.apply(it.nextKey, v)) != null)
3411 action.accept(u);
3412 }
3413 }
3414
3415 /**
3416 * Returns a non-null result from applying the given search
3417 * function on each (key, value), or null if none.
3418 *
3419 * @param searchFunction a function returning a non-null
3420 * result on success, else null
3421 * @return a non-null result from applying the given search
3422 * function on each (key, value), or null if none
3423 */
3424 public <U> U searchSequentially
3425 (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3426 if (searchFunction == null) throw new NullPointerException();
3427 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3428 V v; U u;
3429 while ((v = it.advanceValue()) != null) {
3430 if ((u = searchFunction.apply(it.nextKey, v)) != null)
3431 return u;
3432 }
3433 return null;
3434 }
3435
3436 /**
3437 * Returns the result of accumulating the given transformation
3438 * of all (key, value) pairs using the given reducer to
3439 * combine values, or null if none.
3440 *
3441 * @param transformer a function returning the transformation
3442 * for an element, or null if there is no transformation (in
3443 * which case it is not combined)
3444 * @param reducer a commutative associative combining function
3445 * @return the result of accumulating the given transformation
3446 * of all (key, value) pairs
3447 */
3448 public <U> U reduceSequentially
3449 (BiFunction<? super K, ? super V, ? extends U> transformer,
3450 BiFunction<? super U, ? super U, ? extends U> reducer) {
3451 if (transformer == null || reducer == null)
3452 throw new NullPointerException();
3453 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3454 U r = null, u; V v;
3455 while ((v = it.advanceValue()) != null) {
3456 if ((u = transformer.apply(it.nextKey, v)) != null)
3457 r = (r == null) ? u : reducer.apply(r, u);
3458 }
3459 return r;
3460 }
3461
3462 /**
3463 * Returns the result of accumulating the given transformation
3464 * of all (key, value) pairs using the given reducer to
3465 * combine values, and the given basis as an identity value.
3466 *
3467 * @param transformer a function returning the transformation
3468 * for an element
3469 * @param basis the identity (initial default value) for the reduction
3470 * @param reducer a commutative associative combining function
3471 * @return the result of accumulating the given transformation
3472 * of all (key, value) pairs
3473 */
3474 public double reduceToDoubleSequentially
3475 (ToDoubleBiFunction<? super K, ? super V> transformer,
3476 double basis,
3477 DoubleBinaryOperator reducer) {
3478 if (transformer == null || reducer == null)
3479 throw new NullPointerException();
3480 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3481 double r = basis; V v;
3482 while ((v = it.advanceValue()) != null)
3483 r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3484 return r;
3485 }
3486
3487 /**
3488 * Returns the result of accumulating the given transformation
3489 * of all (key, value) pairs using the given reducer to
3490 * combine values, and the given basis as an identity value.
3491 *
3492 * @param transformer a function returning the transformation
3493 * for an element
3494 * @param basis the identity (initial default value) for the reduction
3495 * @param reducer a commutative associative combining function
3496 * @return the result of accumulating the given transformation
3497 * of all (key, value) pairs
3498 */
3499 public long reduceToLongSequentially
3500 (ToLongBiFunction<? super K, ? super V> transformer,
3501 long basis,
3502 LongBinaryOperator reducer) {
3503 if (transformer == null || reducer == null)
3504 throw new NullPointerException();
3505 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3506 long r = basis; V v;
3507 while ((v = it.advanceValue()) != null)
3508 r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3509 return r;
3510 }
3511
3512 /**
3513 * Returns the result of accumulating the given transformation
3514 * of all (key, value) pairs using the given reducer to
3515 * combine values, and the given basis as an identity value.
3516 *
3517 * @param transformer a function returning the transformation
3518 * for an element
3519 * @param basis the identity (initial default value) for the reduction
3520 * @param reducer a commutative associative combining function
3521 * @return the result of accumulating the given transformation
3522 * of all (key, value) pairs
3523 */
3524 public int reduceToIntSequentially
3525 (ToIntBiFunction<? super K, ? super V> transformer,
3526 int basis,
3527 IntBinaryOperator reducer) {
3528 if (transformer == null || reducer == null)
3529 throw new NullPointerException();
3530 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3531 int r = basis; V v;
3532 while ((v = it.advanceValue()) != null)
3533 r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3534 return r;
3535 }
3536
3537 /**
3538 * Performs the given action for each key.
3539 *
3540 * @param action the action
3541 */
3542 public void forEachKeySequentially
3543 (Consumer<? super K> action) {
3544 new Traverser<K,V,Object>(this).forEachKey(action);
3545 }
3546
3547 /**
3548 * Performs the given action for each non-null transformation
3549 * of each key.
3550 *
3551 * @param transformer a function returning the transformation
3552 * for an element, or null if there is no transformation (in
3553 * which case the action is not applied)
3554 * @param action the action
3555 */
3556 public <U> void forEachKeySequentially
3557 (Function<? super K, ? extends U> transformer,
3558 Consumer<? super U> action) {
3559 if (transformer == null || action == null)
3560 throw new NullPointerException();
3561 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3562 K k; U u;
3563 while ((k = it.advanceKey()) != null) {
3564 if ((u = transformer.apply(k)) != null)
3565 action.accept(u);
3566 }
3567 ForkJoinTasks.forEachKey
3568 (this, transformer, action).invoke();
3569 }
3570
3571 /**
3572 * Returns a non-null result from applying the given search
3573 * function on each key, or null if none.
3574 *
3575 * @param searchFunction a function returning a non-null
3576 * result on success, else null
3577 * @return a non-null result from applying the given search
3578 * function on each key, or null if none
3579 */
3580 public <U> U searchKeysSequentially
3581 (Function<? super K, ? extends U> searchFunction) {
3582 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3583 K k; U u;
3584 while ((k = it.advanceKey()) != null) {
3585 if ((u = searchFunction.apply(k)) != null)
3586 return u;
3587 }
3588 return null;
3589 }
3590
3591 /**
3592 * Returns the result of accumulating all keys using the given
3593 * reducer to combine values, or null if none.
3594 *
3595 * @param reducer a commutative associative combining function
3596 * @return the result of accumulating all keys using the given
3597 * reducer to combine values, or null if none
3598 */
3599 public K reduceKeysSequentially
3600 (BiFunction<? super K, ? super K, ? extends K> reducer) {
3601 if (reducer == null) throw new NullPointerException();
3602 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3603 K u, r = null;
3604 while ((u = it.advanceKey()) != null) {
3605 r = (r == null) ? u : reducer.apply(r, u);
3606 }
3607 return r;
3608 }
3609
3610 /**
3611 * Returns the result of accumulating the given transformation
3612 * of all keys using the given reducer to combine values, or
3613 * null if none.
3614 *
3615 * @param transformer a function returning the transformation
3616 * for an element, or null if there is no transformation (in
3617 * which case it is not combined)
3618 * @param reducer a commutative associative combining function
3619 * @return the result of accumulating the given transformation
3620 * of all keys
3621 */
3622 public <U> U reduceKeysSequentially
3623 (Function<? super K, ? extends U> transformer,
3624 BiFunction<? super U, ? super U, ? extends U> reducer) {
3625 if (transformer == null || reducer == null)
3626 throw new NullPointerException();
3627 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3628 K k; U r = null, u;
3629 while ((k = it.advanceKey()) != null) {
3630 if ((u = transformer.apply(k)) != null)
3631 r = (r == null) ? u : reducer.apply(r, u);
3632 }
3633 return r;
3634 }
3635
3636 /**
3637 * Returns the result of accumulating the given transformation
3638 * of all keys using the given reducer to combine values, and
3639 * the given basis as an identity value.
3640 *
3641 * @param transformer a function returning the transformation
3642 * for an element
3643 * @param basis the identity (initial default value) for the reduction
3644 * @param reducer a commutative associative combining function
3645 * @return the result of accumulating the given transformation
3646 * of all keys
3647 */
3648 public double reduceKeysToDoubleSequentially
3649 (ToDoubleFunction<? super K> transformer,
3650 double basis,
3651 DoubleBinaryOperator reducer) {
3652 if (transformer == null || reducer == null)
3653 throw new NullPointerException();
3654 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3655 double r = basis;
3656 K k;
3657 while ((k = it.advanceKey()) != null)
3658 r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
3659 return r;
3660 }
3661
3662 /**
3663 * Returns the result of accumulating the given transformation
3664 * of all keys using the given reducer to combine values, and
3665 * the given basis as an identity value.
3666 *
3667 * @param transformer a function returning the transformation
3668 * for an element
3669 * @param basis the identity (initial default value) for the reduction
3670 * @param reducer a commutative associative combining function
3671 * @return the result of accumulating the given transformation
3672 * of all keys
3673 */
3674 public long reduceKeysToLongSequentially
3675 (ToLongFunction<? super K> transformer,
3676 long basis,
3677 LongBinaryOperator reducer) {
3678 if (transformer == null || reducer == null)
3679 throw new NullPointerException();
3680 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3681 long r = basis;
3682 K k;
3683 while ((k = it.advanceKey()) != null)
3684 r = reducer.applyAsLong(r, transformer.applyAsLong(k));
3685 return r;
3686 }
3687
3688 /**
3689 * Returns the result of accumulating the given transformation
3690 * of all keys using the given reducer to combine values, and
3691 * the given basis as an identity value.
3692 *
3693 * @param transformer a function returning the transformation
3694 * for an element
3695 * @param basis the identity (initial default value) for the reduction
3696 * @param reducer a commutative associative combining function
3697 * @return the result of accumulating the given transformation
3698 * of all keys
3699 */
3700 public int reduceKeysToIntSequentially
3701 (ToIntFunction<? super K> transformer,
3702 int basis,
3703 IntBinaryOperator reducer) {
3704 if (transformer == null || reducer == null)
3705 throw new NullPointerException();
3706 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3707 int r = basis;
3708 K k;
3709 while ((k = it.advanceKey()) != null)
3710 r = reducer.applyAsInt(r, transformer.applyAsInt(k));
3711 return r;
3712 }
3713
3714 /**
3715 * Performs the given action for each value.
3716 *
3717 * @param action the action
3718 */
3719 public void forEachValueSequentially(Consumer<? super V> action) {
3720 new Traverser<K,V,Object>(this).forEachValue(action);
3721 }
3722
3723 /**
3724 * Performs the given action for each non-null transformation
3725 * of each value.
3726 *
3727 * @param transformer a function returning the transformation
3728 * for an element, or null if there is no transformation (in
3729 * which case the action is not applied)
3730 * @param action the action
3731 */
3732 public <U> void forEachValueSequentially
3733 (Function<? super V, ? extends U> transformer,
3734 Consumer<? super U> action) {
3735 if (transformer == null || action == null)
3736 throw new NullPointerException();
3737 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3738 V v; U u;
3739 while ((v = it.advanceValue()) != null) {
3740 if ((u = transformer.apply(v)) != null)
3741 action.accept(u);
3742 }
3743 }
3744
3745 /**
3746 * Returns a non-null result from applying the given search
3747 * function on each value, or null if none.
3748 *
3749 * @param searchFunction a function returning a non-null
3750 * result on success, else null
3751 * @return a non-null result from applying the given search
3752 * function on each value, or null if none
3753 */
3754 public <U> U searchValuesSequentially
3755 (Function<? super V, ? extends U> searchFunction) {
3756 if (searchFunction == null) throw new NullPointerException();
3757 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3758 V v; U u;
3759 while ((v = it.advanceValue()) != null) {
3760 if ((u = searchFunction.apply(v)) != null)
3761 return u;
3762 }
3763 return null;
3764 }
3765
3766 /**
3767 * Returns the result of accumulating all values using the
3768 * given reducer to combine values, or null if none.
3769 *
3770 * @param reducer a commutative associative combining function
3771 * @return the result of accumulating all values
3772 */
3773 public V reduceValuesSequentially
3774 (BiFunction<? super V, ? super V, ? extends V> reducer) {
3775 if (reducer == null) throw new NullPointerException();
3776 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3777 V r = null; V v;
3778 while ((v = it.advanceValue()) != null)
3779 r = (r == null) ? v : reducer.apply(r, v);
3780 return r;
3781 }
3782
3783 /**
3784 * Returns the result of accumulating the given transformation
3785 * of all values using the given reducer to combine values, or
3786 * null if none.
3787 *
3788 * @param transformer a function returning the transformation
3789 * for an element, or null if there is no transformation (in
3790 * which case it is not combined)
3791 * @param reducer a commutative associative combining function
3792 * @return the result of accumulating the given transformation
3793 * of all values
3794 */
3795 public <U> U reduceValuesSequentially
3796 (Function<? super V, ? extends U> transformer,
3797 BiFunction<? super U, ? super U, ? extends U> reducer) {
3798 if (transformer == null || reducer == null)
3799 throw new NullPointerException();
3800 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3801 U r = null, u; V v;
3802 while ((v = it.advanceValue()) != null) {
3803 if ((u = transformer.apply(v)) != null)
3804 r = (r == null) ? u : reducer.apply(r, u);
3805 }
3806 return r;
3807 }
3808
3809 /**
3810 * Returns the result of accumulating the given transformation
3811 * of all values using the given reducer to combine values,
3812 * and the given basis as an identity value.
3813 *
3814 * @param transformer a function returning the transformation
3815 * for an element
3816 * @param basis the identity (initial default value) for the reduction
3817 * @param reducer a commutative associative combining function
3818 * @return the result of accumulating the given transformation
3819 * of all values
3820 */
3821 public double reduceValuesToDoubleSequentially
3822 (ToDoubleFunction<? super V> transformer,
3823 double basis,
3824 DoubleBinaryOperator reducer) {
3825 if (transformer == null || reducer == null)
3826 throw new NullPointerException();
3827 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3828 double r = basis; V v;
3829 while ((v = it.advanceValue()) != null)
3830 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3831 return r;
3832 }
3833
3834 /**
3835 * Returns the result of accumulating the given transformation
3836 * of all values using the given reducer to combine values,
3837 * and the given basis as an identity value.
3838 *
3839 * @param transformer a function returning the transformation
3840 * for an element
3841 * @param basis the identity (initial default value) for the reduction
3842 * @param reducer a commutative associative combining function
3843 * @return the result of accumulating the given transformation
3844 * of all values
3845 */
3846 public long reduceValuesToLongSequentially
3847 (ToLongFunction<? super V> transformer,
3848 long basis,
3849 LongBinaryOperator reducer) {
3850 if (transformer == null || reducer == null)
3851 throw new NullPointerException();
3852 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3853 long r = basis; V v;
3854 while ((v = it.advanceValue()) != null)
3855 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3856 return r;
3857 }
3858
3859 /**
3860 * Returns the result of accumulating the given transformation
3861 * of all values using the given reducer to combine values,
3862 * and the given basis as an identity value.
3863 *
3864 * @param transformer a function returning the transformation
3865 * for an element
3866 * @param basis the identity (initial default value) for the reduction
3867 * @param reducer a commutative associative combining function
3868 * @return the result of accumulating the given transformation
3869 * of all values
3870 */
3871 public int reduceValuesToIntSequentially
3872 (ToIntFunction<? super V> transformer,
3873 int basis,
3874 IntBinaryOperator reducer) {
3875 if (transformer == null || reducer == null)
3876 throw new NullPointerException();
3877 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3878 int r = basis; V v;
3879 while ((v = it.advanceValue()) != null)
3880 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3881 return r;
3882 }
3883
3884 /**
3885 * Performs the given action for each entry.
3886 *
3887 * @param action the action
3888 */
3889 public void forEachEntrySequentially
3890 (Consumer<? super Map.Entry<K,V>> action) {
3891 if (action == null) throw new NullPointerException();
3892 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3893 V v;
3894 while ((v = it.advanceValue()) != null)
3895 action.accept(entryFor(it.nextKey, v));
3896 }
3897
3898 /**
3899 * Performs the given action for each non-null transformation
3900 * of each entry.
3901 *
3902 * @param transformer a function returning the transformation
3903 * for an element, or null if there is no transformation (in
3904 * which case the action is not applied)
3905 * @param action the action
3906 */
3907 public <U> void forEachEntrySequentially
3908 (Function<Map.Entry<K,V>, ? extends U> transformer,
3909 Consumer<? super U> action) {
3910 if (transformer == null || action == null)
3911 throw new NullPointerException();
3912 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3913 V v; U u;
3914 while ((v = it.advanceValue()) != null) {
3915 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3916 action.accept(u);
3917 }
3918 }
3919
3920 /**
3921 * Returns a non-null result from applying the given search
3922 * function on each entry, or null if none.
3923 *
3924 * @param searchFunction a function returning a non-null
3925 * result on success, else null
3926 * @return a non-null result from applying the given search
3927 * function on each entry, or null if none
3928 */
3929 public <U> U searchEntriesSequentially
3930 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3931 if (searchFunction == null) throw new NullPointerException();
3932 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3933 V v; U u;
3934 while ((v = it.advanceValue()) != null) {
3935 if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3936 return u;
3937 }
3938 return null;
3939 }
3940
3941 /**
3942 * Returns the result of accumulating all entries using the
3943 * given reducer to combine values, or null if none.
3944 *
3945 * @param reducer a commutative associative combining function
3946 * @return the result of accumulating all entries
3947 */
3948 public Map.Entry<K,V> reduceEntriesSequentially
3949 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3950 if (reducer == null) throw new NullPointerException();
3951 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3952 Map.Entry<K,V> r = null; V v;
3953 while ((v = it.advanceValue()) != null) {
3954 Map.Entry<K,V> u = entryFor(it.nextKey, v);
3955 r = (r == null) ? u : reducer.apply(r, u);
3956 }
3957 return r;
3958 }
3959
3960 /**
3961 * Returns the result of accumulating the given transformation
3962 * of all entries using the given reducer to combine values,
3963 * or null if none.
3964 *
3965 * @param transformer a function returning the transformation
3966 * for an element, or null if there is no transformation (in
3967 * which case it is not combined)
3968 * @param reducer a commutative associative combining function
3969 * @return the result of accumulating the given transformation
3970 * of all entries
3971 */
3972 public <U> U reduceEntriesSequentially
3973 (Function<Map.Entry<K,V>, ? extends U> transformer,
3974 BiFunction<? super U, ? super U, ? extends U> reducer) {
3975 if (transformer == null || reducer == null)
3976 throw new NullPointerException();
3977 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3978 U r = null, u; V v;
3979 while ((v = it.advanceValue()) != null) {
3980 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3981 r = (r == null) ? u : reducer.apply(r, u);
3982 }
3983 return r;
3984 }
3985
3986 /**
3987 * Returns the result of accumulating the given transformation
3988 * of all entries using the given reducer to combine values,
3989 * 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 entries
3997 */
3998 public double reduceEntriesToDoubleSequentially
3999 (ToDoubleFunction<Map.Entry<K,V>> transformer,
4000 double basis,
4001 DoubleBinaryOperator reducer) {
4002 if (transformer == null || reducer == null)
4003 throw new NullPointerException();
4004 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4005 double r = basis; V v;
4006 while ((v = it.advanceValue()) != null)
4007 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
4008 return r;
4009 }
4010
4011 /**
4012 * Returns the result of accumulating the given transformation
4013 * of all entries using the given reducer to combine values,
4014 * and the given basis as an identity value.
4015 *
4016 * @param transformer a function returning the transformation
4017 * for an element
4018 * @param basis the identity (initial default value) for the reduction
4019 * @param reducer a commutative associative combining function
4020 * @return the result of accumulating the given transformation
4021 * of all entries
4022 */
4023 public long reduceEntriesToLongSequentially
4024 (ToLongFunction<Map.Entry<K,V>> transformer,
4025 long basis,
4026 LongBinaryOperator reducer) {
4027 if (transformer == null || reducer == null)
4028 throw new NullPointerException();
4029 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4030 long r = basis; V v;
4031 while ((v = it.advanceValue()) != null)
4032 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
4033 return r;
4034 }
4035
4036 /**
4037 * Returns the result of accumulating the given transformation
4038 * of all entries using the given reducer to combine values,
4039 * and the given basis as an identity value.
4040 *
4041 * @param transformer a function returning the transformation
4042 * for an element
4043 * @param basis the identity (initial default value) for the reduction
4044 * @param reducer a commutative associative combining function
4045 * @return the result of accumulating the given transformation
4046 * of all entries
4047 */
4048 public int reduceEntriesToIntSequentially
4049 (ToIntFunction<Map.Entry<K,V>> transformer,
4050 int basis,
4051 IntBinaryOperator reducer) {
4052 if (transformer == null || reducer == null)
4053 throw new NullPointerException();
4054 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4055 int r = basis; V v;
4056 while ((v = it.advanceValue()) != null)
4057 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
4058 return r;
4059 }
4060
4061 // Parallel bulk operations
4062
4063 /**
4064 * Performs the given action for each (key, value).
4065 *
4066 * @param action the action
4067 */
4068 public void forEachInParallel(BiConsumer<? super K,? super V> action) {
4069 ForkJoinTasks.forEach
4070 (this, action).invoke();
4071 }
4072
4073 /**
4074 * Performs the given action for each non-null transformation
4075 * of each (key, value).
4076 *
4077 * @param transformer a function returning the transformation
4078 * for an element, or null if there is no transformation (in
4079 * which case the action is not applied)
4080 * @param action the action
4081 */
4082 public <U> void forEachInParallel
4083 (BiFunction<? super K, ? super V, ? extends U> transformer,
4084 Consumer<? super U> action) {
4085 ForkJoinTasks.forEach
4086 (this, transformer, action).invoke();
4087 }
4088
4089 /**
4090 * Returns a non-null result from applying the given search
4091 * function on each (key, value), or null if none. Upon
4092 * success, further element processing is suppressed and the
4093 * results of any other parallel invocations of the search
4094 * function are ignored.
4095 *
4096 * @param searchFunction a function returning a non-null
4097 * result on success, else null
4098 * @return a non-null result from applying the given search
4099 * function on each (key, value), or null if none
4100 */
4101 public <U> U searchInParallel
4102 (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4103 return ForkJoinTasks.search
4104 (this, searchFunction).invoke();
4105 }
4106
4107 /**
4108 * Returns the result of accumulating the given transformation
4109 * of all (key, value) pairs using the given reducer to
4110 * combine values, or null if none.
4111 *
4112 * @param transformer a function returning the transformation
4113 * for an element, or null if there is no transformation (in
4114 * which case it is not combined)
4115 * @param reducer a commutative associative combining function
4116 * @return the result of accumulating the given transformation
4117 * of all (key, value) pairs
4118 */
4119 public <U> U reduceInParallel
4120 (BiFunction<? super K, ? super V, ? extends U> transformer,
4121 BiFunction<? super U, ? super U, ? extends U> reducer) {
4122 return ForkJoinTasks.reduce
4123 (this, transformer, reducer).invoke();
4124 }
4125
4126 /**
4127 * Returns the result of accumulating the given transformation
4128 * of all (key, value) pairs using the given reducer to
4129 * combine values, and the given basis as an identity value.
4130 *
4131 * @param transformer a function returning the transformation
4132 * for an element
4133 * @param basis the identity (initial default value) for the reduction
4134 * @param reducer a commutative associative combining function
4135 * @return the result of accumulating the given transformation
4136 * of all (key, value) pairs
4137 */
4138 public double reduceToDoubleInParallel
4139 (ToDoubleBiFunction<? super K, ? super V> transformer,
4140 double basis,
4141 DoubleBinaryOperator reducer) {
4142 return ForkJoinTasks.reduceToDouble
4143 (this, transformer, basis, reducer).invoke();
4144 }
4145
4146 /**
4147 * Returns the result of accumulating the given transformation
4148 * of all (key, value) pairs using the given reducer to
4149 * combine values, and the given basis as an identity value.
4150 *
4151 * @param transformer a function returning the transformation
4152 * for an element
4153 * @param basis the identity (initial default value) for the reduction
4154 * @param reducer a commutative associative combining function
4155 * @return the result of accumulating the given transformation
4156 * of all (key, value) pairs
4157 */
4158 public long reduceToLongInParallel
4159 (ToLongBiFunction<? super K, ? super V> transformer,
4160 long basis,
4161 LongBinaryOperator reducer) {
4162 return ForkJoinTasks.reduceToLong
4163 (this, transformer, basis, reducer).invoke();
4164 }
4165
4166 /**
4167 * Returns the result of accumulating the given transformation
4168 * of all (key, value) pairs using the given reducer to
4169 * combine values, and the given basis as an identity value.
4170 *
4171 * @param transformer a function returning the transformation
4172 * for an element
4173 * @param basis the identity (initial default value) for the reduction
4174 * @param reducer a commutative associative combining function
4175 * @return the result of accumulating the given transformation
4176 * of all (key, value) pairs
4177 */
4178 public int reduceToIntInParallel
4179 (ToIntBiFunction<? super K, ? super V> transformer,
4180 int basis,
4181 IntBinaryOperator reducer) {
4182 return ForkJoinTasks.reduceToInt
4183 (this, transformer, basis, reducer).invoke();
4184 }
4185
4186 /**
4187 * Performs the given action for each key.
4188 *
4189 * @param action the action
4190 */
4191 public void forEachKeyInParallel(Consumer<? super K> action) {
4192 ForkJoinTasks.forEachKey
4193 (this, action).invoke();
4194 }
4195
4196 /**
4197 * Performs the given action for each non-null transformation
4198 * of each key.
4199 *
4200 * @param transformer a function returning the transformation
4201 * for an element, or null if there is no transformation (in
4202 * which case the action is not applied)
4203 * @param action the action
4204 */
4205 public <U> void forEachKeyInParallel
4206 (Function<? super K, ? extends U> transformer,
4207 Consumer<? super U> action) {
4208 ForkJoinTasks.forEachKey
4209 (this, transformer, action).invoke();
4210 }
4211
4212 /**
4213 * Returns a non-null result from applying the given search
4214 * function on each key, or null if none. Upon success,
4215 * further element processing is suppressed and the results of
4216 * any other parallel invocations of the search function are
4217 * ignored.
4218 *
4219 * @param searchFunction a function returning a non-null
4220 * result on success, else null
4221 * @return a non-null result from applying the given search
4222 * function on each key, or null if none
4223 */
4224 public <U> U searchKeysInParallel
4225 (Function<? super K, ? extends U> searchFunction) {
4226 return ForkJoinTasks.searchKeys
4227 (this, searchFunction).invoke();
4228 }
4229
4230 /**
4231 * Returns the result of accumulating all keys using the given
4232 * reducer to combine values, or null if none.
4233 *
4234 * @param reducer a commutative associative combining function
4235 * @return the result of accumulating all keys using the given
4236 * reducer to combine values, or null if none
4237 */
4238 public K reduceKeysInParallel
4239 (BiFunction<? super K, ? super K, ? extends K> reducer) {
4240 return ForkJoinTasks.reduceKeys
4241 (this, reducer).invoke();
4242 }
4243
4244 /**
4245 * Returns the result of accumulating the given transformation
4246 * of all keys using the given reducer to combine values, or
4247 * null if none.
4248 *
4249 * @param transformer a function returning the transformation
4250 * for an element, or null if there is no transformation (in
4251 * which case it is not combined)
4252 * @param reducer a commutative associative combining function
4253 * @return the result of accumulating the given transformation
4254 * of all keys
4255 */
4256 public <U> U reduceKeysInParallel
4257 (Function<? super K, ? extends U> transformer,
4258 BiFunction<? super U, ? super U, ? extends U> reducer) {
4259 return ForkJoinTasks.reduceKeys
4260 (this, transformer, reducer).invoke();
4261 }
4262
4263 /**
4264 * Returns the result of accumulating the given transformation
4265 * of all keys using the given reducer to combine values, and
4266 * the given basis as an identity value.
4267 *
4268 * @param transformer a function returning the transformation
4269 * for an element
4270 * @param basis the identity (initial default value) for the reduction
4271 * @param reducer a commutative associative combining function
4272 * @return the result of accumulating the given transformation
4273 * of all keys
4274 */
4275 public double reduceKeysToDoubleInParallel
4276 (ToDoubleFunction<? super K> transformer,
4277 double basis,
4278 DoubleBinaryOperator reducer) {
4279 return ForkJoinTasks.reduceKeysToDouble
4280 (this, transformer, basis, reducer).invoke();
4281 }
4282
4283 /**
4284 * Returns the result of accumulating the given transformation
4285 * of all keys using the given reducer to combine values, and
4286 * the given basis as an identity value.
4287 *
4288 * @param transformer a function returning the transformation
4289 * for an element
4290 * @param basis the identity (initial default value) for the reduction
4291 * @param reducer a commutative associative combining function
4292 * @return the result of accumulating the given transformation
4293 * of all keys
4294 */
4295 public long reduceKeysToLongInParallel
4296 (ToLongFunction<? super K> transformer,
4297 long basis,
4298 LongBinaryOperator reducer) {
4299 return ForkJoinTasks.reduceKeysToLong
4300 (this, transformer, basis, reducer).invoke();
4301 }
4302
4303 /**
4304 * Returns the result of accumulating the given transformation
4305 * of all keys using the given reducer to combine values, and
4306 * the given basis as an identity value.
4307 *
4308 * @param transformer a function returning the transformation
4309 * for an element
4310 * @param basis the identity (initial default value) for the reduction
4311 * @param reducer a commutative associative combining function
4312 * @return the result of accumulating the given transformation
4313 * of all keys
4314 */
4315 public int reduceKeysToIntInParallel
4316 (ToIntFunction<? super K> transformer,
4317 int basis,
4318 IntBinaryOperator reducer) {
4319 return ForkJoinTasks.reduceKeysToInt
4320 (this, transformer, basis, reducer).invoke();
4321 }
4322
4323 /**
4324 * Performs the given action for each value.
4325 *
4326 * @param action the action
4327 */
4328 public void forEachValueInParallel(Consumer<? super V> action) {
4329 ForkJoinTasks.forEachValue
4330 (this, action).invoke();
4331 }
4332
4333 /**
4334 * Performs the given action for each non-null transformation
4335 * of each value.
4336 *
4337 * @param transformer a function returning the transformation
4338 * for an element, or null if there is no transformation (in
4339 * which case the action is not applied)
4340 * @param action the action
4341 */
4342 public <U> void forEachValueInParallel
4343 (Function<? super V, ? extends U> transformer,
4344 Consumer<? super U> action) {
4345 ForkJoinTasks.forEachValue
4346 (this, transformer, action).invoke();
4347 }
4348
4349 /**
4350 * Returns a non-null result from applying the given search
4351 * function on each value, or null if none. Upon success,
4352 * further element processing is suppressed and the results of
4353 * any other parallel invocations of the search function are
4354 * ignored.
4355 *
4356 * @param searchFunction a function returning a non-null
4357 * result on success, else null
4358 * @return a non-null result from applying the given search
4359 * function on each value, or null if none
4360 */
4361 public <U> U searchValuesInParallel
4362 (Function<? super V, ? extends U> searchFunction) {
4363 return ForkJoinTasks.searchValues
4364 (this, searchFunction).invoke();
4365 }
4366
4367 /**
4368 * Returns the result of accumulating all values using the
4369 * given reducer to combine values, or null if none.
4370 *
4371 * @param reducer a commutative associative combining function
4372 * @return the result of accumulating all values
4373 */
4374 public V reduceValuesInParallel
4375 (BiFunction<? super V, ? super V, ? extends V> reducer) {
4376 return ForkJoinTasks.reduceValues
4377 (this, reducer).invoke();
4378 }
4379
4380 /**
4381 * Returns the result of accumulating the given transformation
4382 * of all values using the given reducer to combine values, or
4383 * null if none.
4384 *
4385 * @param transformer a function returning the transformation
4386 * for an element, or null if there is no transformation (in
4387 * which case it is not combined)
4388 * @param reducer a commutative associative combining function
4389 * @return the result of accumulating the given transformation
4390 * of all values
4391 */
4392 public <U> U reduceValuesInParallel
4393 (Function<? super V, ? extends U> transformer,
4394 BiFunction<? super U, ? super U, ? extends U> reducer) {
4395 return ForkJoinTasks.reduceValues
4396 (this, transformer, reducer).invoke();
4397 }
4398
4399 /**
4400 * Returns the result of accumulating the given transformation
4401 * of all values using the given reducer to combine values,
4402 * and the given basis as an identity value.
4403 *
4404 * @param transformer a function returning the transformation
4405 * for an element
4406 * @param basis the identity (initial default value) for the reduction
4407 * @param reducer a commutative associative combining function
4408 * @return the result of accumulating the given transformation
4409 * of all values
4410 */
4411 public double reduceValuesToDoubleInParallel
4412 (ToDoubleFunction<? super V> transformer,
4413 double basis,
4414 DoubleBinaryOperator reducer) {
4415 return ForkJoinTasks.reduceValuesToDouble
4416 (this, transformer, basis, reducer).invoke();
4417 }
4418
4419 /**
4420 * Returns the result of accumulating the given transformation
4421 * of all values using the given reducer to combine values,
4422 * and the given basis as an identity value.
4423 *
4424 * @param transformer a function returning the transformation
4425 * for an element
4426 * @param basis the identity (initial default value) for the reduction
4427 * @param reducer a commutative associative combining function
4428 * @return the result of accumulating the given transformation
4429 * of all values
4430 */
4431 public long reduceValuesToLongInParallel
4432 (ToLongFunction<? super V> transformer,
4433 long basis,
4434 LongBinaryOperator reducer) {
4435 return ForkJoinTasks.reduceValuesToLong
4436 (this, transformer, basis, reducer).invoke();
4437 }
4438
4439 /**
4440 * Returns the result of accumulating the given transformation
4441 * of all values using the given reducer to combine values,
4442 * and the given basis as an identity value.
4443 *
4444 * @param transformer a function returning the transformation
4445 * for an element
4446 * @param basis the identity (initial default value) for the reduction
4447 * @param reducer a commutative associative combining function
4448 * @return the result of accumulating the given transformation
4449 * of all values
4450 */
4451 public int reduceValuesToIntInParallel
4452 (ToIntFunction<? super V> transformer,
4453 int basis,
4454 IntBinaryOperator reducer) {
4455 return ForkJoinTasks.reduceValuesToInt
4456 (this, transformer, basis, reducer).invoke();
4457 }
4458
4459 /**
4460 * Performs the given action for each entry.
4461 *
4462 * @param action the action
4463 */
4464 public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4465 ForkJoinTasks.forEachEntry
4466 (this, action).invoke();
4467 }
4468
4469 /**
4470 * Performs the given action for each non-null transformation
4471 * of each entry.
4472 *
4473 * @param transformer a function returning the transformation
4474 * for an element, or null if there is no transformation (in
4475 * which case the action is not applied)
4476 * @param action the action
4477 */
4478 public <U> void forEachEntryInParallel
4479 (Function<Map.Entry<K,V>, ? extends U> transformer,
4480 Consumer<? super U> action) {
4481 ForkJoinTasks.forEachEntry
4482 (this, transformer, action).invoke();
4483 }
4484
4485 /**
4486 * Returns a non-null result from applying the given search
4487 * function on each entry, or null if none. Upon success,
4488 * further element processing is suppressed and the results of
4489 * any other parallel invocations of the search function are
4490 * ignored.
4491 *
4492 * @param searchFunction a function returning a non-null
4493 * result on success, else null
4494 * @return a non-null result from applying the given search
4495 * function on each entry, or null if none
4496 */
4497 public <U> U searchEntriesInParallel
4498 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4499 return ForkJoinTasks.searchEntries
4500 (this, searchFunction).invoke();
4501 }
4502
4503 /**
4504 * Returns the result of accumulating all entries using the
4505 * given reducer to combine values, or null if none.
4506 *
4507 * @param reducer a commutative associative combining function
4508 * @return the result of accumulating all entries
4509 */
4510 public Map.Entry<K,V> reduceEntriesInParallel
4511 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4512 return ForkJoinTasks.reduceEntries
4513 (this, reducer).invoke();
4514 }
4515
4516 /**
4517 * Returns the result of accumulating the given transformation
4518 * of all entries using the given reducer to combine values,
4519 * or null if none.
4520 *
4521 * @param transformer a function returning the transformation
4522 * for an element, or null if there is no transformation (in
4523 * which case it is not combined)
4524 * @param reducer a commutative associative combining function
4525 * @return the result of accumulating the given transformation
4526 * of all entries
4527 */
4528 public <U> U reduceEntriesInParallel
4529 (Function<Map.Entry<K,V>, ? extends U> transformer,
4530 BiFunction<? super U, ? super U, ? extends U> reducer) {
4531 return ForkJoinTasks.reduceEntries
4532 (this, transformer, reducer).invoke();
4533 }
4534
4535 /**
4536 * Returns the result of accumulating the given transformation
4537 * of all entries using the given reducer to combine values,
4538 * and the given basis as an identity value.
4539 *
4540 * @param transformer a function returning the transformation
4541 * for an element
4542 * @param basis the identity (initial default value) for the reduction
4543 * @param reducer a commutative associative combining function
4544 * @return the result of accumulating the given transformation
4545 * of all entries
4546 */
4547 public double reduceEntriesToDoubleInParallel
4548 (ToDoubleFunction<Map.Entry<K,V>> transformer,
4549 double basis,
4550 DoubleBinaryOperator reducer) {
4551 return ForkJoinTasks.reduceEntriesToDouble
4552 (this, transformer, basis, reducer).invoke();
4553 }
4554
4555 /**
4556 * Returns the result of accumulating the given transformation
4557 * of all entries using the given reducer to combine values,
4558 * and the given basis as an identity value.
4559 *
4560 * @param transformer a function returning the transformation
4561 * for an element
4562 * @param basis the identity (initial default value) for the reduction
4563 * @param reducer a commutative associative combining function
4564 * @return the result of accumulating the given transformation
4565 * of all entries
4566 */
4567 public long reduceEntriesToLongInParallel
4568 (ToLongFunction<Map.Entry<K,V>> transformer,
4569 long basis,
4570 LongBinaryOperator reducer) {
4571 return ForkJoinTasks.reduceEntriesToLong
4572 (this, transformer, basis, reducer).invoke();
4573 }
4574
4575 /**
4576 * Returns the result of accumulating the given transformation
4577 * of all entries using the given reducer to combine values,
4578 * and the given basis as an identity value.
4579 *
4580 * @param transformer a function returning the transformation
4581 * for an element
4582 * @param basis the identity (initial default value) for the reduction
4583 * @param reducer a commutative associative combining function
4584 * @return the result of accumulating the given transformation
4585 * of all entries
4586 */
4587 public int reduceEntriesToIntInParallel
4588 (ToIntFunction<Map.Entry<K,V>> transformer,
4589 int basis,
4590 IntBinaryOperator reducer) {
4591 return ForkJoinTasks.reduceEntriesToInt
4592 (this, transformer, basis, reducer).invoke();
4593 }
4594
4595
4596 /* ----------------Views -------------- */
4597
4598 /**
4599 * Base class for views.
4600 */
4601 abstract static class CHMCollectionView<K,V,E>
4602 implements Collection<E>, java.io.Serializable {
4603 private static final long serialVersionUID = 7249069246763182397L;
4604 final ConcurrentHashMap<K,V> map;
4605 CHMCollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4606
4607 /**
4608 * Returns the map backing this view.
4609 *
4610 * @return the map backing this view
4611 */
4612 public ConcurrentHashMap<K,V> getMap() { return map; }
4613
4614 /**
4615 * Removes all of the elements from this view, by removing all
4616 * the mappings from the map backing this view.
4617 */
4618 public final void clear() { map.clear(); }
4619 public final int size() { return map.size(); }
4620 public final boolean isEmpty() { return map.isEmpty(); }
4621
4622 // implementations below rely on concrete classes supplying these
4623 // abstract methods
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 public abstract Iterator<E> iterator();
4633 public abstract boolean contains(Object o);
4634 public abstract boolean remove(Object o);
4635
4636 private static final String oomeMsg = "Required array size too large";
4637
4638 public final Object[] toArray() {
4639 long sz = map.mappingCount();
4640 if (sz > MAX_ARRAY_SIZE)
4641 throw new OutOfMemoryError(oomeMsg);
4642 int n = (int)sz;
4643 Object[] r = new Object[n];
4644 int i = 0;
4645 for (E e : this) {
4646 if (i == n) {
4647 if (n >= MAX_ARRAY_SIZE)
4648 throw new OutOfMemoryError(oomeMsg);
4649 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4650 n = MAX_ARRAY_SIZE;
4651 else
4652 n += (n >>> 1) + 1;
4653 r = Arrays.copyOf(r, n);
4654 }
4655 r[i++] = e;
4656 }
4657 return (i == n) ? r : Arrays.copyOf(r, i);
4658 }
4659
4660 @SuppressWarnings("unchecked")
4661 public final <T> T[] toArray(T[] a) {
4662 long sz = map.mappingCount();
4663 if (sz > MAX_ARRAY_SIZE)
4664 throw new OutOfMemoryError(oomeMsg);
4665 int m = (int)sz;
4666 T[] r = (a.length >= m) ? a :
4667 (T[])java.lang.reflect.Array
4668 .newInstance(a.getClass().getComponentType(), m);
4669 int n = r.length;
4670 int i = 0;
4671 for (E e : this) {
4672 if (i == n) {
4673 if (n >= MAX_ARRAY_SIZE)
4674 throw new OutOfMemoryError(oomeMsg);
4675 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4676 n = MAX_ARRAY_SIZE;
4677 else
4678 n += (n >>> 1) + 1;
4679 r = Arrays.copyOf(r, n);
4680 }
4681 r[i++] = (T)e;
4682 }
4683 if (a == r && i < n) {
4684 r[i] = null; // null-terminate
4685 return r;
4686 }
4687 return (i == n) ? r : Arrays.copyOf(r, i);
4688 }
4689
4690 /**
4691 * Returns a string representation of this collection.
4692 * The string representation consists of the string representations
4693 * of the collection's elements in the order they are returned by
4694 * its iterator, enclosed in square brackets ({@code "[]"}).
4695 * Adjacent elements are separated by the characters {@code ", "}
4696 * (comma and space). Elements are converted to strings as by
4697 * {@link String#valueOf(Object)}.
4698 *
4699 * @return a string representation of this collection
4700 */
4701 public final String toString() {
4702 StringBuilder sb = new StringBuilder();
4703 sb.append('[');
4704 Iterator<E> it = iterator();
4705 if (it.hasNext()) {
4706 for (;;) {
4707 Object e = it.next();
4708 sb.append(e == this ? "(this Collection)" : e);
4709 if (!it.hasNext())
4710 break;
4711 sb.append(',').append(' ');
4712 }
4713 }
4714 return sb.append(']').toString();
4715 }
4716
4717 public final boolean containsAll(Collection<?> c) {
4718 if (c != this) {
4719 for (Object e : c) {
4720 if (e == null || !contains(e))
4721 return false;
4722 }
4723 }
4724 return true;
4725 }
4726
4727 public final boolean removeAll(Collection<?> c) {
4728 boolean modified = false;
4729 for (Iterator<E> it = iterator(); it.hasNext();) {
4730 if (c.contains(it.next())) {
4731 it.remove();
4732 modified = true;
4733 }
4734 }
4735 return modified;
4736 }
4737
4738 public final boolean retainAll(Collection<?> c) {
4739 boolean modified = false;
4740 for (Iterator<E> it = iterator(); it.hasNext();) {
4741 if (!c.contains(it.next())) {
4742 it.remove();
4743 modified = true;
4744 }
4745 }
4746 return modified;
4747 }
4748
4749 }
4750
4751 abstract static class CHMSetView<K,V,E>
4752 extends CHMCollectionView<K,V,E>
4753 implements Set<E>, java.io.Serializable {
4754 private static final long serialVersionUID = 7249069246763182397L;
4755 CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4756
4757 // Implement Set API
4758
4759 /**
4760 * Implements {@link Set#hashCode()}.
4761 * @return the hash code value for this set
4762 */
4763 public final int hashCode() {
4764 int h = 0;
4765 for (E e : this)
4766 h += e.hashCode();
4767 return h;
4768 }
4769
4770 /**
4771 * Implements {@link Set#equals(Object)}.
4772 * @param o object to be compared for equality with this set
4773 * @return {@code true} if the specified object is equal to this set
4774 */
4775 public final boolean equals(Object o) {
4776 Set<?> c;
4777 return ((o instanceof Set) &&
4778 ((c = (Set<?>)o) == this ||
4779 (containsAll(c) && c.containsAll(this))));
4780 }
4781 }
4782
4783 /**
4784 * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4785 * which additions may optionally be enabled by mapping to a
4786 * common value. This class cannot be directly instantiated.
4787 * See {@link #keySet() keySet()},
4788 * {@link #keySet(Object) keySet(V)},
4789 * {@link #newKeySet() newKeySet()},
4790 * {@link #newKeySet(int) newKeySet(int)}.
4791 */
4792 public static class KeySetView<K,V>
4793 extends CHMSetView<K,V,K>
4794 implements Set<K>, java.io.Serializable {
4795 private static final long serialVersionUID = 7249069246763182397L;
4796 private final V value;
4797 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4798 super(map);
4799 this.value = value;
4800 }
4801
4802 /**
4803 * Returns the default mapped value for additions,
4804 * or {@code null} if additions are not supported.
4805 *
4806 * @return the default mapped value for additions, or {@code null}
4807 * if not supported
4808 */
4809 public V getMappedValue() { return value; }
4810
4811 /**
4812 * {@inheritDoc}
4813 * @throws NullPointerException if the specified key is null
4814 */
4815 public boolean contains(Object o) { return map.containsKey(o); }
4816
4817 /**
4818 * Removes the key from this map view, by removing the key (and its
4819 * corresponding value) from the backing map. This method does
4820 * nothing if the key is not in the map.
4821 *
4822 * @param o the key to be removed from the backing map
4823 * @return {@code true} if the backing map contained the specified key
4824 * @throws NullPointerException if the specified key is null
4825 */
4826 public boolean remove(Object o) { return map.remove(o) != null; }
4827
4828 /**
4829 * @return an iterator over the keys of the backing map
4830 */
4831 public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4832
4833 /**
4834 * Adds the specified key to this set view by mapping the key to
4835 * the default mapped value in the backing map, if defined.
4836 *
4837 * @param e key to be added
4838 * @return {@code true} if this set changed as a result of the call
4839 * @throws NullPointerException if the specified key is null
4840 * @throws UnsupportedOperationException if no default mapped value
4841 * for additions was provided
4842 */
4843 public boolean add(K e) {
4844 V v;
4845 if ((v = value) == null)
4846 throw new UnsupportedOperationException();
4847 return map.internalPut(e, v, true) == null;
4848 }
4849
4850 /**
4851 * Adds all of the elements in the specified collection to this set,
4852 * as if by calling {@link #add} on each one.
4853 *
4854 * @param c the elements to be inserted into this set
4855 * @return {@code true} if this set changed as a result of the call
4856 * @throws NullPointerException if the collection or any of its
4857 * elements are {@code null}
4858 * @throws UnsupportedOperationException if no default mapped value
4859 * for additions was provided
4860 */
4861 public boolean addAll(Collection<? extends K> c) {
4862 boolean added = false;
4863 V v;
4864 if ((v = value) == null)
4865 throw new UnsupportedOperationException();
4866 for (K e : c) {
4867 if (map.internalPut(e, v, true) == null)
4868 added = true;
4869 }
4870 return added;
4871 }
4872
4873 Spliterator<K> spliterator() {
4874 return new KeyIterator<>(map, null);
4875 }
4876
4877 public Stream<K> stream() {
4878 return Streams.stream(spliterator());
4879 }
4880 public Stream<K> parallelStream() {
4881 return Streams.parallelStream(spliterator());
4882 }
4883 }
4884
4885 /**
4886 * A view of a ConcurrentHashMap as a {@link Collection} of
4887 * values, in which additions are disabled. This class cannot be
4888 * directly instantiated. See {@link #values()}.
4889 *
4890 * <p>The view's {@code iterator} is a "weakly consistent" iterator
4891 * that will never throw {@link ConcurrentModificationException},
4892 * and guarantees to traverse elements as they existed upon
4893 * construction of the iterator, and may (but is not guaranteed to)
4894 * reflect any modifications subsequent to construction.
4895 */
4896 public static final class ValuesView<K,V>
4897 extends CHMCollectionView<K,V,V>
4898 implements Collection<V>, java.io.Serializable {
4899 private static final long serialVersionUID = 2249069246763182397L;
4900 ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4901 public final boolean contains(Object o) {
4902 return map.containsValue(o);
4903 }
4904 public final boolean remove(Object o) {
4905 if (o != null) {
4906 for (Iterator<V> it = iterator(); it.hasNext();) {
4907 if (o.equals(it.next())) {
4908 it.remove();
4909 return true;
4910 }
4911 }
4912 }
4913 return false;
4914 }
4915
4916 /**
4917 * @return an iterator over the values of the backing map
4918 */
4919 public final Iterator<V> iterator() {
4920 return new ValueIterator<K,V>(map);
4921 }
4922
4923 /** Always throws {@link UnsupportedOperationException}. */
4924 public final boolean add(V e) {
4925 throw new UnsupportedOperationException();
4926 }
4927 /** Always throws {@link UnsupportedOperationException}. */
4928 public final boolean addAll(Collection<? extends V> c) {
4929 throw new UnsupportedOperationException();
4930 }
4931
4932 Spliterator<V> spliterator() {
4933 return new ValueIterator<K,V>(map, null);
4934 }
4935
4936 public Stream<V> stream() {
4937 return Streams.stream(spliterator());
4938 }
4939
4940 public Stream<V> parallelStream() {
4941 return Streams.parallelStream(spliterator());
4942 }
4943
4944 }
4945
4946 /**
4947 * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4948 * entries. This class cannot be directly instantiated. See
4949 * {@link #entrySet()}.
4950 */
4951 public static final class EntrySetView<K,V>
4952 extends CHMSetView<K,V,Map.Entry<K,V>>
4953 implements Set<Map.Entry<K,V>>, java.io.Serializable {
4954 private static final long serialVersionUID = 2249069246763182397L;
4955 EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4956
4957 public final boolean contains(Object o) {
4958 Object k, v, r; Map.Entry<?,?> e;
4959 return ((o instanceof Map.Entry) &&
4960 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4961 (r = map.get(k)) != null &&
4962 (v = e.getValue()) != null &&
4963 (v == r || v.equals(r)));
4964 }
4965 public final boolean remove(Object o) {
4966 Object k, v; Map.Entry<?,?> e;
4967 return ((o instanceof Map.Entry) &&
4968 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4969 (v = e.getValue()) != null &&
4970 map.remove(k, v));
4971 }
4972
4973 /**
4974 * @return an iterator over the entries of the backing map
4975 */
4976 public final Iterator<Map.Entry<K,V>> iterator() {
4977 return new EntryIterator<K,V>(map);
4978 }
4979
4980 /**
4981 * Adds the specified mapping to this view.
4982 *
4983 * @param e mapping to be added
4984 * @return {@code true} if this set changed as a result of the call
4985 * @throws NullPointerException if the entry, its key, or its
4986 * value is null
4987 */
4988 public final boolean add(Entry<K,V> e) {
4989 return map.internalPut(e.getKey(), e.getValue(), false) == null;
4990 }
4991 /**
4992 * Adds all of the mappings in the specified collection to this
4993 * set, as if by calling {@link #add(Map.Entry)} on each one.
4994 * @param c the mappings to be inserted into this set
4995 * @return {@code true} if this set changed as a result of the call
4996 * @throws NullPointerException if the collection or any of its
4997 * entries, keys, or values are null
4998 */
4999 public final boolean addAll(Collection<? extends Entry<K,V>> c) {
5000 boolean added = false;
5001 for (Entry<K,V> e : c) {
5002 if (add(e))
5003 added = true;
5004 }
5005 return added;
5006 }
5007
5008 Spliterator<Map.Entry<K,V>> spliterator() {
5009 return new EntryIterator<K,V>(map, null);
5010 }
5011
5012 public Stream<Map.Entry<K,V>> stream() {
5013 return Streams.stream(spliterator());
5014 }
5015
5016 public Stream<Map.Entry<K,V>> parallelStream() {
5017 return Streams.parallelStream(spliterator());
5018 }
5019 }
5020
5021 // ---------------------------------------------------------------------
5022
5023 /**
5024 * Predefined tasks for performing bulk parallel operations on
5025 * ConcurrentHashMaps. These tasks follow the forms and rules used
5026 * for bulk operations. Each method has the same name, but returns
5027 * a task rather than invoking it. These methods may be useful in
5028 * custom applications such as submitting a task without waiting
5029 * for completion, using a custom pool, or combining with other
5030 * tasks.
5031 */
5032 public static class ForkJoinTasks {
5033 private ForkJoinTasks() {}
5034
5035 /**
5036 * Returns a task that when invoked, performs the given
5037 * action for each (key, value)
5038 *
5039 * @param map the map
5040 * @param action the action
5041 * @return the task
5042 */
5043 public static <K,V> ForkJoinTask<Void> forEach
5044 (ConcurrentHashMap<K,V> map,
5045 BiConsumer<? super K, ? super V> action) {
5046 if (action == null) throw new NullPointerException();
5047 return new ForEachMappingTask<K,V>(map, null, -1, action);
5048 }
5049
5050 /**
5051 * Returns a task that when invoked, performs the given
5052 * action for each non-null transformation of each (key, value)
5053 *
5054 * @param map the map
5055 * @param transformer a function returning the transformation
5056 * for an element, or null if there is no transformation (in
5057 * which case the action is not applied)
5058 * @param action the action
5059 * @return the task
5060 */
5061 public static <K,V,U> ForkJoinTask<Void> forEach
5062 (ConcurrentHashMap<K,V> map,
5063 BiFunction<? super K, ? super V, ? extends U> transformer,
5064 Consumer<? super U> action) {
5065 if (transformer == null || action == null)
5066 throw new NullPointerException();
5067 return new ForEachTransformedMappingTask<K,V,U>
5068 (map, null, -1, transformer, action);
5069 }
5070
5071 /**
5072 * Returns a task that when invoked, returns a non-null result
5073 * from applying the given search function on each (key,
5074 * value), or null if none. Upon success, further element
5075 * processing is suppressed and the results of any other
5076 * parallel invocations of the search function are ignored.
5077 *
5078 * @param map the map
5079 * @param searchFunction a function returning a non-null
5080 * result on success, else null
5081 * @return the task
5082 */
5083 public static <K,V,U> ForkJoinTask<U> search
5084 (ConcurrentHashMap<K,V> map,
5085 BiFunction<? super K, ? super V, ? extends U> searchFunction) {
5086 if (searchFunction == null) throw new NullPointerException();
5087 return new SearchMappingsTask<K,V,U>
5088 (map, null, -1, searchFunction,
5089 new AtomicReference<U>());
5090 }
5091
5092 /**
5093 * Returns a task that when invoked, returns the result of
5094 * accumulating the given transformation of all (key, value) pairs
5095 * using the given reducer to combine values, or null if none.
5096 *
5097 * @param map the map
5098 * @param transformer a function returning the transformation
5099 * for an element, or null if there is no transformation (in
5100 * which case it is not combined)
5101 * @param reducer a commutative associative combining function
5102 * @return the task
5103 */
5104 public static <K,V,U> ForkJoinTask<U> reduce
5105 (ConcurrentHashMap<K,V> map,
5106 BiFunction<? super K, ? super V, ? extends U> transformer,
5107 BiFunction<? super U, ? super U, ? extends U> reducer) {
5108 if (transformer == null || reducer == null)
5109 throw new NullPointerException();
5110 return new MapReduceMappingsTask<K,V,U>
5111 (map, null, -1, null, transformer, reducer);
5112 }
5113
5114 /**
5115 * Returns a task that when invoked, returns the result of
5116 * accumulating the given transformation of all (key, value) pairs
5117 * using the given reducer to combine values, and the given
5118 * basis as an identity value.
5119 *
5120 * @param map the map
5121 * @param transformer a function returning the transformation
5122 * for an element
5123 * @param basis the identity (initial default value) for the reduction
5124 * @param reducer a commutative associative combining function
5125 * @return the task
5126 */
5127 public static <K,V> ForkJoinTask<Double> reduceToDouble
5128 (ConcurrentHashMap<K,V> map,
5129 ToDoubleBiFunction<? super K, ? super V> transformer,
5130 double basis,
5131 DoubleBinaryOperator reducer) {
5132 if (transformer == null || reducer == null)
5133 throw new NullPointerException();
5134 return new MapReduceMappingsToDoubleTask<K,V>
5135 (map, null, -1, null, transformer, basis, reducer);
5136 }
5137
5138 /**
5139 * Returns a task that when invoked, returns the result of
5140 * accumulating the given transformation of all (key, value) pairs
5141 * using the given reducer to combine values, and the given
5142 * basis as an identity value.
5143 *
5144 * @param map the map
5145 * @param transformer a function returning the transformation
5146 * for an element
5147 * @param basis the identity (initial default value) for the reduction
5148 * @param reducer a commutative associative combining function
5149 * @return the task
5150 */
5151 public static <K,V> ForkJoinTask<Long> reduceToLong
5152 (ConcurrentHashMap<K,V> map,
5153 ToLongBiFunction<? super K, ? super V> transformer,
5154 long basis,
5155 LongBinaryOperator reducer) {
5156 if (transformer == null || reducer == null)
5157 throw new NullPointerException();
5158 return new MapReduceMappingsToLongTask<K,V>
5159 (map, null, -1, null, transformer, basis, reducer);
5160 }
5161
5162 /**
5163 * Returns a task that when invoked, returns the result of
5164 * accumulating the given transformation of all (key, value) pairs
5165 * using the given reducer to combine values, and the given
5166 * basis as an identity value.
5167 *
5168 * @param map the map
5169 * @param transformer a function returning the transformation
5170 * for an element
5171 * @param basis the identity (initial default value) for the reduction
5172 * @param reducer a commutative associative combining function
5173 * @return the task
5174 */
5175 public static <K,V> ForkJoinTask<Integer> reduceToInt
5176 (ConcurrentHashMap<K,V> map,
5177 ToIntBiFunction<? super K, ? super V> transformer,
5178 int basis,
5179 IntBinaryOperator reducer) {
5180 if (transformer == null || reducer == null)
5181 throw new NullPointerException();
5182 return new MapReduceMappingsToIntTask<K,V>
5183 (map, null, -1, null, transformer, basis, reducer);
5184 }
5185
5186 /**
5187 * Returns a task that when invoked, performs the given action
5188 * for each key.
5189 *
5190 * @param map the map
5191 * @param action the action
5192 * @return the task
5193 */
5194 public static <K,V> ForkJoinTask<Void> forEachKey
5195 (ConcurrentHashMap<K,V> map,
5196 Consumer<? super K> action) {
5197 if (action == null) throw new NullPointerException();
5198 return new ForEachKeyTask<K,V>(map, null, -1, action);
5199 }
5200
5201 /**
5202 * Returns a task that when invoked, performs the given action
5203 * for each non-null transformation of each key.
5204 *
5205 * @param map the map
5206 * @param transformer a function returning the transformation
5207 * for an element, or null if there is no transformation (in
5208 * which case the action is not applied)
5209 * @param action the action
5210 * @return the task
5211 */
5212 public static <K,V,U> ForkJoinTask<Void> forEachKey
5213 (ConcurrentHashMap<K,V> map,
5214 Function<? super K, ? extends U> transformer,
5215 Consumer<? super U> action) {
5216 if (transformer == null || action == null)
5217 throw new NullPointerException();
5218 return new ForEachTransformedKeyTask<K,V,U>
5219 (map, null, -1, transformer, action);
5220 }
5221
5222 /**
5223 * Returns a task that when invoked, returns a non-null result
5224 * from applying the given search function on each key, or
5225 * null if none. Upon success, further element processing is
5226 * suppressed and the results of any other parallel
5227 * invocations of the search function are ignored.
5228 *
5229 * @param map the map
5230 * @param searchFunction a function returning a non-null
5231 * result on success, else null
5232 * @return the task
5233 */
5234 public static <K,V,U> ForkJoinTask<U> searchKeys
5235 (ConcurrentHashMap<K,V> map,
5236 Function<? super K, ? extends U> searchFunction) {
5237 if (searchFunction == null) throw new NullPointerException();
5238 return new SearchKeysTask<K,V,U>
5239 (map, null, -1, searchFunction,
5240 new AtomicReference<U>());
5241 }
5242
5243 /**
5244 * Returns a task that when invoked, returns the result of
5245 * accumulating all keys using the given reducer to combine
5246 * values, or null if none.
5247 *
5248 * @param map the map
5249 * @param reducer a commutative associative combining function
5250 * @return the task
5251 */
5252 public static <K,V> ForkJoinTask<K> reduceKeys
5253 (ConcurrentHashMap<K,V> map,
5254 BiFunction<? super K, ? super K, ? extends K> reducer) {
5255 if (reducer == null) throw new NullPointerException();
5256 return new ReduceKeysTask<K,V>
5257 (map, null, -1, null, reducer);
5258 }
5259
5260 /**
5261 * Returns a task that when invoked, returns the result of
5262 * accumulating the given transformation of all keys using the given
5263 * reducer to combine values, or null if none.
5264 *
5265 * @param map the map
5266 * @param transformer a function returning the transformation
5267 * for an element, or null if there is no transformation (in
5268 * which case it is not combined)
5269 * @param reducer a commutative associative combining function
5270 * @return the task
5271 */
5272 public static <K,V,U> ForkJoinTask<U> reduceKeys
5273 (ConcurrentHashMap<K,V> map,
5274 Function<? super K, ? extends U> transformer,
5275 BiFunction<? super U, ? super U, ? extends U> reducer) {
5276 if (transformer == null || reducer == null)
5277 throw new NullPointerException();
5278 return new MapReduceKeysTask<K,V,U>
5279 (map, null, -1, null, transformer, reducer);
5280 }
5281
5282 /**
5283 * Returns a task that when invoked, returns the result of
5284 * accumulating the given transformation of all keys using the given
5285 * reducer to combine values, and the given basis as an
5286 * identity value.
5287 *
5288 * @param map the map
5289 * @param transformer a function returning the transformation
5290 * for an element
5291 * @param basis the identity (initial default value) for the reduction
5292 * @param reducer a commutative associative combining function
5293 * @return the task
5294 */
5295 public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5296 (ConcurrentHashMap<K,V> map,
5297 ToDoubleFunction<? super K> transformer,
5298 double basis,
5299 DoubleBinaryOperator reducer) {
5300 if (transformer == null || reducer == null)
5301 throw new NullPointerException();
5302 return new MapReduceKeysToDoubleTask<K,V>
5303 (map, null, -1, null, transformer, basis, reducer);
5304 }
5305
5306 /**
5307 * Returns a task that when invoked, returns the result of
5308 * accumulating the given transformation of all keys using the given
5309 * reducer to combine values, and the given basis as an
5310 * identity value.
5311 *
5312 * @param map the map
5313 * @param transformer a function returning the transformation
5314 * for an element
5315 * @param basis the identity (initial default value) for the reduction
5316 * @param reducer a commutative associative combining function
5317 * @return the task
5318 */
5319 public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5320 (ConcurrentHashMap<K,V> map,
5321 ToLongFunction<? super K> transformer,
5322 long basis,
5323 LongBinaryOperator reducer) {
5324 if (transformer == null || reducer == null)
5325 throw new NullPointerException();
5326 return new MapReduceKeysToLongTask<K,V>
5327 (map, null, -1, null, transformer, basis, reducer);
5328 }
5329
5330 /**
5331 * Returns a task that when invoked, returns the result of
5332 * accumulating the given transformation of all keys using the given
5333 * reducer to combine values, and the given basis as an
5334 * identity value.
5335 *
5336 * @param map the map
5337 * @param transformer a function returning the transformation
5338 * for an element
5339 * @param basis the identity (initial default value) for the reduction
5340 * @param reducer a commutative associative combining function
5341 * @return the task
5342 */
5343 public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5344 (ConcurrentHashMap<K,V> map,
5345 ToIntFunction<? super K> transformer,
5346 int basis,
5347 IntBinaryOperator reducer) {
5348 if (transformer == null || reducer == null)
5349 throw new NullPointerException();
5350 return new MapReduceKeysToIntTask<K,V>
5351 (map, null, -1, null, transformer, basis, reducer);
5352 }
5353
5354 /**
5355 * Returns a task that when invoked, performs the given action
5356 * for each value.
5357 *
5358 * @param map the map
5359 * @param action the action
5360 * @return the task
5361 */
5362 public static <K,V> ForkJoinTask<Void> forEachValue
5363 (ConcurrentHashMap<K,V> map,
5364 Consumer<? super V> action) {
5365 if (action == null) throw new NullPointerException();
5366 return new ForEachValueTask<K,V>(map, null, -1, action);
5367 }
5368
5369 /**
5370 * Returns a task that when invoked, performs the given action
5371 * for each non-null transformation of each value.
5372 *
5373 * @param map the map
5374 * @param transformer a function returning the transformation
5375 * for an element, or null if there is no transformation (in
5376 * which case the action is not applied)
5377 * @param action the action
5378 * @return the task
5379 */
5380 public static <K,V,U> ForkJoinTask<Void> forEachValue
5381 (ConcurrentHashMap<K,V> map,
5382 Function<? super V, ? extends U> transformer,
5383 Consumer<? super U> action) {
5384 if (transformer == null || action == null)
5385 throw new NullPointerException();
5386 return new ForEachTransformedValueTask<K,V,U>
5387 (map, null, -1, transformer, action);
5388 }
5389
5390 /**
5391 * Returns a task that when invoked, returns a non-null result
5392 * from applying the given search function on each value, or
5393 * null if none. Upon success, further element processing is
5394 * suppressed and the results of any other parallel
5395 * invocations of the search function are ignored.
5396 *
5397 * @param map the map
5398 * @param searchFunction a function returning a non-null
5399 * result on success, else null
5400 * @return the task
5401 */
5402 public static <K,V,U> ForkJoinTask<U> searchValues
5403 (ConcurrentHashMap<K,V> map,
5404 Function<? super V, ? extends U> searchFunction) {
5405 if (searchFunction == null) throw new NullPointerException();
5406 return new SearchValuesTask<K,V,U>
5407 (map, null, -1, searchFunction,
5408 new AtomicReference<U>());
5409 }
5410
5411 /**
5412 * Returns a task that when invoked, returns the result of
5413 * accumulating all values using the given reducer to combine
5414 * values, or null if none.
5415 *
5416 * @param map the map
5417 * @param reducer a commutative associative combining function
5418 * @return the task
5419 */
5420 public static <K,V> ForkJoinTask<V> reduceValues
5421 (ConcurrentHashMap<K,V> map,
5422 BiFunction<? super V, ? super V, ? extends V> reducer) {
5423 if (reducer == null) throw new NullPointerException();
5424 return new ReduceValuesTask<K,V>
5425 (map, null, -1, null, reducer);
5426 }
5427
5428 /**
5429 * Returns a task that when invoked, returns the result of
5430 * accumulating the given transformation of all values using the
5431 * given reducer to combine values, or null if none.
5432 *
5433 * @param map the map
5434 * @param transformer a function returning the transformation
5435 * for an element, or null if there is no transformation (in
5436 * which case it is not combined)
5437 * @param reducer a commutative associative combining function
5438 * @return the task
5439 */
5440 public static <K,V,U> ForkJoinTask<U> reduceValues
5441 (ConcurrentHashMap<K,V> map,
5442 Function<? super V, ? extends U> transformer,
5443 BiFunction<? super U, ? super U, ? extends U> reducer) {
5444 if (transformer == null || reducer == null)
5445 throw new NullPointerException();
5446 return new MapReduceValuesTask<K,V,U>
5447 (map, null, -1, null, transformer, reducer);
5448 }
5449
5450 /**
5451 * Returns a task that when invoked, returns the result of
5452 * accumulating the given transformation of all values using the
5453 * given reducer to combine values, and the given basis as an
5454 * identity value.
5455 *
5456 * @param map the map
5457 * @param transformer a function returning the transformation
5458 * for an element
5459 * @param basis the identity (initial default value) for the reduction
5460 * @param reducer a commutative associative combining function
5461 * @return the task
5462 */
5463 public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5464 (ConcurrentHashMap<K,V> map,
5465 ToDoubleFunction<? super V> transformer,
5466 double basis,
5467 DoubleBinaryOperator reducer) {
5468 if (transformer == null || reducer == null)
5469 throw new NullPointerException();
5470 return new MapReduceValuesToDoubleTask<K,V>
5471 (map, null, -1, null, transformer, basis, reducer);
5472 }
5473
5474 /**
5475 * Returns a task that when invoked, returns the result of
5476 * accumulating the given transformation of all values using the
5477 * given reducer to combine values, and the given basis as an
5478 * identity value.
5479 *
5480 * @param map the map
5481 * @param transformer a function returning the transformation
5482 * for an element
5483 * @param basis the identity (initial default value) for the reduction
5484 * @param reducer a commutative associative combining function
5485 * @return the task
5486 */
5487 public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5488 (ConcurrentHashMap<K,V> map,
5489 ToLongFunction<? super V> transformer,
5490 long basis,
5491 LongBinaryOperator reducer) {
5492 if (transformer == null || reducer == null)
5493 throw new NullPointerException();
5494 return new MapReduceValuesToLongTask<K,V>
5495 (map, null, -1, null, transformer, basis, reducer);
5496 }
5497
5498 /**
5499 * Returns a task that when invoked, returns the result of
5500 * accumulating the given transformation of all values using the
5501 * given reducer to combine values, and the given basis as an
5502 * identity value.
5503 *
5504 * @param map the map
5505 * @param transformer a function returning the transformation
5506 * for an element
5507 * @param basis the identity (initial default value) for the reduction
5508 * @param reducer a commutative associative combining function
5509 * @return the task
5510 */
5511 public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5512 (ConcurrentHashMap<K,V> map,
5513 ToIntFunction<? super V> transformer,
5514 int basis,
5515 IntBinaryOperator reducer) {
5516 if (transformer == null || reducer == null)
5517 throw new NullPointerException();
5518 return new MapReduceValuesToIntTask<K,V>
5519 (map, null, -1, null, transformer, basis, reducer);
5520 }
5521
5522 /**
5523 * Returns a task that when invoked, perform the given action
5524 * for each entry.
5525 *
5526 * @param map the map
5527 * @param action the action
5528 * @return the task
5529 */
5530 public static <K,V> ForkJoinTask<Void> forEachEntry
5531 (ConcurrentHashMap<K,V> map,
5532 Consumer<? super Map.Entry<K,V>> action) {
5533 if (action == null) throw new NullPointerException();
5534 return new ForEachEntryTask<K,V>(map, null, -1, action);
5535 }
5536
5537 /**
5538 * Returns a task that when invoked, perform the given action
5539 * for each non-null transformation of each entry.
5540 *
5541 * @param map the map
5542 * @param transformer a function returning the transformation
5543 * for an element, or null if there is no transformation (in
5544 * which case the action is not applied)
5545 * @param action the action
5546 * @return the task
5547 */
5548 public static <K,V,U> ForkJoinTask<Void> forEachEntry
5549 (ConcurrentHashMap<K,V> map,
5550 Function<Map.Entry<K,V>, ? extends U> transformer,
5551 Consumer<? super U> action) {
5552 if (transformer == null || action == null)
5553 throw new NullPointerException();
5554 return new ForEachTransformedEntryTask<K,V,U>
5555 (map, null, -1, transformer, action);
5556 }
5557
5558 /**
5559 * Returns a task that when invoked, returns a non-null result
5560 * from applying the given search function on each entry, or
5561 * null if none. Upon success, further element processing is
5562 * suppressed and the results of any other parallel
5563 * invocations of the search function are ignored.
5564 *
5565 * @param map the map
5566 * @param searchFunction a function returning a non-null
5567 * result on success, else null
5568 * @return the task
5569 */
5570 public static <K,V,U> ForkJoinTask<U> searchEntries
5571 (ConcurrentHashMap<K,V> map,
5572 Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5573 if (searchFunction == null) throw new NullPointerException();
5574 return new SearchEntriesTask<K,V,U>
5575 (map, null, -1, searchFunction,
5576 new AtomicReference<U>());
5577 }
5578
5579 /**
5580 * Returns a task that when invoked, returns the result of
5581 * accumulating all entries using the given reducer to combine
5582 * values, or null if none.
5583 *
5584 * @param map the map
5585 * @param reducer a commutative associative combining function
5586 * @return the task
5587 */
5588 public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5589 (ConcurrentHashMap<K,V> map,
5590 BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5591 if (reducer == null) throw new NullPointerException();
5592 return new ReduceEntriesTask<K,V>
5593 (map, null, -1, null, reducer);
5594 }
5595
5596 /**
5597 * Returns a task that when invoked, returns the result of
5598 * accumulating the given transformation of all entries using the
5599 * given reducer to combine values, or null if none.
5600 *
5601 * @param map the map
5602 * @param transformer a function returning the transformation
5603 * for an element, or null if there is no transformation (in
5604 * which case it is not combined)
5605 * @param reducer a commutative associative combining function
5606 * @return the task
5607 */
5608 public static <K,V,U> ForkJoinTask<U> reduceEntries
5609 (ConcurrentHashMap<K,V> map,
5610 Function<Map.Entry<K,V>, ? extends U> transformer,
5611 BiFunction<? super U, ? super U, ? extends U> reducer) {
5612 if (transformer == null || reducer == null)
5613 throw new NullPointerException();
5614 return new MapReduceEntriesTask<K,V,U>
5615 (map, null, -1, null, transformer, reducer);
5616 }
5617
5618 /**
5619 * Returns a task that when invoked, returns the result of
5620 * accumulating the given transformation of all entries using the
5621 * given reducer to combine values, and the given basis as an
5622 * identity value.
5623 *
5624 * @param map the map
5625 * @param transformer a function returning the transformation
5626 * for an element
5627 * @param basis the identity (initial default value) for the reduction
5628 * @param reducer a commutative associative combining function
5629 * @return the task
5630 */
5631 public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5632 (ConcurrentHashMap<K,V> map,
5633 ToDoubleFunction<Map.Entry<K,V>> transformer,
5634 double basis,
5635 DoubleBinaryOperator reducer) {
5636 if (transformer == null || reducer == null)
5637 throw new NullPointerException();
5638 return new MapReduceEntriesToDoubleTask<K,V>
5639 (map, null, -1, null, transformer, basis, reducer);
5640 }
5641
5642 /**
5643 * Returns a task that when invoked, returns the result of
5644 * accumulating the given transformation of all entries using the
5645 * given reducer to combine values, and the given basis as an
5646 * identity value.
5647 *
5648 * @param map the map
5649 * @param transformer a function returning the transformation
5650 * for an element
5651 * @param basis the identity (initial default value) for the reduction
5652 * @param reducer a commutative associative combining function
5653 * @return the task
5654 */
5655 public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5656 (ConcurrentHashMap<K,V> map,
5657 ToLongFunction<Map.Entry<K,V>> transformer,
5658 long basis,
5659 LongBinaryOperator reducer) {
5660 if (transformer == null || reducer == null)
5661 throw new NullPointerException();
5662 return new MapReduceEntriesToLongTask<K,V>
5663 (map, null, -1, null, transformer, basis, reducer);
5664 }
5665
5666 /**
5667 * Returns a task that when invoked, returns the result of
5668 * accumulating the given transformation of all entries using the
5669 * given reducer to combine values, and the given basis as an
5670 * identity value.
5671 *
5672 * @param map the map
5673 * @param transformer a function returning the transformation
5674 * for an element
5675 * @param basis the identity (initial default value) for the reduction
5676 * @param reducer a commutative associative combining function
5677 * @return the task
5678 */
5679 public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5680 (ConcurrentHashMap<K,V> map,
5681 ToIntFunction<Map.Entry<K,V>> transformer,
5682 int basis,
5683 IntBinaryOperator reducer) {
5684 if (transformer == null || reducer == null)
5685 throw new NullPointerException();
5686 return new MapReduceEntriesToIntTask<K,V>
5687 (map, null, -1, null, transformer, basis, reducer);
5688 }
5689 }
5690
5691 // -------------------------------------------------------
5692
5693 /*
5694 * Task classes. Coded in a regular but ugly format/style to
5695 * simplify checks that each variant differs in the right way from
5696 * others. The null screenings exist because compilers cannot tell
5697 * that we've already null-checked task arguments, so we force
5698 * simplest hoisted bypass to help avoid convoluted traps.
5699 */
5700
5701 @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5702 extends Traverser<K,V,Void> {
5703 final Consumer<? super K> action;
5704 ForEachKeyTask
5705 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5706 Consumer<? super K> action) {
5707 super(m, p, b);
5708 this.action = action;
5709 }
5710 public final void compute() {
5711 final Consumer<? super K> action;
5712 if ((action = this.action) != null) {
5713 for (int b; (b = preSplit()) > 0;)
5714 new ForEachKeyTask<K,V>(map, this, b, action).fork();
5715 forEachKey(action);
5716 propagateCompletion();
5717 }
5718 }
5719 }
5720
5721 @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5722 extends Traverser<K,V,Void> {
5723 final Consumer<? super V> action;
5724 ForEachValueTask
5725 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5726 Consumer<? super V> action) {
5727 super(m, p, b);
5728 this.action = action;
5729 }
5730 public final void compute() {
5731 final Consumer<? super V> action;
5732 if ((action = this.action) != null) {
5733 for (int b; (b = preSplit()) > 0;)
5734 new ForEachValueTask<K,V>(map, this, b, action).fork();
5735 forEachValue(action);
5736 propagateCompletion();
5737 }
5738 }
5739 }
5740
5741 @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5742 extends Traverser<K,V,Void> {
5743 final Consumer<? super Entry<K,V>> action;
5744 ForEachEntryTask
5745 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5746 Consumer<? super Entry<K,V>> action) {
5747 super(m, p, b);
5748 this.action = action;
5749 }
5750 public final void compute() {
5751 final Consumer<? super Entry<K,V>> action;
5752 if ((action = this.action) != null) {
5753 for (int b; (b = preSplit()) > 0;)
5754 new ForEachEntryTask<K,V>(map, this, b, action).fork();
5755 V v;
5756 while ((v = advanceValue()) != null)
5757 action.accept(entryFor(nextKey, v));
5758 propagateCompletion();
5759 }
5760 }
5761 }
5762
5763 @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5764 extends Traverser<K,V,Void> {
5765 final BiConsumer<? super K, ? super V> action;
5766 ForEachMappingTask
5767 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5768 BiConsumer<? super K,? super V> action) {
5769 super(m, p, b);
5770 this.action = action;
5771 }
5772 public final void compute() {
5773 final BiConsumer<? super K, ? super V> action;
5774 if ((action = this.action) != null) {
5775 for (int b; (b = preSplit()) > 0;)
5776 new ForEachMappingTask<K,V>(map, this, b, action).fork();
5777 V v;
5778 while ((v = advanceValue()) != null)
5779 action.accept(nextKey, v);
5780 propagateCompletion();
5781 }
5782 }
5783 }
5784
5785 @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5786 extends Traverser<K,V,Void> {
5787 final Function<? super K, ? extends U> transformer;
5788 final Consumer<? super U> action;
5789 ForEachTransformedKeyTask
5790 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5791 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5792 super(m, p, b);
5793 this.transformer = transformer; this.action = action;
5794 }
5795 public final void compute() {
5796 final Function<? super K, ? extends U> transformer;
5797 final Consumer<? super U> action;
5798 if ((transformer = this.transformer) != null &&
5799 (action = this.action) != null) {
5800 for (int b; (b = preSplit()) > 0;)
5801 new ForEachTransformedKeyTask<K,V,U>
5802 (map, this, b, transformer, action).fork();
5803 K k; U u;
5804 while ((k = advanceKey()) != null) {
5805 if ((u = transformer.apply(k)) != null)
5806 action.accept(u);
5807 }
5808 propagateCompletion();
5809 }
5810 }
5811 }
5812
5813 @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5814 extends Traverser<K,V,Void> {
5815 final Function<? super V, ? extends U> transformer;
5816 final Consumer<? super U> action;
5817 ForEachTransformedValueTask
5818 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5819 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5820 super(m, p, b);
5821 this.transformer = transformer; this.action = action;
5822 }
5823 public final void compute() {
5824 final Function<? super V, ? extends U> transformer;
5825 final Consumer<? super U> action;
5826 if ((transformer = this.transformer) != null &&
5827 (action = this.action) != null) {
5828 for (int b; (b = preSplit()) > 0;)
5829 new ForEachTransformedValueTask<K,V,U>
5830 (map, this, b, transformer, action).fork();
5831 V v; U u;
5832 while ((v = advanceValue()) != null) {
5833 if ((u = transformer.apply(v)) != null)
5834 action.accept(u);
5835 }
5836 propagateCompletion();
5837 }
5838 }
5839 }
5840
5841 @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5842 extends Traverser<K,V,Void> {
5843 final Function<Map.Entry<K,V>, ? extends U> transformer;
5844 final Consumer<? super U> action;
5845 ForEachTransformedEntryTask
5846 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5847 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5848 super(m, p, b);
5849 this.transformer = transformer; this.action = action;
5850 }
5851 public final void compute() {
5852 final Function<Map.Entry<K,V>, ? extends U> transformer;
5853 final Consumer<? super U> action;
5854 if ((transformer = this.transformer) != null &&
5855 (action = this.action) != null) {
5856 for (int b; (b = preSplit()) > 0;)
5857 new ForEachTransformedEntryTask<K,V,U>
5858 (map, this, b, transformer, action).fork();
5859 V v; U u;
5860 while ((v = advanceValue()) != null) {
5861 if ((u = transformer.apply(entryFor(nextKey,
5862 v))) != null)
5863 action.accept(u);
5864 }
5865 propagateCompletion();
5866 }
5867 }
5868 }
5869
5870 @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5871 extends Traverser<K,V,Void> {
5872 final BiFunction<? super K, ? super V, ? extends U> transformer;
5873 final Consumer<? super U> action;
5874 ForEachTransformedMappingTask
5875 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5876 BiFunction<? super K, ? super V, ? extends U> transformer,
5877 Consumer<? super U> action) {
5878 super(m, p, b);
5879 this.transformer = transformer; this.action = action;
5880 }
5881 public final void compute() {
5882 final BiFunction<? super K, ? super V, ? extends U> transformer;
5883 final Consumer<? super U> action;
5884 if ((transformer = this.transformer) != null &&
5885 (action = this.action) != null) {
5886 for (int b; (b = preSplit()) > 0;)
5887 new ForEachTransformedMappingTask<K,V,U>
5888 (map, this, b, transformer, action).fork();
5889 V v; U u;
5890 while ((v = advanceValue()) != null) {
5891 if ((u = transformer.apply(nextKey, v)) != null)
5892 action.accept(u);
5893 }
5894 propagateCompletion();
5895 }
5896 }
5897 }
5898
5899 @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5900 extends Traverser<K,V,U> {
5901 final Function<? super K, ? extends U> searchFunction;
5902 final AtomicReference<U> result;
5903 SearchKeysTask
5904 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5905 Function<? super K, ? extends U> searchFunction,
5906 AtomicReference<U> result) {
5907 super(m, p, b);
5908 this.searchFunction = searchFunction; this.result = result;
5909 }
5910 public final U getRawResult() { return result.get(); }
5911 public final void compute() {
5912 final Function<? super K, ? extends U> searchFunction;
5913 final AtomicReference<U> result;
5914 if ((searchFunction = this.searchFunction) != null &&
5915 (result = this.result) != null) {
5916 for (int b;;) {
5917 if (result.get() != null)
5918 return;
5919 if ((b = preSplit()) <= 0)
5920 break;
5921 new SearchKeysTask<K,V,U>
5922 (map, this, b, searchFunction, result).fork();
5923 }
5924 while (result.get() == null) {
5925 K k; U u;
5926 if ((k = advanceKey()) == null) {
5927 propagateCompletion();
5928 break;
5929 }
5930 if ((u = searchFunction.apply(k)) != null) {
5931 if (result.compareAndSet(null, u))
5932 quietlyCompleteRoot();
5933 break;
5934 }
5935 }
5936 }
5937 }
5938 }
5939
5940 @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5941 extends Traverser<K,V,U> {
5942 final Function<? super V, ? extends U> searchFunction;
5943 final AtomicReference<U> result;
5944 SearchValuesTask
5945 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5946 Function<? super V, ? extends U> searchFunction,
5947 AtomicReference<U> result) {
5948 super(m, p, b);
5949 this.searchFunction = searchFunction; this.result = result;
5950 }
5951 public final U getRawResult() { return result.get(); }
5952 public final void compute() {
5953 final Function<? super V, ? extends U> searchFunction;
5954 final AtomicReference<U> result;
5955 if ((searchFunction = this.searchFunction) != null &&
5956 (result = this.result) != null) {
5957 for (int b;;) {
5958 if (result.get() != null)
5959 return;
5960 if ((b = preSplit()) <= 0)
5961 break;
5962 new SearchValuesTask<K,V,U>
5963 (map, this, b, searchFunction, result).fork();
5964 }
5965 while (result.get() == null) {
5966 V v; U u;
5967 if ((v = advanceValue()) == null) {
5968 propagateCompletion();
5969 break;
5970 }
5971 if ((u = searchFunction.apply(v)) != null) {
5972 if (result.compareAndSet(null, u))
5973 quietlyCompleteRoot();
5974 break;
5975 }
5976 }
5977 }
5978 }
5979 }
5980
5981 @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5982 extends Traverser<K,V,U> {
5983 final Function<Entry<K,V>, ? extends U> searchFunction;
5984 final AtomicReference<U> result;
5985 SearchEntriesTask
5986 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5987 Function<Entry<K,V>, ? extends U> searchFunction,
5988 AtomicReference<U> result) {
5989 super(m, p, b);
5990 this.searchFunction = searchFunction; this.result = result;
5991 }
5992 public final U getRawResult() { return result.get(); }
5993 public final void compute() {
5994 final Function<Entry<K,V>, ? extends U> searchFunction;
5995 final AtomicReference<U> result;
5996 if ((searchFunction = this.searchFunction) != null &&
5997 (result = this.result) != null) {
5998 for (int b;;) {
5999 if (result.get() != null)
6000 return;
6001 if ((b = preSplit()) <= 0)
6002 break;
6003 new SearchEntriesTask<K,V,U>
6004 (map, this, b, searchFunction, result).fork();
6005 }
6006 while (result.get() == null) {
6007 V v; U u;
6008 if ((v = advanceValue()) == null) {
6009 propagateCompletion();
6010 break;
6011 }
6012 if ((u = searchFunction.apply(entryFor(nextKey,
6013 v))) != null) {
6014 if (result.compareAndSet(null, u))
6015 quietlyCompleteRoot();
6016 return;
6017 }
6018 }
6019 }
6020 }
6021 }
6022
6023 @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
6024 extends Traverser<K,V,U> {
6025 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
6026 final AtomicReference<U> result;
6027 SearchMappingsTask
6028 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6029 BiFunction<? super K, ? super V, ? extends U> searchFunction,
6030 AtomicReference<U> result) {
6031 super(m, p, b);
6032 this.searchFunction = searchFunction; this.result = result;
6033 }
6034 public final U getRawResult() { return result.get(); }
6035 public final void compute() {
6036 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
6037 final AtomicReference<U> result;
6038 if ((searchFunction = this.searchFunction) != null &&
6039 (result = this.result) != null) {
6040 for (int b;;) {
6041 if (result.get() != null)
6042 return;
6043 if ((b = preSplit()) <= 0)
6044 break;
6045 new SearchMappingsTask<K,V,U>
6046 (map, this, b, searchFunction, result).fork();
6047 }
6048 while (result.get() == null) {
6049 V v; U u;
6050 if ((v = advanceValue()) == null) {
6051 propagateCompletion();
6052 break;
6053 }
6054 if ((u = searchFunction.apply(nextKey, v)) != null) {
6055 if (result.compareAndSet(null, u))
6056 quietlyCompleteRoot();
6057 break;
6058 }
6059 }
6060 }
6061 }
6062 }
6063
6064 @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
6065 extends Traverser<K,V,K> {
6066 final BiFunction<? super K, ? super K, ? extends K> reducer;
6067 K result;
6068 ReduceKeysTask<K,V> rights, nextRight;
6069 ReduceKeysTask
6070 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6071 ReduceKeysTask<K,V> nextRight,
6072 BiFunction<? super K, ? super K, ? extends K> reducer) {
6073 super(m, p, b); this.nextRight = nextRight;
6074 this.reducer = reducer;
6075 }
6076 public final K getRawResult() { return result; }
6077 @SuppressWarnings("unchecked") public final void compute() {
6078 final BiFunction<? super K, ? super K, ? extends K> reducer;
6079 if ((reducer = this.reducer) != null) {
6080 for (int b; (b = preSplit()) > 0;)
6081 (rights = new ReduceKeysTask<K,V>
6082 (map, this, b, rights, reducer)).fork();
6083 K u, r = null;
6084 while ((u = advanceKey()) != null) {
6085 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
6086 }
6087 result = r;
6088 CountedCompleter<?> c;
6089 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6090 ReduceKeysTask<K,V>
6091 t = (ReduceKeysTask<K,V>)c,
6092 s = t.rights;
6093 while (s != null) {
6094 K tr, sr;
6095 if ((sr = s.result) != null)
6096 t.result = (((tr = t.result) == null) ? sr :
6097 reducer.apply(tr, sr));
6098 s = t.rights = s.nextRight;
6099 }
6100 }
6101 }
6102 }
6103 }
6104
6105 @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
6106 extends Traverser<K,V,V> {
6107 final BiFunction<? super V, ? super V, ? extends V> reducer;
6108 V result;
6109 ReduceValuesTask<K,V> rights, nextRight;
6110 ReduceValuesTask
6111 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6112 ReduceValuesTask<K,V> nextRight,
6113 BiFunction<? super V, ? super V, ? extends V> reducer) {
6114 super(m, p, b); this.nextRight = nextRight;
6115 this.reducer = reducer;
6116 }
6117 public final V getRawResult() { return result; }
6118 @SuppressWarnings("unchecked") public final void compute() {
6119 final BiFunction<? super V, ? super V, ? extends V> reducer;
6120 if ((reducer = this.reducer) != null) {
6121 for (int b; (b = preSplit()) > 0;)
6122 (rights = new ReduceValuesTask<K,V>
6123 (map, this, b, rights, reducer)).fork();
6124 V r = null, v;
6125 while ((v = advanceValue()) != null)
6126 r = (r == null) ? v : reducer.apply(r, v);
6127 result = r;
6128 CountedCompleter<?> c;
6129 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6130 ReduceValuesTask<K,V>
6131 t = (ReduceValuesTask<K,V>)c,
6132 s = t.rights;
6133 while (s != null) {
6134 V tr, sr;
6135 if ((sr = s.result) != null)
6136 t.result = (((tr = t.result) == null) ? sr :
6137 reducer.apply(tr, sr));
6138 s = t.rights = s.nextRight;
6139 }
6140 }
6141 }
6142 }
6143 }
6144
6145 @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6146 extends Traverser<K,V,Map.Entry<K,V>> {
6147 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6148 Map.Entry<K,V> result;
6149 ReduceEntriesTask<K,V> rights, nextRight;
6150 ReduceEntriesTask
6151 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6152 ReduceEntriesTask<K,V> nextRight,
6153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6154 super(m, p, b); this.nextRight = nextRight;
6155 this.reducer = reducer;
6156 }
6157 public final Map.Entry<K,V> getRawResult() { return result; }
6158 @SuppressWarnings("unchecked") public final void compute() {
6159 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6160 if ((reducer = this.reducer) != null) {
6161 for (int b; (b = preSplit()) > 0;)
6162 (rights = new ReduceEntriesTask<K,V>
6163 (map, this, b, rights, reducer)).fork();
6164 Map.Entry<K,V> r = null;
6165 V v;
6166 while ((v = advanceValue()) != null) {
6167 Map.Entry<K,V> u = entryFor(nextKey, v);
6168 r = (r == null) ? u : reducer.apply(r, u);
6169 }
6170 result = r;
6171 CountedCompleter<?> c;
6172 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6173 ReduceEntriesTask<K,V>
6174 t = (ReduceEntriesTask<K,V>)c,
6175 s = t.rights;
6176 while (s != null) {
6177 Map.Entry<K,V> tr, sr;
6178 if ((sr = s.result) != null)
6179 t.result = (((tr = t.result) == null) ? sr :
6180 reducer.apply(tr, sr));
6181 s = t.rights = s.nextRight;
6182 }
6183 }
6184 }
6185 }
6186 }
6187
6188 @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6189 extends Traverser<K,V,U> {
6190 final Function<? super K, ? extends U> transformer;
6191 final BiFunction<? super U, ? super U, ? extends U> reducer;
6192 U result;
6193 MapReduceKeysTask<K,V,U> rights, nextRight;
6194 MapReduceKeysTask
6195 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6196 MapReduceKeysTask<K,V,U> nextRight,
6197 Function<? super K, ? extends U> transformer,
6198 BiFunction<? super U, ? super U, ? extends U> reducer) {
6199 super(m, p, b); this.nextRight = nextRight;
6200 this.transformer = transformer;
6201 this.reducer = reducer;
6202 }
6203 public final U getRawResult() { return result; }
6204 @SuppressWarnings("unchecked") public final void compute() {
6205 final Function<? super K, ? extends U> transformer;
6206 final BiFunction<? super U, ? super U, ? extends U> reducer;
6207 if ((transformer = this.transformer) != null &&
6208 (reducer = this.reducer) != null) {
6209 for (int b; (b = preSplit()) > 0;)
6210 (rights = new MapReduceKeysTask<K,V,U>
6211 (map, this, b, rights, transformer, reducer)).fork();
6212 K k; U r = null, u;
6213 while ((k = advanceKey()) != null) {
6214 if ((u = transformer.apply(k)) != null)
6215 r = (r == null) ? u : reducer.apply(r, u);
6216 }
6217 result = r;
6218 CountedCompleter<?> c;
6219 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6220 MapReduceKeysTask<K,V,U>
6221 t = (MapReduceKeysTask<K,V,U>)c,
6222 s = t.rights;
6223 while (s != null) {
6224 U tr, sr;
6225 if ((sr = s.result) != null)
6226 t.result = (((tr = t.result) == null) ? sr :
6227 reducer.apply(tr, sr));
6228 s = t.rights = s.nextRight;
6229 }
6230 }
6231 }
6232 }
6233 }
6234
6235 @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6236 extends Traverser<K,V,U> {
6237 final Function<? super V, ? extends U> transformer;
6238 final BiFunction<? super U, ? super U, ? extends U> reducer;
6239 U result;
6240 MapReduceValuesTask<K,V,U> rights, nextRight;
6241 MapReduceValuesTask
6242 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6243 MapReduceValuesTask<K,V,U> nextRight,
6244 Function<? super V, ? extends U> transformer,
6245 BiFunction<? super U, ? super U, ? extends U> reducer) {
6246 super(m, p, b); this.nextRight = nextRight;
6247 this.transformer = transformer;
6248 this.reducer = reducer;
6249 }
6250 public final U getRawResult() { return result; }
6251 @SuppressWarnings("unchecked") public final void compute() {
6252 final Function<? super V, ? extends U> transformer;
6253 final BiFunction<? super U, ? super U, ? extends U> reducer;
6254 if ((transformer = this.transformer) != null &&
6255 (reducer = this.reducer) != null) {
6256 for (int b; (b = preSplit()) > 0;)
6257 (rights = new MapReduceValuesTask<K,V,U>
6258 (map, this, b, rights, transformer, reducer)).fork();
6259 U r = null, u;
6260 V v;
6261 while ((v = advanceValue()) != null) {
6262 if ((u = transformer.apply(v)) != null)
6263 r = (r == null) ? u : reducer.apply(r, u);
6264 }
6265 result = r;
6266 CountedCompleter<?> c;
6267 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6268 MapReduceValuesTask<K,V,U>
6269 t = (MapReduceValuesTask<K,V,U>)c,
6270 s = t.rights;
6271 while (s != null) {
6272 U tr, sr;
6273 if ((sr = s.result) != null)
6274 t.result = (((tr = t.result) == null) ? sr :
6275 reducer.apply(tr, sr));
6276 s = t.rights = s.nextRight;
6277 }
6278 }
6279 }
6280 }
6281 }
6282
6283 @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6284 extends Traverser<K,V,U> {
6285 final Function<Map.Entry<K,V>, ? extends U> transformer;
6286 final BiFunction<? super U, ? super U, ? extends U> reducer;
6287 U result;
6288 MapReduceEntriesTask<K,V,U> rights, nextRight;
6289 MapReduceEntriesTask
6290 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6291 MapReduceEntriesTask<K,V,U> nextRight,
6292 Function<Map.Entry<K,V>, ? extends U> transformer,
6293 BiFunction<? super U, ? super U, ? extends U> reducer) {
6294 super(m, p, b); this.nextRight = nextRight;
6295 this.transformer = transformer;
6296 this.reducer = reducer;
6297 }
6298 public final U getRawResult() { return result; }
6299 @SuppressWarnings("unchecked") public final void compute() {
6300 final Function<Map.Entry<K,V>, ? extends U> transformer;
6301 final BiFunction<? super U, ? super U, ? extends U> reducer;
6302 if ((transformer = this.transformer) != null &&
6303 (reducer = this.reducer) != null) {
6304 for (int b; (b = preSplit()) > 0;)
6305 (rights = new MapReduceEntriesTask<K,V,U>
6306 (map, this, b, rights, transformer, reducer)).fork();
6307 U r = null, u;
6308 V v;
6309 while ((v = advanceValue()) != null) {
6310 if ((u = transformer.apply(entryFor(nextKey,
6311 v))) != null)
6312 r = (r == null) ? u : reducer.apply(r, u);
6313 }
6314 result = r;
6315 CountedCompleter<?> c;
6316 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6317 MapReduceEntriesTask<K,V,U>
6318 t = (MapReduceEntriesTask<K,V,U>)c,
6319 s = t.rights;
6320 while (s != null) {
6321 U tr, sr;
6322 if ((sr = s.result) != null)
6323 t.result = (((tr = t.result) == null) ? sr :
6324 reducer.apply(tr, sr));
6325 s = t.rights = s.nextRight;
6326 }
6327 }
6328 }
6329 }
6330 }
6331
6332 @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6333 extends Traverser<K,V,U> {
6334 final BiFunction<? super K, ? super V, ? extends U> transformer;
6335 final BiFunction<? super U, ? super U, ? extends U> reducer;
6336 U result;
6337 MapReduceMappingsTask<K,V,U> rights, nextRight;
6338 MapReduceMappingsTask
6339 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6340 MapReduceMappingsTask<K,V,U> nextRight,
6341 BiFunction<? super K, ? super V, ? extends U> transformer,
6342 BiFunction<? super U, ? super U, ? extends U> reducer) {
6343 super(m, p, b); this.nextRight = nextRight;
6344 this.transformer = transformer;
6345 this.reducer = reducer;
6346 }
6347 public final U getRawResult() { return result; }
6348 @SuppressWarnings("unchecked") public final void compute() {
6349 final BiFunction<? super K, ? super V, ? extends U> transformer;
6350 final BiFunction<? super U, ? super U, ? extends U> reducer;
6351 if ((transformer = this.transformer) != null &&
6352 (reducer = this.reducer) != null) {
6353 for (int b; (b = preSplit()) > 0;)
6354 (rights = new MapReduceMappingsTask<K,V,U>
6355 (map, this, b, rights, transformer, reducer)).fork();
6356 U r = null, u;
6357 V v;
6358 while ((v = advanceValue()) != null) {
6359 if ((u = transformer.apply(nextKey, v)) != null)
6360 r = (r == null) ? u : reducer.apply(r, u);
6361 }
6362 result = r;
6363 CountedCompleter<?> c;
6364 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6365 MapReduceMappingsTask<K,V,U>
6366 t = (MapReduceMappingsTask<K,V,U>)c,
6367 s = t.rights;
6368 while (s != null) {
6369 U tr, sr;
6370 if ((sr = s.result) != null)
6371 t.result = (((tr = t.result) == null) ? sr :
6372 reducer.apply(tr, sr));
6373 s = t.rights = s.nextRight;
6374 }
6375 }
6376 }
6377 }
6378 }
6379
6380 @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6381 extends Traverser<K,V,Double> {
6382 final ToDoubleFunction<? super K> transformer;
6383 final DoubleBinaryOperator reducer;
6384 final double basis;
6385 double result;
6386 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6387 MapReduceKeysToDoubleTask
6388 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6389 MapReduceKeysToDoubleTask<K,V> nextRight,
6390 ToDoubleFunction<? super K> transformer,
6391 double basis,
6392 DoubleBinaryOperator reducer) {
6393 super(m, p, b); this.nextRight = nextRight;
6394 this.transformer = transformer;
6395 this.basis = basis; this.reducer = reducer;
6396 }
6397 public final Double getRawResult() { return result; }
6398 @SuppressWarnings("unchecked") public final void compute() {
6399 final ToDoubleFunction<? super K> transformer;
6400 final DoubleBinaryOperator reducer;
6401 if ((transformer = this.transformer) != null &&
6402 (reducer = this.reducer) != null) {
6403 double r = this.basis;
6404 for (int b; (b = preSplit()) > 0;)
6405 (rights = new MapReduceKeysToDoubleTask<K,V>
6406 (map, this, b, rights, transformer, r, reducer)).fork();
6407 K k;
6408 while ((k = advanceKey()) != null)
6409 r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
6410 result = r;
6411 CountedCompleter<?> c;
6412 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6413 MapReduceKeysToDoubleTask<K,V>
6414 t = (MapReduceKeysToDoubleTask<K,V>)c,
6415 s = t.rights;
6416 while (s != null) {
6417 t.result = reducer.applyAsDouble(t.result, s.result);
6418 s = t.rights = s.nextRight;
6419 }
6420 }
6421 }
6422 }
6423 }
6424
6425 @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6426 extends Traverser<K,V,Double> {
6427 final ToDoubleFunction<? super V> transformer;
6428 final DoubleBinaryOperator reducer;
6429 final double basis;
6430 double result;
6431 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6432 MapReduceValuesToDoubleTask
6433 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6434 MapReduceValuesToDoubleTask<K,V> nextRight,
6435 ToDoubleFunction<? super V> transformer,
6436 double basis,
6437 DoubleBinaryOperator reducer) {
6438 super(m, p, b); this.nextRight = nextRight;
6439 this.transformer = transformer;
6440 this.basis = basis; this.reducer = reducer;
6441 }
6442 public final Double getRawResult() { return result; }
6443 @SuppressWarnings("unchecked") public final void compute() {
6444 final ToDoubleFunction<? super V> transformer;
6445 final DoubleBinaryOperator reducer;
6446 if ((transformer = this.transformer) != null &&
6447 (reducer = this.reducer) != null) {
6448 double r = this.basis;
6449 for (int b; (b = preSplit()) > 0;)
6450 (rights = new MapReduceValuesToDoubleTask<K,V>
6451 (map, this, b, rights, transformer, r, reducer)).fork();
6452 V v;
6453 while ((v = advanceValue()) != null)
6454 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
6455 result = r;
6456 CountedCompleter<?> c;
6457 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6458 MapReduceValuesToDoubleTask<K,V>
6459 t = (MapReduceValuesToDoubleTask<K,V>)c,
6460 s = t.rights;
6461 while (s != null) {
6462 t.result = reducer.applyAsDouble(t.result, s.result);
6463 s = t.rights = s.nextRight;
6464 }
6465 }
6466 }
6467 }
6468 }
6469
6470 @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6471 extends Traverser<K,V,Double> {
6472 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6473 final DoubleBinaryOperator reducer;
6474 final double basis;
6475 double result;
6476 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6477 MapReduceEntriesToDoubleTask
6478 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6479 MapReduceEntriesToDoubleTask<K,V> nextRight,
6480 ToDoubleFunction<Map.Entry<K,V>> transformer,
6481 double basis,
6482 DoubleBinaryOperator reducer) {
6483 super(m, p, b); this.nextRight = nextRight;
6484 this.transformer = transformer;
6485 this.basis = basis; this.reducer = reducer;
6486 }
6487 public final Double getRawResult() { return result; }
6488 @SuppressWarnings("unchecked") public final void compute() {
6489 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6490 final DoubleBinaryOperator reducer;
6491 if ((transformer = this.transformer) != null &&
6492 (reducer = this.reducer) != null) {
6493 double r = this.basis;
6494 for (int b; (b = preSplit()) > 0;)
6495 (rights = new MapReduceEntriesToDoubleTask<K,V>
6496 (map, this, b, rights, transformer, r, reducer)).fork();
6497 V v;
6498 while ((v = advanceValue()) != null)
6499 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
6500 v)));
6501 result = r;
6502 CountedCompleter<?> c;
6503 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6504 MapReduceEntriesToDoubleTask<K,V>
6505 t = (MapReduceEntriesToDoubleTask<K,V>)c,
6506 s = t.rights;
6507 while (s != null) {
6508 t.result = reducer.applyAsDouble(t.result, s.result);
6509 s = t.rights = s.nextRight;
6510 }
6511 }
6512 }
6513 }
6514 }
6515
6516 @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6517 extends Traverser<K,V,Double> {
6518 final ToDoubleBiFunction<? super K, ? super V> transformer;
6519 final DoubleBinaryOperator reducer;
6520 final double basis;
6521 double result;
6522 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6523 MapReduceMappingsToDoubleTask
6524 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6525 MapReduceMappingsToDoubleTask<K,V> nextRight,
6526 ToDoubleBiFunction<? super K, ? super V> transformer,
6527 double basis,
6528 DoubleBinaryOperator reducer) {
6529 super(m, p, b); this.nextRight = nextRight;
6530 this.transformer = transformer;
6531 this.basis = basis; this.reducer = reducer;
6532 }
6533 public final Double getRawResult() { return result; }
6534 @SuppressWarnings("unchecked") public final void compute() {
6535 final ToDoubleBiFunction<? super K, ? super V> transformer;
6536 final DoubleBinaryOperator reducer;
6537 if ((transformer = this.transformer) != null &&
6538 (reducer = this.reducer) != null) {
6539 double r = this.basis;
6540 for (int b; (b = preSplit()) > 0;)
6541 (rights = new MapReduceMappingsToDoubleTask<K,V>
6542 (map, this, b, rights, transformer, r, reducer)).fork();
6543 V v;
6544 while ((v = advanceValue()) != null)
6545 r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
6546 result = r;
6547 CountedCompleter<?> c;
6548 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6549 MapReduceMappingsToDoubleTask<K,V>
6550 t = (MapReduceMappingsToDoubleTask<K,V>)c,
6551 s = t.rights;
6552 while (s != null) {
6553 t.result = reducer.applyAsDouble(t.result, s.result);
6554 s = t.rights = s.nextRight;
6555 }
6556 }
6557 }
6558 }
6559 }
6560
6561 @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6562 extends Traverser<K,V,Long> {
6563 final ToLongFunction<? super K> transformer;
6564 final LongBinaryOperator reducer;
6565 final long basis;
6566 long result;
6567 MapReduceKeysToLongTask<K,V> rights, nextRight;
6568 MapReduceKeysToLongTask
6569 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6570 MapReduceKeysToLongTask<K,V> nextRight,
6571 ToLongFunction<? super K> transformer,
6572 long basis,
6573 LongBinaryOperator reducer) {
6574 super(m, p, b); this.nextRight = nextRight;
6575 this.transformer = transformer;
6576 this.basis = basis; this.reducer = reducer;
6577 }
6578 public final Long getRawResult() { return result; }
6579 @SuppressWarnings("unchecked") public final void compute() {
6580 final ToLongFunction<? super K> transformer;
6581 final LongBinaryOperator reducer;
6582 if ((transformer = this.transformer) != null &&
6583 (reducer = this.reducer) != null) {
6584 long r = this.basis;
6585 for (int b; (b = preSplit()) > 0;)
6586 (rights = new MapReduceKeysToLongTask<K,V>
6587 (map, this, b, rights, transformer, r, reducer)).fork();
6588 K k;
6589 while ((k = advanceKey()) != null)
6590 r = reducer.applyAsLong(r, transformer.applyAsLong(k));
6591 result = r;
6592 CountedCompleter<?> c;
6593 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6594 MapReduceKeysToLongTask<K,V>
6595 t = (MapReduceKeysToLongTask<K,V>)c,
6596 s = t.rights;
6597 while (s != null) {
6598 t.result = reducer.applyAsLong(t.result, s.result);
6599 s = t.rights = s.nextRight;
6600 }
6601 }
6602 }
6603 }
6604 }
6605
6606 @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6607 extends Traverser<K,V,Long> {
6608 final ToLongFunction<? super V> transformer;
6609 final LongBinaryOperator reducer;
6610 final long basis;
6611 long result;
6612 MapReduceValuesToLongTask<K,V> rights, nextRight;
6613 MapReduceValuesToLongTask
6614 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6615 MapReduceValuesToLongTask<K,V> nextRight,
6616 ToLongFunction<? super V> transformer,
6617 long basis,
6618 LongBinaryOperator reducer) {
6619 super(m, p, b); this.nextRight = nextRight;
6620 this.transformer = transformer;
6621 this.basis = basis; this.reducer = reducer;
6622 }
6623 public final Long getRawResult() { return result; }
6624 @SuppressWarnings("unchecked") public final void compute() {
6625 final ToLongFunction<? super V> transformer;
6626 final LongBinaryOperator reducer;
6627 if ((transformer = this.transformer) != null &&
6628 (reducer = this.reducer) != null) {
6629 long r = this.basis;
6630 for (int b; (b = preSplit()) > 0;)
6631 (rights = new MapReduceValuesToLongTask<K,V>
6632 (map, this, b, rights, transformer, r, reducer)).fork();
6633 V v;
6634 while ((v = advanceValue()) != null)
6635 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6636 result = r;
6637 CountedCompleter<?> c;
6638 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6639 MapReduceValuesToLongTask<K,V>
6640 t = (MapReduceValuesToLongTask<K,V>)c,
6641 s = t.rights;
6642 while (s != null) {
6643 t.result = reducer.applyAsLong(t.result, s.result);
6644 s = t.rights = s.nextRight;
6645 }
6646 }
6647 }
6648 }
6649 }
6650
6651 @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6652 extends Traverser<K,V,Long> {
6653 final ToLongFunction<Map.Entry<K,V>> transformer;
6654 final LongBinaryOperator reducer;
6655 final long basis;
6656 long result;
6657 MapReduceEntriesToLongTask<K,V> rights, nextRight;
6658 MapReduceEntriesToLongTask
6659 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6660 MapReduceEntriesToLongTask<K,V> nextRight,
6661 ToLongFunction<Map.Entry<K,V>> transformer,
6662 long basis,
6663 LongBinaryOperator reducer) {
6664 super(m, p, b); this.nextRight = nextRight;
6665 this.transformer = transformer;
6666 this.basis = basis; this.reducer = reducer;
6667 }
6668 public final Long getRawResult() { return result; }
6669 @SuppressWarnings("unchecked") public final void compute() {
6670 final ToLongFunction<Map.Entry<K,V>> transformer;
6671 final LongBinaryOperator reducer;
6672 if ((transformer = this.transformer) != null &&
6673 (reducer = this.reducer) != null) {
6674 long r = this.basis;
6675 for (int b; (b = preSplit()) > 0;)
6676 (rights = new MapReduceEntriesToLongTask<K,V>
6677 (map, this, b, rights, transformer, r, reducer)).fork();
6678 V v;
6679 while ((v = advanceValue()) != null)
6680 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6681 result = r;
6682 CountedCompleter<?> c;
6683 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6684 MapReduceEntriesToLongTask<K,V>
6685 t = (MapReduceEntriesToLongTask<K,V>)c,
6686 s = t.rights;
6687 while (s != null) {
6688 t.result = reducer.applyAsLong(t.result, s.result);
6689 s = t.rights = s.nextRight;
6690 }
6691 }
6692 }
6693 }
6694 }
6695
6696 @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6697 extends Traverser<K,V,Long> {
6698 final ToLongBiFunction<? super K, ? super V> transformer;
6699 final LongBinaryOperator reducer;
6700 final long basis;
6701 long result;
6702 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6703 MapReduceMappingsToLongTask
6704 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6705 MapReduceMappingsToLongTask<K,V> nextRight,
6706 ToLongBiFunction<? super K, ? super V> transformer,
6707 long basis,
6708 LongBinaryOperator reducer) {
6709 super(m, p, b); this.nextRight = nextRight;
6710 this.transformer = transformer;
6711 this.basis = basis; this.reducer = reducer;
6712 }
6713 public final Long getRawResult() { return result; }
6714 @SuppressWarnings("unchecked") public final void compute() {
6715 final ToLongBiFunction<? super K, ? super V> transformer;
6716 final LongBinaryOperator reducer;
6717 if ((transformer = this.transformer) != null &&
6718 (reducer = this.reducer) != null) {
6719 long r = this.basis;
6720 for (int b; (b = preSplit()) > 0;)
6721 (rights = new MapReduceMappingsToLongTask<K,V>
6722 (map, this, b, rights, transformer, r, reducer)).fork();
6723 V v;
6724 while ((v = advanceValue()) != null)
6725 r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6726 result = r;
6727 CountedCompleter<?> c;
6728 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6729 MapReduceMappingsToLongTask<K,V>
6730 t = (MapReduceMappingsToLongTask<K,V>)c,
6731 s = t.rights;
6732 while (s != null) {
6733 t.result = reducer.applyAsLong(t.result, s.result);
6734 s = t.rights = s.nextRight;
6735 }
6736 }
6737 }
6738 }
6739 }
6740
6741 @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6742 extends Traverser<K,V,Integer> {
6743 final ToIntFunction<? super K> transformer;
6744 final IntBinaryOperator reducer;
6745 final int basis;
6746 int result;
6747 MapReduceKeysToIntTask<K,V> rights, nextRight;
6748 MapReduceKeysToIntTask
6749 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6750 MapReduceKeysToIntTask<K,V> nextRight,
6751 ToIntFunction<? super K> transformer,
6752 int basis,
6753 IntBinaryOperator reducer) {
6754 super(m, p, b); this.nextRight = nextRight;
6755 this.transformer = transformer;
6756 this.basis = basis; this.reducer = reducer;
6757 }
6758 public final Integer getRawResult() { return result; }
6759 @SuppressWarnings("unchecked") public final void compute() {
6760 final ToIntFunction<? super K> transformer;
6761 final IntBinaryOperator reducer;
6762 if ((transformer = this.transformer) != null &&
6763 (reducer = this.reducer) != null) {
6764 int r = this.basis;
6765 for (int b; (b = preSplit()) > 0;)
6766 (rights = new MapReduceKeysToIntTask<K,V>
6767 (map, this, b, rights, transformer, r, reducer)).fork();
6768 K k;
6769 while ((k = advanceKey()) != null)
6770 r = reducer.applyAsInt(r, transformer.applyAsInt(k));
6771 result = r;
6772 CountedCompleter<?> c;
6773 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6774 MapReduceKeysToIntTask<K,V>
6775 t = (MapReduceKeysToIntTask<K,V>)c,
6776 s = t.rights;
6777 while (s != null) {
6778 t.result = reducer.applyAsInt(t.result, s.result);
6779 s = t.rights = s.nextRight;
6780 }
6781 }
6782 }
6783 }
6784 }
6785
6786 @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6787 extends Traverser<K,V,Integer> {
6788 final ToIntFunction<? super V> transformer;
6789 final IntBinaryOperator reducer;
6790 final int basis;
6791 int result;
6792 MapReduceValuesToIntTask<K,V> rights, nextRight;
6793 MapReduceValuesToIntTask
6794 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6795 MapReduceValuesToIntTask<K,V> nextRight,
6796 ToIntFunction<? super V> transformer,
6797 int basis,
6798 IntBinaryOperator reducer) {
6799 super(m, p, b); this.nextRight = nextRight;
6800 this.transformer = transformer;
6801 this.basis = basis; this.reducer = reducer;
6802 }
6803 public final Integer getRawResult() { return result; }
6804 @SuppressWarnings("unchecked") public final void compute() {
6805 final ToIntFunction<? super V> transformer;
6806 final IntBinaryOperator reducer;
6807 if ((transformer = this.transformer) != null &&
6808 (reducer = this.reducer) != null) {
6809 int r = this.basis;
6810 for (int b; (b = preSplit()) > 0;)
6811 (rights = new MapReduceValuesToIntTask<K,V>
6812 (map, this, b, rights, transformer, r, reducer)).fork();
6813 V v;
6814 while ((v = advanceValue()) != null)
6815 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6816 result = r;
6817 CountedCompleter<?> c;
6818 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6819 MapReduceValuesToIntTask<K,V>
6820 t = (MapReduceValuesToIntTask<K,V>)c,
6821 s = t.rights;
6822 while (s != null) {
6823 t.result = reducer.applyAsInt(t.result, s.result);
6824 s = t.rights = s.nextRight;
6825 }
6826 }
6827 }
6828 }
6829 }
6830
6831 @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6832 extends Traverser<K,V,Integer> {
6833 final ToIntFunction<Map.Entry<K,V>> transformer;
6834 final IntBinaryOperator reducer;
6835 final int basis;
6836 int result;
6837 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6838 MapReduceEntriesToIntTask
6839 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6840 MapReduceEntriesToIntTask<K,V> nextRight,
6841 ToIntFunction<Map.Entry<K,V>> transformer,
6842 int basis,
6843 IntBinaryOperator reducer) {
6844 super(m, p, b); this.nextRight = nextRight;
6845 this.transformer = transformer;
6846 this.basis = basis; this.reducer = reducer;
6847 }
6848 public final Integer getRawResult() { return result; }
6849 @SuppressWarnings("unchecked") public final void compute() {
6850 final ToIntFunction<Map.Entry<K,V>> transformer;
6851 final IntBinaryOperator reducer;
6852 if ((transformer = this.transformer) != null &&
6853 (reducer = this.reducer) != null) {
6854 int r = this.basis;
6855 for (int b; (b = preSplit()) > 0;)
6856 (rights = new MapReduceEntriesToIntTask<K,V>
6857 (map, this, b, rights, transformer, r, reducer)).fork();
6858 V v;
6859 while ((v = advanceValue()) != null)
6860 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6861 v)));
6862 result = r;
6863 CountedCompleter<?> c;
6864 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6865 MapReduceEntriesToIntTask<K,V>
6866 t = (MapReduceEntriesToIntTask<K,V>)c,
6867 s = t.rights;
6868 while (s != null) {
6869 t.result = reducer.applyAsInt(t.result, s.result);
6870 s = t.rights = s.nextRight;
6871 }
6872 }
6873 }
6874 }
6875 }
6876
6877 @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6878 extends Traverser<K,V,Integer> {
6879 final ToIntBiFunction<? super K, ? super V> transformer;
6880 final IntBinaryOperator reducer;
6881 final int basis;
6882 int result;
6883 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6884 MapReduceMappingsToIntTask
6885 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6886 MapReduceMappingsToIntTask<K,V> nextRight,
6887 ToIntBiFunction<? super K, ? super V> transformer,
6888 int basis,
6889 IntBinaryOperator reducer) {
6890 super(m, p, b); this.nextRight = nextRight;
6891 this.transformer = transformer;
6892 this.basis = basis; this.reducer = reducer;
6893 }
6894 public final Integer getRawResult() { return result; }
6895 @SuppressWarnings("unchecked") public final void compute() {
6896 final ToIntBiFunction<? super K, ? super V> transformer;
6897 final IntBinaryOperator reducer;
6898 if ((transformer = this.transformer) != null &&
6899 (reducer = this.reducer) != null) {
6900 int r = this.basis;
6901 for (int b; (b = preSplit()) > 0;)
6902 (rights = new MapReduceMappingsToIntTask<K,V>
6903 (map, this, b, rights, transformer, r, reducer)).fork();
6904 V v;
6905 while ((v = advanceValue()) != null)
6906 r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6907 result = r;
6908 CountedCompleter<?> c;
6909 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6910 MapReduceMappingsToIntTask<K,V>
6911 t = (MapReduceMappingsToIntTask<K,V>)c,
6912 s = t.rights;
6913 while (s != null) {
6914 t.result = reducer.applyAsInt(t.result, s.result);
6915 s = t.rights = s.nextRight;
6916 }
6917 }
6918 }
6919 }
6920 }
6921
6922 // Unsafe mechanics
6923 private static final sun.misc.Unsafe U;
6924 private static final long SIZECTL;
6925 private static final long TRANSFERINDEX;
6926 private static final long TRANSFERORIGIN;
6927 private static final long BASECOUNT;
6928 private static final long CELLSBUSY;
6929 private static final long CELLVALUE;
6930 private static final long ABASE;
6931 private static final int ASHIFT;
6932
6933 static {
6934 try {
6935 U = sun.misc.Unsafe.getUnsafe();
6936 Class<?> k = ConcurrentHashMap.class;
6937 SIZECTL = U.objectFieldOffset
6938 (k.getDeclaredField("sizeCtl"));
6939 TRANSFERINDEX = U.objectFieldOffset
6940 (k.getDeclaredField("transferIndex"));
6941 TRANSFERORIGIN = U.objectFieldOffset
6942 (k.getDeclaredField("transferOrigin"));
6943 BASECOUNT = U.objectFieldOffset
6944 (k.getDeclaredField("baseCount"));
6945 CELLSBUSY = U.objectFieldOffset
6946 (k.getDeclaredField("cellsBusy"));
6947 Class<?> ck = Cell.class;
6948 CELLVALUE = U.objectFieldOffset
6949 (ck.getDeclaredField("value"));
6950 Class<?> sc = Node[].class;
6951 ABASE = U.arrayBaseOffset(sc);
6952 int scale = U.arrayIndexScale(sc);
6953 if ((scale & (scale - 1)) != 0)
6954 throw new Error("data type scale not a power of two");
6955 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6956 } catch (Exception e) {
6957 throw new Error(e);
6958 }
6959 }
6960
6961 }