ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.207
Committed: Tue Apr 16 05:45:59 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.206: +3 -3 lines
Log Message:
whitespace

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