ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.4
Committed: Mon Jan 14 07:15:18 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.3: +0 -7 lines
Log Message:
remove jdk8isms

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