ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.201
Committed: Thu Apr 11 17:41:10 2013 UTC (11 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.200: +103 -64 lines
Log Message:
Avoid potential Comparable exceptions by inspecting type parameters

File Contents

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