ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
Revision: 1.100
Committed: Mon Feb 18 03:15:10 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.99: +1 -1 lines
Log Message:
whitespace

File Contents

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