ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.199
Committed: Wed Mar 27 19:46:34 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.198: +3 -3 lines
Log Message:
conform to updated lambda Spliterator

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