ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.205
Committed: Thu Apr 11 20:13:38 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.204: +5 -17 lines
Log Message:
Simplify comparisons

File Contents

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