ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.5
Committed: Thu Jan 17 14:12:56 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.4: +4 -1 lines
Log Message:
test conformance

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 if (key == null)
2838 throw new NullPointerException();
2839 return value != null && internalReplace(key, null, value) != null;
2840 }
2841
2842 /**
2843 * {@inheritDoc}
2844 *
2845 * @throws NullPointerException if any of the arguments are null
2846 */
2847 public boolean replace(K key, V oldValue, V newValue) {
2848 if (key == null || oldValue == null || newValue == null)
2849 throw new NullPointerException();
2850 return internalReplace(key, newValue, oldValue) != null;
2851 }
2852
2853 /**
2854 * {@inheritDoc}
2855 *
2856 * @return the previous value associated with the specified key,
2857 * or {@code null} if there was no mapping for the key
2858 * @throws NullPointerException if the specified key or value is null
2859 */
2860 public V replace(K key, V value) {
2861 if (key == null || value == null)
2862 throw new NullPointerException();
2863 return internalReplace(key, value, null);
2864 }
2865
2866 /**
2867 * Removes all of the mappings from this map.
2868 */
2869 public void clear() {
2870 internalClear();
2871 }
2872
2873 /**
2874 * Returns a {@link Set} view of the keys contained in this map.
2875 * The set is backed by the map, so changes to the map are
2876 * reflected in the set, and vice-versa.
2877 *
2878 * @return the set view
2879 */
2880 public KeySetView<K,V> keySet() {
2881 KeySetView<K,V> ks = keySet;
2882 return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2883 }
2884
2885 /**
2886 * Returns a {@link Set} view of the keys in this map, using the
2887 * given common mapped value for any additions (i.e., {@link
2888 * Collection#add} and {@link Collection#addAll}). This is of
2889 * course only appropriate if it is acceptable to use the same
2890 * value for all additions from this view.
2891 *
2892 * @param mappedValue the mapped value to use for any
2893 * additions.
2894 * @return the set view
2895 * @throws NullPointerException if the mappedValue is null
2896 */
2897 public KeySetView<K,V> keySet(V mappedValue) {
2898 if (mappedValue == null)
2899 throw new NullPointerException();
2900 return new KeySetView<K,V>(this, mappedValue);
2901 }
2902
2903 /**
2904 * Returns a {@link Collection} view of the values contained in this map.
2905 * The collection is backed by the map, so changes to the map are
2906 * reflected in the collection, and vice-versa.
2907 */
2908 public ValuesView<K,V> values() {
2909 ValuesView<K,V> vs = values;
2910 return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2911 }
2912
2913 /**
2914 * Returns a {@link Set} view of the mappings contained in this map.
2915 * The set is backed by the map, so changes to the map are
2916 * reflected in the set, and vice-versa. The set supports element
2917 * removal, which removes the corresponding mapping from the map,
2918 * via the {@code Iterator.remove}, {@code Set.remove},
2919 * {@code removeAll}, {@code retainAll}, and {@code clear}
2920 * operations. It does not support the {@code add} or
2921 * {@code addAll} operations.
2922 *
2923 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2924 * that will never throw {@link ConcurrentModificationException},
2925 * and guarantees to traverse elements as they existed upon
2926 * construction of the iterator, and may (but is not guaranteed to)
2927 * reflect any modifications subsequent to construction.
2928 */
2929 public Set<Map.Entry<K,V>> entrySet() {
2930 EntrySetView<K,V> es = entrySet;
2931 return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2932 }
2933
2934 /**
2935 * Returns an enumeration of the keys in this table.
2936 *
2937 * @return an enumeration of the keys in this table
2938 * @see #keySet()
2939 */
2940 public Enumeration<K> keys() {
2941 return new KeyIterator<K,V>(this);
2942 }
2943
2944 /**
2945 * Returns an enumeration of the values in this table.
2946 *
2947 * @return an enumeration of the values in this table
2948 * @see #values()
2949 */
2950 public Enumeration<V> elements() {
2951 return new ValueIterator<K,V>(this);
2952 }
2953
2954 /**
2955 * Returns a partitionable iterator of the keys in this map.
2956 *
2957 * @return a partitionable iterator of the keys in this map
2958 */
2959 public Spliterator<K> keySpliterator() {
2960 return new KeyIterator<K,V>(this);
2961 }
2962
2963 /**
2964 * Returns a partitionable iterator of the values in this map.
2965 *
2966 * @return a partitionable iterator of the values in this map
2967 */
2968 public Spliterator<V> valueSpliterator() {
2969 return new ValueIterator<K,V>(this);
2970 }
2971
2972 /**
2973 * Returns a partitionable iterator of the entries in this map.
2974 *
2975 * @return a partitionable iterator of the entries in this map
2976 */
2977 public Spliterator<Map.Entry<K,V>> entrySpliterator() {
2978 return new EntryIterator<K,V>(this);
2979 }
2980
2981 /**
2982 * Returns the hash code value for this {@link Map}, i.e.,
2983 * the sum of, for each key-value pair in the map,
2984 * {@code key.hashCode() ^ value.hashCode()}.
2985 *
2986 * @return the hash code value for this map
2987 */
2988 public int hashCode() {
2989 int h = 0;
2990 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2991 V v;
2992 while ((v = it.advance()) != null) {
2993 h += it.nextKey.hashCode() ^ v.hashCode();
2994 }
2995 return h;
2996 }
2997
2998 /**
2999 * Returns a string representation of this map. The string
3000 * representation consists of a list of key-value mappings (in no
3001 * particular order) enclosed in braces ("{@code {}}"). Adjacent
3002 * mappings are separated by the characters {@code ", "} (comma
3003 * and space). Each key-value mapping is rendered as the key
3004 * followed by an equals sign ("{@code =}") followed by the
3005 * associated value.
3006 *
3007 * @return a string representation of this map
3008 */
3009 public String toString() {
3010 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3011 StringBuilder sb = new StringBuilder();
3012 sb.append('{');
3013 V v;
3014 if ((v = it.advance()) != null) {
3015 for (;;) {
3016 Object k = it.nextKey;
3017 sb.append(k == this ? "(this Map)" : k);
3018 sb.append('=');
3019 sb.append(v == this ? "(this Map)" : v);
3020 if ((v = it.advance()) == null)
3021 break;
3022 sb.append(',').append(' ');
3023 }
3024 }
3025 return sb.append('}').toString();
3026 }
3027
3028 /**
3029 * Compares the specified object with this map for equality.
3030 * Returns {@code true} if the given object is a map with the same
3031 * mappings as this map. This operation may return misleading
3032 * results if either map is concurrently modified during execution
3033 * of this method.
3034 *
3035 * @param o object to be compared for equality with this map
3036 * @return {@code true} if the specified object is equal to this map
3037 */
3038 public boolean equals(Object o) {
3039 if (o != this) {
3040 if (!(o instanceof Map))
3041 return false;
3042 Map<?,?> m = (Map<?,?>) o;
3043 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3044 V val;
3045 while ((val = it.advance()) != null) {
3046 Object v = m.get(it.nextKey);
3047 if (v == null || (v != val && !v.equals(val)))
3048 return false;
3049 }
3050 for (Map.Entry<?,?> e : m.entrySet()) {
3051 Object mk, mv, v;
3052 if ((mk = e.getKey()) == null ||
3053 (mv = e.getValue()) == null ||
3054 (v = internalGet(mk)) == null ||
3055 (mv != v && !mv.equals(v)))
3056 return false;
3057 }
3058 }
3059 return true;
3060 }
3061
3062 /* ----------------Iterators -------------- */
3063
3064 @SuppressWarnings("serial") static final class KeyIterator<K,V>
3065 extends Traverser<K,V,Object>
3066 implements Spliterator<K>, Enumeration<K> {
3067 KeyIterator(ConcurrentHashMap<K, V> map) { super(map); }
3068 KeyIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3069 super(map, it, -1);
3070 }
3071 public KeyIterator<K,V> split() {
3072 if (nextKey != null)
3073 throw new IllegalStateException();
3074 return new KeyIterator<K,V>(map, this);
3075 }
3076 @SuppressWarnings("unchecked") public final K next() {
3077 if (nextVal == null && advance() == null)
3078 throw new NoSuchElementException();
3079 Object k = nextKey;
3080 nextVal = null;
3081 return (K) k;
3082 }
3083
3084 public final K nextElement() { return next(); }
3085 }
3086
3087 @SuppressWarnings("serial") static final class ValueIterator<K,V>
3088 extends Traverser<K,V,Object>
3089 implements Spliterator<V>, Enumeration<V> {
3090 ValueIterator(ConcurrentHashMap<K, V> map) { super(map); }
3091 ValueIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3092 super(map, it, -1);
3093 }
3094 public ValueIterator<K,V> split() {
3095 if (nextKey != null)
3096 throw new IllegalStateException();
3097 return new ValueIterator<K,V>(map, this);
3098 }
3099
3100 public final V next() {
3101 V v;
3102 if ((v = nextVal) == null && (v = advance()) == null)
3103 throw new NoSuchElementException();
3104 nextVal = null;
3105 return v;
3106 }
3107
3108 public final V nextElement() { return next(); }
3109 }
3110
3111 @SuppressWarnings("serial") static final class EntryIterator<K,V>
3112 extends Traverser<K,V,Object>
3113 implements Spliterator<Map.Entry<K,V>> {
3114 EntryIterator(ConcurrentHashMap<K, V> map) { super(map); }
3115 EntryIterator(ConcurrentHashMap<K, V> map, Traverser<K,V,Object> it) {
3116 super(map, it, -1);
3117 }
3118 public EntryIterator<K,V> split() {
3119 if (nextKey != null)
3120 throw new IllegalStateException();
3121 return new EntryIterator<K,V>(map, this);
3122 }
3123
3124 @SuppressWarnings("unchecked") public final Map.Entry<K,V> next() {
3125 V v;
3126 if ((v = nextVal) == null && (v = advance()) == null)
3127 throw new NoSuchElementException();
3128 Object k = nextKey;
3129 nextVal = null;
3130 return new MapEntry<K,V>((K)k, v, map);
3131 }
3132 }
3133
3134 /**
3135 * Exported Entry for iterators
3136 */
3137 static final class MapEntry<K,V> implements Map.Entry<K, V> {
3138 final K key; // non-null
3139 V val; // non-null
3140 final ConcurrentHashMap<K, V> map;
3141 MapEntry(K key, V val, ConcurrentHashMap<K, V> map) {
3142 this.key = key;
3143 this.val = val;
3144 this.map = map;
3145 }
3146 public final K getKey() { return key; }
3147 public final V getValue() { return val; }
3148 public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
3149 public final String toString(){ return key + "=" + val; }
3150
3151 public final boolean equals(Object o) {
3152 Object k, v; Map.Entry<?,?> e;
3153 return ((o instanceof Map.Entry) &&
3154 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3155 (v = e.getValue()) != null &&
3156 (k == key || k.equals(key)) &&
3157 (v == val || v.equals(val)));
3158 }
3159
3160 /**
3161 * Sets our entry's value and writes through to the map. The
3162 * value to return is somewhat arbitrary here. Since we do not
3163 * necessarily track asynchronous changes, the most recent
3164 * "previous" value could be different from what we return (or
3165 * could even have been removed in which case the put will
3166 * re-establish). We do not and cannot guarantee more.
3167 */
3168 public final V setValue(V value) {
3169 if (value == null) throw new NullPointerException();
3170 V v = val;
3171 val = value;
3172 map.put(key, value);
3173 return v;
3174 }
3175 }
3176
3177 /**
3178 * Returns exportable snapshot entry for the given key and value
3179 * when write-through can't or shouldn't be used.
3180 */
3181 static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3182 return new AbstractMap.SimpleEntry<K,V>(k, v);
3183 }
3184
3185 /* ---------------- Serialization Support -------------- */
3186
3187 /**
3188 * Stripped-down version of helper class used in previous version,
3189 * declared for the sake of serialization compatibility
3190 */
3191 static class Segment<K,V> implements Serializable {
3192 private static final long serialVersionUID = 2249069246763182397L;
3193 final float loadFactor;
3194 Segment(float lf) { this.loadFactor = lf; }
3195 }
3196
3197 /**
3198 * Saves the state of the {@code ConcurrentHashMap} instance to a
3199 * stream (i.e., serializes it).
3200 * @param s the stream
3201 * @serialData
3202 * the key (Object) and value (Object)
3203 * for each key-value mapping, followed by a null pair.
3204 * The key-value mappings are emitted in no particular order.
3205 */
3206 @SuppressWarnings("unchecked") private void writeObject
3207 (java.io.ObjectOutputStream s)
3208 throws java.io.IOException {
3209 if (segments == null) { // for serialization compatibility
3210 segments = (Segment<K,V>[])
3211 new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3212 for (int i = 0; i < segments.length; ++i)
3213 segments[i] = new Segment<K,V>(LOAD_FACTOR);
3214 }
3215 s.defaultWriteObject();
3216 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3217 V v;
3218 while ((v = it.advance()) != null) {
3219 s.writeObject(it.nextKey);
3220 s.writeObject(v);
3221 }
3222 s.writeObject(null);
3223 s.writeObject(null);
3224 segments = null; // throw away
3225 }
3226
3227 /**
3228 * Reconstitutes the instance from a stream (that is, deserializes it).
3229 * @param s the stream
3230 */
3231 @SuppressWarnings("unchecked") private void readObject
3232 (java.io.ObjectInputStream s)
3233 throws java.io.IOException, ClassNotFoundException {
3234 s.defaultReadObject();
3235 this.segments = null; // unneeded
3236
3237 // Create all nodes, then place in table once size is known
3238 long size = 0L;
3239 Node<V> p = null;
3240 for (;;) {
3241 K k = (K) s.readObject();
3242 V v = (V) s.readObject();
3243 if (k != null && v != null) {
3244 int h = spread(k.hashCode());
3245 p = new Node<V>(h, k, v, p);
3246 ++size;
3247 }
3248 else
3249 break;
3250 }
3251 if (p != null) {
3252 boolean init = false;
3253 int n;
3254 if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3255 n = MAXIMUM_CAPACITY;
3256 else {
3257 int sz = (int)size;
3258 n = tableSizeFor(sz + (sz >>> 1) + 1);
3259 }
3260 int sc = sizeCtl;
3261 boolean collide = false;
3262 if (n > sc &&
3263 U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3264 try {
3265 if (table == null) {
3266 init = true;
3267 @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3268 Node<V>[] tab = (Node<V>[])rt;
3269 int mask = n - 1;
3270 while (p != null) {
3271 int j = p.hash & mask;
3272 Node<V> next = p.next;
3273 Node<V> q = p.next = tabAt(tab, j);
3274 setTabAt(tab, j, p);
3275 if (!collide && q != null && q.hash == p.hash)
3276 collide = true;
3277 p = next;
3278 }
3279 table = tab;
3280 addCount(size, -1);
3281 sc = n - (n >>> 2);
3282 }
3283 } finally {
3284 sizeCtl = sc;
3285 }
3286 if (collide) { // rescan and convert to TreeBins
3287 Node<V>[] tab = table;
3288 for (int i = 0; i < tab.length; ++i) {
3289 int c = 0;
3290 for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3291 if (++c > TREE_THRESHOLD &&
3292 (e.key instanceof Comparable)) {
3293 replaceWithTreeBin(tab, i, e.key);
3294 break;
3295 }
3296 }
3297 }
3298 }
3299 }
3300 if (!init) { // Can only happen if unsafely published.
3301 while (p != null) {
3302 internalPut((K)p.key, p.val, false);
3303 p = p.next;
3304 }
3305 }
3306 }
3307 }
3308
3309 // -------------------------------------------------------
3310
3311 // Sams
3312 /** Interface describing a void action of one argument */
3313 public interface Action<A> { void apply(A a); }
3314 /** Interface describing a void action of two arguments */
3315 public interface BiAction<A,B> { void apply(A a, B b); }
3316 /** Interface describing a function of one argument */
3317 public interface Fun<A,T> { T apply(A a); }
3318 /** Interface describing a function of two arguments */
3319 public interface BiFun<A,B,T> { T apply(A a, B b); }
3320 /** Interface describing a function of no arguments */
3321 public interface Generator<T> { T apply(); }
3322 /** Interface describing a function mapping its argument to a double */
3323 public interface ObjectToDouble<A> { double apply(A a); }
3324 /** Interface describing a function mapping its argument to a long */
3325 public interface ObjectToLong<A> { long apply(A a); }
3326 /** Interface describing a function mapping its argument to an int */
3327 public interface ObjectToInt<A> {int apply(A a); }
3328 /** Interface describing a function mapping two arguments to a double */
3329 public interface ObjectByObjectToDouble<A,B> { double apply(A a, B b); }
3330 /** Interface describing a function mapping two arguments to a long */
3331 public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
3332 /** Interface describing a function mapping two arguments to an int */
3333 public interface ObjectByObjectToInt<A,B> {int apply(A a, B b); }
3334 /** Interface describing a function mapping a double to a double */
3335 public interface DoubleToDouble { double apply(double a); }
3336 /** Interface describing a function mapping a long to a long */
3337 public interface LongToLong { long apply(long a); }
3338 /** Interface describing a function mapping an int to an int */
3339 public interface IntToInt { int apply(int a); }
3340 /** Interface describing a function mapping two doubles to a double */
3341 public interface DoubleByDoubleToDouble { double apply(double a, double b); }
3342 /** Interface describing a function mapping two longs to a long */
3343 public interface LongByLongToLong { long apply(long a, long b); }
3344 /** Interface describing a function mapping two ints to an int */
3345 public interface IntByIntToInt { int apply(int a, int b); }
3346
3347
3348 // -------------------------------------------------------
3349
3350 // Sequential bulk operations
3351
3352 /**
3353 * Performs the given action for each (key, value).
3354 *
3355 * @param action the action
3356 */
3357 @SuppressWarnings("unchecked") public void forEachSequentially
3358 (BiAction<K,V> action) {
3359 if (action == null) throw new NullPointerException();
3360 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3361 V v;
3362 while ((v = it.advance()) != null)
3363 action.apply((K)it.nextKey, v);
3364 }
3365
3366 /**
3367 * Performs the given action for each non-null transformation
3368 * of each (key, value).
3369 *
3370 * @param transformer a function returning the transformation
3371 * for an element, or null of there is no transformation (in
3372 * which case the action is not applied).
3373 * @param action the action
3374 */
3375 @SuppressWarnings("unchecked") public <U> void forEachSequentially
3376 (BiFun<? super K, ? super V, ? extends U> transformer,
3377 Action<U> action) {
3378 if (transformer == null || action == null)
3379 throw new NullPointerException();
3380 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3381 V v; U u;
3382 while ((v = it.advance()) != null) {
3383 if ((u = transformer.apply((K)it.nextKey, v)) != null)
3384 action.apply(u);
3385 }
3386 }
3387
3388 /**
3389 * Returns a non-null result from applying the given search
3390 * function on each (key, value), or null if none.
3391 *
3392 * @param searchFunction a function returning a non-null
3393 * result on success, else null
3394 * @return a non-null result from applying the given search
3395 * function on each (key, value), or null if none
3396 */
3397 @SuppressWarnings("unchecked") public <U> U searchSequentially
3398 (BiFun<? super K, ? super V, ? extends U> searchFunction) {
3399 if (searchFunction == null) throw new NullPointerException();
3400 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3401 V v; U u;
3402 while ((v = it.advance()) != null) {
3403 if ((u = searchFunction.apply((K)it.nextKey, v)) != null)
3404 return u;
3405 }
3406 return null;
3407 }
3408
3409 /**
3410 * Returns the result of accumulating the given transformation
3411 * of all (key, value) pairs using the given reducer to
3412 * combine values, or null if none.
3413 *
3414 * @param transformer a function returning the transformation
3415 * for an element, or null of there is no transformation (in
3416 * which case it is not combined).
3417 * @param reducer a commutative associative combining function
3418 * @return the result of accumulating the given transformation
3419 * of all (key, value) pairs
3420 */
3421 @SuppressWarnings("unchecked") public <U> U reduceSequentially
3422 (BiFun<? super K, ? super V, ? extends U> transformer,
3423 BiFun<? super U, ? super U, ? extends U> reducer) {
3424 if (transformer == null || reducer == null)
3425 throw new NullPointerException();
3426 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3427 U r = null, u; V v;
3428 while ((v = it.advance()) != null) {
3429 if ((u = transformer.apply((K)it.nextKey, v)) != null)
3430 r = (r == null) ? u : reducer.apply(r, u);
3431 }
3432 return r;
3433 }
3434
3435 /**
3436 * Returns the result of accumulating the given transformation
3437 * of all (key, value) pairs using the given reducer to
3438 * combine values, and the given basis as an identity value.
3439 *
3440 * @param transformer a function returning the transformation
3441 * for an element
3442 * @param basis the identity (initial default value) for the reduction
3443 * @param reducer a commutative associative combining function
3444 * @return the result of accumulating the given transformation
3445 * of all (key, value) pairs
3446 */
3447 @SuppressWarnings("unchecked") public double reduceToDoubleSequentially
3448 (ObjectByObjectToDouble<? super K, ? super V> transformer,
3449 double basis,
3450 DoubleByDoubleToDouble reducer) {
3451 if (transformer == null || reducer == null)
3452 throw new NullPointerException();
3453 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3454 double r = basis; V v;
3455 while ((v = it.advance()) != null)
3456 r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3457 return r;
3458 }
3459
3460 /**
3461 * Returns the result of accumulating the given transformation
3462 * of all (key, value) pairs using the given reducer to
3463 * combine values, and the given basis as an identity value.
3464 *
3465 * @param transformer a function returning the transformation
3466 * for an element
3467 * @param basis the identity (initial default value) for the reduction
3468 * @param reducer a commutative associative combining function
3469 * @return the result of accumulating the given transformation
3470 * of all (key, value) pairs
3471 */
3472 @SuppressWarnings("unchecked") public long reduceToLongSequentially
3473 (ObjectByObjectToLong<? super K, ? super V> transformer,
3474 long basis,
3475 LongByLongToLong reducer) {
3476 if (transformer == null || reducer == null)
3477 throw new NullPointerException();
3478 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3479 long r = basis; V v;
3480 while ((v = it.advance()) != null)
3481 r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3482 return r;
3483 }
3484
3485 /**
3486 * Returns the result of accumulating the given transformation
3487 * of all (key, value) pairs using the given reducer to
3488 * combine values, and the given basis as an identity value.
3489 *
3490 * @param transformer a function returning the transformation
3491 * for an element
3492 * @param basis the identity (initial default value) for the reduction
3493 * @param reducer a commutative associative combining function
3494 * @return the result of accumulating the given transformation
3495 * of all (key, value) pairs
3496 */
3497 @SuppressWarnings("unchecked") public int reduceToIntSequentially
3498 (ObjectByObjectToInt<? super K, ? super V> transformer,
3499 int basis,
3500 IntByIntToInt reducer) {
3501 if (transformer == null || reducer == null)
3502 throw new NullPointerException();
3503 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3504 int r = basis; V v;
3505 while ((v = it.advance()) != null)
3506 r = reducer.apply(r, transformer.apply((K)it.nextKey, v));
3507 return r;
3508 }
3509
3510 /**
3511 * Performs the given action for each key.
3512 *
3513 * @param action the action
3514 */
3515 @SuppressWarnings("unchecked") public void forEachKeySequentially
3516 (Action<K> action) {
3517 if (action == null) throw new NullPointerException();
3518 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3519 while (it.advance() != null)
3520 action.apply((K)it.nextKey);
3521 }
3522
3523 /**
3524 * Performs the given action for each non-null transformation
3525 * of each key.
3526 *
3527 * @param transformer a function returning the transformation
3528 * for an element, or null of there is no transformation (in
3529 * which case the action is not applied).
3530 * @param action the action
3531 */
3532 @SuppressWarnings("unchecked") public <U> void forEachKeySequentially
3533 (Fun<? super K, ? extends U> transformer,
3534 Action<U> action) {
3535 if (transformer == null || action == null)
3536 throw new NullPointerException();
3537 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3538 U u;
3539 while (it.advance() != null) {
3540 if ((u = transformer.apply((K)it.nextKey)) != null)
3541 action.apply(u);
3542 }
3543 ForkJoinTasks.forEachKey
3544 (this, transformer, action).invoke();
3545 }
3546
3547 /**
3548 * Returns a non-null result from applying the given search
3549 * function on each key, or null if none.
3550 *
3551 * @param searchFunction a function returning a non-null
3552 * result on success, else null
3553 * @return a non-null result from applying the given search
3554 * function on each key, or null if none
3555 */
3556 @SuppressWarnings("unchecked") public <U> U searchKeysSequentially
3557 (Fun<? super K, ? extends U> searchFunction) {
3558 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3559 U u;
3560 while (it.advance() != null) {
3561 if ((u = searchFunction.apply((K)it.nextKey)) != null)
3562 return u;
3563 }
3564 return null;
3565 }
3566
3567 /**
3568 * Returns the result of accumulating all keys using the given
3569 * reducer to combine values, or null if none.
3570 *
3571 * @param reducer a commutative associative combining function
3572 * @return the result of accumulating all keys using the given
3573 * reducer to combine values, or null if none
3574 */
3575 @SuppressWarnings("unchecked") public K reduceKeysSequentially
3576 (BiFun<? super K, ? super K, ? extends K> reducer) {
3577 if (reducer == null) throw new NullPointerException();
3578 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3579 K r = null;
3580 while (it.advance() != null) {
3581 K u = (K)it.nextKey;
3582 r = (r == null) ? u : reducer.apply(r, u);
3583 }
3584 return r;
3585 }
3586
3587 /**
3588 * Returns the result of accumulating the given transformation
3589 * of all keys using the given reducer to combine values, or
3590 * null if none.
3591 *
3592 * @param transformer a function returning the transformation
3593 * for an element, or null of there is no transformation (in
3594 * which case it is not combined).
3595 * @param reducer a commutative associative combining function
3596 * @return the result of accumulating the given transformation
3597 * of all keys
3598 */
3599 @SuppressWarnings("unchecked") public <U> U reduceKeysSequentially
3600 (Fun<? super K, ? extends U> transformer,
3601 BiFun<? super U, ? super U, ? extends U> reducer) {
3602 if (transformer == null || reducer == null)
3603 throw new NullPointerException();
3604 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3605 U r = null, u;
3606 while (it.advance() != null) {
3607 if ((u = transformer.apply((K)it.nextKey)) != null)
3608 r = (r == null) ? u : reducer.apply(r, u);
3609 }
3610 return r;
3611 }
3612
3613 /**
3614 * Returns the result of accumulating the given transformation
3615 * of all keys using the given reducer to combine values, and
3616 * the given basis as an identity value.
3617 *
3618 * @param transformer a function returning the transformation
3619 * for an element
3620 * @param basis the identity (initial default value) for the reduction
3621 * @param reducer a commutative associative combining function
3622 * @return the result of accumulating the given transformation
3623 * of all keys
3624 */
3625 @SuppressWarnings("unchecked") public double reduceKeysToDoubleSequentially
3626 (ObjectToDouble<? super K> transformer,
3627 double basis,
3628 DoubleByDoubleToDouble reducer) {
3629 if (transformer == null || reducer == null)
3630 throw new NullPointerException();
3631 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3632 double r = basis;
3633 while (it.advance() != null)
3634 r = reducer.apply(r, transformer.apply((K)it.nextKey));
3635 return r;
3636 }
3637
3638 /**
3639 * Returns the result of accumulating the given transformation
3640 * of all keys using the given reducer to combine values, and
3641 * the given basis as an identity value.
3642 *
3643 * @param transformer a function returning the transformation
3644 * for an element
3645 * @param basis the identity (initial default value) for the reduction
3646 * @param reducer a commutative associative combining function
3647 * @return the result of accumulating the given transformation
3648 * of all keys
3649 */
3650 @SuppressWarnings("unchecked") public long reduceKeysToLongSequentially
3651 (ObjectToLong<? super K> transformer,
3652 long basis,
3653 LongByLongToLong reducer) {
3654 if (transformer == null || reducer == null)
3655 throw new NullPointerException();
3656 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3657 long r = basis;
3658 while (it.advance() != null)
3659 r = reducer.apply(r, transformer.apply((K)it.nextKey));
3660 return r;
3661 }
3662
3663 /**
3664 * Returns the result of accumulating the given transformation
3665 * of all keys using the given reducer to combine values, and
3666 * the given basis as an identity value.
3667 *
3668 * @param transformer a function returning the transformation
3669 * for an element
3670 * @param basis the identity (initial default value) for the reduction
3671 * @param reducer a commutative associative combining function
3672 * @return the result of accumulating the given transformation
3673 * of all keys
3674 */
3675 @SuppressWarnings("unchecked") public int reduceKeysToIntSequentially
3676 (ObjectToInt<? super K> transformer,
3677 int basis,
3678 IntByIntToInt reducer) {
3679 if (transformer == null || reducer == null)
3680 throw new NullPointerException();
3681 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3682 int r = basis;
3683 while (it.advance() != null)
3684 r = reducer.apply(r, transformer.apply((K)it.nextKey));
3685 return r;
3686 }
3687
3688 /**
3689 * Performs the given action for each value.
3690 *
3691 * @param action the action
3692 */
3693 public void forEachValueSequentially(Action<V> action) {
3694 if (action == null) throw new NullPointerException();
3695 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3696 V v;
3697 while ((v = it.advance()) != null)
3698 action.apply(v);
3699 }
3700
3701 /**
3702 * Performs the given action for each non-null transformation
3703 * of each value.
3704 *
3705 * @param transformer a function returning the transformation
3706 * for an element, or null of there is no transformation (in
3707 * which case the action is not applied).
3708 */
3709 public <U> void forEachValueSequentially
3710 (Fun<? super V, ? extends U> transformer,
3711 Action<U> action) {
3712 if (transformer == null || action == null)
3713 throw new NullPointerException();
3714 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3715 V v; U u;
3716 while ((v = it.advance()) != null) {
3717 if ((u = transformer.apply(v)) != null)
3718 action.apply(u);
3719 }
3720 }
3721
3722 /**
3723 * Returns a non-null result from applying the given search
3724 * function on each value, or null if none.
3725 *
3726 * @param searchFunction a function returning a non-null
3727 * result on success, else null
3728 * @return a non-null result from applying the given search
3729 * function on each value, or null if none
3730 */
3731 public <U> U searchValuesSequentially
3732 (Fun<? super V, ? extends U> searchFunction) {
3733 if (searchFunction == null) throw new NullPointerException();
3734 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3735 V v; U u;
3736 while ((v = it.advance()) != null) {
3737 if ((u = searchFunction.apply(v)) != null)
3738 return u;
3739 }
3740 return null;
3741 }
3742
3743 /**
3744 * Returns the result of accumulating all values using the
3745 * given reducer to combine values, or null if none.
3746 *
3747 * @param reducer a commutative associative combining function
3748 * @return the result of accumulating all values
3749 */
3750 public V reduceValuesSequentially
3751 (BiFun<? super V, ? super V, ? extends V> reducer) {
3752 if (reducer == null) throw new NullPointerException();
3753 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3754 V r = null; V v;
3755 while ((v = it.advance()) != null)
3756 r = (r == null) ? v : reducer.apply(r, v);
3757 return r;
3758 }
3759
3760 /**
3761 * Returns the result of accumulating the given transformation
3762 * of all values using the given reducer to combine values, or
3763 * null if none.
3764 *
3765 * @param transformer a function returning the transformation
3766 * for an element, or null of there is no transformation (in
3767 * which case it is not combined).
3768 * @param reducer a commutative associative combining function
3769 * @return the result of accumulating the given transformation
3770 * of all values
3771 */
3772 public <U> U reduceValuesSequentially
3773 (Fun<? super V, ? extends U> transformer,
3774 BiFun<? super U, ? super U, ? extends U> reducer) {
3775 if (transformer == null || reducer == null)
3776 throw new NullPointerException();
3777 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3778 U r = null, u; V v;
3779 while ((v = it.advance()) != null) {
3780 if ((u = transformer.apply(v)) != null)
3781 r = (r == null) ? u : reducer.apply(r, u);
3782 }
3783 return r;
3784 }
3785
3786 /**
3787 * Returns the result of accumulating the given transformation
3788 * of all values using the given reducer to combine values,
3789 * and the given basis as an identity value.
3790 *
3791 * @param transformer a function returning the transformation
3792 * for an element
3793 * @param basis the identity (initial default value) for the reduction
3794 * @param reducer a commutative associative combining function
3795 * @return the result of accumulating the given transformation
3796 * of all values
3797 */
3798 public double reduceValuesToDoubleSequentially
3799 (ObjectToDouble<? super V> transformer,
3800 double basis,
3801 DoubleByDoubleToDouble reducer) {
3802 if (transformer == null || reducer == null)
3803 throw new NullPointerException();
3804 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3805 double r = basis; V v;
3806 while ((v = it.advance()) != null)
3807 r = reducer.apply(r, transformer.apply(v));
3808 return r;
3809 }
3810
3811 /**
3812 * Returns the result of accumulating the given transformation
3813 * of all values using the given reducer to combine values,
3814 * and the given basis as an identity value.
3815 *
3816 * @param transformer a function returning the transformation
3817 * for an element
3818 * @param basis the identity (initial default value) for the reduction
3819 * @param reducer a commutative associative combining function
3820 * @return the result of accumulating the given transformation
3821 * of all values
3822 */
3823 public long reduceValuesToLongSequentially
3824 (ObjectToLong<? super V> transformer,
3825 long basis,
3826 LongByLongToLong reducer) {
3827 if (transformer == null || reducer == null)
3828 throw new NullPointerException();
3829 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3830 long r = basis; V v;
3831 while ((v = it.advance()) != null)
3832 r = reducer.apply(r, transformer.apply(v));
3833 return r;
3834 }
3835
3836 /**
3837 * Returns the result of accumulating the given transformation
3838 * of all values using the given reducer to combine values,
3839 * and the given basis as an identity value.
3840 *
3841 * @param transformer a function returning the transformation
3842 * for an element
3843 * @param basis the identity (initial default value) for the reduction
3844 * @param reducer a commutative associative combining function
3845 * @return the result of accumulating the given transformation
3846 * of all values
3847 */
3848 public int reduceValuesToIntSequentially
3849 (ObjectToInt<? super V> transformer,
3850 int basis,
3851 IntByIntToInt reducer) {
3852 if (transformer == null || reducer == null)
3853 throw new NullPointerException();
3854 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3855 int r = basis; V v;
3856 while ((v = it.advance()) != null)
3857 r = reducer.apply(r, transformer.apply(v));
3858 return r;
3859 }
3860
3861 /**
3862 * Performs the given action for each entry.
3863 *
3864 * @param action the action
3865 */
3866 @SuppressWarnings("unchecked") public void forEachEntrySequentially
3867 (Action<Map.Entry<K,V>> action) {
3868 if (action == null) throw new NullPointerException();
3869 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3870 V v;
3871 while ((v = it.advance()) != null)
3872 action.apply(entryFor((K)it.nextKey, v));
3873 }
3874
3875 /**
3876 * Performs the given action for each non-null transformation
3877 * of each entry.
3878 *
3879 * @param transformer a function returning the transformation
3880 * for an element, or null of there is no transformation (in
3881 * which case the action is not applied).
3882 * @param action the action
3883 */
3884 @SuppressWarnings("unchecked") public <U> void forEachEntrySequentially
3885 (Fun<Map.Entry<K,V>, ? extends U> transformer,
3886 Action<U> action) {
3887 if (transformer == null || action == null)
3888 throw new NullPointerException();
3889 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3890 V v; U u;
3891 while ((v = it.advance()) != null) {
3892 if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3893 action.apply(u);
3894 }
3895 }
3896
3897 /**
3898 * Returns a non-null result from applying the given search
3899 * function on each entry, or null if none.
3900 *
3901 * @param searchFunction a function returning a non-null
3902 * result on success, else null
3903 * @return a non-null result from applying the given search
3904 * function on each entry, or null if none
3905 */
3906 @SuppressWarnings("unchecked") public <U> U searchEntriesSequentially
3907 (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
3908 if (searchFunction == null) throw new NullPointerException();
3909 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3910 V v; U u;
3911 while ((v = it.advance()) != null) {
3912 if ((u = searchFunction.apply(entryFor((K)it.nextKey, v))) != null)
3913 return u;
3914 }
3915 return null;
3916 }
3917
3918 /**
3919 * Returns the result of accumulating all entries using the
3920 * given reducer to combine values, or null if none.
3921 *
3922 * @param reducer a commutative associative combining function
3923 * @return the result of accumulating all entries
3924 */
3925 @SuppressWarnings("unchecked") public Map.Entry<K,V> reduceEntriesSequentially
3926 (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3927 if (reducer == null) throw new NullPointerException();
3928 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3929 Map.Entry<K,V> r = null; V v;
3930 while ((v = it.advance()) != null) {
3931 Map.Entry<K,V> u = entryFor((K)it.nextKey, v);
3932 r = (r == null) ? u : reducer.apply(r, u);
3933 }
3934 return r;
3935 }
3936
3937 /**
3938 * Returns the result of accumulating the given transformation
3939 * of all entries using the given reducer to combine values,
3940 * or null if none.
3941 *
3942 * @param transformer a function returning the transformation
3943 * for an element, or null of there is no transformation (in
3944 * which case it is not combined).
3945 * @param reducer a commutative associative combining function
3946 * @return the result of accumulating the given transformation
3947 * of all entries
3948 */
3949 @SuppressWarnings("unchecked") public <U> U reduceEntriesSequentially
3950 (Fun<Map.Entry<K,V>, ? extends U> transformer,
3951 BiFun<? super U, ? super U, ? extends U> reducer) {
3952 if (transformer == null || reducer == null)
3953 throw new NullPointerException();
3954 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3955 U r = null, u; V v;
3956 while ((v = it.advance()) != null) {
3957 if ((u = transformer.apply(entryFor((K)it.nextKey, v))) != null)
3958 r = (r == null) ? u : reducer.apply(r, u);
3959 }
3960 return r;
3961 }
3962
3963 /**
3964 * Returns the result of accumulating the given transformation
3965 * of all entries using the given reducer to combine values,
3966 * and the given basis as an identity value.
3967 *
3968 * @param transformer a function returning the transformation
3969 * for an element
3970 * @param basis the identity (initial default value) for the reduction
3971 * @param reducer a commutative associative combining function
3972 * @return the result of accumulating the given transformation
3973 * of all entries
3974 */
3975 @SuppressWarnings("unchecked") public double reduceEntriesToDoubleSequentially
3976 (ObjectToDouble<Map.Entry<K,V>> transformer,
3977 double basis,
3978 DoubleByDoubleToDouble reducer) {
3979 if (transformer == null || reducer == null)
3980 throw new NullPointerException();
3981 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3982 double r = basis; V v;
3983 while ((v = it.advance()) != null)
3984 r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
3985 return r;
3986 }
3987
3988 /**
3989 * Returns the result of accumulating the given transformation
3990 * of all entries using the given reducer to combine values,
3991 * and the given basis as an identity value.
3992 *
3993 * @param transformer a function returning the transformation
3994 * for an element
3995 * @param basis the identity (initial default value) for the reduction
3996 * @param reducer a commutative associative combining function
3997 * @return the result of accumulating the given transformation
3998 * of all entries
3999 */
4000 @SuppressWarnings("unchecked") public long reduceEntriesToLongSequentially
4001 (ObjectToLong<Map.Entry<K,V>> transformer,
4002 long basis,
4003 LongByLongToLong reducer) {
4004 if (transformer == null || reducer == null)
4005 throw new NullPointerException();
4006 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4007 long r = basis; V v;
4008 while ((v = it.advance()) != null)
4009 r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4010 return r;
4011 }
4012
4013 /**
4014 * Returns the result of accumulating the given transformation
4015 * of all entries using the given reducer to combine values,
4016 * and the given basis as an identity value.
4017 *
4018 * @param transformer a function returning the transformation
4019 * for an element
4020 * @param basis the identity (initial default value) for the reduction
4021 * @param reducer a commutative associative combining function
4022 * @return the result of accumulating the given transformation
4023 * of all entries
4024 */
4025 @SuppressWarnings("unchecked") public int reduceEntriesToIntSequentially
4026 (ObjectToInt<Map.Entry<K,V>> transformer,
4027 int basis,
4028 IntByIntToInt reducer) {
4029 if (transformer == null || reducer == null)
4030 throw new NullPointerException();
4031 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4032 int r = basis; V v;
4033 while ((v = it.advance()) != null)
4034 r = reducer.apply(r, transformer.apply(entryFor((K)it.nextKey, v)));
4035 return r;
4036 }
4037
4038 // Parallel bulk operations
4039
4040 /**
4041 * Performs the given action for each (key, value).
4042 *
4043 * @param action the action
4044 */
4045 public void forEachInParallel(BiAction<K,V> action) {
4046 ForkJoinTasks.forEach
4047 (this, action).invoke();
4048 }
4049
4050 /**
4051 * Performs the given action for each non-null transformation
4052 * of each (key, value).
4053 *
4054 * @param transformer a function returning the transformation
4055 * for an element, or null of there is no transformation (in
4056 * which case the action is not applied).
4057 * @param action the action
4058 */
4059 public <U> void forEachInParallel
4060 (BiFun<? super K, ? super V, ? extends U> transformer,
4061 Action<U> action) {
4062 ForkJoinTasks.forEach
4063 (this, transformer, action).invoke();
4064 }
4065
4066 /**
4067 * Returns a non-null result from applying the given search
4068 * function on each (key, value), or null if none. Upon
4069 * success, further element processing is suppressed and the
4070 * results of any other parallel invocations of the search
4071 * function are ignored.
4072 *
4073 * @param searchFunction a function returning a non-null
4074 * result on success, else null
4075 * @return a non-null result from applying the given search
4076 * function on each (key, value), or null if none
4077 */
4078 public <U> U searchInParallel
4079 (BiFun<? super K, ? super V, ? extends U> searchFunction) {
4080 return ForkJoinTasks.search
4081 (this, searchFunction).invoke();
4082 }
4083
4084 /**
4085 * Returns the result of accumulating the given transformation
4086 * of all (key, value) pairs using the given reducer to
4087 * combine values, or null if none.
4088 *
4089 * @param transformer a function returning the transformation
4090 * for an element, or null of there is no transformation (in
4091 * which case it is not combined).
4092 * @param reducer a commutative associative combining function
4093 * @return the result of accumulating the given transformation
4094 * of all (key, value) pairs
4095 */
4096 public <U> U reduceInParallel
4097 (BiFun<? super K, ? super V, ? extends U> transformer,
4098 BiFun<? super U, ? super U, ? extends U> reducer) {
4099 return ForkJoinTasks.reduce
4100 (this, transformer, reducer).invoke();
4101 }
4102
4103 /**
4104 * Returns the result of accumulating the given transformation
4105 * of all (key, value) pairs using the given reducer to
4106 * combine values, and the given basis as an identity value.
4107 *
4108 * @param transformer a function returning the transformation
4109 * for an element
4110 * @param basis the identity (initial default value) for the reduction
4111 * @param reducer a commutative associative combining function
4112 * @return the result of accumulating the given transformation
4113 * of all (key, value) pairs
4114 */
4115 public double reduceToDoubleInParallel
4116 (ObjectByObjectToDouble<? super K, ? super V> transformer,
4117 double basis,
4118 DoubleByDoubleToDouble reducer) {
4119 return ForkJoinTasks.reduceToDouble
4120 (this, transformer, basis, reducer).invoke();
4121 }
4122
4123 /**
4124 * Returns the result of accumulating the given transformation
4125 * of all (key, value) pairs using the given reducer to
4126 * combine values, and the given basis as an identity value.
4127 *
4128 * @param transformer a function returning the transformation
4129 * for an element
4130 * @param basis the identity (initial default value) for the reduction
4131 * @param reducer a commutative associative combining function
4132 * @return the result of accumulating the given transformation
4133 * of all (key, value) pairs
4134 */
4135 public long reduceToLongInParallel
4136 (ObjectByObjectToLong<? super K, ? super V> transformer,
4137 long basis,
4138 LongByLongToLong reducer) {
4139 return ForkJoinTasks.reduceToLong
4140 (this, transformer, basis, reducer).invoke();
4141 }
4142
4143 /**
4144 * Returns the result of accumulating the given transformation
4145 * of all (key, value) pairs using the given reducer to
4146 * combine values, and the given basis as an identity value.
4147 *
4148 * @param transformer a function returning the transformation
4149 * for an element
4150 * @param basis the identity (initial default value) for the reduction
4151 * @param reducer a commutative associative combining function
4152 * @return the result of accumulating the given transformation
4153 * of all (key, value) pairs
4154 */
4155 public int reduceToIntInParallel
4156 (ObjectByObjectToInt<? super K, ? super V> transformer,
4157 int basis,
4158 IntByIntToInt reducer) {
4159 return ForkJoinTasks.reduceToInt
4160 (this, transformer, basis, reducer).invoke();
4161 }
4162
4163 /**
4164 * Performs the given action for each key.
4165 *
4166 * @param action the action
4167 */
4168 public void forEachKeyInParallel(Action<K> action) {
4169 ForkJoinTasks.forEachKey
4170 (this, action).invoke();
4171 }
4172
4173 /**
4174 * Performs the given action for each non-null transformation
4175 * of each key.
4176 *
4177 * @param transformer a function returning the transformation
4178 * for an element, or null of there is no transformation (in
4179 * which case the action is not applied).
4180 * @param action the action
4181 */
4182 public <U> void forEachKeyInParallel
4183 (Fun<? super K, ? extends U> transformer,
4184 Action<U> action) {
4185 ForkJoinTasks.forEachKey
4186 (this, transformer, action).invoke();
4187 }
4188
4189 /**
4190 * Returns a non-null result from applying the given search
4191 * function on each key, or null if none. Upon success,
4192 * further element processing is suppressed and the results of
4193 * any other parallel invocations of the search function are
4194 * ignored.
4195 *
4196 * @param searchFunction a function returning a non-null
4197 * result on success, else null
4198 * @return a non-null result from applying the given search
4199 * function on each key, or null if none
4200 */
4201 public <U> U searchKeysInParallel
4202 (Fun<? super K, ? extends U> searchFunction) {
4203 return ForkJoinTasks.searchKeys
4204 (this, searchFunction).invoke();
4205 }
4206
4207 /**
4208 * Returns the result of accumulating all keys using the given
4209 * reducer to combine values, or null if none.
4210 *
4211 * @param reducer a commutative associative combining function
4212 * @return the result of accumulating all keys using the given
4213 * reducer to combine values, or null if none
4214 */
4215 public K reduceKeysInParallel
4216 (BiFun<? super K, ? super K, ? extends K> reducer) {
4217 return ForkJoinTasks.reduceKeys
4218 (this, reducer).invoke();
4219 }
4220
4221 /**
4222 * Returns the result of accumulating the given transformation
4223 * of all keys using the given reducer to combine values, or
4224 * null if none.
4225 *
4226 * @param transformer a function returning the transformation
4227 * for an element, or null of there is no transformation (in
4228 * which case it is not combined).
4229 * @param reducer a commutative associative combining function
4230 * @return the result of accumulating the given transformation
4231 * of all keys
4232 */
4233 public <U> U reduceKeysInParallel
4234 (Fun<? super K, ? extends U> transformer,
4235 BiFun<? super U, ? super U, ? extends U> reducer) {
4236 return ForkJoinTasks.reduceKeys
4237 (this, transformer, reducer).invoke();
4238 }
4239
4240 /**
4241 * Returns the result of accumulating the given transformation
4242 * of all keys using the given reducer to combine values, and
4243 * the given basis as an identity value.
4244 *
4245 * @param transformer a function returning the transformation
4246 * for an element
4247 * @param basis the identity (initial default value) for the reduction
4248 * @param reducer a commutative associative combining function
4249 * @return the result of accumulating the given transformation
4250 * of all keys
4251 */
4252 public double reduceKeysToDoubleInParallel
4253 (ObjectToDouble<? super K> transformer,
4254 double basis,
4255 DoubleByDoubleToDouble reducer) {
4256 return ForkJoinTasks.reduceKeysToDouble
4257 (this, transformer, basis, reducer).invoke();
4258 }
4259
4260 /**
4261 * Returns the result of accumulating the given transformation
4262 * of all keys using the given reducer to combine values, and
4263 * the given basis as an identity value.
4264 *
4265 * @param transformer a function returning the transformation
4266 * for an element
4267 * @param basis the identity (initial default value) for the reduction
4268 * @param reducer a commutative associative combining function
4269 * @return the result of accumulating the given transformation
4270 * of all keys
4271 */
4272 public long reduceKeysToLongInParallel
4273 (ObjectToLong<? super K> transformer,
4274 long basis,
4275 LongByLongToLong reducer) {
4276 return ForkJoinTasks.reduceKeysToLong
4277 (this, transformer, basis, reducer).invoke();
4278 }
4279
4280 /**
4281 * Returns the result of accumulating the given transformation
4282 * of all keys using the given reducer to combine values, and
4283 * the given basis as an identity value.
4284 *
4285 * @param transformer a function returning the transformation
4286 * for an element
4287 * @param basis the identity (initial default value) for the reduction
4288 * @param reducer a commutative associative combining function
4289 * @return the result of accumulating the given transformation
4290 * of all keys
4291 */
4292 public int reduceKeysToIntInParallel
4293 (ObjectToInt<? super K> transformer,
4294 int basis,
4295 IntByIntToInt reducer) {
4296 return ForkJoinTasks.reduceKeysToInt
4297 (this, transformer, basis, reducer).invoke();
4298 }
4299
4300 /**
4301 * Performs the given action for each value.
4302 *
4303 * @param action the action
4304 */
4305 public void forEachValueInParallel(Action<V> action) {
4306 ForkJoinTasks.forEachValue
4307 (this, action).invoke();
4308 }
4309
4310 /**
4311 * Performs the given action for each non-null transformation
4312 * of each value.
4313 *
4314 * @param transformer a function returning the transformation
4315 * for an element, or null of there is no transformation (in
4316 * which case the action is not applied).
4317 */
4318 public <U> void forEachValueInParallel
4319 (Fun<? super V, ? extends U> transformer,
4320 Action<U> action) {
4321 ForkJoinTasks.forEachValue
4322 (this, transformer, action).invoke();
4323 }
4324
4325 /**
4326 * Returns a non-null result from applying the given search
4327 * function on each value, or null if none. Upon success,
4328 * further element processing is suppressed and the results of
4329 * any other parallel invocations of the search function are
4330 * ignored.
4331 *
4332 * @param searchFunction a function returning a non-null
4333 * result on success, else null
4334 * @return a non-null result from applying the given search
4335 * function on each value, or null if none
4336 */
4337 public <U> U searchValuesInParallel
4338 (Fun<? super V, ? extends U> searchFunction) {
4339 return ForkJoinTasks.searchValues
4340 (this, searchFunction).invoke();
4341 }
4342
4343 /**
4344 * Returns the result of accumulating all values using the
4345 * given reducer to combine values, or null if none.
4346 *
4347 * @param reducer a commutative associative combining function
4348 * @return the result of accumulating all values
4349 */
4350 public V reduceValuesInParallel
4351 (BiFun<? super V, ? super V, ? extends V> reducer) {
4352 return ForkJoinTasks.reduceValues
4353 (this, reducer).invoke();
4354 }
4355
4356 /**
4357 * Returns the result of accumulating the given transformation
4358 * of all values using the given reducer to combine values, or
4359 * null if none.
4360 *
4361 * @param transformer a function returning the transformation
4362 * for an element, or null of there is no transformation (in
4363 * which case it is not combined).
4364 * @param reducer a commutative associative combining function
4365 * @return the result of accumulating the given transformation
4366 * of all values
4367 */
4368 public <U> U reduceValuesInParallel
4369 (Fun<? super V, ? extends U> transformer,
4370 BiFun<? super U, ? super U, ? extends U> reducer) {
4371 return ForkJoinTasks.reduceValues
4372 (this, transformer, reducer).invoke();
4373 }
4374
4375 /**
4376 * Returns the result of accumulating the given transformation
4377 * of all values using the given reducer to combine values,
4378 * and the given basis as an identity value.
4379 *
4380 * @param transformer a function returning the transformation
4381 * for an element
4382 * @param basis the identity (initial default value) for the reduction
4383 * @param reducer a commutative associative combining function
4384 * @return the result of accumulating the given transformation
4385 * of all values
4386 */
4387 public double reduceValuesToDoubleInParallel
4388 (ObjectToDouble<? super V> transformer,
4389 double basis,
4390 DoubleByDoubleToDouble reducer) {
4391 return ForkJoinTasks.reduceValuesToDouble
4392 (this, transformer, basis, reducer).invoke();
4393 }
4394
4395 /**
4396 * Returns the result of accumulating the given transformation
4397 * of all values using the given reducer to combine values,
4398 * and the given basis as an identity value.
4399 *
4400 * @param transformer a function returning the transformation
4401 * for an element
4402 * @param basis the identity (initial default value) for the reduction
4403 * @param reducer a commutative associative combining function
4404 * @return the result of accumulating the given transformation
4405 * of all values
4406 */
4407 public long reduceValuesToLongInParallel
4408 (ObjectToLong<? super V> transformer,
4409 long basis,
4410 LongByLongToLong reducer) {
4411 return ForkJoinTasks.reduceValuesToLong
4412 (this, transformer, basis, reducer).invoke();
4413 }
4414
4415 /**
4416 * Returns the result of accumulating the given transformation
4417 * of all values using the given reducer to combine values,
4418 * and the given basis as an identity value.
4419 *
4420 * @param transformer a function returning the transformation
4421 * for an element
4422 * @param basis the identity (initial default value) for the reduction
4423 * @param reducer a commutative associative combining function
4424 * @return the result of accumulating the given transformation
4425 * of all values
4426 */
4427 public int reduceValuesToIntInParallel
4428 (ObjectToInt<? super V> transformer,
4429 int basis,
4430 IntByIntToInt reducer) {
4431 return ForkJoinTasks.reduceValuesToInt
4432 (this, transformer, basis, reducer).invoke();
4433 }
4434
4435 /**
4436 * Performs the given action for each entry.
4437 *
4438 * @param action the action
4439 */
4440 public void forEachEntryInParallel(Action<Map.Entry<K,V>> action) {
4441 ForkJoinTasks.forEachEntry
4442 (this, action).invoke();
4443 }
4444
4445 /**
4446 * Performs the given action for each non-null transformation
4447 * of each entry.
4448 *
4449 * @param transformer a function returning the transformation
4450 * for an element, or null of there is no transformation (in
4451 * which case the action is not applied).
4452 * @param action the action
4453 */
4454 public <U> void forEachEntryInParallel
4455 (Fun<Map.Entry<K,V>, ? extends U> transformer,
4456 Action<U> action) {
4457 ForkJoinTasks.forEachEntry
4458 (this, transformer, action).invoke();
4459 }
4460
4461 /**
4462 * Returns a non-null result from applying the given search
4463 * function on each entry, or null if none. Upon success,
4464 * further element processing is suppressed and the results of
4465 * any other parallel invocations of the search function are
4466 * ignored.
4467 *
4468 * @param searchFunction a function returning a non-null
4469 * result on success, else null
4470 * @return a non-null result from applying the given search
4471 * function on each entry, or null if none
4472 */
4473 public <U> U searchEntriesInParallel
4474 (Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
4475 return ForkJoinTasks.searchEntries
4476 (this, searchFunction).invoke();
4477 }
4478
4479 /**
4480 * Returns the result of accumulating all entries using the
4481 * given reducer to combine values, or null if none.
4482 *
4483 * @param reducer a commutative associative combining function
4484 * @return the result of accumulating all entries
4485 */
4486 public Map.Entry<K,V> reduceEntriesInParallel
4487 (BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4488 return ForkJoinTasks.reduceEntries
4489 (this, reducer).invoke();
4490 }
4491
4492 /**
4493 * Returns the result of accumulating the given transformation
4494 * of all entries using the given reducer to combine values,
4495 * or null if none.
4496 *
4497 * @param transformer a function returning the transformation
4498 * for an element, or null of there is no transformation (in
4499 * which case it is not combined).
4500 * @param reducer a commutative associative combining function
4501 * @return the result of accumulating the given transformation
4502 * of all entries
4503 */
4504 public <U> U reduceEntriesInParallel
4505 (Fun<Map.Entry<K,V>, ? extends U> transformer,
4506 BiFun<? super U, ? super U, ? extends U> reducer) {
4507 return ForkJoinTasks.reduceEntries
4508 (this, transformer, reducer).invoke();
4509 }
4510
4511 /**
4512 * Returns the result of accumulating the given transformation
4513 * of all entries using the given reducer to combine values,
4514 * and the given basis as an identity value.
4515 *
4516 * @param transformer a function returning the transformation
4517 * for an element
4518 * @param basis the identity (initial default value) for the reduction
4519 * @param reducer a commutative associative combining function
4520 * @return the result of accumulating the given transformation
4521 * of all entries
4522 */
4523 public double reduceEntriesToDoubleInParallel
4524 (ObjectToDouble<Map.Entry<K,V>> transformer,
4525 double basis,
4526 DoubleByDoubleToDouble reducer) {
4527 return ForkJoinTasks.reduceEntriesToDouble
4528 (this, transformer, basis, reducer).invoke();
4529 }
4530
4531 /**
4532 * Returns the result of accumulating the given transformation
4533 * of all entries using the given reducer to combine values,
4534 * and the given basis as an identity value.
4535 *
4536 * @param transformer a function returning the transformation
4537 * for an element
4538 * @param basis the identity (initial default value) for the reduction
4539 * @param reducer a commutative associative combining function
4540 * @return the result of accumulating the given transformation
4541 * of all entries
4542 */
4543 public long reduceEntriesToLongInParallel
4544 (ObjectToLong<Map.Entry<K,V>> transformer,
4545 long basis,
4546 LongByLongToLong reducer) {
4547 return ForkJoinTasks.reduceEntriesToLong
4548 (this, transformer, basis, reducer).invoke();
4549 }
4550
4551 /**
4552 * Returns the result of accumulating the given transformation
4553 * of all entries using the given reducer to combine values,
4554 * and the given basis as an identity value.
4555 *
4556 * @param transformer a function returning the transformation
4557 * for an element
4558 * @param basis the identity (initial default value) for the reduction
4559 * @param reducer a commutative associative combining function
4560 * @return the result of accumulating the given transformation
4561 * of all entries
4562 */
4563 public int reduceEntriesToIntInParallel
4564 (ObjectToInt<Map.Entry<K,V>> transformer,
4565 int basis,
4566 IntByIntToInt reducer) {
4567 return ForkJoinTasks.reduceEntriesToInt
4568 (this, transformer, basis, reducer).invoke();
4569 }
4570
4571
4572 /* ----------------Views -------------- */
4573
4574 /**
4575 * Base class for views.
4576 */
4577 static abstract class CHMView<K, V> implements java.io.Serializable {
4578 private static final long serialVersionUID = 7249069246763182397L;
4579 final ConcurrentHashMap<K, V> map;
4580 CHMView(ConcurrentHashMap<K, V> map) { this.map = map; }
4581
4582 /**
4583 * Returns the map backing this view.
4584 *
4585 * @return the map backing this view
4586 */
4587 public ConcurrentHashMap<K,V> getMap() { return map; }
4588
4589 public final int size() { return map.size(); }
4590 public final boolean isEmpty() { return map.isEmpty(); }
4591 public final void clear() { map.clear(); }
4592
4593 // implementations below rely on concrete classes supplying these
4594 abstract public Iterator<?> iterator();
4595 abstract public boolean contains(Object o);
4596 abstract public boolean remove(Object o);
4597
4598 private static final String oomeMsg = "Required array size too large";
4599
4600 public final Object[] toArray() {
4601 long sz = map.mappingCount();
4602 if (sz > (long)(MAX_ARRAY_SIZE))
4603 throw new OutOfMemoryError(oomeMsg);
4604 int n = (int)sz;
4605 Object[] r = new Object[n];
4606 int i = 0;
4607 Iterator<?> it = iterator();
4608 while (it.hasNext()) {
4609 if (i == n) {
4610 if (n >= MAX_ARRAY_SIZE)
4611 throw new OutOfMemoryError(oomeMsg);
4612 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4613 n = MAX_ARRAY_SIZE;
4614 else
4615 n += (n >>> 1) + 1;
4616 r = Arrays.copyOf(r, n);
4617 }
4618 r[i++] = it.next();
4619 }
4620 return (i == n) ? r : Arrays.copyOf(r, i);
4621 }
4622
4623 @SuppressWarnings("unchecked") public final <T> T[] toArray(T[] a) {
4624 long sz = map.mappingCount();
4625 if (sz > (long)(MAX_ARRAY_SIZE))
4626 throw new OutOfMemoryError(oomeMsg);
4627 int m = (int)sz;
4628 T[] r = (a.length >= m) ? a :
4629 (T[])java.lang.reflect.Array
4630 .newInstance(a.getClass().getComponentType(), m);
4631 int n = r.length;
4632 int i = 0;
4633 Iterator<?> it = iterator();
4634 while (it.hasNext()) {
4635 if (i == n) {
4636 if (n >= MAX_ARRAY_SIZE)
4637 throw new OutOfMemoryError(oomeMsg);
4638 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4639 n = MAX_ARRAY_SIZE;
4640 else
4641 n += (n >>> 1) + 1;
4642 r = Arrays.copyOf(r, n);
4643 }
4644 r[i++] = (T)it.next();
4645 }
4646 if (a == r && i < n) {
4647 r[i] = null; // null-terminate
4648 return r;
4649 }
4650 return (i == n) ? r : Arrays.copyOf(r, i);
4651 }
4652
4653 public final int hashCode() {
4654 int h = 0;
4655 for (Iterator<?> it = iterator(); it.hasNext();)
4656 h += it.next().hashCode();
4657 return h;
4658 }
4659
4660 public final String toString() {
4661 StringBuilder sb = new StringBuilder();
4662 sb.append('[');
4663 Iterator<?> it = iterator();
4664 if (it.hasNext()) {
4665 for (;;) {
4666 Object e = it.next();
4667 sb.append(e == this ? "(this Collection)" : e);
4668 if (!it.hasNext())
4669 break;
4670 sb.append(',').append(' ');
4671 }
4672 }
4673 return sb.append(']').toString();
4674 }
4675
4676 public final boolean containsAll(Collection<?> c) {
4677 if (c != this) {
4678 for (Iterator<?> it = c.iterator(); it.hasNext();) {
4679 Object e = it.next();
4680 if (e == null || !contains(e))
4681 return false;
4682 }
4683 }
4684 return true;
4685 }
4686
4687 public final boolean removeAll(Collection<?> c) {
4688 boolean modified = false;
4689 for (Iterator<?> it = iterator(); it.hasNext();) {
4690 if (c.contains(it.next())) {
4691 it.remove();
4692 modified = true;
4693 }
4694 }
4695 return modified;
4696 }
4697
4698 public final boolean retainAll(Collection<?> c) {
4699 boolean modified = false;
4700 for (Iterator<?> it = iterator(); it.hasNext();) {
4701 if (!c.contains(it.next())) {
4702 it.remove();
4703 modified = true;
4704 }
4705 }
4706 return modified;
4707 }
4708
4709 }
4710
4711 /**
4712 * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4713 * which additions may optionally be enabled by mapping to a
4714 * common value. This class cannot be directly instantiated. See
4715 * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
4716 * {@link #newKeySet(int)}.
4717 */
4718 public static class KeySetView<K,V> extends CHMView<K,V>
4719 implements Set<K>, java.io.Serializable {
4720 private static final long serialVersionUID = 7249069246763182397L;
4721 private final V value;
4722 KeySetView(ConcurrentHashMap<K, V> map, V value) { // non-public
4723 super(map);
4724 this.value = value;
4725 }
4726
4727 /**
4728 * Returns the default mapped value for additions,
4729 * or {@code null} if additions are not supported.
4730 *
4731 * @return the default mapped value for additions, or {@code null}
4732 * if not supported.
4733 */
4734 public V getMappedValue() { return value; }
4735
4736 // implement Set API
4737
4738 public boolean contains(Object o) { return map.containsKey(o); }
4739 public boolean remove(Object o) { return map.remove(o) != null; }
4740
4741 /**
4742 * Returns a "weakly consistent" iterator that will never
4743 * throw {@link ConcurrentModificationException}, and
4744 * guarantees to traverse elements as they existed upon
4745 * construction of the iterator, and may (but is not
4746 * guaranteed to) reflect any modifications subsequent to
4747 * construction.
4748 *
4749 * @return an iterator over the keys of this map
4750 */
4751 public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4752 public boolean add(K e) {
4753 V v;
4754 if ((v = value) == null)
4755 throw new UnsupportedOperationException();
4756 if (e == null)
4757 throw new NullPointerException();
4758 return map.internalPut(e, v, true) == null;
4759 }
4760 public boolean addAll(Collection<? extends K> c) {
4761 boolean added = false;
4762 V v;
4763 if ((v = value) == null)
4764 throw new UnsupportedOperationException();
4765 for (K e : c) {
4766 if (e == null)
4767 throw new NullPointerException();
4768 if (map.internalPut(e, v, true) == null)
4769 added = true;
4770 }
4771 return added;
4772 }
4773 public boolean equals(Object o) {
4774 Set<?> c;
4775 return ((o instanceof Set) &&
4776 ((c = (Set<?>)o) == this ||
4777 (containsAll(c) && c.containsAll(this))));
4778 }
4779 }
4780
4781 /**
4782 * A view of a ConcurrentHashMap as a {@link Collection} of
4783 * values, in which additions are disabled. This class cannot be
4784 * directly instantiated. See {@link #values},
4785 *
4786 * <p>The view's {@code iterator} is a "weakly consistent" iterator
4787 * that will never throw {@link ConcurrentModificationException},
4788 * and guarantees to traverse elements as they existed upon
4789 * construction of the iterator, and may (but is not guaranteed to)
4790 * reflect any modifications subsequent to construction.
4791 */
4792 public static final class ValuesView<K,V> extends CHMView<K,V>
4793 implements Collection<V> {
4794 ValuesView(ConcurrentHashMap<K, V> map) { super(map); }
4795 public final boolean contains(Object o) { return map.containsValue(o); }
4796 public final boolean remove(Object o) {
4797 if (o != null) {
4798 Iterator<V> it = new ValueIterator<K,V>(map);
4799 while (it.hasNext()) {
4800 if (o.equals(it.next())) {
4801 it.remove();
4802 return true;
4803 }
4804 }
4805 }
4806 return false;
4807 }
4808
4809 /**
4810 * Returns a "weakly consistent" iterator that will never
4811 * throw {@link ConcurrentModificationException}, and
4812 * guarantees to traverse elements as they existed upon
4813 * construction of the iterator, and may (but is not
4814 * guaranteed to) reflect any modifications subsequent to
4815 * construction.
4816 *
4817 * @return an iterator over the values of this map
4818 */
4819 public final Iterator<V> iterator() {
4820 return new ValueIterator<K,V>(map);
4821 }
4822 public final boolean add(V e) {
4823 throw new UnsupportedOperationException();
4824 }
4825 public final boolean addAll(Collection<? extends V> c) {
4826 throw new UnsupportedOperationException();
4827 }
4828
4829 }
4830
4831 /**
4832 * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4833 * entries. This class cannot be directly instantiated. See
4834 * {@link #entrySet}.
4835 */
4836 public static final class EntrySetView<K,V> extends CHMView<K,V>
4837 implements Set<Map.Entry<K,V>> {
4838 EntrySetView(ConcurrentHashMap<K, V> map) { super(map); }
4839 public final boolean contains(Object o) {
4840 Object k, v, r; Map.Entry<?,?> e;
4841 return ((o instanceof Map.Entry) &&
4842 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4843 (r = map.get(k)) != null &&
4844 (v = e.getValue()) != null &&
4845 (v == r || v.equals(r)));
4846 }
4847 public final boolean remove(Object o) {
4848 Object k, v; Map.Entry<?,?> e;
4849 return ((o instanceof Map.Entry) &&
4850 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4851 (v = e.getValue()) != null &&
4852 map.remove(k, v));
4853 }
4854
4855 /**
4856 * Returns a "weakly consistent" iterator that will never
4857 * throw {@link ConcurrentModificationException}, and
4858 * guarantees to traverse elements as they existed upon
4859 * construction of the iterator, and may (but is not
4860 * guaranteed to) reflect any modifications subsequent to
4861 * construction.
4862 *
4863 * @return an iterator over the entries of this map
4864 */
4865 public final Iterator<Map.Entry<K,V>> iterator() {
4866 return new EntryIterator<K,V>(map);
4867 }
4868
4869 public final boolean add(Entry<K,V> e) {
4870 K key = e.getKey();
4871 V value = e.getValue();
4872 if (key == null || value == null)
4873 throw new NullPointerException();
4874 return map.internalPut(key, value, false) == null;
4875 }
4876 public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4877 boolean added = false;
4878 for (Entry<K,V> e : c) {
4879 if (add(e))
4880 added = true;
4881 }
4882 return added;
4883 }
4884 public boolean equals(Object o) {
4885 Set<?> c;
4886 return ((o instanceof Set) &&
4887 ((c = (Set<?>)o) == this ||
4888 (containsAll(c) && c.containsAll(this))));
4889 }
4890 }
4891
4892 // ---------------------------------------------------------------------
4893
4894 /**
4895 * Predefined tasks for performing bulk parallel operations on
4896 * ConcurrentHashMaps. These tasks follow the forms and rules used
4897 * for bulk operations. Each method has the same name, but returns
4898 * a task rather than invoking it. These methods may be useful in
4899 * custom applications such as submitting a task without waiting
4900 * for completion, using a custom pool, or combining with other
4901 * tasks.
4902 */
4903 public static class ForkJoinTasks {
4904 private ForkJoinTasks() {}
4905
4906 /**
4907 * Returns a task that when invoked, performs the given
4908 * action for each (key, value)
4909 *
4910 * @param map the map
4911 * @param action the action
4912 * @return the task
4913 */
4914 public static <K,V> ForkJoinTask<Void> forEach
4915 (ConcurrentHashMap<K,V> map,
4916 BiAction<K,V> action) {
4917 if (action == null) throw new NullPointerException();
4918 return new ForEachMappingTask<K,V>(map, null, -1, action);
4919 }
4920
4921 /**
4922 * Returns a task that when invoked, performs the given
4923 * action for each non-null transformation of each (key, value)
4924 *
4925 * @param map the map
4926 * @param transformer a function returning the transformation
4927 * for an element, or null if there is no transformation (in
4928 * which case the action is not applied)
4929 * @param action the action
4930 * @return the task
4931 */
4932 public static <K,V,U> ForkJoinTask<Void> forEach
4933 (ConcurrentHashMap<K,V> map,
4934 BiFun<? super K, ? super V, ? extends U> transformer,
4935 Action<U> action) {
4936 if (transformer == null || action == null)
4937 throw new NullPointerException();
4938 return new ForEachTransformedMappingTask<K,V,U>
4939 (map, null, -1, transformer, action);
4940 }
4941
4942 /**
4943 * Returns a task that when invoked, returns a non-null result
4944 * from applying the given search function on each (key,
4945 * value), or null if none. Upon success, further element
4946 * processing is suppressed and the results of any other
4947 * parallel invocations of the search function are ignored.
4948 *
4949 * @param map the map
4950 * @param searchFunction a function returning a non-null
4951 * result on success, else null
4952 * @return the task
4953 */
4954 public static <K,V,U> ForkJoinTask<U> search
4955 (ConcurrentHashMap<K,V> map,
4956 BiFun<? super K, ? super V, ? extends U> searchFunction) {
4957 if (searchFunction == null) throw new NullPointerException();
4958 return new SearchMappingsTask<K,V,U>
4959 (map, null, -1, searchFunction,
4960 new AtomicReference<U>());
4961 }
4962
4963 /**
4964 * Returns a task that when invoked, returns the result of
4965 * accumulating the given transformation of all (key, value) pairs
4966 * using the given reducer to combine values, or null if none.
4967 *
4968 * @param map the map
4969 * @param transformer a function returning the transformation
4970 * for an element, or null if there is no transformation (in
4971 * which case it is not combined).
4972 * @param reducer a commutative associative combining function
4973 * @return the task
4974 */
4975 public static <K,V,U> ForkJoinTask<U> reduce
4976 (ConcurrentHashMap<K,V> map,
4977 BiFun<? super K, ? super V, ? extends U> transformer,
4978 BiFun<? super U, ? super U, ? extends U> reducer) {
4979 if (transformer == null || reducer == null)
4980 throw new NullPointerException();
4981 return new MapReduceMappingsTask<K,V,U>
4982 (map, null, -1, null, transformer, reducer);
4983 }
4984
4985 /**
4986 * Returns a task that when invoked, returns the result of
4987 * accumulating the given transformation of all (key, value) pairs
4988 * using the given reducer to combine values, and the given
4989 * basis as an identity value.
4990 *
4991 * @param map the map
4992 * @param transformer a function returning the transformation
4993 * for an element
4994 * @param basis the identity (initial default value) for the reduction
4995 * @param reducer a commutative associative combining function
4996 * @return the task
4997 */
4998 public static <K,V> ForkJoinTask<Double> reduceToDouble
4999 (ConcurrentHashMap<K,V> map,
5000 ObjectByObjectToDouble<? super K, ? super V> transformer,
5001 double basis,
5002 DoubleByDoubleToDouble reducer) {
5003 if (transformer == null || reducer == null)
5004 throw new NullPointerException();
5005 return new MapReduceMappingsToDoubleTask<K,V>
5006 (map, null, -1, null, transformer, basis, reducer);
5007 }
5008
5009 /**
5010 * Returns a task that when invoked, returns the result of
5011 * accumulating the given transformation of all (key, value) pairs
5012 * using the given reducer to combine values, and the given
5013 * basis as an identity value.
5014 *
5015 * @param map the map
5016 * @param transformer a function returning the transformation
5017 * for an element
5018 * @param basis the identity (initial default value) for the reduction
5019 * @param reducer a commutative associative combining function
5020 * @return the task
5021 */
5022 public static <K,V> ForkJoinTask<Long> reduceToLong
5023 (ConcurrentHashMap<K,V> map,
5024 ObjectByObjectToLong<? super K, ? super V> transformer,
5025 long basis,
5026 LongByLongToLong reducer) {
5027 if (transformer == null || reducer == null)
5028 throw new NullPointerException();
5029 return new MapReduceMappingsToLongTask<K,V>
5030 (map, null, -1, null, transformer, basis, reducer);
5031 }
5032
5033 /**
5034 * Returns a task that when invoked, returns the result of
5035 * accumulating the given transformation of all (key, value) pairs
5036 * using the given reducer to combine values, and the given
5037 * basis as an identity value.
5038 *
5039 * @param transformer a function returning the transformation
5040 * for an element
5041 * @param basis the identity (initial default value) for the reduction
5042 * @param reducer a commutative associative combining function
5043 * @return the task
5044 */
5045 public static <K,V> ForkJoinTask<Integer> reduceToInt
5046 (ConcurrentHashMap<K,V> map,
5047 ObjectByObjectToInt<? super K, ? super V> transformer,
5048 int basis,
5049 IntByIntToInt reducer) {
5050 if (transformer == null || reducer == null)
5051 throw new NullPointerException();
5052 return new MapReduceMappingsToIntTask<K,V>
5053 (map, null, -1, null, transformer, basis, reducer);
5054 }
5055
5056 /**
5057 * Returns a task that when invoked, performs the given action
5058 * for each key.
5059 *
5060 * @param map the map
5061 * @param action the action
5062 * @return the task
5063 */
5064 public static <K,V> ForkJoinTask<Void> forEachKey
5065 (ConcurrentHashMap<K,V> map,
5066 Action<K> action) {
5067 if (action == null) throw new NullPointerException();
5068 return new ForEachKeyTask<K,V>(map, null, -1, action);
5069 }
5070
5071 /**
5072 * Returns a task that when invoked, performs the given action
5073 * for each non-null transformation of each key.
5074 *
5075 * @param map the map
5076 * @param transformer a function returning the transformation
5077 * for an element, or null if there is no transformation (in
5078 * which case the action is not applied)
5079 * @param action the action
5080 * @return the task
5081 */
5082 public static <K,V,U> ForkJoinTask<Void> forEachKey
5083 (ConcurrentHashMap<K,V> map,
5084 Fun<? super K, ? extends U> transformer,
5085 Action<U> action) {
5086 if (transformer == null || action == null)
5087 throw new NullPointerException();
5088 return new ForEachTransformedKeyTask<K,V,U>
5089 (map, null, -1, transformer, action);
5090 }
5091
5092 /**
5093 * Returns a task that when invoked, returns a non-null result
5094 * from applying the given search function on each key, or
5095 * null if none. Upon success, further element processing is
5096 * suppressed and the results of any other parallel
5097 * invocations of the search function are ignored.
5098 *
5099 * @param map the map
5100 * @param searchFunction a function returning a non-null
5101 * result on success, else null
5102 * @return the task
5103 */
5104 public static <K,V,U> ForkJoinTask<U> searchKeys
5105 (ConcurrentHashMap<K,V> map,
5106 Fun<? super K, ? extends U> searchFunction) {
5107 if (searchFunction == null) throw new NullPointerException();
5108 return new SearchKeysTask<K,V,U>
5109 (map, null, -1, searchFunction,
5110 new AtomicReference<U>());
5111 }
5112
5113 /**
5114 * Returns a task that when invoked, returns the result of
5115 * accumulating all keys using the given reducer to combine
5116 * values, or null if none.
5117 *
5118 * @param map the map
5119 * @param reducer a commutative associative combining function
5120 * @return the task
5121 */
5122 public static <K,V> ForkJoinTask<K> reduceKeys
5123 (ConcurrentHashMap<K,V> map,
5124 BiFun<? super K, ? super K, ? extends K> reducer) {
5125 if (reducer == null) throw new NullPointerException();
5126 return new ReduceKeysTask<K,V>
5127 (map, null, -1, null, reducer);
5128 }
5129
5130 /**
5131 * Returns a task that when invoked, returns the result of
5132 * accumulating the given transformation of all keys using the given
5133 * reducer to combine values, or null if none.
5134 *
5135 * @param map the map
5136 * @param transformer a function returning the transformation
5137 * for an element, or null if there is no transformation (in
5138 * which case it is not combined).
5139 * @param reducer a commutative associative combining function
5140 * @return the task
5141 */
5142 public static <K,V,U> ForkJoinTask<U> reduceKeys
5143 (ConcurrentHashMap<K,V> map,
5144 Fun<? super K, ? extends U> transformer,
5145 BiFun<? super U, ? super U, ? extends U> reducer) {
5146 if (transformer == null || reducer == null)
5147 throw new NullPointerException();
5148 return new MapReduceKeysTask<K,V,U>
5149 (map, null, -1, null, transformer, reducer);
5150 }
5151
5152 /**
5153 * Returns a task that when invoked, returns the result of
5154 * accumulating the given transformation of all keys using the given
5155 * reducer to combine values, and the given basis as an
5156 * identity value.
5157 *
5158 * @param map the map
5159 * @param transformer a function returning the transformation
5160 * for an element
5161 * @param basis the identity (initial default value) for the reduction
5162 * @param reducer a commutative associative combining function
5163 * @return the task
5164 */
5165 public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5166 (ConcurrentHashMap<K,V> map,
5167 ObjectToDouble<? super K> transformer,
5168 double basis,
5169 DoubleByDoubleToDouble reducer) {
5170 if (transformer == null || reducer == null)
5171 throw new NullPointerException();
5172 return new MapReduceKeysToDoubleTask<K,V>
5173 (map, null, -1, null, transformer, basis, reducer);
5174 }
5175
5176 /**
5177 * Returns a task that when invoked, returns the result of
5178 * accumulating the given transformation of all keys using the given
5179 * reducer to combine values, and the given basis as an
5180 * identity value.
5181 *
5182 * @param map the map
5183 * @param transformer a function returning the transformation
5184 * for an element
5185 * @param basis the identity (initial default value) for the reduction
5186 * @param reducer a commutative associative combining function
5187 * @return the task
5188 */
5189 public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5190 (ConcurrentHashMap<K,V> map,
5191 ObjectToLong<? super K> transformer,
5192 long basis,
5193 LongByLongToLong reducer) {
5194 if (transformer == null || reducer == null)
5195 throw new NullPointerException();
5196 return new MapReduceKeysToLongTask<K,V>
5197 (map, null, -1, null, transformer, basis, reducer);
5198 }
5199
5200 /**
5201 * Returns a task that when invoked, returns the result of
5202 * accumulating the given transformation of all keys using the given
5203 * reducer to combine values, and the given basis as an
5204 * identity value.
5205 *
5206 * @param map the map
5207 * @param transformer a function returning the transformation
5208 * for an element
5209 * @param basis the identity (initial default value) for the reduction
5210 * @param reducer a commutative associative combining function
5211 * @return the task
5212 */
5213 public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5214 (ConcurrentHashMap<K,V> map,
5215 ObjectToInt<? super K> transformer,
5216 int basis,
5217 IntByIntToInt reducer) {
5218 if (transformer == null || reducer == null)
5219 throw new NullPointerException();
5220 return new MapReduceKeysToIntTask<K,V>
5221 (map, null, -1, null, transformer, basis, reducer);
5222 }
5223
5224 /**
5225 * Returns a task that when invoked, performs the given action
5226 * for each value.
5227 *
5228 * @param map the map
5229 * @param action the action
5230 */
5231 public static <K,V> ForkJoinTask<Void> forEachValue
5232 (ConcurrentHashMap<K,V> map,
5233 Action<V> action) {
5234 if (action == null) throw new NullPointerException();
5235 return new ForEachValueTask<K,V>(map, null, -1, action);
5236 }
5237
5238 /**
5239 * Returns a task that when invoked, performs the given action
5240 * for each non-null transformation of each value.
5241 *
5242 * @param map the map
5243 * @param transformer a function returning the transformation
5244 * for an element, or null if there is no transformation (in
5245 * which case the action is not applied)
5246 * @param action the action
5247 */
5248 public static <K,V,U> ForkJoinTask<Void> forEachValue
5249 (ConcurrentHashMap<K,V> map,
5250 Fun<? super V, ? extends U> transformer,
5251 Action<U> action) {
5252 if (transformer == null || action == null)
5253 throw new NullPointerException();
5254 return new ForEachTransformedValueTask<K,V,U>
5255 (map, null, -1, transformer, action);
5256 }
5257
5258 /**
5259 * Returns a task that when invoked, returns a non-null result
5260 * from applying the given search function on each value, or
5261 * null if none. Upon success, further element processing is
5262 * suppressed and the results of any other parallel
5263 * invocations of the search function are ignored.
5264 *
5265 * @param map the map
5266 * @param searchFunction a function returning a non-null
5267 * result on success, else null
5268 * @return the task
5269 */
5270 public static <K,V,U> ForkJoinTask<U> searchValues
5271 (ConcurrentHashMap<K,V> map,
5272 Fun<? super V, ? extends U> searchFunction) {
5273 if (searchFunction == null) throw new NullPointerException();
5274 return new SearchValuesTask<K,V,U>
5275 (map, null, -1, searchFunction,
5276 new AtomicReference<U>());
5277 }
5278
5279 /**
5280 * Returns a task that when invoked, returns the result of
5281 * accumulating all values using the given reducer to combine
5282 * values, or null if none.
5283 *
5284 * @param map the map
5285 * @param reducer a commutative associative combining function
5286 * @return the task
5287 */
5288 public static <K,V> ForkJoinTask<V> reduceValues
5289 (ConcurrentHashMap<K,V> map,
5290 BiFun<? super V, ? super V, ? extends V> reducer) {
5291 if (reducer == null) throw new NullPointerException();
5292 return new ReduceValuesTask<K,V>
5293 (map, null, -1, null, reducer);
5294 }
5295
5296 /**
5297 * Returns a task that when invoked, returns the result of
5298 * accumulating the given transformation of all values using the
5299 * given reducer to combine values, or null if none.
5300 *
5301 * @param map the map
5302 * @param transformer a function returning the transformation
5303 * for an element, or null if there is no transformation (in
5304 * which case it is not combined).
5305 * @param reducer a commutative associative combining function
5306 * @return the task
5307 */
5308 public static <K,V,U> ForkJoinTask<U> reduceValues
5309 (ConcurrentHashMap<K,V> map,
5310 Fun<? super V, ? extends U> transformer,
5311 BiFun<? super U, ? super U, ? extends U> reducer) {
5312 if (transformer == null || reducer == null)
5313 throw new NullPointerException();
5314 return new MapReduceValuesTask<K,V,U>
5315 (map, null, -1, null, transformer, reducer);
5316 }
5317
5318 /**
5319 * Returns a task that when invoked, returns the result of
5320 * accumulating the given transformation of all values using the
5321 * given reducer to combine values, and the given basis as an
5322 * identity value.
5323 *
5324 * @param map the map
5325 * @param transformer a function returning the transformation
5326 * for an element
5327 * @param basis the identity (initial default value) for the reduction
5328 * @param reducer a commutative associative combining function
5329 * @return the task
5330 */
5331 public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5332 (ConcurrentHashMap<K,V> map,
5333 ObjectToDouble<? super V> transformer,
5334 double basis,
5335 DoubleByDoubleToDouble reducer) {
5336 if (transformer == null || reducer == null)
5337 throw new NullPointerException();
5338 return new MapReduceValuesToDoubleTask<K,V>
5339 (map, null, -1, null, transformer, basis, reducer);
5340 }
5341
5342 /**
5343 * Returns a task that when invoked, returns the result of
5344 * accumulating the given transformation of all values using the
5345 * given reducer to combine values, and the given basis as an
5346 * identity value.
5347 *
5348 * @param map the map
5349 * @param transformer a function returning the transformation
5350 * for an element
5351 * @param basis the identity (initial default value) for the reduction
5352 * @param reducer a commutative associative combining function
5353 * @return the task
5354 */
5355 public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5356 (ConcurrentHashMap<K,V> map,
5357 ObjectToLong<? super V> transformer,
5358 long basis,
5359 LongByLongToLong reducer) {
5360 if (transformer == null || reducer == null)
5361 throw new NullPointerException();
5362 return new MapReduceValuesToLongTask<K,V>
5363 (map, null, -1, null, transformer, basis, reducer);
5364 }
5365
5366 /**
5367 * Returns a task that when invoked, returns the result of
5368 * accumulating the given transformation of all values using the
5369 * given reducer to combine values, and the given basis as an
5370 * identity value.
5371 *
5372 * @param map the map
5373 * @param transformer a function returning the transformation
5374 * for an element
5375 * @param basis the identity (initial default value) for the reduction
5376 * @param reducer a commutative associative combining function
5377 * @return the task
5378 */
5379 public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5380 (ConcurrentHashMap<K,V> map,
5381 ObjectToInt<? super V> transformer,
5382 int basis,
5383 IntByIntToInt reducer) {
5384 if (transformer == null || reducer == null)
5385 throw new NullPointerException();
5386 return new MapReduceValuesToIntTask<K,V>
5387 (map, null, -1, null, transformer, basis, reducer);
5388 }
5389
5390 /**
5391 * Returns a task that when invoked, perform the given action
5392 * for each entry.
5393 *
5394 * @param map the map
5395 * @param action the action
5396 */
5397 public static <K,V> ForkJoinTask<Void> forEachEntry
5398 (ConcurrentHashMap<K,V> map,
5399 Action<Map.Entry<K,V>> action) {
5400 if (action == null) throw new NullPointerException();
5401 return new ForEachEntryTask<K,V>(map, null, -1, action);
5402 }
5403
5404 /**
5405 * Returns a task that when invoked, perform the given action
5406 * for each non-null transformation of each entry.
5407 *
5408 * @param map the map
5409 * @param transformer a function returning the transformation
5410 * for an element, or null if there is no transformation (in
5411 * which case the action is not applied)
5412 * @param action the action
5413 */
5414 public static <K,V,U> ForkJoinTask<Void> forEachEntry
5415 (ConcurrentHashMap<K,V> map,
5416 Fun<Map.Entry<K,V>, ? extends U> transformer,
5417 Action<U> action) {
5418 if (transformer == null || action == null)
5419 throw new NullPointerException();
5420 return new ForEachTransformedEntryTask<K,V,U>
5421 (map, null, -1, transformer, action);
5422 }
5423
5424 /**
5425 * Returns a task that when invoked, returns a non-null result
5426 * from applying the given search function on each entry, or
5427 * null if none. Upon success, further element processing is
5428 * suppressed and the results of any other parallel
5429 * invocations of the search function are ignored.
5430 *
5431 * @param map the map
5432 * @param searchFunction a function returning a non-null
5433 * result on success, else null
5434 * @return the task
5435 */
5436 public static <K,V,U> ForkJoinTask<U> searchEntries
5437 (ConcurrentHashMap<K,V> map,
5438 Fun<Map.Entry<K,V>, ? extends U> searchFunction) {
5439 if (searchFunction == null) throw new NullPointerException();
5440 return new SearchEntriesTask<K,V,U>
5441 (map, null, -1, searchFunction,
5442 new AtomicReference<U>());
5443 }
5444
5445 /**
5446 * Returns a task that when invoked, returns the result of
5447 * accumulating all entries using the given reducer to combine
5448 * values, or null if none.
5449 *
5450 * @param map the map
5451 * @param reducer a commutative associative combining function
5452 * @return the task
5453 */
5454 public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5455 (ConcurrentHashMap<K,V> map,
5456 BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5457 if (reducer == null) throw new NullPointerException();
5458 return new ReduceEntriesTask<K,V>
5459 (map, null, -1, null, reducer);
5460 }
5461
5462 /**
5463 * Returns a task that when invoked, returns the result of
5464 * accumulating the given transformation of all entries using the
5465 * given reducer to combine values, or null if none.
5466 *
5467 * @param map the map
5468 * @param transformer a function returning the transformation
5469 * for an element, or null if there is no transformation (in
5470 * which case it is not combined).
5471 * @param reducer a commutative associative combining function
5472 * @return the task
5473 */
5474 public static <K,V,U> ForkJoinTask<U> reduceEntries
5475 (ConcurrentHashMap<K,V> map,
5476 Fun<Map.Entry<K,V>, ? extends U> transformer,
5477 BiFun<? super U, ? super U, ? extends U> reducer) {
5478 if (transformer == null || reducer == null)
5479 throw new NullPointerException();
5480 return new MapReduceEntriesTask<K,V,U>
5481 (map, null, -1, null, transformer, reducer);
5482 }
5483
5484 /**
5485 * Returns a task that when invoked, returns the result of
5486 * accumulating the given transformation of all entries using the
5487 * given reducer to combine values, and the given basis as an
5488 * identity value.
5489 *
5490 * @param map the map
5491 * @param transformer a function returning the transformation
5492 * for an element
5493 * @param basis the identity (initial default value) for the reduction
5494 * @param reducer a commutative associative combining function
5495 * @return the task
5496 */
5497 public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5498 (ConcurrentHashMap<K,V> map,
5499 ObjectToDouble<Map.Entry<K,V>> transformer,
5500 double basis,
5501 DoubleByDoubleToDouble reducer) {
5502 if (transformer == null || reducer == null)
5503 throw new NullPointerException();
5504 return new MapReduceEntriesToDoubleTask<K,V>
5505 (map, null, -1, null, transformer, basis, reducer);
5506 }
5507
5508 /**
5509 * Returns a task that when invoked, returns the result of
5510 * accumulating the given transformation of all entries using the
5511 * given reducer to combine values, and the given basis as an
5512 * identity value.
5513 *
5514 * @param map the map
5515 * @param transformer a function returning the transformation
5516 * for an element
5517 * @param basis the identity (initial default value) for the reduction
5518 * @param reducer a commutative associative combining function
5519 * @return the task
5520 */
5521 public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5522 (ConcurrentHashMap<K,V> map,
5523 ObjectToLong<Map.Entry<K,V>> transformer,
5524 long basis,
5525 LongByLongToLong reducer) {
5526 if (transformer == null || reducer == null)
5527 throw new NullPointerException();
5528 return new MapReduceEntriesToLongTask<K,V>
5529 (map, null, -1, null, transformer, basis, reducer);
5530 }
5531
5532 /**
5533 * Returns a task that when invoked, returns the result of
5534 * accumulating the given transformation of all entries using the
5535 * given reducer to combine values, and the given basis as an
5536 * identity value.
5537 *
5538 * @param map the map
5539 * @param transformer a function returning the transformation
5540 * for an element
5541 * @param basis the identity (initial default value) for the reduction
5542 * @param reducer a commutative associative combining function
5543 * @return the task
5544 */
5545 public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5546 (ConcurrentHashMap<K,V> map,
5547 ObjectToInt<Map.Entry<K,V>> transformer,
5548 int basis,
5549 IntByIntToInt reducer) {
5550 if (transformer == null || reducer == null)
5551 throw new NullPointerException();
5552 return new MapReduceEntriesToIntTask<K,V>
5553 (map, null, -1, null, transformer, basis, reducer);
5554 }
5555 }
5556
5557 // -------------------------------------------------------
5558
5559 /*
5560 * Task classes. Coded in a regular but ugly format/style to
5561 * simplify checks that each variant differs in the right way from
5562 * others. The null screenings exist because compilers cannot tell
5563 * that we've already null-checked task arguments, so we force
5564 * simplest hoisted bypass to help avoid convoluted traps.
5565 */
5566
5567 @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5568 extends Traverser<K,V,Void> {
5569 final Action<K> action;
5570 ForEachKeyTask
5571 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5572 Action<K> action) {
5573 super(m, p, b);
5574 this.action = action;
5575 }
5576 @SuppressWarnings("unchecked") public final void compute() {
5577 final Action<K> action;
5578 if ((action = this.action) != null) {
5579 for (int b; (b = preSplit()) > 0;)
5580 new ForEachKeyTask<K,V>(map, this, b, action).fork();
5581 while (advance() != null)
5582 action.apply((K)nextKey);
5583 propagateCompletion();
5584 }
5585 }
5586 }
5587
5588 @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5589 extends Traverser<K,V,Void> {
5590 final Action<V> action;
5591 ForEachValueTask
5592 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5593 Action<V> action) {
5594 super(m, p, b);
5595 this.action = action;
5596 }
5597 @SuppressWarnings("unchecked") public final void compute() {
5598 final Action<V> action;
5599 if ((action = this.action) != null) {
5600 for (int b; (b = preSplit()) > 0;)
5601 new ForEachValueTask<K,V>(map, this, b, action).fork();
5602 V v;
5603 while ((v = advance()) != null)
5604 action.apply(v);
5605 propagateCompletion();
5606 }
5607 }
5608 }
5609
5610 @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5611 extends Traverser<K,V,Void> {
5612 final Action<Entry<K,V>> action;
5613 ForEachEntryTask
5614 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5615 Action<Entry<K,V>> action) {
5616 super(m, p, b);
5617 this.action = action;
5618 }
5619 @SuppressWarnings("unchecked") public final void compute() {
5620 final Action<Entry<K,V>> action;
5621 if ((action = this.action) != null) {
5622 for (int b; (b = preSplit()) > 0;)
5623 new ForEachEntryTask<K,V>(map, this, b, action).fork();
5624 V v;
5625 while ((v = advance()) != null)
5626 action.apply(entryFor((K)nextKey, v));
5627 propagateCompletion();
5628 }
5629 }
5630 }
5631
5632 @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5633 extends Traverser<K,V,Void> {
5634 final BiAction<K,V> action;
5635 ForEachMappingTask
5636 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5637 BiAction<K,V> action) {
5638 super(m, p, b);
5639 this.action = action;
5640 }
5641 @SuppressWarnings("unchecked") public final void compute() {
5642 final BiAction<K,V> action;
5643 if ((action = this.action) != null) {
5644 for (int b; (b = preSplit()) > 0;)
5645 new ForEachMappingTask<K,V>(map, this, b, action).fork();
5646 V v;
5647 while ((v = advance()) != null)
5648 action.apply((K)nextKey, v);
5649 propagateCompletion();
5650 }
5651 }
5652 }
5653
5654 @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5655 extends Traverser<K,V,Void> {
5656 final Fun<? super K, ? extends U> transformer;
5657 final Action<U> action;
5658 ForEachTransformedKeyTask
5659 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5660 Fun<? super K, ? extends U> transformer, Action<U> action) {
5661 super(m, p, b);
5662 this.transformer = transformer; this.action = action;
5663 }
5664 @SuppressWarnings("unchecked") public final void compute() {
5665 final Fun<? super K, ? extends U> transformer;
5666 final Action<U> action;
5667 if ((transformer = this.transformer) != null &&
5668 (action = this.action) != null) {
5669 for (int b; (b = preSplit()) > 0;)
5670 new ForEachTransformedKeyTask<K,V,U>
5671 (map, this, b, transformer, action).fork();
5672 U u;
5673 while (advance() != null) {
5674 if ((u = transformer.apply((K)nextKey)) != null)
5675 action.apply(u);
5676 }
5677 propagateCompletion();
5678 }
5679 }
5680 }
5681
5682 @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5683 extends Traverser<K,V,Void> {
5684 final Fun<? super V, ? extends U> transformer;
5685 final Action<U> action;
5686 ForEachTransformedValueTask
5687 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5688 Fun<? super V, ? extends U> transformer, Action<U> action) {
5689 super(m, p, b);
5690 this.transformer = transformer; this.action = action;
5691 }
5692 @SuppressWarnings("unchecked") public final void compute() {
5693 final Fun<? super V, ? extends U> transformer;
5694 final Action<U> action;
5695 if ((transformer = this.transformer) != null &&
5696 (action = this.action) != null) {
5697 for (int b; (b = preSplit()) > 0;)
5698 new ForEachTransformedValueTask<K,V,U>
5699 (map, this, b, transformer, action).fork();
5700 V v; U u;
5701 while ((v = advance()) != null) {
5702 if ((u = transformer.apply(v)) != null)
5703 action.apply(u);
5704 }
5705 propagateCompletion();
5706 }
5707 }
5708 }
5709
5710 @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5711 extends Traverser<K,V,Void> {
5712 final Fun<Map.Entry<K,V>, ? extends U> transformer;
5713 final Action<U> action;
5714 ForEachTransformedEntryTask
5715 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5716 Fun<Map.Entry<K,V>, ? extends U> transformer, Action<U> action) {
5717 super(m, p, b);
5718 this.transformer = transformer; this.action = action;
5719 }
5720 @SuppressWarnings("unchecked") public final void compute() {
5721 final Fun<Map.Entry<K,V>, ? extends U> transformer;
5722 final Action<U> action;
5723 if ((transformer = this.transformer) != null &&
5724 (action = this.action) != null) {
5725 for (int b; (b = preSplit()) > 0;)
5726 new ForEachTransformedEntryTask<K,V,U>
5727 (map, this, b, transformer, action).fork();
5728 V v; U u;
5729 while ((v = advance()) != null) {
5730 if ((u = transformer.apply(entryFor((K)nextKey,
5731 v))) != null)
5732 action.apply(u);
5733 }
5734 propagateCompletion();
5735 }
5736 }
5737 }
5738
5739 @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5740 extends Traverser<K,V,Void> {
5741 final BiFun<? super K, ? super V, ? extends U> transformer;
5742 final Action<U> action;
5743 ForEachTransformedMappingTask
5744 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5745 BiFun<? super K, ? super V, ? extends U> transformer,
5746 Action<U> action) {
5747 super(m, p, b);
5748 this.transformer = transformer; this.action = action;
5749 }
5750 @SuppressWarnings("unchecked") public final void compute() {
5751 final BiFun<? super K, ? super V, ? extends U> transformer;
5752 final Action<U> action;
5753 if ((transformer = this.transformer) != null &&
5754 (action = this.action) != null) {
5755 for (int b; (b = preSplit()) > 0;)
5756 new ForEachTransformedMappingTask<K,V,U>
5757 (map, this, b, transformer, action).fork();
5758 V v; U u;
5759 while ((v = advance()) != null) {
5760 if ((u = transformer.apply((K)nextKey, v)) != null)
5761 action.apply(u);
5762 }
5763 propagateCompletion();
5764 }
5765 }
5766 }
5767
5768 @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5769 extends Traverser<K,V,U> {
5770 final Fun<? super K, ? extends U> searchFunction;
5771 final AtomicReference<U> result;
5772 SearchKeysTask
5773 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5774 Fun<? super K, ? extends U> searchFunction,
5775 AtomicReference<U> result) {
5776 super(m, p, b);
5777 this.searchFunction = searchFunction; this.result = result;
5778 }
5779 public final U getRawResult() { return result.get(); }
5780 @SuppressWarnings("unchecked") public final void compute() {
5781 final Fun<? super K, ? extends U> searchFunction;
5782 final AtomicReference<U> result;
5783 if ((searchFunction = this.searchFunction) != null &&
5784 (result = this.result) != null) {
5785 for (int b;;) {
5786 if (result.get() != null)
5787 return;
5788 if ((b = preSplit()) <= 0)
5789 break;
5790 new SearchKeysTask<K,V,U>
5791 (map, this, b, searchFunction, result).fork();
5792 }
5793 while (result.get() == null) {
5794 U u;
5795 if (advance() == null) {
5796 propagateCompletion();
5797 break;
5798 }
5799 if ((u = searchFunction.apply((K)nextKey)) != null) {
5800 if (result.compareAndSet(null, u))
5801 quietlyCompleteRoot();
5802 break;
5803 }
5804 }
5805 }
5806 }
5807 }
5808
5809 @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5810 extends Traverser<K,V,U> {
5811 final Fun<? super V, ? extends U> searchFunction;
5812 final AtomicReference<U> result;
5813 SearchValuesTask
5814 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5815 Fun<? super V, ? extends U> searchFunction,
5816 AtomicReference<U> result) {
5817 super(m, p, b);
5818 this.searchFunction = searchFunction; this.result = result;
5819 }
5820 public final U getRawResult() { return result.get(); }
5821 @SuppressWarnings("unchecked") public final void compute() {
5822 final Fun<? super V, ? extends U> searchFunction;
5823 final AtomicReference<U> result;
5824 if ((searchFunction = this.searchFunction) != null &&
5825 (result = this.result) != null) {
5826 for (int b;;) {
5827 if (result.get() != null)
5828 return;
5829 if ((b = preSplit()) <= 0)
5830 break;
5831 new SearchValuesTask<K,V,U>
5832 (map, this, b, searchFunction, result).fork();
5833 }
5834 while (result.get() == null) {
5835 V v; U u;
5836 if ((v = advance()) == null) {
5837 propagateCompletion();
5838 break;
5839 }
5840 if ((u = searchFunction.apply(v)) != null) {
5841 if (result.compareAndSet(null, u))
5842 quietlyCompleteRoot();
5843 break;
5844 }
5845 }
5846 }
5847 }
5848 }
5849
5850 @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5851 extends Traverser<K,V,U> {
5852 final Fun<Entry<K,V>, ? extends U> searchFunction;
5853 final AtomicReference<U> result;
5854 SearchEntriesTask
5855 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5856 Fun<Entry<K,V>, ? extends U> searchFunction,
5857 AtomicReference<U> result) {
5858 super(m, p, b);
5859 this.searchFunction = searchFunction; this.result = result;
5860 }
5861 public final U getRawResult() { return result.get(); }
5862 @SuppressWarnings("unchecked") public final void compute() {
5863 final Fun<Entry<K,V>, ? extends U> searchFunction;
5864 final AtomicReference<U> result;
5865 if ((searchFunction = this.searchFunction) != null &&
5866 (result = this.result) != null) {
5867 for (int b;;) {
5868 if (result.get() != null)
5869 return;
5870 if ((b = preSplit()) <= 0)
5871 break;
5872 new SearchEntriesTask<K,V,U>
5873 (map, this, b, searchFunction, result).fork();
5874 }
5875 while (result.get() == null) {
5876 V v; U u;
5877 if ((v = advance()) == null) {
5878 propagateCompletion();
5879 break;
5880 }
5881 if ((u = searchFunction.apply(entryFor((K)nextKey,
5882 v))) != null) {
5883 if (result.compareAndSet(null, u))
5884 quietlyCompleteRoot();
5885 return;
5886 }
5887 }
5888 }
5889 }
5890 }
5891
5892 @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5893 extends Traverser<K,V,U> {
5894 final BiFun<? super K, ? super V, ? extends U> searchFunction;
5895 final AtomicReference<U> result;
5896 SearchMappingsTask
5897 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5898 BiFun<? super K, ? super V, ? extends U> searchFunction,
5899 AtomicReference<U> result) {
5900 super(m, p, b);
5901 this.searchFunction = searchFunction; this.result = result;
5902 }
5903 public final U getRawResult() { return result.get(); }
5904 @SuppressWarnings("unchecked") public final void compute() {
5905 final BiFun<? super K, ? super V, ? extends U> searchFunction;
5906 final AtomicReference<U> result;
5907 if ((searchFunction = this.searchFunction) != null &&
5908 (result = this.result) != null) {
5909 for (int b;;) {
5910 if (result.get() != null)
5911 return;
5912 if ((b = preSplit()) <= 0)
5913 break;
5914 new SearchMappingsTask<K,V,U>
5915 (map, this, b, searchFunction, result).fork();
5916 }
5917 while (result.get() == null) {
5918 V v; U u;
5919 if ((v = advance()) == null) {
5920 propagateCompletion();
5921 break;
5922 }
5923 if ((u = searchFunction.apply((K)nextKey, v)) != null) {
5924 if (result.compareAndSet(null, u))
5925 quietlyCompleteRoot();
5926 break;
5927 }
5928 }
5929 }
5930 }
5931 }
5932
5933 @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5934 extends Traverser<K,V,K> {
5935 final BiFun<? super K, ? super K, ? extends K> reducer;
5936 K result;
5937 ReduceKeysTask<K,V> rights, nextRight;
5938 ReduceKeysTask
5939 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5940 ReduceKeysTask<K,V> nextRight,
5941 BiFun<? super K, ? super K, ? extends K> reducer) {
5942 super(m, p, b); this.nextRight = nextRight;
5943 this.reducer = reducer;
5944 }
5945 public final K getRawResult() { return result; }
5946 @SuppressWarnings("unchecked") public final void compute() {
5947 final BiFun<? super K, ? super K, ? extends K> reducer;
5948 if ((reducer = this.reducer) != null) {
5949 for (int b; (b = preSplit()) > 0;)
5950 (rights = new ReduceKeysTask<K,V>
5951 (map, this, b, rights, reducer)).fork();
5952 K r = null;
5953 while (advance() != null) {
5954 K u = (K)nextKey;
5955 r = (r == null) ? u : reducer.apply(r, u);
5956 }
5957 result = r;
5958 CountedCompleter<?> c;
5959 for (c = firstComplete(); c != null; c = c.nextComplete()) {
5960 ReduceKeysTask<K,V>
5961 t = (ReduceKeysTask<K,V>)c,
5962 s = t.rights;
5963 while (s != null) {
5964 K tr, sr;
5965 if ((sr = s.result) != null)
5966 t.result = (((tr = t.result) == null) ? sr :
5967 reducer.apply(tr, sr));
5968 s = t.rights = s.nextRight;
5969 }
5970 }
5971 }
5972 }
5973 }
5974
5975 @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5976 extends Traverser<K,V,V> {
5977 final BiFun<? super V, ? super V, ? extends V> reducer;
5978 V result;
5979 ReduceValuesTask<K,V> rights, nextRight;
5980 ReduceValuesTask
5981 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5982 ReduceValuesTask<K,V> nextRight,
5983 BiFun<? super V, ? super V, ? extends V> reducer) {
5984 super(m, p, b); this.nextRight = nextRight;
5985 this.reducer = reducer;
5986 }
5987 public final V getRawResult() { return result; }
5988 @SuppressWarnings("unchecked") public final void compute() {
5989 final BiFun<? super V, ? super V, ? extends V> reducer;
5990 if ((reducer = this.reducer) != null) {
5991 for (int b; (b = preSplit()) > 0;)
5992 (rights = new ReduceValuesTask<K,V>
5993 (map, this, b, rights, reducer)).fork();
5994 V r = null;
5995 V v;
5996 while ((v = advance()) != null) {
5997 V u = v;
5998 r = (r == null) ? u : reducer.apply(r, u);
5999 }
6000 result = r;
6001 CountedCompleter<?> c;
6002 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6003 ReduceValuesTask<K,V>
6004 t = (ReduceValuesTask<K,V>)c,
6005 s = t.rights;
6006 while (s != null) {
6007 V tr, sr;
6008 if ((sr = s.result) != null)
6009 t.result = (((tr = t.result) == null) ? sr :
6010 reducer.apply(tr, sr));
6011 s = t.rights = s.nextRight;
6012 }
6013 }
6014 }
6015 }
6016 }
6017
6018 @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6019 extends Traverser<K,V,Map.Entry<K,V>> {
6020 final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6021 Map.Entry<K,V> result;
6022 ReduceEntriesTask<K,V> rights, nextRight;
6023 ReduceEntriesTask
6024 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6025 ReduceEntriesTask<K,V> nextRight,
6026 BiFun<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6027 super(m, p, b); this.nextRight = nextRight;
6028 this.reducer = reducer;
6029 }
6030 public final Map.Entry<K,V> getRawResult() { return result; }
6031 @SuppressWarnings("unchecked") public final void compute() {
6032 final BiFun<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6033 if ((reducer = this.reducer) != null) {
6034 for (int b; (b = preSplit()) > 0;)
6035 (rights = new ReduceEntriesTask<K,V>
6036 (map, this, b, rights, reducer)).fork();
6037 Map.Entry<K,V> r = null;
6038 V v;
6039 while ((v = advance()) != null) {
6040 Map.Entry<K,V> u = entryFor((K)nextKey, v);
6041 r = (r == null) ? u : reducer.apply(r, u);
6042 }
6043 result = r;
6044 CountedCompleter<?> c;
6045 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6046 ReduceEntriesTask<K,V>
6047 t = (ReduceEntriesTask<K,V>)c,
6048 s = t.rights;
6049 while (s != null) {
6050 Map.Entry<K,V> tr, sr;
6051 if ((sr = s.result) != null)
6052 t.result = (((tr = t.result) == null) ? sr :
6053 reducer.apply(tr, sr));
6054 s = t.rights = s.nextRight;
6055 }
6056 }
6057 }
6058 }
6059 }
6060
6061 @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6062 extends Traverser<K,V,U> {
6063 final Fun<? super K, ? extends U> transformer;
6064 final BiFun<? super U, ? super U, ? extends U> reducer;
6065 U result;
6066 MapReduceKeysTask<K,V,U> rights, nextRight;
6067 MapReduceKeysTask
6068 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6069 MapReduceKeysTask<K,V,U> nextRight,
6070 Fun<? super K, ? extends U> transformer,
6071 BiFun<? super U, ? super U, ? extends U> reducer) {
6072 super(m, p, b); this.nextRight = nextRight;
6073 this.transformer = transformer;
6074 this.reducer = reducer;
6075 }
6076 public final U getRawResult() { return result; }
6077 @SuppressWarnings("unchecked") public final void compute() {
6078 final Fun<? super K, ? extends U> transformer;
6079 final BiFun<? super U, ? super U, ? extends U> reducer;
6080 if ((transformer = this.transformer) != null &&
6081 (reducer = this.reducer) != null) {
6082 for (int b; (b = preSplit()) > 0;)
6083 (rights = new MapReduceKeysTask<K,V,U>
6084 (map, this, b, rights, transformer, reducer)).fork();
6085 U r = null, u;
6086 while (advance() != null) {
6087 if ((u = transformer.apply((K)nextKey)) != null)
6088 r = (r == null) ? u : reducer.apply(r, u);
6089 }
6090 result = r;
6091 CountedCompleter<?> c;
6092 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6093 MapReduceKeysTask<K,V,U>
6094 t = (MapReduceKeysTask<K,V,U>)c,
6095 s = t.rights;
6096 while (s != null) {
6097 U tr, sr;
6098 if ((sr = s.result) != null)
6099 t.result = (((tr = t.result) == null) ? sr :
6100 reducer.apply(tr, sr));
6101 s = t.rights = s.nextRight;
6102 }
6103 }
6104 }
6105 }
6106 }
6107
6108 @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6109 extends Traverser<K,V,U> {
6110 final Fun<? super V, ? extends U> transformer;
6111 final BiFun<? super U, ? super U, ? extends U> reducer;
6112 U result;
6113 MapReduceValuesTask<K,V,U> rights, nextRight;
6114 MapReduceValuesTask
6115 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6116 MapReduceValuesTask<K,V,U> nextRight,
6117 Fun<? super V, ? extends U> transformer,
6118 BiFun<? super U, ? super U, ? extends U> reducer) {
6119 super(m, p, b); this.nextRight = nextRight;
6120 this.transformer = transformer;
6121 this.reducer = reducer;
6122 }
6123 public final U getRawResult() { return result; }
6124 @SuppressWarnings("unchecked") public final void compute() {
6125 final Fun<? super V, ? extends U> transformer;
6126 final BiFun<? super U, ? super U, ? extends U> reducer;
6127 if ((transformer = this.transformer) != null &&
6128 (reducer = this.reducer) != null) {
6129 for (int b; (b = preSplit()) > 0;)
6130 (rights = new MapReduceValuesTask<K,V,U>
6131 (map, this, b, rights, transformer, reducer)).fork();
6132 U r = null, u;
6133 V v;
6134 while ((v = advance()) != null) {
6135 if ((u = transformer.apply(v)) != null)
6136 r = (r == null) ? u : reducer.apply(r, u);
6137 }
6138 result = r;
6139 CountedCompleter<?> c;
6140 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6141 MapReduceValuesTask<K,V,U>
6142 t = (MapReduceValuesTask<K,V,U>)c,
6143 s = t.rights;
6144 while (s != null) {
6145 U tr, sr;
6146 if ((sr = s.result) != null)
6147 t.result = (((tr = t.result) == null) ? sr :
6148 reducer.apply(tr, sr));
6149 s = t.rights = s.nextRight;
6150 }
6151 }
6152 }
6153 }
6154 }
6155
6156 @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6157 extends Traverser<K,V,U> {
6158 final Fun<Map.Entry<K,V>, ? extends U> transformer;
6159 final BiFun<? super U, ? super U, ? extends U> reducer;
6160 U result;
6161 MapReduceEntriesTask<K,V,U> rights, nextRight;
6162 MapReduceEntriesTask
6163 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6164 MapReduceEntriesTask<K,V,U> nextRight,
6165 Fun<Map.Entry<K,V>, ? extends U> transformer,
6166 BiFun<? super U, ? super U, ? extends U> reducer) {
6167 super(m, p, b); this.nextRight = nextRight;
6168 this.transformer = transformer;
6169 this.reducer = reducer;
6170 }
6171 public final U getRawResult() { return result; }
6172 @SuppressWarnings("unchecked") public final void compute() {
6173 final Fun<Map.Entry<K,V>, ? extends U> transformer;
6174 final BiFun<? super U, ? super U, ? extends U> reducer;
6175 if ((transformer = this.transformer) != null &&
6176 (reducer = this.reducer) != null) {
6177 for (int b; (b = preSplit()) > 0;)
6178 (rights = new MapReduceEntriesTask<K,V,U>
6179 (map, this, b, rights, transformer, reducer)).fork();
6180 U r = null, u;
6181 V v;
6182 while ((v = advance()) != null) {
6183 if ((u = transformer.apply(entryFor((K)nextKey,
6184 v))) != null)
6185 r = (r == null) ? u : reducer.apply(r, u);
6186 }
6187 result = r;
6188 CountedCompleter<?> c;
6189 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6190 MapReduceEntriesTask<K,V,U>
6191 t = (MapReduceEntriesTask<K,V,U>)c,
6192 s = t.rights;
6193 while (s != null) {
6194 U tr, sr;
6195 if ((sr = s.result) != null)
6196 t.result = (((tr = t.result) == null) ? sr :
6197 reducer.apply(tr, sr));
6198 s = t.rights = s.nextRight;
6199 }
6200 }
6201 }
6202 }
6203 }
6204
6205 @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6206 extends Traverser<K,V,U> {
6207 final BiFun<? super K, ? super V, ? extends U> transformer;
6208 final BiFun<? super U, ? super U, ? extends U> reducer;
6209 U result;
6210 MapReduceMappingsTask<K,V,U> rights, nextRight;
6211 MapReduceMappingsTask
6212 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6213 MapReduceMappingsTask<K,V,U> nextRight,
6214 BiFun<? super K, ? super V, ? extends U> transformer,
6215 BiFun<? super U, ? super U, ? extends U> reducer) {
6216 super(m, p, b); this.nextRight = nextRight;
6217 this.transformer = transformer;
6218 this.reducer = reducer;
6219 }
6220 public final U getRawResult() { return result; }
6221 @SuppressWarnings("unchecked") public final void compute() {
6222 final BiFun<? super K, ? super V, ? extends U> transformer;
6223 final BiFun<? super U, ? super U, ? extends U> reducer;
6224 if ((transformer = this.transformer) != null &&
6225 (reducer = this.reducer) != null) {
6226 for (int b; (b = preSplit()) > 0;)
6227 (rights = new MapReduceMappingsTask<K,V,U>
6228 (map, this, b, rights, transformer, reducer)).fork();
6229 U r = null, u;
6230 V v;
6231 while ((v = advance()) != null) {
6232 if ((u = transformer.apply((K)nextKey, v)) != null)
6233 r = (r == null) ? u : reducer.apply(r, u);
6234 }
6235 result = r;
6236 CountedCompleter<?> c;
6237 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6238 MapReduceMappingsTask<K,V,U>
6239 t = (MapReduceMappingsTask<K,V,U>)c,
6240 s = t.rights;
6241 while (s != null) {
6242 U tr, sr;
6243 if ((sr = s.result) != null)
6244 t.result = (((tr = t.result) == null) ? sr :
6245 reducer.apply(tr, sr));
6246 s = t.rights = s.nextRight;
6247 }
6248 }
6249 }
6250 }
6251 }
6252
6253 @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6254 extends Traverser<K,V,Double> {
6255 final ObjectToDouble<? super K> transformer;
6256 final DoubleByDoubleToDouble reducer;
6257 final double basis;
6258 double result;
6259 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6260 MapReduceKeysToDoubleTask
6261 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6262 MapReduceKeysToDoubleTask<K,V> nextRight,
6263 ObjectToDouble<? super K> transformer,
6264 double basis,
6265 DoubleByDoubleToDouble reducer) {
6266 super(m, p, b); this.nextRight = nextRight;
6267 this.transformer = transformer;
6268 this.basis = basis; this.reducer = reducer;
6269 }
6270 public final Double getRawResult() { return result; }
6271 @SuppressWarnings("unchecked") public final void compute() {
6272 final ObjectToDouble<? super K> transformer;
6273 final DoubleByDoubleToDouble reducer;
6274 if ((transformer = this.transformer) != null &&
6275 (reducer = this.reducer) != null) {
6276 double r = this.basis;
6277 for (int b; (b = preSplit()) > 0;)
6278 (rights = new MapReduceKeysToDoubleTask<K,V>
6279 (map, this, b, rights, transformer, r, reducer)).fork();
6280 while (advance() != null)
6281 r = reducer.apply(r, transformer.apply((K)nextKey));
6282 result = r;
6283 CountedCompleter<?> c;
6284 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6285 MapReduceKeysToDoubleTask<K,V>
6286 t = (MapReduceKeysToDoubleTask<K,V>)c,
6287 s = t.rights;
6288 while (s != null) {
6289 t.result = reducer.apply(t.result, s.result);
6290 s = t.rights = s.nextRight;
6291 }
6292 }
6293 }
6294 }
6295 }
6296
6297 @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6298 extends Traverser<K,V,Double> {
6299 final ObjectToDouble<? super V> transformer;
6300 final DoubleByDoubleToDouble reducer;
6301 final double basis;
6302 double result;
6303 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6304 MapReduceValuesToDoubleTask
6305 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6306 MapReduceValuesToDoubleTask<K,V> nextRight,
6307 ObjectToDouble<? super V> transformer,
6308 double basis,
6309 DoubleByDoubleToDouble reducer) {
6310 super(m, p, b); this.nextRight = nextRight;
6311 this.transformer = transformer;
6312 this.basis = basis; this.reducer = reducer;
6313 }
6314 public final Double getRawResult() { return result; }
6315 @SuppressWarnings("unchecked") public final void compute() {
6316 final ObjectToDouble<? super V> transformer;
6317 final DoubleByDoubleToDouble reducer;
6318 if ((transformer = this.transformer) != null &&
6319 (reducer = this.reducer) != null) {
6320 double r = this.basis;
6321 for (int b; (b = preSplit()) > 0;)
6322 (rights = new MapReduceValuesToDoubleTask<K,V>
6323 (map, this, b, rights, transformer, r, reducer)).fork();
6324 V v;
6325 while ((v = advance()) != null)
6326 r = reducer.apply(r, transformer.apply(v));
6327 result = r;
6328 CountedCompleter<?> c;
6329 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6330 MapReduceValuesToDoubleTask<K,V>
6331 t = (MapReduceValuesToDoubleTask<K,V>)c,
6332 s = t.rights;
6333 while (s != null) {
6334 t.result = reducer.apply(t.result, s.result);
6335 s = t.rights = s.nextRight;
6336 }
6337 }
6338 }
6339 }
6340 }
6341
6342 @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6343 extends Traverser<K,V,Double> {
6344 final ObjectToDouble<Map.Entry<K,V>> transformer;
6345 final DoubleByDoubleToDouble reducer;
6346 final double basis;
6347 double result;
6348 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6349 MapReduceEntriesToDoubleTask
6350 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6351 MapReduceEntriesToDoubleTask<K,V> nextRight,
6352 ObjectToDouble<Map.Entry<K,V>> transformer,
6353 double basis,
6354 DoubleByDoubleToDouble reducer) {
6355 super(m, p, b); this.nextRight = nextRight;
6356 this.transformer = transformer;
6357 this.basis = basis; this.reducer = reducer;
6358 }
6359 public final Double getRawResult() { return result; }
6360 @SuppressWarnings("unchecked") public final void compute() {
6361 final ObjectToDouble<Map.Entry<K,V>> transformer;
6362 final DoubleByDoubleToDouble reducer;
6363 if ((transformer = this.transformer) != null &&
6364 (reducer = this.reducer) != null) {
6365 double r = this.basis;
6366 for (int b; (b = preSplit()) > 0;)
6367 (rights = new MapReduceEntriesToDoubleTask<K,V>
6368 (map, this, b, rights, transformer, r, reducer)).fork();
6369 V v;
6370 while ((v = advance()) != null)
6371 r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6372 v)));
6373 result = r;
6374 CountedCompleter<?> c;
6375 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6376 MapReduceEntriesToDoubleTask<K,V>
6377 t = (MapReduceEntriesToDoubleTask<K,V>)c,
6378 s = t.rights;
6379 while (s != null) {
6380 t.result = reducer.apply(t.result, s.result);
6381 s = t.rights = s.nextRight;
6382 }
6383 }
6384 }
6385 }
6386 }
6387
6388 @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6389 extends Traverser<K,V,Double> {
6390 final ObjectByObjectToDouble<? super K, ? super V> transformer;
6391 final DoubleByDoubleToDouble reducer;
6392 final double basis;
6393 double result;
6394 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6395 MapReduceMappingsToDoubleTask
6396 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6397 MapReduceMappingsToDoubleTask<K,V> nextRight,
6398 ObjectByObjectToDouble<? super K, ? super V> transformer,
6399 double basis,
6400 DoubleByDoubleToDouble reducer) {
6401 super(m, p, b); this.nextRight = nextRight;
6402 this.transformer = transformer;
6403 this.basis = basis; this.reducer = reducer;
6404 }
6405 public final Double getRawResult() { return result; }
6406 @SuppressWarnings("unchecked") public final void compute() {
6407 final ObjectByObjectToDouble<? super K, ? super V> transformer;
6408 final DoubleByDoubleToDouble reducer;
6409 if ((transformer = this.transformer) != null &&
6410 (reducer = this.reducer) != null) {
6411 double r = this.basis;
6412 for (int b; (b = preSplit()) > 0;)
6413 (rights = new MapReduceMappingsToDoubleTask<K,V>
6414 (map, this, b, rights, transformer, r, reducer)).fork();
6415 V v;
6416 while ((v = advance()) != null)
6417 r = reducer.apply(r, transformer.apply((K)nextKey, v));
6418 result = r;
6419 CountedCompleter<?> c;
6420 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6421 MapReduceMappingsToDoubleTask<K,V>
6422 t = (MapReduceMappingsToDoubleTask<K,V>)c,
6423 s = t.rights;
6424 while (s != null) {
6425 t.result = reducer.apply(t.result, s.result);
6426 s = t.rights = s.nextRight;
6427 }
6428 }
6429 }
6430 }
6431 }
6432
6433 @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6434 extends Traverser<K,V,Long> {
6435 final ObjectToLong<? super K> transformer;
6436 final LongByLongToLong reducer;
6437 final long basis;
6438 long result;
6439 MapReduceKeysToLongTask<K,V> rights, nextRight;
6440 MapReduceKeysToLongTask
6441 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6442 MapReduceKeysToLongTask<K,V> nextRight,
6443 ObjectToLong<? super K> transformer,
6444 long basis,
6445 LongByLongToLong reducer) {
6446 super(m, p, b); this.nextRight = nextRight;
6447 this.transformer = transformer;
6448 this.basis = basis; this.reducer = reducer;
6449 }
6450 public final Long getRawResult() { return result; }
6451 @SuppressWarnings("unchecked") public final void compute() {
6452 final ObjectToLong<? super K> transformer;
6453 final LongByLongToLong reducer;
6454 if ((transformer = this.transformer) != null &&
6455 (reducer = this.reducer) != null) {
6456 long r = this.basis;
6457 for (int b; (b = preSplit()) > 0;)
6458 (rights = new MapReduceKeysToLongTask<K,V>
6459 (map, this, b, rights, transformer, r, reducer)).fork();
6460 while (advance() != null)
6461 r = reducer.apply(r, transformer.apply((K)nextKey));
6462 result = r;
6463 CountedCompleter<?> c;
6464 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6465 MapReduceKeysToLongTask<K,V>
6466 t = (MapReduceKeysToLongTask<K,V>)c,
6467 s = t.rights;
6468 while (s != null) {
6469 t.result = reducer.apply(t.result, s.result);
6470 s = t.rights = s.nextRight;
6471 }
6472 }
6473 }
6474 }
6475 }
6476
6477 @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6478 extends Traverser<K,V,Long> {
6479 final ObjectToLong<? super V> transformer;
6480 final LongByLongToLong reducer;
6481 final long basis;
6482 long result;
6483 MapReduceValuesToLongTask<K,V> rights, nextRight;
6484 MapReduceValuesToLongTask
6485 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6486 MapReduceValuesToLongTask<K,V> nextRight,
6487 ObjectToLong<? super V> transformer,
6488 long basis,
6489 LongByLongToLong reducer) {
6490 super(m, p, b); this.nextRight = nextRight;
6491 this.transformer = transformer;
6492 this.basis = basis; this.reducer = reducer;
6493 }
6494 public final Long getRawResult() { return result; }
6495 @SuppressWarnings("unchecked") public final void compute() {
6496 final ObjectToLong<? super V> transformer;
6497 final LongByLongToLong reducer;
6498 if ((transformer = this.transformer) != null &&
6499 (reducer = this.reducer) != null) {
6500 long r = this.basis;
6501 for (int b; (b = preSplit()) > 0;)
6502 (rights = new MapReduceValuesToLongTask<K,V>
6503 (map, this, b, rights, transformer, r, reducer)).fork();
6504 V v;
6505 while ((v = advance()) != null)
6506 r = reducer.apply(r, transformer.apply(v));
6507 result = r;
6508 CountedCompleter<?> c;
6509 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6510 MapReduceValuesToLongTask<K,V>
6511 t = (MapReduceValuesToLongTask<K,V>)c,
6512 s = t.rights;
6513 while (s != null) {
6514 t.result = reducer.apply(t.result, s.result);
6515 s = t.rights = s.nextRight;
6516 }
6517 }
6518 }
6519 }
6520 }
6521
6522 @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6523 extends Traverser<K,V,Long> {
6524 final ObjectToLong<Map.Entry<K,V>> transformer;
6525 final LongByLongToLong reducer;
6526 final long basis;
6527 long result;
6528 MapReduceEntriesToLongTask<K,V> rights, nextRight;
6529 MapReduceEntriesToLongTask
6530 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6531 MapReduceEntriesToLongTask<K,V> nextRight,
6532 ObjectToLong<Map.Entry<K,V>> transformer,
6533 long basis,
6534 LongByLongToLong reducer) {
6535 super(m, p, b); this.nextRight = nextRight;
6536 this.transformer = transformer;
6537 this.basis = basis; this.reducer = reducer;
6538 }
6539 public final Long getRawResult() { return result; }
6540 @SuppressWarnings("unchecked") public final void compute() {
6541 final ObjectToLong<Map.Entry<K,V>> transformer;
6542 final LongByLongToLong reducer;
6543 if ((transformer = this.transformer) != null &&
6544 (reducer = this.reducer) != null) {
6545 long r = this.basis;
6546 for (int b; (b = preSplit()) > 0;)
6547 (rights = new MapReduceEntriesToLongTask<K,V>
6548 (map, this, b, rights, transformer, r, reducer)).fork();
6549 V v;
6550 while ((v = advance()) != null)
6551 r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6552 v)));
6553 result = r;
6554 CountedCompleter<?> c;
6555 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6556 MapReduceEntriesToLongTask<K,V>
6557 t = (MapReduceEntriesToLongTask<K,V>)c,
6558 s = t.rights;
6559 while (s != null) {
6560 t.result = reducer.apply(t.result, s.result);
6561 s = t.rights = s.nextRight;
6562 }
6563 }
6564 }
6565 }
6566 }
6567
6568 @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6569 extends Traverser<K,V,Long> {
6570 final ObjectByObjectToLong<? super K, ? super V> transformer;
6571 final LongByLongToLong reducer;
6572 final long basis;
6573 long result;
6574 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6575 MapReduceMappingsToLongTask
6576 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6577 MapReduceMappingsToLongTask<K,V> nextRight,
6578 ObjectByObjectToLong<? super K, ? super V> transformer,
6579 long basis,
6580 LongByLongToLong reducer) {
6581 super(m, p, b); this.nextRight = nextRight;
6582 this.transformer = transformer;
6583 this.basis = basis; this.reducer = reducer;
6584 }
6585 public final Long getRawResult() { return result; }
6586 @SuppressWarnings("unchecked") public final void compute() {
6587 final ObjectByObjectToLong<? super K, ? super V> transformer;
6588 final LongByLongToLong reducer;
6589 if ((transformer = this.transformer) != null &&
6590 (reducer = this.reducer) != null) {
6591 long r = this.basis;
6592 for (int b; (b = preSplit()) > 0;)
6593 (rights = new MapReduceMappingsToLongTask<K,V>
6594 (map, this, b, rights, transformer, r, reducer)).fork();
6595 V v;
6596 while ((v = advance()) != null)
6597 r = reducer.apply(r, transformer.apply((K)nextKey, v));
6598 result = r;
6599 CountedCompleter<?> c;
6600 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6601 MapReduceMappingsToLongTask<K,V>
6602 t = (MapReduceMappingsToLongTask<K,V>)c,
6603 s = t.rights;
6604 while (s != null) {
6605 t.result = reducer.apply(t.result, s.result);
6606 s = t.rights = s.nextRight;
6607 }
6608 }
6609 }
6610 }
6611 }
6612
6613 @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6614 extends Traverser<K,V,Integer> {
6615 final ObjectToInt<? super K> transformer;
6616 final IntByIntToInt reducer;
6617 final int basis;
6618 int result;
6619 MapReduceKeysToIntTask<K,V> rights, nextRight;
6620 MapReduceKeysToIntTask
6621 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6622 MapReduceKeysToIntTask<K,V> nextRight,
6623 ObjectToInt<? super K> transformer,
6624 int basis,
6625 IntByIntToInt reducer) {
6626 super(m, p, b); this.nextRight = nextRight;
6627 this.transformer = transformer;
6628 this.basis = basis; this.reducer = reducer;
6629 }
6630 public final Integer getRawResult() { return result; }
6631 @SuppressWarnings("unchecked") public final void compute() {
6632 final ObjectToInt<? super K> transformer;
6633 final IntByIntToInt reducer;
6634 if ((transformer = this.transformer) != null &&
6635 (reducer = this.reducer) != null) {
6636 int r = this.basis;
6637 for (int b; (b = preSplit()) > 0;)
6638 (rights = new MapReduceKeysToIntTask<K,V>
6639 (map, this, b, rights, transformer, r, reducer)).fork();
6640 while (advance() != null)
6641 r = reducer.apply(r, transformer.apply((K)nextKey));
6642 result = r;
6643 CountedCompleter<?> c;
6644 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6645 MapReduceKeysToIntTask<K,V>
6646 t = (MapReduceKeysToIntTask<K,V>)c,
6647 s = t.rights;
6648 while (s != null) {
6649 t.result = reducer.apply(t.result, s.result);
6650 s = t.rights = s.nextRight;
6651 }
6652 }
6653 }
6654 }
6655 }
6656
6657 @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6658 extends Traverser<K,V,Integer> {
6659 final ObjectToInt<? super V> transformer;
6660 final IntByIntToInt reducer;
6661 final int basis;
6662 int result;
6663 MapReduceValuesToIntTask<K,V> rights, nextRight;
6664 MapReduceValuesToIntTask
6665 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6666 MapReduceValuesToIntTask<K,V> nextRight,
6667 ObjectToInt<? super V> transformer,
6668 int basis,
6669 IntByIntToInt reducer) {
6670 super(m, p, b); this.nextRight = nextRight;
6671 this.transformer = transformer;
6672 this.basis = basis; this.reducer = reducer;
6673 }
6674 public final Integer getRawResult() { return result; }
6675 @SuppressWarnings("unchecked") public final void compute() {
6676 final ObjectToInt<? super V> transformer;
6677 final IntByIntToInt reducer;
6678 if ((transformer = this.transformer) != null &&
6679 (reducer = this.reducer) != null) {
6680 int r = this.basis;
6681 for (int b; (b = preSplit()) > 0;)
6682 (rights = new MapReduceValuesToIntTask<K,V>
6683 (map, this, b, rights, transformer, r, reducer)).fork();
6684 V v;
6685 while ((v = advance()) != null)
6686 r = reducer.apply(r, transformer.apply(v));
6687 result = r;
6688 CountedCompleter<?> c;
6689 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6690 MapReduceValuesToIntTask<K,V>
6691 t = (MapReduceValuesToIntTask<K,V>)c,
6692 s = t.rights;
6693 while (s != null) {
6694 t.result = reducer.apply(t.result, s.result);
6695 s = t.rights = s.nextRight;
6696 }
6697 }
6698 }
6699 }
6700 }
6701
6702 @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6703 extends Traverser<K,V,Integer> {
6704 final ObjectToInt<Map.Entry<K,V>> transformer;
6705 final IntByIntToInt reducer;
6706 final int basis;
6707 int result;
6708 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6709 MapReduceEntriesToIntTask
6710 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6711 MapReduceEntriesToIntTask<K,V> nextRight,
6712 ObjectToInt<Map.Entry<K,V>> transformer,
6713 int basis,
6714 IntByIntToInt reducer) {
6715 super(m, p, b); this.nextRight = nextRight;
6716 this.transformer = transformer;
6717 this.basis = basis; this.reducer = reducer;
6718 }
6719 public final Integer getRawResult() { return result; }
6720 @SuppressWarnings("unchecked") public final void compute() {
6721 final ObjectToInt<Map.Entry<K,V>> transformer;
6722 final IntByIntToInt reducer;
6723 if ((transformer = this.transformer) != null &&
6724 (reducer = this.reducer) != null) {
6725 int r = this.basis;
6726 for (int b; (b = preSplit()) > 0;)
6727 (rights = new MapReduceEntriesToIntTask<K,V>
6728 (map, this, b, rights, transformer, r, reducer)).fork();
6729 V v;
6730 while ((v = advance()) != null)
6731 r = reducer.apply(r, transformer.apply(entryFor((K)nextKey,
6732 v)));
6733 result = r;
6734 CountedCompleter<?> c;
6735 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6736 MapReduceEntriesToIntTask<K,V>
6737 t = (MapReduceEntriesToIntTask<K,V>)c,
6738 s = t.rights;
6739 while (s != null) {
6740 t.result = reducer.apply(t.result, s.result);
6741 s = t.rights = s.nextRight;
6742 }
6743 }
6744 }
6745 }
6746 }
6747
6748 @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6749 extends Traverser<K,V,Integer> {
6750 final ObjectByObjectToInt<? super K, ? super V> transformer;
6751 final IntByIntToInt reducer;
6752 final int basis;
6753 int result;
6754 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6755 MapReduceMappingsToIntTask
6756 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6757 MapReduceMappingsToIntTask<K,V> nextRight,
6758 ObjectByObjectToInt<? super K, ? super V> transformer,
6759 int basis,
6760 IntByIntToInt reducer) {
6761 super(m, p, b); this.nextRight = nextRight;
6762 this.transformer = transformer;
6763 this.basis = basis; this.reducer = reducer;
6764 }
6765 public final Integer getRawResult() { return result; }
6766 @SuppressWarnings("unchecked") public final void compute() {
6767 final ObjectByObjectToInt<? super K, ? super V> transformer;
6768 final IntByIntToInt reducer;
6769 if ((transformer = this.transformer) != null &&
6770 (reducer = this.reducer) != null) {
6771 int r = this.basis;
6772 for (int b; (b = preSplit()) > 0;)
6773 (rights = new MapReduceMappingsToIntTask<K,V>
6774 (map, this, b, rights, transformer, r, reducer)).fork();
6775 V v;
6776 while ((v = advance()) != null)
6777 r = reducer.apply(r, transformer.apply((K)nextKey, v));
6778 result = r;
6779 CountedCompleter<?> c;
6780 for (c = firstComplete(); c != null; c = c.nextComplete()) {
6781 MapReduceMappingsToIntTask<K,V>
6782 t = (MapReduceMappingsToIntTask<K,V>)c,
6783 s = t.rights;
6784 while (s != null) {
6785 t.result = reducer.apply(t.result, s.result);
6786 s = t.rights = s.nextRight;
6787 }
6788 }
6789 }
6790 }
6791 }
6792
6793 // Unsafe mechanics
6794 private static final sun.misc.Unsafe U;
6795 private static final long SIZECTL;
6796 private static final long TRANSFERINDEX;
6797 private static final long TRANSFERORIGIN;
6798 private static final long BASECOUNT;
6799 private static final long COUNTERBUSY;
6800 private static final long CELLVALUE;
6801 private static final long ABASE;
6802 private static final int ASHIFT;
6803
6804 static {
6805 int ss;
6806 try {
6807 U = sun.misc.Unsafe.getUnsafe();
6808 Class<?> k = ConcurrentHashMap.class;
6809 SIZECTL = U.objectFieldOffset
6810 (k.getDeclaredField("sizeCtl"));
6811 TRANSFERINDEX = U.objectFieldOffset
6812 (k.getDeclaredField("transferIndex"));
6813 TRANSFERORIGIN = U.objectFieldOffset
6814 (k.getDeclaredField("transferOrigin"));
6815 BASECOUNT = U.objectFieldOffset
6816 (k.getDeclaredField("baseCount"));
6817 COUNTERBUSY = U.objectFieldOffset
6818 (k.getDeclaredField("counterBusy"));
6819 Class<?> ck = CounterCell.class;
6820 CELLVALUE = U.objectFieldOffset
6821 (ck.getDeclaredField("value"));
6822 Class<?> sc = Node[].class;
6823 ABASE = U.arrayBaseOffset(sc);
6824 ss = U.arrayIndexScale(sc);
6825 ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
6826 } catch (Exception e) {
6827 throw new Error(e);
6828 }
6829 if ((ss & (ss-1)) != 0)
6830 throw new Error("data type scale not a power of two");
6831 }
6832
6833 }