ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.204
Committed: Thu Apr 11 18:43:33 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.203: +5 -6 lines
Log Message:
Improve cccompare

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