ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.197
Committed: Mon Mar 18 19:35:09 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.196: +1 -1 lines
Log Message:
key param specs

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.171 public void forEach(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.171 public void forEach(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.171 public void forEach(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 ForkJoinTasks.forEachKey
3575     (this, transformer, action).invoke();
3576     }
3577 dl 1.119
3578 dl 1.137 /**
3579     * Returns a non-null result from applying the given search
3580 dl 1.151 * function on each key, or null if none.
3581 dl 1.137 *
3582     * @param searchFunction a function returning a non-null
3583     * result on success, else null
3584     * @return a non-null result from applying the given search
3585     * function on each key, or null if none
3586     */
3587 jsr166 1.168 public <U> U searchKeysSequentially
3588 dl 1.153 (Function<? super K, ? extends U> searchFunction) {
3589 dl 1.151 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3590 dl 1.191 K k; U u;
3591     while ((k = it.advanceKey()) != null) {
3592     if ((u = searchFunction.apply(k)) != null)
3593 dl 1.151 return u;
3594     }
3595     return null;
3596 dl 1.137 }
3597 dl 1.119
3598 dl 1.137 /**
3599     * Returns the result of accumulating all keys using the given
3600     * reducer to combine values, or null if none.
3601     *
3602     * @param reducer a commutative associative combining function
3603     * @return the result of accumulating all keys using the given
3604     * reducer to combine values, or null if none
3605     */
3606 jsr166 1.168 public K reduceKeysSequentially
3607 dl 1.153 (BiFunction<? super K, ? super K, ? extends K> reducer) {
3608 dl 1.151 if (reducer == null) throw new NullPointerException();
3609     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3610 dl 1.191 K u, r = null;
3611     while ((u = it.advanceKey()) != null) {
3612 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3613     }
3614     return r;
3615 dl 1.137 }
3616 dl 1.119
3617 dl 1.137 /**
3618     * Returns the result of accumulating the given transformation
3619     * of all keys using the given reducer to combine values, or
3620     * null if none.
3621     *
3622     * @param transformer a function returning the transformation
3623 jsr166 1.169 * for an element, or null if there is no transformation (in
3624 jsr166 1.172 * which case it is not combined)
3625 dl 1.137 * @param reducer a commutative associative combining function
3626     * @return the result of accumulating the given transformation
3627     * of all keys
3628     */
3629 jsr166 1.168 public <U> U reduceKeysSequentially
3630 dl 1.153 (Function<? super K, ? extends U> transformer,
3631     BiFunction<? super U, ? super U, ? extends U> reducer) {
3632 dl 1.151 if (transformer == null || reducer == null)
3633     throw new NullPointerException();
3634     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3635 dl 1.191 K k; U r = null, u;
3636     while ((k = it.advanceKey()) != null) {
3637     if ((u = transformer.apply(k)) != null)
3638 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3639     }
3640     return r;
3641 dl 1.137 }
3642 dl 1.119
3643 dl 1.137 /**
3644     * Returns the result of accumulating the given transformation
3645     * of all keys using the given reducer to combine values, and
3646     * the given basis as an identity value.
3647     *
3648     * @param transformer a function returning the transformation
3649     * for an element
3650     * @param basis the identity (initial default value) for the reduction
3651     * @param reducer a commutative associative combining function
3652 jsr166 1.157 * @return the result of accumulating the given transformation
3653 dl 1.137 * of all keys
3654     */
3655 jsr166 1.168 public double reduceKeysToDoubleSequentially
3656 dl 1.171 (ToDoubleFunction<? super K> transformer,
3657 dl 1.151 double basis,
3658 dl 1.153 DoubleBinaryOperator reducer) {
3659 dl 1.151 if (transformer == null || reducer == null)
3660     throw new NullPointerException();
3661     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3662     double r = basis;
3663 dl 1.191 K k;
3664     while ((k = it.advanceKey()) != null)
3665     r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
3666 dl 1.151 return r;
3667 dl 1.137 }
3668 dl 1.119
3669 dl 1.137 /**
3670     * Returns the result of accumulating the given transformation
3671     * of all keys using the given reducer to combine values, and
3672     * the given basis as an identity value.
3673     *
3674     * @param transformer a function returning the transformation
3675     * for an element
3676     * @param basis the identity (initial default value) for the reduction
3677     * @param reducer a commutative associative combining function
3678     * @return the result of accumulating the given transformation
3679     * of all keys
3680     */
3681 jsr166 1.168 public long reduceKeysToLongSequentially
3682 dl 1.171 (ToLongFunction<? super K> transformer,
3683 dl 1.151 long basis,
3684 dl 1.153 LongBinaryOperator reducer) {
3685 dl 1.151 if (transformer == null || reducer == null)
3686     throw new NullPointerException();
3687     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3688     long r = basis;
3689 dl 1.191 K k;
3690     while ((k = it.advanceKey()) != null)
3691     r = reducer.applyAsLong(r, transformer.applyAsLong(k));
3692 dl 1.151 return r;
3693 dl 1.137 }
3694 dl 1.119
3695 dl 1.137 /**
3696     * Returns the result of accumulating the given transformation
3697     * of all keys using the given reducer to combine values, and
3698     * the given basis as an identity value.
3699     *
3700     * @param transformer a function returning the transformation
3701     * for an element
3702     * @param basis the identity (initial default value) for the reduction
3703     * @param reducer a commutative associative combining function
3704     * @return the result of accumulating the given transformation
3705     * of all keys
3706     */
3707 jsr166 1.168 public int reduceKeysToIntSequentially
3708 dl 1.171 (ToIntFunction<? super K> transformer,
3709 dl 1.151 int basis,
3710 dl 1.153 IntBinaryOperator reducer) {
3711 dl 1.151 if (transformer == null || reducer == null)
3712     throw new NullPointerException();
3713     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3714     int r = basis;
3715 dl 1.191 K k;
3716     while ((k = it.advanceKey()) != null)
3717     r = reducer.applyAsInt(r, transformer.applyAsInt(k));
3718 dl 1.151 return r;
3719 dl 1.137 }
3720 dl 1.119
3721 dl 1.137 /**
3722     * Performs the given action for each value.
3723     *
3724     * @param action the action
3725     */
3726 dl 1.171 public void forEachValueSequentially(Consumer<? super V> action) {
3727 dl 1.192 new Traverser<K,V,Object>(this).forEachValue(action);
3728 dl 1.137 }
3729 dl 1.119
3730 dl 1.137 /**
3731     * Performs the given action for each non-null transformation
3732     * of each value.
3733     *
3734     * @param transformer a function returning the transformation
3735 jsr166 1.169 * for an element, or null if there is no transformation (in
3736 jsr166 1.172 * which case the action is not applied)
3737 jsr166 1.179 * @param action the action
3738 dl 1.137 */
3739 dl 1.151 public <U> void forEachValueSequentially
3740 dl 1.153 (Function<? super V, ? extends U> transformer,
3741 dl 1.171 Consumer<? super U> action) {
3742 dl 1.151 if (transformer == null || action == null)
3743     throw new NullPointerException();
3744     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3745     V v; U u;
3746 dl 1.191 while ((v = it.advanceValue()) != null) {
3747 dl 1.151 if ((u = transformer.apply(v)) != null)
3748 dl 1.153 action.accept(u);
3749 dl 1.151 }
3750 dl 1.137 }
3751 dl 1.119
3752 dl 1.137 /**
3753     * Returns a non-null result from applying the given search
3754 dl 1.151 * function on each value, or null if none.
3755 dl 1.137 *
3756     * @param searchFunction a function returning a non-null
3757     * result on success, else null
3758     * @return a non-null result from applying the given search
3759     * function on each value, or null if none
3760     */
3761 dl 1.151 public <U> U searchValuesSequentially
3762 dl 1.153 (Function<? super V, ? extends U> searchFunction) {
3763 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3764     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3765     V v; U u;
3766 dl 1.191 while ((v = it.advanceValue()) != null) {
3767 dl 1.151 if ((u = searchFunction.apply(v)) != null)
3768     return u;
3769     }
3770     return null;
3771 dl 1.137 }
3772 dl 1.119
3773 dl 1.137 /**
3774     * Returns the result of accumulating all values using the
3775     * given reducer to combine values, or null if none.
3776     *
3777     * @param reducer a commutative associative combining function
3778 jsr166 1.157 * @return the result of accumulating all values
3779 dl 1.137 */
3780 dl 1.151 public V reduceValuesSequentially
3781 dl 1.153 (BiFunction<? super V, ? super V, ? extends V> reducer) {
3782 dl 1.151 if (reducer == null) throw new NullPointerException();
3783     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3784     V r = null; V v;
3785 dl 1.191 while ((v = it.advanceValue()) != null)
3786 dl 1.151 r = (r == null) ? v : reducer.apply(r, v);
3787     return r;
3788 dl 1.137 }
3789 dl 1.119
3790 dl 1.137 /**
3791     * Returns the result of accumulating the given transformation
3792     * of all values using the given reducer to combine values, or
3793     * null if none.
3794     *
3795     * @param transformer a function returning the transformation
3796 jsr166 1.169 * for an element, or null if there is no transformation (in
3797 jsr166 1.172 * which case it is not combined)
3798 dl 1.137 * @param reducer a commutative associative combining function
3799     * @return the result of accumulating the given transformation
3800     * of all values
3801     */
3802 dl 1.151 public <U> U reduceValuesSequentially
3803 dl 1.153 (Function<? super V, ? extends U> transformer,
3804     BiFunction<? super U, ? super U, ? extends U> reducer) {
3805 dl 1.151 if (transformer == null || reducer == null)
3806     throw new NullPointerException();
3807     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3808     U r = null, u; V v;
3809 dl 1.191 while ((v = it.advanceValue()) != null) {
3810 dl 1.151 if ((u = transformer.apply(v)) != null)
3811     r = (r == null) ? u : reducer.apply(r, u);
3812     }
3813     return r;
3814 dl 1.137 }
3815 dl 1.119
3816 dl 1.137 /**
3817     * Returns the result of accumulating the given transformation
3818     * of all values using the given reducer to combine values,
3819     * and the given basis as an identity value.
3820     *
3821     * @param transformer a function returning the transformation
3822     * for an element
3823     * @param basis the identity (initial default value) for the reduction
3824     * @param reducer a commutative associative combining function
3825     * @return the result of accumulating the given transformation
3826     * of all values
3827     */
3828 dl 1.151 public double reduceValuesToDoubleSequentially
3829 dl 1.171 (ToDoubleFunction<? super V> transformer,
3830 dl 1.151 double basis,
3831 dl 1.153 DoubleBinaryOperator reducer) {
3832 dl 1.151 if (transformer == null || reducer == null)
3833     throw new NullPointerException();
3834     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3835     double r = basis; V v;
3836 dl 1.191 while ((v = it.advanceValue()) != null)
3837 dl 1.153 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3838 dl 1.151 return r;
3839 dl 1.137 }
3840 dl 1.119
3841 dl 1.137 /**
3842     * Returns the result of accumulating the given transformation
3843     * of all values using the given reducer to combine values,
3844     * and the given basis as an identity value.
3845     *
3846     * @param transformer a function returning the transformation
3847     * for an element
3848     * @param basis the identity (initial default value) for the reduction
3849     * @param reducer a commutative associative combining function
3850     * @return the result of accumulating the given transformation
3851     * of all values
3852     */
3853 dl 1.151 public long reduceValuesToLongSequentially
3854 dl 1.171 (ToLongFunction<? super V> transformer,
3855 dl 1.151 long basis,
3856 dl 1.153 LongBinaryOperator reducer) {
3857 dl 1.151 if (transformer == null || reducer == null)
3858     throw new NullPointerException();
3859     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3860     long r = basis; V v;
3861 dl 1.191 while ((v = it.advanceValue()) != null)
3862 dl 1.153 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3863 dl 1.151 return r;
3864 dl 1.137 }
3865 dl 1.119
3866 dl 1.137 /**
3867     * Returns the result of accumulating the given transformation
3868     * of all values using the given reducer to combine values,
3869     * and the given basis as an identity value.
3870     *
3871     * @param transformer a function returning the transformation
3872     * for an element
3873     * @param basis the identity (initial default value) for the reduction
3874     * @param reducer a commutative associative combining function
3875     * @return the result of accumulating the given transformation
3876     * of all values
3877     */
3878 dl 1.151 public int reduceValuesToIntSequentially
3879 dl 1.171 (ToIntFunction<? super V> transformer,
3880 dl 1.151 int basis,
3881 dl 1.153 IntBinaryOperator reducer) {
3882 dl 1.151 if (transformer == null || reducer == null)
3883     throw new NullPointerException();
3884     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3885     int r = basis; V v;
3886 dl 1.191 while ((v = it.advanceValue()) != null)
3887 dl 1.153 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3888 dl 1.151 return r;
3889 dl 1.137 }
3890 dl 1.119
3891 dl 1.137 /**
3892     * Performs the given action for each entry.
3893     *
3894     * @param action the action
3895     */
3896 jsr166 1.168 public void forEachEntrySequentially
3897 dl 1.171 (Consumer<? super Map.Entry<K,V>> action) {
3898 dl 1.151 if (action == null) throw new NullPointerException();
3899     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3900     V v;
3901 dl 1.191 while ((v = it.advanceValue()) != null)
3902 jsr166 1.168 action.accept(entryFor(it.nextKey, v));
3903 dl 1.137 }
3904 dl 1.119
3905 dl 1.137 /**
3906     * Performs the given action for each non-null transformation
3907     * of each entry.
3908     *
3909     * @param transformer a function returning the transformation
3910 jsr166 1.169 * for an element, or null if there is no transformation (in
3911 jsr166 1.172 * which case the action is not applied)
3912 dl 1.137 * @param action the action
3913     */
3914 jsr166 1.168 public <U> void forEachEntrySequentially
3915 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
3916 dl 1.171 Consumer<? super U> action) {
3917 dl 1.151 if (transformer == null || action == null)
3918     throw new NullPointerException();
3919     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3920     V v; U u;
3921 dl 1.191 while ((v = it.advanceValue()) != null) {
3922 jsr166 1.168 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3923 dl 1.153 action.accept(u);
3924 dl 1.151 }
3925 dl 1.137 }
3926 dl 1.119
3927 dl 1.137 /**
3928     * Returns a non-null result from applying the given search
3929 dl 1.151 * function on each entry, or null if none.
3930 dl 1.137 *
3931     * @param searchFunction a function returning a non-null
3932     * result on success, else null
3933     * @return a non-null result from applying the given search
3934     * function on each entry, or null if none
3935     */
3936 jsr166 1.168 public <U> U searchEntriesSequentially
3937 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3938 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3939     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3940     V v; U u;
3941 dl 1.191 while ((v = it.advanceValue()) != null) {
3942 jsr166 1.168 if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3943 dl 1.151 return u;
3944     }
3945     return null;
3946 dl 1.137 }
3947 dl 1.119
3948 dl 1.137 /**
3949     * Returns the result of accumulating all entries using the
3950     * given reducer to combine values, or null if none.
3951     *
3952     * @param reducer a commutative associative combining function
3953     * @return the result of accumulating all entries
3954     */
3955 jsr166 1.168 public Map.Entry<K,V> reduceEntriesSequentially
3956 dl 1.153 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3957 dl 1.151 if (reducer == null) throw new NullPointerException();
3958     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3959     Map.Entry<K,V> r = null; V v;
3960 dl 1.191 while ((v = it.advanceValue()) != null) {
3961 jsr166 1.168 Map.Entry<K,V> u = entryFor(it.nextKey, v);
3962 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3963     }
3964     return r;
3965 dl 1.137 }
3966 dl 1.119
3967 dl 1.137 /**
3968     * Returns the result of accumulating the given transformation
3969     * of all entries using the given reducer to combine values,
3970     * or null if none.
3971     *
3972     * @param transformer a function returning the transformation
3973 jsr166 1.169 * for an element, or null if there is no transformation (in
3974 jsr166 1.172 * which case it is not combined)
3975 dl 1.137 * @param reducer a commutative associative combining function
3976     * @return the result of accumulating the given transformation
3977     * of all entries
3978     */
3979 jsr166 1.168 public <U> U reduceEntriesSequentially
3980 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
3981     BiFunction<? super U, ? super U, ? extends U> reducer) {
3982 dl 1.151 if (transformer == null || reducer == null)
3983     throw new NullPointerException();
3984     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3985     U r = null, u; V v;
3986 dl 1.191 while ((v = it.advanceValue()) != null) {
3987 jsr166 1.168 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3988 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3989     }
3990     return r;
3991 dl 1.137 }
3992 dl 1.119
3993 dl 1.137 /**
3994     * Returns the result of accumulating the given transformation
3995     * of all entries using the given reducer to combine values,
3996     * and the given basis as an identity value.
3997     *
3998     * @param transformer a function returning the transformation
3999     * for an element
4000     * @param basis the identity (initial default value) for the reduction
4001     * @param reducer a commutative associative combining function
4002     * @return the result of accumulating the given transformation
4003     * of all entries
4004     */
4005 jsr166 1.168 public double reduceEntriesToDoubleSequentially
4006 dl 1.171 (ToDoubleFunction<Map.Entry<K,V>> transformer,
4007 dl 1.151 double basis,
4008 dl 1.153 DoubleBinaryOperator reducer) {
4009 dl 1.151 if (transformer == null || reducer == null)
4010     throw new NullPointerException();
4011     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4012     double r = basis; V v;
4013 dl 1.191 while ((v = it.advanceValue()) != null)
4014 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
4015 dl 1.151 return r;
4016 dl 1.137 }
4017 dl 1.119
4018 dl 1.137 /**
4019     * Returns the result of accumulating the given transformation
4020     * of all entries using the given reducer to combine values,
4021     * and the given basis as an identity value.
4022     *
4023     * @param transformer a function returning the transformation
4024     * for an element
4025     * @param basis the identity (initial default value) for the reduction
4026     * @param reducer a commutative associative combining function
4027 jsr166 1.157 * @return the result of accumulating the given transformation
4028 dl 1.137 * of all entries
4029     */
4030 jsr166 1.168 public long reduceEntriesToLongSequentially
4031 dl 1.171 (ToLongFunction<Map.Entry<K,V>> transformer,
4032 dl 1.151 long basis,
4033 dl 1.153 LongBinaryOperator reducer) {
4034 dl 1.151 if (transformer == null || reducer == null)
4035     throw new NullPointerException();
4036     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4037     long r = basis; V v;
4038 dl 1.191 while ((v = it.advanceValue()) != null)
4039 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
4040 dl 1.151 return r;
4041 dl 1.137 }
4042 dl 1.119
4043 dl 1.137 /**
4044     * Returns the result of accumulating the given transformation
4045     * of all entries using the given reducer to combine values,
4046     * and the given basis as an identity value.
4047     *
4048     * @param transformer a function returning the transformation
4049     * for an element
4050     * @param basis the identity (initial default value) for the reduction
4051     * @param reducer a commutative associative combining function
4052     * @return the result of accumulating the given transformation
4053     * of all entries
4054     */
4055 jsr166 1.168 public int reduceEntriesToIntSequentially
4056 dl 1.171 (ToIntFunction<Map.Entry<K,V>> transformer,
4057 dl 1.151 int basis,
4058 dl 1.153 IntBinaryOperator reducer) {
4059 dl 1.151 if (transformer == null || reducer == null)
4060     throw new NullPointerException();
4061     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
4062     int r = basis; V v;
4063 dl 1.191 while ((v = it.advanceValue()) != null)
4064 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
4065 dl 1.151 return r;
4066 dl 1.119 }
4067    
4068 dl 1.151 // Parallel bulk operations
4069 dl 1.142
4070     /**
4071 dl 1.151 * Performs the given action for each (key, value).
4072     *
4073     * @param action the action
4074 dl 1.142 */
4075 dl 1.171 public void forEachInParallel(BiConsumer<? super K,? super V> action) {
4076 dl 1.151 ForkJoinTasks.forEach
4077     (this, action).invoke();
4078     }
4079 dl 1.142
4080 dl 1.151 /**
4081     * Performs the given action for each non-null transformation
4082     * of each (key, value).
4083     *
4084     * @param transformer a function returning the transformation
4085 jsr166 1.169 * for an element, or null if there is no transformation (in
4086 jsr166 1.172 * which case the action is not applied)
4087 dl 1.151 * @param action the action
4088     */
4089     public <U> void forEachInParallel
4090 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
4091 dl 1.171 Consumer<? super U> action) {
4092 dl 1.151 ForkJoinTasks.forEach
4093     (this, transformer, action).invoke();
4094     }
4095 dl 1.142
4096 dl 1.151 /**
4097     * Returns a non-null result from applying the given search
4098     * function on each (key, value), or null if none. Upon
4099     * success, further element processing is suppressed and the
4100     * results of any other parallel invocations of the search
4101     * function are ignored.
4102     *
4103     * @param searchFunction a function returning a non-null
4104     * result on success, else null
4105     * @return a non-null result from applying the given search
4106     * function on each (key, value), or null if none
4107     */
4108     public <U> U searchInParallel
4109 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4110 dl 1.151 return ForkJoinTasks.search
4111     (this, searchFunction).invoke();
4112     }
4113 dl 1.142
4114 dl 1.151 /**
4115     * Returns the result of accumulating the given transformation
4116     * of all (key, value) pairs using the given reducer to
4117     * combine values, or null if none.
4118     *
4119     * @param transformer a function returning the transformation
4120 jsr166 1.169 * for an element, or null if there is no transformation (in
4121 jsr166 1.172 * which case it is not combined)
4122 dl 1.151 * @param reducer a commutative associative combining function
4123     * @return the result of accumulating the given transformation
4124     * of all (key, value) pairs
4125     */
4126     public <U> U reduceInParallel
4127 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
4128     BiFunction<? super U, ? super U, ? extends U> reducer) {
4129 dl 1.151 return ForkJoinTasks.reduce
4130     (this, transformer, reducer).invoke();
4131     }
4132 dl 1.142
4133 dl 1.151 /**
4134     * Returns the result of accumulating the given transformation
4135     * of all (key, value) pairs using the given reducer to
4136     * combine values, and the given basis as an identity value.
4137     *
4138     * @param transformer a function returning the transformation
4139     * for an element
4140     * @param basis the identity (initial default value) for the reduction
4141     * @param reducer a commutative associative combining function
4142     * @return the result of accumulating the given transformation
4143     * of all (key, value) pairs
4144     */
4145     public double reduceToDoubleInParallel
4146 dl 1.171 (ToDoubleBiFunction<? super K, ? super V> transformer,
4147 dl 1.151 double basis,
4148 dl 1.153 DoubleBinaryOperator reducer) {
4149 dl 1.151 return ForkJoinTasks.reduceToDouble
4150     (this, transformer, basis, reducer).invoke();
4151     }
4152    
4153     /**
4154     * Returns the result of accumulating the given transformation
4155     * of all (key, value) pairs using the given reducer to
4156     * combine values, and the given basis as an identity value.
4157     *
4158     * @param transformer a function returning the transformation
4159     * for an element
4160     * @param basis the identity (initial default value) for the reduction
4161     * @param reducer a commutative associative combining function
4162     * @return the result of accumulating the given transformation
4163     * of all (key, value) pairs
4164     */
4165     public long reduceToLongInParallel
4166 dl 1.171 (ToLongBiFunction<? super K, ? super V> transformer,
4167 dl 1.151 long basis,
4168 dl 1.153 LongBinaryOperator reducer) {
4169 dl 1.151 return ForkJoinTasks.reduceToLong
4170     (this, transformer, basis, reducer).invoke();
4171     }
4172    
4173     /**
4174     * Returns the result of accumulating the given transformation
4175     * of all (key, value) pairs using the given reducer to
4176     * combine values, and the given basis as an identity value.
4177     *
4178     * @param transformer a function returning the transformation
4179     * for an element
4180     * @param basis the identity (initial default value) for the reduction
4181     * @param reducer a commutative associative combining function
4182     * @return the result of accumulating the given transformation
4183     * of all (key, value) pairs
4184     */
4185     public int reduceToIntInParallel
4186 dl 1.171 (ToIntBiFunction<? super K, ? super V> transformer,
4187 dl 1.151 int basis,
4188 dl 1.153 IntBinaryOperator reducer) {
4189 dl 1.151 return ForkJoinTasks.reduceToInt
4190     (this, transformer, basis, reducer).invoke();
4191     }
4192    
4193     /**
4194     * Performs the given action for each key.
4195     *
4196     * @param action the action
4197     */
4198 dl 1.171 public void forEachKeyInParallel(Consumer<? super K> action) {
4199 dl 1.151 ForkJoinTasks.forEachKey
4200     (this, action).invoke();
4201     }
4202    
4203     /**
4204     * Performs the given action for each non-null transformation
4205     * of each key.
4206     *
4207     * @param transformer a function returning the transformation
4208 jsr166 1.169 * for an element, or null if there is no transformation (in
4209 jsr166 1.172 * which case the action is not applied)
4210 dl 1.151 * @param action the action
4211     */
4212     public <U> void forEachKeyInParallel
4213 dl 1.153 (Function<? super K, ? extends U> transformer,
4214 dl 1.171 Consumer<? super U> action) {
4215 dl 1.151 ForkJoinTasks.forEachKey
4216     (this, transformer, action).invoke();
4217     }
4218    
4219     /**
4220     * Returns a non-null result from applying the given search
4221     * function on each key, or null if none. Upon success,
4222     * further element processing is suppressed and the results of
4223     * any other parallel invocations of the search function are
4224     * ignored.
4225     *
4226     * @param searchFunction a function returning a non-null
4227     * result on success, else null
4228     * @return a non-null result from applying the given search
4229     * function on each key, or null if none
4230     */
4231     public <U> U searchKeysInParallel
4232 dl 1.153 (Function<? super K, ? extends U> searchFunction) {
4233 dl 1.151 return ForkJoinTasks.searchKeys
4234     (this, searchFunction).invoke();
4235     }
4236    
4237     /**
4238     * Returns the result of accumulating all keys using the given
4239     * reducer to combine values, or null if none.
4240     *
4241     * @param reducer a commutative associative combining function
4242     * @return the result of accumulating all keys using the given
4243     * reducer to combine values, or null if none
4244     */
4245     public K reduceKeysInParallel
4246 dl 1.153 (BiFunction<? super K, ? super K, ? extends K> reducer) {
4247 dl 1.151 return ForkJoinTasks.reduceKeys
4248     (this, reducer).invoke();
4249     }
4250    
4251     /**
4252     * Returns the result of accumulating the given transformation
4253     * of all keys using the given reducer to combine values, or
4254     * null if none.
4255     *
4256     * @param transformer a function returning the transformation
4257 jsr166 1.169 * for an element, or null if there is no transformation (in
4258 jsr166 1.172 * which case it is not combined)
4259 dl 1.151 * @param reducer a commutative associative combining function
4260     * @return the result of accumulating the given transformation
4261     * of all keys
4262     */
4263     public <U> U reduceKeysInParallel
4264 dl 1.153 (Function<? super K, ? extends U> transformer,
4265     BiFunction<? super U, ? super U, ? extends U> reducer) {
4266 dl 1.151 return ForkJoinTasks.reduceKeys
4267     (this, transformer, reducer).invoke();
4268     }
4269    
4270     /**
4271     * Returns the result of accumulating the given transformation
4272     * of all keys using the given reducer to combine values, and
4273     * the given basis as an identity value.
4274     *
4275     * @param transformer a function returning the transformation
4276     * for an element
4277     * @param basis the identity (initial default value) for the reduction
4278     * @param reducer a commutative associative combining function
4279 jsr166 1.157 * @return the result of accumulating the given transformation
4280 dl 1.151 * of all keys
4281     */
4282     public double reduceKeysToDoubleInParallel
4283 dl 1.171 (ToDoubleFunction<? super K> transformer,
4284 dl 1.151 double basis,
4285 dl 1.153 DoubleBinaryOperator reducer) {
4286 dl 1.151 return ForkJoinTasks.reduceKeysToDouble
4287     (this, transformer, basis, reducer).invoke();
4288     }
4289    
4290     /**
4291     * Returns the result of accumulating the given transformation
4292     * of all keys using the given reducer to combine values, and
4293     * the given basis as an identity value.
4294     *
4295     * @param transformer a function returning the transformation
4296     * for an element
4297     * @param basis the identity (initial default value) for the reduction
4298     * @param reducer a commutative associative combining function
4299     * @return the result of accumulating the given transformation
4300     * of all keys
4301     */
4302     public long reduceKeysToLongInParallel
4303 dl 1.171 (ToLongFunction<? super K> transformer,
4304 dl 1.151 long basis,
4305 dl 1.153 LongBinaryOperator reducer) {
4306 dl 1.151 return ForkJoinTasks.reduceKeysToLong
4307     (this, transformer, basis, reducer).invoke();
4308     }
4309    
4310     /**
4311     * Returns the result of accumulating the given transformation
4312     * of all keys using the given reducer to combine values, and
4313     * the given basis as an identity value.
4314     *
4315     * @param transformer a function returning the transformation
4316     * for an element
4317     * @param basis the identity (initial default value) for the reduction
4318     * @param reducer a commutative associative combining function
4319     * @return the result of accumulating the given transformation
4320     * of all keys
4321     */
4322     public int reduceKeysToIntInParallel
4323 dl 1.171 (ToIntFunction<? super K> transformer,
4324 dl 1.151 int basis,
4325 dl 1.153 IntBinaryOperator reducer) {
4326 dl 1.151 return ForkJoinTasks.reduceKeysToInt
4327     (this, transformer, basis, reducer).invoke();
4328     }
4329    
4330     /**
4331     * Performs the given action for each value.
4332     *
4333     * @param action the action
4334     */
4335 dl 1.171 public void forEachValueInParallel(Consumer<? super V> action) {
4336 dl 1.151 ForkJoinTasks.forEachValue
4337     (this, action).invoke();
4338     }
4339    
4340     /**
4341     * Performs the given action for each non-null transformation
4342     * of each value.
4343     *
4344     * @param transformer a function returning the transformation
4345 jsr166 1.169 * for an element, or null if there is no transformation (in
4346 jsr166 1.172 * which case the action is not applied)
4347 jsr166 1.179 * @param action the action
4348 dl 1.151 */
4349     public <U> void forEachValueInParallel
4350 dl 1.153 (Function<? super V, ? extends U> transformer,
4351 dl 1.171 Consumer<? super U> action) {
4352 dl 1.151 ForkJoinTasks.forEachValue
4353     (this, transformer, action).invoke();
4354     }
4355    
4356     /**
4357     * Returns a non-null result from applying the given search
4358     * function on each value, or null if none. Upon success,
4359     * further element processing is suppressed and the results of
4360     * any other parallel invocations of the search function are
4361     * ignored.
4362     *
4363     * @param searchFunction a function returning a non-null
4364     * result on success, else null
4365     * @return a non-null result from applying the given search
4366     * function on each value, or null if none
4367     */
4368     public <U> U searchValuesInParallel
4369 dl 1.153 (Function<? super V, ? extends U> searchFunction) {
4370 dl 1.151 return ForkJoinTasks.searchValues
4371     (this, searchFunction).invoke();
4372     }
4373    
4374     /**
4375     * Returns the result of accumulating all values using the
4376     * given reducer to combine values, or null if none.
4377     *
4378     * @param reducer a commutative associative combining function
4379 jsr166 1.157 * @return the result of accumulating all values
4380 dl 1.151 */
4381     public V reduceValuesInParallel
4382 dl 1.153 (BiFunction<? super V, ? super V, ? extends V> reducer) {
4383 dl 1.151 return ForkJoinTasks.reduceValues
4384     (this, reducer).invoke();
4385     }
4386    
4387     /**
4388     * Returns the result of accumulating the given transformation
4389     * of all values using the given reducer to combine values, or
4390     * null if none.
4391     *
4392     * @param transformer a function returning the transformation
4393 jsr166 1.169 * for an element, or null if there is no transformation (in
4394 jsr166 1.172 * which case it is not combined)
4395 dl 1.151 * @param reducer a commutative associative combining function
4396     * @return the result of accumulating the given transformation
4397     * of all values
4398     */
4399     public <U> U reduceValuesInParallel
4400 dl 1.153 (Function<? super V, ? extends U> transformer,
4401     BiFunction<? super U, ? super U, ? extends U> reducer) {
4402 dl 1.151 return ForkJoinTasks.reduceValues
4403     (this, transformer, reducer).invoke();
4404     }
4405    
4406     /**
4407     * Returns the result of accumulating the given transformation
4408     * of all values using the given reducer to combine values,
4409     * and the given basis as an identity value.
4410     *
4411     * @param transformer a function returning the transformation
4412     * for an element
4413     * @param basis the identity (initial default value) for the reduction
4414     * @param reducer a commutative associative combining function
4415     * @return the result of accumulating the given transformation
4416     * of all values
4417     */
4418     public double reduceValuesToDoubleInParallel
4419 dl 1.171 (ToDoubleFunction<? super V> transformer,
4420 dl 1.151 double basis,
4421 dl 1.153 DoubleBinaryOperator reducer) {
4422 dl 1.151 return ForkJoinTasks.reduceValuesToDouble
4423     (this, transformer, basis, reducer).invoke();
4424     }
4425    
4426     /**
4427     * Returns the result of accumulating the given transformation
4428     * of all values using the given reducer to combine values,
4429     * and the given basis as an identity value.
4430     *
4431     * @param transformer a function returning the transformation
4432     * for an element
4433     * @param basis the identity (initial default value) for the reduction
4434     * @param reducer a commutative associative combining function
4435     * @return the result of accumulating the given transformation
4436     * of all values
4437     */
4438     public long reduceValuesToLongInParallel
4439 dl 1.171 (ToLongFunction<? super V> transformer,
4440 dl 1.151 long basis,
4441 dl 1.153 LongBinaryOperator reducer) {
4442 dl 1.151 return ForkJoinTasks.reduceValuesToLong
4443     (this, transformer, basis, reducer).invoke();
4444     }
4445    
4446     /**
4447     * Returns the result of accumulating the given transformation
4448     * of all values using the given reducer to combine values,
4449     * and the given basis as an identity value.
4450     *
4451     * @param transformer a function returning the transformation
4452     * for an element
4453     * @param basis the identity (initial default value) for the reduction
4454     * @param reducer a commutative associative combining function
4455     * @return the result of accumulating the given transformation
4456     * of all values
4457     */
4458     public int reduceValuesToIntInParallel
4459 dl 1.171 (ToIntFunction<? super V> transformer,
4460 dl 1.151 int basis,
4461 dl 1.153 IntBinaryOperator reducer) {
4462 dl 1.151 return ForkJoinTasks.reduceValuesToInt
4463     (this, transformer, basis, reducer).invoke();
4464     }
4465    
4466     /**
4467     * Performs the given action for each entry.
4468     *
4469     * @param action the action
4470     */
4471 dl 1.171 public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4472 dl 1.151 ForkJoinTasks.forEachEntry
4473     (this, action).invoke();
4474     }
4475    
4476     /**
4477     * Performs the given action for each non-null transformation
4478     * of each entry.
4479     *
4480     * @param transformer a function returning the transformation
4481 jsr166 1.169 * for an element, or null if there is no transformation (in
4482 jsr166 1.172 * which case the action is not applied)
4483 dl 1.151 * @param action the action
4484     */
4485     public <U> void forEachEntryInParallel
4486 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
4487 dl 1.171 Consumer<? super U> action) {
4488 dl 1.151 ForkJoinTasks.forEachEntry
4489     (this, transformer, action).invoke();
4490     }
4491    
4492     /**
4493     * Returns a non-null result from applying the given search
4494     * function on each entry, or null if none. Upon success,
4495     * further element processing is suppressed and the results of
4496     * any other parallel invocations of the search function are
4497     * ignored.
4498     *
4499     * @param searchFunction a function returning a non-null
4500     * result on success, else null
4501     * @return a non-null result from applying the given search
4502     * function on each entry, or null if none
4503     */
4504     public <U> U searchEntriesInParallel
4505 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4506 dl 1.151 return ForkJoinTasks.searchEntries
4507     (this, searchFunction).invoke();
4508     }
4509    
4510     /**
4511     * Returns the result of accumulating all entries using the
4512     * given reducer to combine values, or null if none.
4513     *
4514     * @param reducer a commutative associative combining function
4515     * @return the result of accumulating all entries
4516     */
4517     public Map.Entry<K,V> reduceEntriesInParallel
4518 dl 1.153 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4519 dl 1.151 return ForkJoinTasks.reduceEntries
4520     (this, reducer).invoke();
4521     }
4522    
4523     /**
4524     * Returns the result of accumulating the given transformation
4525     * of all entries using the given reducer to combine values,
4526     * or null if none.
4527     *
4528     * @param transformer a function returning the transformation
4529 jsr166 1.169 * for an element, or null if there is no transformation (in
4530 jsr166 1.172 * which case it is not combined)
4531 dl 1.151 * @param reducer a commutative associative combining function
4532     * @return the result of accumulating the given transformation
4533     * of all entries
4534     */
4535     public <U> U reduceEntriesInParallel
4536 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
4537     BiFunction<? super U, ? super U, ? extends U> reducer) {
4538 dl 1.151 return ForkJoinTasks.reduceEntries
4539     (this, transformer, reducer).invoke();
4540     }
4541    
4542     /**
4543     * Returns the result of accumulating the given transformation
4544     * of all entries using the given reducer to combine values,
4545     * and the given basis as an identity value.
4546     *
4547     * @param transformer a function returning the transformation
4548     * for an element
4549     * @param basis the identity (initial default value) for the reduction
4550     * @param reducer a commutative associative combining function
4551     * @return the result of accumulating the given transformation
4552     * of all entries
4553     */
4554     public double reduceEntriesToDoubleInParallel
4555 dl 1.171 (ToDoubleFunction<Map.Entry<K,V>> transformer,
4556 dl 1.151 double basis,
4557 dl 1.153 DoubleBinaryOperator reducer) {
4558 dl 1.151 return ForkJoinTasks.reduceEntriesToDouble
4559     (this, transformer, basis, reducer).invoke();
4560     }
4561    
4562     /**
4563     * Returns the result of accumulating the given transformation
4564     * of all entries using the given reducer to combine values,
4565     * and the given basis as an identity value.
4566     *
4567     * @param transformer a function returning the transformation
4568     * for an element
4569     * @param basis the identity (initial default value) for the reduction
4570     * @param reducer a commutative associative combining function
4571 jsr166 1.157 * @return the result of accumulating the given transformation
4572 dl 1.151 * of all entries
4573     */
4574     public long reduceEntriesToLongInParallel
4575 dl 1.171 (ToLongFunction<Map.Entry<K,V>> transformer,
4576 dl 1.151 long basis,
4577 dl 1.153 LongBinaryOperator reducer) {
4578 dl 1.151 return ForkJoinTasks.reduceEntriesToLong
4579     (this, transformer, basis, reducer).invoke();
4580     }
4581    
4582     /**
4583     * Returns the result of accumulating the given transformation
4584     * of all entries using the given reducer to combine values,
4585     * and the given basis as an identity value.
4586     *
4587     * @param transformer a function returning the transformation
4588     * for an element
4589     * @param basis the identity (initial default value) for the reduction
4590     * @param reducer a commutative associative combining function
4591     * @return the result of accumulating the given transformation
4592     * of all entries
4593     */
4594     public int reduceEntriesToIntInParallel
4595 dl 1.171 (ToIntFunction<Map.Entry<K,V>> transformer,
4596 dl 1.151 int basis,
4597 dl 1.153 IntBinaryOperator reducer) {
4598 dl 1.151 return ForkJoinTasks.reduceEntriesToInt
4599     (this, transformer, basis, reducer).invoke();
4600     }
4601    
4602    
4603     /* ----------------Views -------------- */
4604    
4605     /**
4606     * Base class for views.
4607     */
4608 jsr166 1.187 abstract static class CHMCollectionView<K,V,E>
4609 jsr166 1.184 implements Collection<E>, java.io.Serializable {
4610 dl 1.163 private static final long serialVersionUID = 7249069246763182397L;
4611 jsr166 1.186 final ConcurrentHashMap<K,V> map;
4612     CHMCollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4613 dl 1.151
4614     /**
4615     * Returns the map backing this view.
4616     *
4617     * @return the map backing this view
4618     */
4619     public ConcurrentHashMap<K,V> getMap() { return map; }
4620    
4621 jsr166 1.184 /**
4622     * Removes all of the elements from this view, by removing all
4623     * the mappings from the map backing this view.
4624     */
4625     public final void clear() { map.clear(); }
4626     public final int size() { return map.size(); }
4627     public final boolean isEmpty() { return map.isEmpty(); }
4628 dl 1.151
4629     // implementations below rely on concrete classes supplying these
4630 jsr166 1.184 // abstract methods
4631     /**
4632     * Returns a "weakly consistent" iterator that will never
4633     * throw {@link ConcurrentModificationException}, and
4634     * guarantees to traverse elements as they existed upon
4635     * construction of the iterator, and may (but is not
4636     * guaranteed to) reflect any modifications subsequent to
4637     * construction.
4638     */
4639     public abstract Iterator<E> iterator();
4640 jsr166 1.165 public abstract boolean contains(Object o);
4641     public abstract boolean remove(Object o);
4642 dl 1.151
4643     private static final String oomeMsg = "Required array size too large";
4644 dl 1.142
4645     public final Object[] toArray() {
4646     long sz = map.mappingCount();
4647 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4648 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4649     int n = (int)sz;
4650     Object[] r = new Object[n];
4651     int i = 0;
4652 jsr166 1.184 for (E e : this) {
4653 dl 1.142 if (i == n) {
4654     if (n >= MAX_ARRAY_SIZE)
4655     throw new OutOfMemoryError(oomeMsg);
4656     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4657     n = MAX_ARRAY_SIZE;
4658     else
4659     n += (n >>> 1) + 1;
4660     r = Arrays.copyOf(r, n);
4661     }
4662 jsr166 1.184 r[i++] = e;
4663 dl 1.142 }
4664     return (i == n) ? r : Arrays.copyOf(r, i);
4665     }
4666    
4667 jsr166 1.184 @SuppressWarnings("unchecked")
4668     public final <T> T[] toArray(T[] a) {
4669 dl 1.142 long sz = map.mappingCount();
4670 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4671 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4672     int m = (int)sz;
4673     T[] r = (a.length >= m) ? a :
4674     (T[])java.lang.reflect.Array
4675     .newInstance(a.getClass().getComponentType(), m);
4676     int n = r.length;
4677     int i = 0;
4678 jsr166 1.184 for (E e : this) {
4679 dl 1.142 if (i == n) {
4680     if (n >= MAX_ARRAY_SIZE)
4681     throw new OutOfMemoryError(oomeMsg);
4682     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4683     n = MAX_ARRAY_SIZE;
4684     else
4685     n += (n >>> 1) + 1;
4686     r = Arrays.copyOf(r, n);
4687     }
4688 jsr166 1.184 r[i++] = (T)e;
4689 dl 1.142 }
4690     if (a == r && i < n) {
4691     r[i] = null; // null-terminate
4692     return r;
4693     }
4694     return (i == n) ? r : Arrays.copyOf(r, i);
4695     }
4696    
4697 jsr166 1.184 /**
4698     * Returns a string representation of this collection.
4699     * The string representation consists of the string representations
4700     * of the collection's elements in the order they are returned by
4701     * its iterator, enclosed in square brackets ({@code "[]"}).
4702     * Adjacent elements are separated by the characters {@code ", "}
4703     * (comma and space). Elements are converted to strings as by
4704     * {@link String#valueOf(Object)}.
4705     *
4706     * @return a string representation of this collection
4707     */
4708 dl 1.142 public final String toString() {
4709     StringBuilder sb = new StringBuilder();
4710     sb.append('[');
4711 jsr166 1.184 Iterator<E> it = iterator();
4712 dl 1.142 if (it.hasNext()) {
4713     for (;;) {
4714     Object e = it.next();
4715     sb.append(e == this ? "(this Collection)" : e);
4716     if (!it.hasNext())
4717     break;
4718     sb.append(',').append(' ');
4719     }
4720     }
4721     return sb.append(']').toString();
4722     }
4723    
4724     public final boolean containsAll(Collection<?> c) {
4725     if (c != this) {
4726 jsr166 1.184 for (Object e : c) {
4727 dl 1.142 if (e == null || !contains(e))
4728     return false;
4729     }
4730     }
4731     return true;
4732     }
4733    
4734     public final boolean removeAll(Collection<?> c) {
4735     boolean modified = false;
4736 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4737 dl 1.142 if (c.contains(it.next())) {
4738     it.remove();
4739     modified = true;
4740     }
4741     }
4742     return modified;
4743     }
4744    
4745     public final boolean retainAll(Collection<?> c) {
4746     boolean modified = false;
4747 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4748 dl 1.142 if (!c.contains(it.next())) {
4749     it.remove();
4750     modified = true;
4751     }
4752     }
4753     return modified;
4754     }
4755    
4756     }
4757    
4758 jsr166 1.187 abstract static class CHMSetView<K,V,E>
4759     extends CHMCollectionView<K,V,E>
4760 jsr166 1.184 implements Set<E>, java.io.Serializable {
4761     private static final long serialVersionUID = 7249069246763182397L;
4762 jsr166 1.186 CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4763 jsr166 1.184
4764     // Implement Set API
4765    
4766     /**
4767     * Implements {@link Set#hashCode()}.
4768     * @return the hash code value for this set
4769     */
4770     public final int hashCode() {
4771     int h = 0;
4772     for (E e : this)
4773     h += e.hashCode();
4774     return h;
4775     }
4776    
4777     /**
4778     * Implements {@link Set#equals(Object)}.
4779     * @param o object to be compared for equality with this set
4780     * @return {@code true} if the specified object is equal to this set
4781     */
4782     public final boolean equals(Object o) {
4783     Set<?> c;
4784     return ((o instanceof Set) &&
4785     ((c = (Set<?>)o) == this ||
4786     (containsAll(c) && c.containsAll(this))));
4787     }
4788     }
4789    
4790 dl 1.142 /**
4791     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4792     * which additions may optionally be enabled by mapping to a
4793 jsr166 1.185 * common value. This class cannot be directly instantiated.
4794     * See {@link #keySet() keySet()},
4795     * {@link #keySet(Object) keySet(V)},
4796     * {@link #newKeySet() newKeySet()},
4797     * {@link #newKeySet(int) newKeySet(int)}.
4798 dl 1.142 */
4799 jsr166 1.184 public static class KeySetView<K,V>
4800     extends CHMSetView<K,V,K>
4801     implements Set<K>, java.io.Serializable {
4802 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4803     private final V value;
4804 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4805 dl 1.142 super(map);
4806     this.value = value;
4807     }
4808    
4809     /**
4810     * Returns the default mapped value for additions,
4811     * or {@code null} if additions are not supported.
4812     *
4813     * @return the default mapped value for additions, or {@code null}
4814 jsr166 1.172 * if not supported
4815 dl 1.142 */
4816     public V getMappedValue() { return value; }
4817    
4818 jsr166 1.184 /**
4819     * {@inheritDoc}
4820     * @throws NullPointerException if the specified key is null
4821     */
4822     public boolean contains(Object o) { return map.containsKey(o); }
4823 dl 1.142
4824 jsr166 1.184 /**
4825     * Removes the key from this map view, by removing the key (and its
4826     * corresponding value) from the backing map. This method does
4827     * nothing if the key is not in the map.
4828     *
4829     * @param o the key to be removed from the backing map
4830     * @return {@code true} if the backing map contained the specified key
4831     * @throws NullPointerException if the specified key is null
4832     */
4833     public boolean remove(Object o) { return map.remove(o) != null; }
4834    
4835     /**
4836     * @return an iterator over the keys of the backing map
4837     */
4838     public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4839 dl 1.142
4840     /**
4841 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4842     * the default mapped value in the backing map, if defined.
4843 dl 1.142 *
4844 jsr166 1.184 * @param e key to be added
4845     * @return {@code true} if this set changed as a result of the call
4846     * @throws NullPointerException if the specified key is null
4847     * @throws UnsupportedOperationException if no default mapped value
4848     * for additions was provided
4849 dl 1.142 */
4850     public boolean add(K e) {
4851     V v;
4852     if ((v = value) == null)
4853     throw new UnsupportedOperationException();
4854 dl 1.149 return map.internalPut(e, v, true) == null;
4855 dl 1.142 }
4856 jsr166 1.184
4857     /**
4858     * Adds all of the elements in the specified collection to this set,
4859     * as if by calling {@link #add} on each one.
4860     *
4861     * @param c the elements to be inserted into this set
4862     * @return {@code true} if this set changed as a result of the call
4863     * @throws NullPointerException if the collection or any of its
4864     * elements are {@code null}
4865     * @throws UnsupportedOperationException if no default mapped value
4866     * for additions was provided
4867     */
4868 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4869     boolean added = false;
4870     V v;
4871     if ((v = value) == null)
4872     throw new UnsupportedOperationException();
4873     for (K e : c) {
4874 dl 1.149 if (map.internalPut(e, v, true) == null)
4875 dl 1.142 added = true;
4876     }
4877     return added;
4878     }
4879 dl 1.153
4880 dl 1.194 public Spliterator<K> spliterator() {
4881 dl 1.191 return new KeyIterator<>(map, null);
4882     }
4883    
4884 dl 1.142 }
4885    
4886     /**
4887     * A view of a ConcurrentHashMap as a {@link Collection} of
4888     * values, in which additions are disabled. This class cannot be
4889 jsr166 1.181 * directly instantiated. See {@link #values()}.
4890 dl 1.142 *
4891     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4892     * that will never throw {@link ConcurrentModificationException},
4893     * and guarantees to traverse elements as they existed upon
4894     * construction of the iterator, and may (but is not guaranteed to)
4895     * reflect any modifications subsequent to construction.
4896     */
4897 jsr166 1.184 public static final class ValuesView<K,V>
4898     extends CHMCollectionView<K,V,V>
4899     implements Collection<V>, java.io.Serializable {
4900 jsr166 1.166 private static final long serialVersionUID = 2249069246763182397L;
4901 jsr166 1.186 ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4902 jsr166 1.184 public final boolean contains(Object o) {
4903     return map.containsValue(o);
4904     }
4905 dl 1.142 public final boolean remove(Object o) {
4906     if (o != null) {
4907 jsr166 1.184 for (Iterator<V> it = iterator(); it.hasNext();) {
4908 dl 1.142 if (o.equals(it.next())) {
4909     it.remove();
4910     return true;
4911     }
4912     }
4913     }
4914     return false;
4915     }
4916    
4917     /**
4918 jsr166 1.184 * @return an iterator over the values of the backing map
4919 dl 1.142 */
4920     public final Iterator<V> iterator() {
4921     return new ValueIterator<K,V>(map);
4922     }
4923 jsr166 1.184
4924     /** Always throws {@link UnsupportedOperationException}. */
4925 dl 1.142 public final boolean add(V e) {
4926     throw new UnsupportedOperationException();
4927     }
4928 jsr166 1.184 /** Always throws {@link UnsupportedOperationException}. */
4929 dl 1.142 public final boolean addAll(Collection<? extends V> c) {
4930     throw new UnsupportedOperationException();
4931     }
4932    
4933 dl 1.194 public Spliterator<V> spliterator() {
4934 dl 1.191 return new ValueIterator<K,V>(map, null);
4935     }
4936    
4937 dl 1.142 }
4938    
4939     /**
4940     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4941     * entries. This class cannot be directly instantiated. See
4942 jsr166 1.180 * {@link #entrySet()}.
4943 dl 1.142 */
4944 jsr166 1.184 public static final class EntrySetView<K,V>
4945     extends CHMSetView<K,V,Map.Entry<K,V>>
4946     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4947 jsr166 1.166 private static final long serialVersionUID = 2249069246763182397L;
4948 jsr166 1.186 EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4949 jsr166 1.184
4950 dl 1.142 public final boolean contains(Object o) {
4951     Object k, v, r; Map.Entry<?,?> e;
4952     return ((o instanceof Map.Entry) &&
4953     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4954     (r = map.get(k)) != null &&
4955     (v = e.getValue()) != null &&
4956     (v == r || v.equals(r)));
4957     }
4958     public final boolean remove(Object o) {
4959     Object k, v; Map.Entry<?,?> e;
4960     return ((o instanceof Map.Entry) &&
4961     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4962     (v = e.getValue()) != null &&
4963     map.remove(k, v));
4964     }
4965    
4966     /**
4967 jsr166 1.184 * @return an iterator over the entries of the backing map
4968 dl 1.142 */
4969     public final Iterator<Map.Entry<K,V>> iterator() {
4970     return new EntryIterator<K,V>(map);
4971     }
4972    
4973 jsr166 1.184 /**
4974     * Adds the specified mapping to this view.
4975     *
4976     * @param e mapping to be added
4977     * @return {@code true} if this set changed as a result of the call
4978     * @throws NullPointerException if the entry, its key, or its
4979     * value is null
4980     */
4981 dl 1.142 public final boolean add(Entry<K,V> e) {
4982 jsr166 1.182 return map.internalPut(e.getKey(), e.getValue(), false) == null;
4983 dl 1.142 }
4984 jsr166 1.184 /**
4985     * Adds all of the mappings in the specified collection to this
4986     * set, as if by calling {@link #add(Map.Entry)} on each one.
4987     * @param c the mappings to be inserted into this set
4988     * @return {@code true} if this set changed as a result of the call
4989     * @throws NullPointerException if the collection or any of its
4990     * entries, keys, or values are null
4991     */
4992 dl 1.142 public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4993     boolean added = false;
4994     for (Entry<K,V> e : c) {
4995     if (add(e))
4996     added = true;
4997     }
4998     return added;
4999     }
5000 dl 1.153
5001 dl 1.194 public Spliterator<Map.Entry<K,V>> spliterator() {
5002 dl 1.191 return new EntryIterator<K,V>(map, null);
5003     }
5004    
5005 dl 1.142 }
5006    
5007 dl 1.119 // ---------------------------------------------------------------------
5008    
5009     /**
5010     * Predefined tasks for performing bulk parallel operations on
5011     * ConcurrentHashMaps. These tasks follow the forms and rules used
5012 dl 1.137 * for bulk operations. Each method has the same name, but returns
5013     * a task rather than invoking it. These methods may be useful in
5014     * custom applications such as submitting a task without waiting
5015     * for completion, using a custom pool, or combining with other
5016     * tasks.
5017 dl 1.119 */
5018     public static class ForkJoinTasks {
5019     private ForkJoinTasks() {}
5020    
5021     /**
5022     * Returns a task that when invoked, performs the given
5023     * action for each (key, value)
5024     *
5025     * @param map the map
5026     * @param action the action
5027     * @return the task
5028     */
5029 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEach
5030 dl 1.119 (ConcurrentHashMap<K,V> map,
5031 dl 1.171 BiConsumer<? super K, ? super V> action) {
5032 dl 1.119 if (action == null) throw new NullPointerException();
5033 dl 1.146 return new ForEachMappingTask<K,V>(map, null, -1, action);
5034 dl 1.119 }
5035    
5036     /**
5037     * Returns a task that when invoked, performs the given
5038     * action for each non-null transformation of each (key, value)
5039     *
5040     * @param map the map
5041     * @param transformer a function returning the transformation
5042 jsr166 1.135 * for an element, or null if there is no transformation (in
5043 jsr166 1.134 * which case the action is not applied)
5044 dl 1.119 * @param action the action
5045     * @return the task
5046     */
5047 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEach
5048 dl 1.119 (ConcurrentHashMap<K,V> map,
5049 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5050 dl 1.171 Consumer<? super U> action) {
5051 dl 1.119 if (transformer == null || action == null)
5052     throw new NullPointerException();
5053     return new ForEachTransformedMappingTask<K,V,U>
5054 dl 1.146 (map, null, -1, transformer, action);
5055 dl 1.119 }
5056    
5057     /**
5058 dl 1.126 * Returns a task that when invoked, returns a non-null result
5059     * from applying the given search function on each (key,
5060     * value), or null if none. Upon success, further element
5061     * processing is suppressed and the results of any other
5062     * parallel invocations of the search function are ignored.
5063 dl 1.119 *
5064     * @param map the map
5065     * @param searchFunction a function returning a non-null
5066     * result on success, else null
5067     * @return the task
5068     */
5069     public static <K,V,U> ForkJoinTask<U> search
5070     (ConcurrentHashMap<K,V> map,
5071 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction) {
5072 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5073     return new SearchMappingsTask<K,V,U>
5074 dl 1.146 (map, null, -1, searchFunction,
5075 dl 1.119 new AtomicReference<U>());
5076     }
5077    
5078     /**
5079     * Returns a task that when invoked, returns the result of
5080     * accumulating the given transformation of all (key, value) pairs
5081     * using the given reducer to combine values, or null if none.
5082     *
5083     * @param map the map
5084     * @param transformer a function returning the transformation
5085 jsr166 1.135 * for an element, or null if there is no transformation (in
5086 jsr166 1.172 * which case it is not combined)
5087 dl 1.119 * @param reducer a commutative associative combining function
5088     * @return the task
5089     */
5090     public static <K,V,U> ForkJoinTask<U> reduce
5091     (ConcurrentHashMap<K,V> map,
5092 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5093     BiFunction<? super U, ? super U, ? extends U> reducer) {
5094 dl 1.119 if (transformer == null || reducer == null)
5095     throw new NullPointerException();
5096     return new MapReduceMappingsTask<K,V,U>
5097 dl 1.130 (map, null, -1, null, transformer, reducer);
5098 dl 1.119 }
5099    
5100     /**
5101     * Returns a task that when invoked, returns the result of
5102     * accumulating the given transformation of all (key, value) pairs
5103     * using the given reducer to combine values, and the given
5104     * basis as an identity value.
5105     *
5106     * @param map the map
5107     * @param transformer a function returning the transformation
5108     * for an element
5109     * @param basis the identity (initial default value) for the reduction
5110     * @param reducer a commutative associative combining function
5111     * @return the task
5112     */
5113     public static <K,V> ForkJoinTask<Double> reduceToDouble
5114     (ConcurrentHashMap<K,V> map,
5115 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
5116 dl 1.119 double basis,
5117 dl 1.153 DoubleBinaryOperator reducer) {
5118 dl 1.119 if (transformer == null || reducer == null)
5119     throw new NullPointerException();
5120     return new MapReduceMappingsToDoubleTask<K,V>
5121 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5122 dl 1.119 }
5123    
5124     /**
5125     * Returns a task that when invoked, returns the result of
5126     * accumulating the given transformation of all (key, value) pairs
5127     * using the given reducer to combine values, and the given
5128     * basis as an identity value.
5129     *
5130     * @param map the map
5131     * @param transformer a function returning the transformation
5132     * for an element
5133     * @param basis the identity (initial default value) for the reduction
5134     * @param reducer a commutative associative combining function
5135     * @return the task
5136     */
5137     public static <K,V> ForkJoinTask<Long> reduceToLong
5138     (ConcurrentHashMap<K,V> map,
5139 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
5140 dl 1.119 long basis,
5141 dl 1.153 LongBinaryOperator reducer) {
5142 dl 1.119 if (transformer == null || reducer == null)
5143     throw new NullPointerException();
5144     return new MapReduceMappingsToLongTask<K,V>
5145 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5146 dl 1.119 }
5147    
5148     /**
5149     * Returns a task that when invoked, returns the result of
5150     * accumulating the given transformation of all (key, value) pairs
5151     * using the given reducer to combine values, and the given
5152     * basis as an identity value.
5153     *
5154 jsr166 1.179 * @param map the map
5155 dl 1.119 * @param transformer a function returning the transformation
5156     * for an element
5157     * @param basis the identity (initial default value) for the reduction
5158     * @param reducer a commutative associative combining function
5159     * @return the task
5160     */
5161     public static <K,V> ForkJoinTask<Integer> reduceToInt
5162     (ConcurrentHashMap<K,V> map,
5163 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
5164 dl 1.119 int basis,
5165 dl 1.153 IntBinaryOperator reducer) {
5166 dl 1.119 if (transformer == null || reducer == null)
5167     throw new NullPointerException();
5168     return new MapReduceMappingsToIntTask<K,V>
5169 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5170 dl 1.119 }
5171    
5172     /**
5173     * Returns a task that when invoked, performs the given action
5174 jsr166 1.123 * for each key.
5175 dl 1.119 *
5176     * @param map the map
5177     * @param action the action
5178     * @return the task
5179     */
5180 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachKey
5181 dl 1.119 (ConcurrentHashMap<K,V> map,
5182 dl 1.171 Consumer<? super K> action) {
5183 dl 1.119 if (action == null) throw new NullPointerException();
5184 dl 1.146 return new ForEachKeyTask<K,V>(map, null, -1, action);
5185 dl 1.119 }
5186    
5187     /**
5188     * Returns a task that when invoked, performs the given action
5189 jsr166 1.123 * for each non-null transformation of each key.
5190 dl 1.119 *
5191     * @param map the map
5192     * @param transformer a function returning the transformation
5193 jsr166 1.135 * for an element, or null if there is no transformation (in
5194 jsr166 1.134 * which case the action is not applied)
5195 dl 1.119 * @param action the action
5196     * @return the task
5197     */
5198 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachKey
5199 dl 1.119 (ConcurrentHashMap<K,V> map,
5200 dl 1.153 Function<? super K, ? extends U> transformer,
5201 dl 1.171 Consumer<? super U> action) {
5202 dl 1.119 if (transformer == null || action == null)
5203     throw new NullPointerException();
5204     return new ForEachTransformedKeyTask<K,V,U>
5205 dl 1.146 (map, null, -1, transformer, action);
5206 dl 1.119 }
5207    
5208     /**
5209     * Returns a task that when invoked, returns a non-null result
5210     * from applying the given search function on each key, or
5211 dl 1.126 * null if none. Upon success, further element processing is
5212     * suppressed and the results of any other parallel
5213     * invocations of the search function are ignored.
5214 dl 1.119 *
5215     * @param map the map
5216     * @param searchFunction a function returning a non-null
5217     * result on success, else null
5218     * @return the task
5219     */
5220     public static <K,V,U> ForkJoinTask<U> searchKeys
5221     (ConcurrentHashMap<K,V> map,
5222 dl 1.153 Function<? super K, ? extends U> searchFunction) {
5223 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5224     return new SearchKeysTask<K,V,U>
5225 dl 1.146 (map, null, -1, searchFunction,
5226 dl 1.119 new AtomicReference<U>());
5227     }
5228    
5229     /**
5230     * Returns a task that when invoked, returns the result of
5231     * accumulating all keys using the given reducer to combine
5232     * values, or null if none.
5233     *
5234     * @param map the map
5235     * @param reducer a commutative associative combining function
5236     * @return the task
5237     */
5238     public static <K,V> ForkJoinTask<K> reduceKeys
5239     (ConcurrentHashMap<K,V> map,
5240 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5241 dl 1.119 if (reducer == null) throw new NullPointerException();
5242     return new ReduceKeysTask<K,V>
5243 dl 1.130 (map, null, -1, null, reducer);
5244 dl 1.119 }
5245 jsr166 1.125
5246 dl 1.119 /**
5247     * Returns a task that when invoked, returns the result of
5248     * accumulating the given transformation of all keys using the given
5249     * reducer to combine values, or null if none.
5250     *
5251     * @param map the map
5252     * @param transformer a function returning the transformation
5253 jsr166 1.135 * for an element, or null if there is no transformation (in
5254 jsr166 1.172 * which case it is not combined)
5255 dl 1.119 * @param reducer a commutative associative combining function
5256     * @return the task
5257     */
5258     public static <K,V,U> ForkJoinTask<U> reduceKeys
5259     (ConcurrentHashMap<K,V> map,
5260 dl 1.153 Function<? super K, ? extends U> transformer,
5261     BiFunction<? super U, ? super U, ? extends U> reducer) {
5262 dl 1.119 if (transformer == null || reducer == null)
5263     throw new NullPointerException();
5264     return new MapReduceKeysTask<K,V,U>
5265 dl 1.130 (map, null, -1, null, transformer, reducer);
5266 dl 1.119 }
5267    
5268     /**
5269     * Returns a task that when invoked, returns the result of
5270     * accumulating the given transformation of all keys using the given
5271     * reducer to combine values, and the given basis as an
5272     * identity value.
5273     *
5274     * @param map the map
5275     * @param transformer a function returning the transformation
5276     * for an element
5277     * @param basis the identity (initial default value) for the reduction
5278     * @param reducer a commutative associative combining function
5279     * @return the task
5280     */
5281     public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5282     (ConcurrentHashMap<K,V> map,
5283 dl 1.171 ToDoubleFunction<? super K> transformer,
5284 dl 1.119 double basis,
5285 dl 1.153 DoubleBinaryOperator reducer) {
5286 dl 1.119 if (transformer == null || reducer == null)
5287     throw new NullPointerException();
5288     return new MapReduceKeysToDoubleTask<K,V>
5289 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5290 dl 1.119 }
5291    
5292     /**
5293     * Returns a task that when invoked, returns the result of
5294     * accumulating the given transformation of all keys using the given
5295     * reducer to combine values, and the given basis as an
5296     * identity value.
5297     *
5298     * @param map the map
5299     * @param transformer a function returning the transformation
5300     * for an element
5301     * @param basis the identity (initial default value) for the reduction
5302     * @param reducer a commutative associative combining function
5303     * @return the task
5304     */
5305     public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5306     (ConcurrentHashMap<K,V> map,
5307 dl 1.171 ToLongFunction<? super K> transformer,
5308 dl 1.119 long basis,
5309 dl 1.153 LongBinaryOperator reducer) {
5310 dl 1.119 if (transformer == null || reducer == null)
5311     throw new NullPointerException();
5312     return new MapReduceKeysToLongTask<K,V>
5313 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5314 dl 1.119 }
5315    
5316     /**
5317     * Returns a task that when invoked, returns the result of
5318     * accumulating the given transformation of all keys using the given
5319     * reducer to combine values, and the given basis as an
5320     * identity value.
5321     *
5322     * @param map the map
5323     * @param transformer a function returning the transformation
5324     * for an element
5325     * @param basis the identity (initial default value) for the reduction
5326     * @param reducer a commutative associative combining function
5327     * @return the task
5328     */
5329     public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5330     (ConcurrentHashMap<K,V> map,
5331 dl 1.171 ToIntFunction<? super K> transformer,
5332 dl 1.119 int basis,
5333 dl 1.153 IntBinaryOperator reducer) {
5334 dl 1.119 if (transformer == null || reducer == null)
5335     throw new NullPointerException();
5336     return new MapReduceKeysToIntTask<K,V>
5337 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5338 dl 1.119 }
5339    
5340     /**
5341     * Returns a task that when invoked, performs the given action
5342 jsr166 1.123 * for each value.
5343 dl 1.119 *
5344     * @param map the map
5345     * @param action the action
5346 jsr166 1.173 * @return the task
5347 dl 1.119 */
5348 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachValue
5349 dl 1.119 (ConcurrentHashMap<K,V> map,
5350 dl 1.171 Consumer<? super V> action) {
5351 dl 1.119 if (action == null) throw new NullPointerException();
5352 dl 1.146 return new ForEachValueTask<K,V>(map, null, -1, action);
5353 dl 1.119 }
5354    
5355     /**
5356     * Returns a task that when invoked, performs the given action
5357 jsr166 1.123 * for each non-null transformation of each value.
5358 dl 1.119 *
5359     * @param map the map
5360     * @param transformer a function returning the transformation
5361 jsr166 1.135 * for an element, or null if there is no transformation (in
5362 jsr166 1.134 * which case the action is not applied)
5363 dl 1.119 * @param action the action
5364 jsr166 1.173 * @return the task
5365 dl 1.119 */
5366 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachValue
5367 dl 1.119 (ConcurrentHashMap<K,V> map,
5368 dl 1.153 Function<? super V, ? extends U> transformer,
5369 dl 1.171 Consumer<? super U> action) {
5370 dl 1.119 if (transformer == null || action == null)
5371     throw new NullPointerException();
5372     return new ForEachTransformedValueTask<K,V,U>
5373 dl 1.146 (map, null, -1, transformer, action);
5374 dl 1.119 }
5375    
5376     /**
5377     * Returns a task that when invoked, returns a non-null result
5378     * from applying the given search function on each value, or
5379 dl 1.126 * null if none. Upon success, further element processing is
5380     * suppressed and the results of any other parallel
5381     * invocations of the search function are ignored.
5382 dl 1.119 *
5383     * @param map the map
5384     * @param searchFunction a function returning a non-null
5385     * result on success, else null
5386     * @return the task
5387     */
5388     public static <K,V,U> ForkJoinTask<U> searchValues
5389     (ConcurrentHashMap<K,V> map,
5390 dl 1.153 Function<? super V, ? extends U> searchFunction) {
5391 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5392     return new SearchValuesTask<K,V,U>
5393 dl 1.146 (map, null, -1, searchFunction,
5394 dl 1.119 new AtomicReference<U>());
5395     }
5396    
5397     /**
5398     * Returns a task that when invoked, returns the result of
5399     * accumulating all values using the given reducer to combine
5400     * values, or null if none.
5401     *
5402     * @param map the map
5403     * @param reducer a commutative associative combining function
5404     * @return the task
5405     */
5406     public static <K,V> ForkJoinTask<V> reduceValues
5407     (ConcurrentHashMap<K,V> map,
5408 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5409 dl 1.119 if (reducer == null) throw new NullPointerException();
5410     return new ReduceValuesTask<K,V>
5411 dl 1.130 (map, null, -1, null, reducer);
5412 dl 1.119 }
5413    
5414     /**
5415     * Returns a task that when invoked, returns the result of
5416     * accumulating the given transformation of all values using the
5417     * given reducer to combine values, or null if none.
5418     *
5419     * @param map the map
5420     * @param transformer a function returning the transformation
5421 jsr166 1.135 * for an element, or null if there is no transformation (in
5422 jsr166 1.172 * which case it is not combined)
5423 dl 1.119 * @param reducer a commutative associative combining function
5424     * @return the task
5425     */
5426     public static <K,V,U> ForkJoinTask<U> reduceValues
5427     (ConcurrentHashMap<K,V> map,
5428 dl 1.153 Function<? super V, ? extends U> transformer,
5429     BiFunction<? super U, ? super U, ? extends U> reducer) {
5430 dl 1.119 if (transformer == null || reducer == null)
5431     throw new NullPointerException();
5432     return new MapReduceValuesTask<K,V,U>
5433 dl 1.130 (map, null, -1, null, transformer, reducer);
5434 dl 1.119 }
5435    
5436     /**
5437     * Returns a task that when invoked, returns the result of
5438     * accumulating the given transformation of all values using the
5439     * given reducer to combine values, and the given basis as an
5440     * identity value.
5441     *
5442     * @param map the map
5443     * @param transformer a function returning the transformation
5444     * for an element
5445     * @param basis the identity (initial default value) for the reduction
5446     * @param reducer a commutative associative combining function
5447     * @return the task
5448     */
5449     public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5450     (ConcurrentHashMap<K,V> map,
5451 dl 1.171 ToDoubleFunction<? super V> transformer,
5452 dl 1.119 double basis,
5453 dl 1.153 DoubleBinaryOperator reducer) {
5454 dl 1.119 if (transformer == null || reducer == null)
5455     throw new NullPointerException();
5456     return new MapReduceValuesToDoubleTask<K,V>
5457 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5458 dl 1.119 }
5459    
5460     /**
5461     * Returns a task that when invoked, returns the result of
5462     * accumulating the given transformation of all values using the
5463     * given reducer to combine values, and the given basis as an
5464     * identity value.
5465     *
5466     * @param map the map
5467     * @param transformer a function returning the transformation
5468     * for an element
5469     * @param basis the identity (initial default value) for the reduction
5470     * @param reducer a commutative associative combining function
5471     * @return the task
5472     */
5473     public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5474     (ConcurrentHashMap<K,V> map,
5475 dl 1.171 ToLongFunction<? super V> transformer,
5476 dl 1.119 long basis,
5477 dl 1.153 LongBinaryOperator reducer) {
5478 dl 1.119 if (transformer == null || reducer == null)
5479     throw new NullPointerException();
5480     return new MapReduceValuesToLongTask<K,V>
5481 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5482 dl 1.119 }
5483    
5484     /**
5485     * Returns a task that when invoked, returns the result of
5486     * accumulating the given transformation of all values using the
5487     * given reducer to combine values, and the given basis as an
5488     * identity value.
5489     *
5490     * @param map the map
5491     * @param transformer a function returning the transformation
5492     * for an element
5493     * @param basis the identity (initial default value) for the reduction
5494     * @param reducer a commutative associative combining function
5495     * @return the task
5496     */
5497     public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5498     (ConcurrentHashMap<K,V> map,
5499 dl 1.171 ToIntFunction<? super V> transformer,
5500 dl 1.119 int basis,
5501 dl 1.153 IntBinaryOperator reducer) {
5502 dl 1.119 if (transformer == null || reducer == null)
5503     throw new NullPointerException();
5504     return new MapReduceValuesToIntTask<K,V>
5505 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5506 dl 1.119 }
5507    
5508     /**
5509     * Returns a task that when invoked, perform the given action
5510 jsr166 1.123 * for each entry.
5511 dl 1.119 *
5512     * @param map the map
5513     * @param action the action
5514 jsr166 1.173 * @return the task
5515 dl 1.119 */
5516 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachEntry
5517 dl 1.119 (ConcurrentHashMap<K,V> map,
5518 dl 1.171 Consumer<? super Map.Entry<K,V>> action) {
5519 dl 1.119 if (action == null) throw new NullPointerException();
5520 dl 1.146 return new ForEachEntryTask<K,V>(map, null, -1, action);
5521 dl 1.119 }
5522    
5523     /**
5524     * Returns a task that when invoked, perform the given action
5525 jsr166 1.123 * for each non-null transformation of each entry.
5526 dl 1.119 *
5527     * @param map the map
5528     * @param transformer a function returning the transformation
5529 jsr166 1.135 * for an element, or null if there is no transformation (in
5530 jsr166 1.134 * which case the action is not applied)
5531 dl 1.119 * @param action the action
5532 jsr166 1.173 * @return the task
5533 dl 1.119 */
5534 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachEntry
5535 dl 1.119 (ConcurrentHashMap<K,V> map,
5536 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5537 dl 1.171 Consumer<? super U> action) {
5538 dl 1.119 if (transformer == null || action == null)
5539     throw new NullPointerException();
5540     return new ForEachTransformedEntryTask<K,V,U>
5541 dl 1.146 (map, null, -1, transformer, action);
5542 dl 1.119 }
5543    
5544     /**
5545     * Returns a task that when invoked, returns a non-null result
5546     * from applying the given search function on each entry, or
5547 dl 1.126 * null if none. Upon success, further element processing is
5548     * suppressed and the results of any other parallel
5549     * invocations of the search function are ignored.
5550 dl 1.119 *
5551     * @param map the map
5552     * @param searchFunction a function returning a non-null
5553     * result on success, else null
5554     * @return the task
5555     */
5556     public static <K,V,U> ForkJoinTask<U> searchEntries
5557     (ConcurrentHashMap<K,V> map,
5558 dl 1.153 Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5559 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5560     return new SearchEntriesTask<K,V,U>
5561 dl 1.146 (map, null, -1, searchFunction,
5562 dl 1.119 new AtomicReference<U>());
5563     }
5564    
5565     /**
5566     * Returns a task that when invoked, returns the result of
5567     * accumulating all entries using the given reducer to combine
5568     * values, or null if none.
5569     *
5570     * @param map the map
5571     * @param reducer a commutative associative combining function
5572     * @return the task
5573     */
5574     public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5575     (ConcurrentHashMap<K,V> map,
5576 dl 1.153 BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5577 dl 1.119 if (reducer == null) throw new NullPointerException();
5578     return new ReduceEntriesTask<K,V>
5579 dl 1.130 (map, null, -1, null, reducer);
5580 dl 1.119 }
5581    
5582     /**
5583     * Returns a task that when invoked, returns the result of
5584     * accumulating the given transformation of all entries using the
5585     * given reducer to combine values, or null if none.
5586     *
5587     * @param map the map
5588     * @param transformer a function returning the transformation
5589 jsr166 1.135 * for an element, or null if there is no transformation (in
5590 jsr166 1.172 * which case it is not combined)
5591 dl 1.119 * @param reducer a commutative associative combining function
5592     * @return the task
5593     */
5594     public static <K,V,U> ForkJoinTask<U> reduceEntries
5595     (ConcurrentHashMap<K,V> map,
5596 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5597     BiFunction<? super U, ? super U, ? extends U> reducer) {
5598 dl 1.119 if (transformer == null || reducer == null)
5599     throw new NullPointerException();
5600     return new MapReduceEntriesTask<K,V,U>
5601 dl 1.130 (map, null, -1, null, transformer, reducer);
5602 dl 1.119 }
5603    
5604     /**
5605     * Returns a task that when invoked, returns the result of
5606     * accumulating the given transformation of all entries using the
5607     * given reducer to combine values, and the given basis as an
5608     * identity value.
5609     *
5610     * @param map the map
5611     * @param transformer a function returning the transformation
5612     * for an element
5613     * @param basis the identity (initial default value) for the reduction
5614     * @param reducer a commutative associative combining function
5615     * @return the task
5616     */
5617     public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5618     (ConcurrentHashMap<K,V> map,
5619 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5620 dl 1.119 double basis,
5621 dl 1.153 DoubleBinaryOperator reducer) {
5622 dl 1.119 if (transformer == null || reducer == null)
5623     throw new NullPointerException();
5624     return new MapReduceEntriesToDoubleTask<K,V>
5625 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5626 dl 1.119 }
5627    
5628     /**
5629     * Returns a task that when invoked, returns the result of
5630     * accumulating the given transformation of all entries using the
5631     * given reducer to combine values, and the given basis as an
5632     * identity value.
5633     *
5634     * @param map the map
5635     * @param transformer a function returning the transformation
5636     * for an element
5637     * @param basis the identity (initial default value) for the reduction
5638     * @param reducer a commutative associative combining function
5639     * @return the task
5640     */
5641     public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5642     (ConcurrentHashMap<K,V> map,
5643 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
5644 dl 1.119 long basis,
5645 dl 1.153 LongBinaryOperator reducer) {
5646 dl 1.119 if (transformer == null || reducer == null)
5647     throw new NullPointerException();
5648     return new MapReduceEntriesToLongTask<K,V>
5649 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5650 dl 1.119 }
5651    
5652     /**
5653     * Returns a task that when invoked, returns the result of
5654     * accumulating the given transformation of all entries using the
5655     * given reducer to combine values, and the given basis as an
5656     * identity value.
5657     *
5658     * @param map the map
5659     * @param transformer a function returning the transformation
5660     * for an element
5661     * @param basis the identity (initial default value) for the reduction
5662     * @param reducer a commutative associative combining function
5663     * @return the task
5664     */
5665     public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5666     (ConcurrentHashMap<K,V> map,
5667 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
5668 dl 1.119 int basis,
5669 dl 1.153 IntBinaryOperator reducer) {
5670 dl 1.119 if (transformer == null || reducer == null)
5671     throw new NullPointerException();
5672     return new MapReduceEntriesToIntTask<K,V>
5673 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5674 dl 1.119 }
5675     }
5676    
5677     // -------------------------------------------------------
5678    
5679     /*
5680     * Task classes. Coded in a regular but ugly format/style to
5681     * simplify checks that each variant differs in the right way from
5682 dl 1.149 * others. The null screenings exist because compilers cannot tell
5683     * that we've already null-checked task arguments, so we force
5684     * simplest hoisted bypass to help avoid convoluted traps.
5685 dl 1.119 */
5686    
5687 dl 1.128 @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5688 dl 1.146 extends Traverser<K,V,Void> {
5689 dl 1.171 final Consumer<? super K> action;
5690 dl 1.119 ForEachKeyTask
5691 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5692 dl 1.171 Consumer<? super K> action) {
5693 dl 1.146 super(m, p, b);
5694 dl 1.119 this.action = action;
5695     }
5696 jsr166 1.168 public final void compute() {
5697 dl 1.171 final Consumer<? super K> action;
5698 dl 1.149 if ((action = this.action) != null) {
5699     for (int b; (b = preSplit()) > 0;)
5700     new ForEachKeyTask<K,V>(map, this, b, action).fork();
5701 dl 1.192 forEachKey(action);
5702 dl 1.149 propagateCompletion();
5703     }
5704 dl 1.119 }
5705     }
5706    
5707 dl 1.128 @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5708 dl 1.146 extends Traverser<K,V,Void> {
5709 dl 1.171 final Consumer<? super V> action;
5710 dl 1.119 ForEachValueTask
5711 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5712 dl 1.171 Consumer<? super V> action) {
5713 dl 1.146 super(m, p, b);
5714 dl 1.119 this.action = action;
5715     }
5716 jsr166 1.168 public final void compute() {
5717 dl 1.171 final Consumer<? super V> action;
5718 dl 1.149 if ((action = this.action) != null) {
5719     for (int b; (b = preSplit()) > 0;)
5720     new ForEachValueTask<K,V>(map, this, b, action).fork();
5721 dl 1.192 forEachValue(action);
5722 dl 1.149 propagateCompletion();
5723     }
5724 dl 1.119 }
5725     }
5726    
5727 dl 1.128 @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5728 dl 1.146 extends Traverser<K,V,Void> {
5729 dl 1.171 final Consumer<? super Entry<K,V>> action;
5730 dl 1.119 ForEachEntryTask
5731 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5732 dl 1.171 Consumer<? super Entry<K,V>> action) {
5733 dl 1.146 super(m, p, b);
5734 dl 1.119 this.action = action;
5735     }
5736 jsr166 1.168 public final void compute() {
5737 dl 1.171 final Consumer<? super Entry<K,V>> action;
5738 dl 1.149 if ((action = this.action) != null) {
5739     for (int b; (b = preSplit()) > 0;)
5740     new ForEachEntryTask<K,V>(map, this, b, action).fork();
5741 dl 1.151 V v;
5742 dl 1.191 while ((v = advanceValue()) != null)
5743 jsr166 1.168 action.accept(entryFor(nextKey, v));
5744 dl 1.149 propagateCompletion();
5745     }
5746 dl 1.119 }
5747     }
5748    
5749 dl 1.128 @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5750 dl 1.146 extends Traverser<K,V,Void> {
5751 dl 1.171 final BiConsumer<? super K, ? super V> action;
5752 dl 1.119 ForEachMappingTask
5753 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5754 dl 1.171 BiConsumer<? super K,? super V> action) {
5755 dl 1.146 super(m, p, b);
5756 dl 1.119 this.action = action;
5757     }
5758 jsr166 1.168 public final void compute() {
5759 dl 1.171 final BiConsumer<? super K, ? super V> action;
5760 dl 1.149 if ((action = this.action) != null) {
5761     for (int b; (b = preSplit()) > 0;)
5762     new ForEachMappingTask<K,V>(map, this, b, action).fork();
5763 dl 1.151 V v;
5764 dl 1.191 while ((v = advanceValue()) != null)
5765 jsr166 1.168 action.accept(nextKey, v);
5766 dl 1.149 propagateCompletion();
5767     }
5768 dl 1.119 }
5769     }
5770    
5771 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5772 dl 1.146 extends Traverser<K,V,Void> {
5773 dl 1.153 final Function<? super K, ? extends U> transformer;
5774 dl 1.171 final Consumer<? super U> action;
5775 dl 1.119 ForEachTransformedKeyTask
5776 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5777 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5778 dl 1.146 super(m, p, b);
5779     this.transformer = transformer; this.action = action;
5780     }
5781 jsr166 1.168 public final void compute() {
5782 dl 1.153 final Function<? super K, ? extends U> transformer;
5783 dl 1.171 final Consumer<? super U> action;
5784 dl 1.149 if ((transformer = this.transformer) != null &&
5785     (action = this.action) != null) {
5786     for (int b; (b = preSplit()) > 0;)
5787     new ForEachTransformedKeyTask<K,V,U>
5788     (map, this, b, transformer, action).fork();
5789 dl 1.191 K k; U u;
5790     while ((k = advanceKey()) != null) {
5791     if ((u = transformer.apply(k)) != null)
5792 dl 1.153 action.accept(u);
5793 dl 1.149 }
5794     propagateCompletion();
5795 dl 1.119 }
5796     }
5797     }
5798    
5799 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5800 dl 1.146 extends Traverser<K,V,Void> {
5801 dl 1.153 final Function<? super V, ? extends U> transformer;
5802 dl 1.171 final Consumer<? super U> action;
5803 dl 1.119 ForEachTransformedValueTask
5804 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5805 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5806 dl 1.146 super(m, p, b);
5807     this.transformer = transformer; this.action = action;
5808     }
5809 jsr166 1.168 public final void compute() {
5810 dl 1.153 final Function<? super V, ? extends U> transformer;
5811 dl 1.171 final Consumer<? super U> action;
5812 dl 1.149 if ((transformer = this.transformer) != null &&
5813     (action = this.action) != null) {
5814     for (int b; (b = preSplit()) > 0;)
5815     new ForEachTransformedValueTask<K,V,U>
5816     (map, this, b, transformer, action).fork();
5817 dl 1.151 V v; U u;
5818 dl 1.191 while ((v = advanceValue()) != null) {
5819 dl 1.151 if ((u = transformer.apply(v)) != null)
5820 dl 1.153 action.accept(u);
5821 dl 1.149 }
5822     propagateCompletion();
5823 dl 1.119 }
5824     }
5825 tim 1.1 }
5826    
5827 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5828 dl 1.146 extends Traverser<K,V,Void> {
5829 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5830 dl 1.171 final Consumer<? super U> action;
5831 dl 1.119 ForEachTransformedEntryTask
5832 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5833 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5834 dl 1.146 super(m, p, b);
5835     this.transformer = transformer; this.action = action;
5836     }
5837 jsr166 1.168 public final void compute() {
5838 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5839 dl 1.171 final Consumer<? super U> action;
5840 dl 1.149 if ((transformer = this.transformer) != null &&
5841     (action = this.action) != null) {
5842     for (int b; (b = preSplit()) > 0;)
5843     new ForEachTransformedEntryTask<K,V,U>
5844     (map, this, b, transformer, action).fork();
5845 dl 1.151 V v; U u;
5846 dl 1.191 while ((v = advanceValue()) != null) {
5847 jsr166 1.168 if ((u = transformer.apply(entryFor(nextKey,
5848 dl 1.151 v))) != null)
5849 dl 1.153 action.accept(u);
5850 dl 1.149 }
5851     propagateCompletion();
5852 dl 1.119 }
5853     }
5854 tim 1.1 }
5855    
5856 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5857 dl 1.146 extends Traverser<K,V,Void> {
5858 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5859 dl 1.171 final Consumer<? super U> action;
5860 dl 1.119 ForEachTransformedMappingTask
5861 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5862 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5863 dl 1.171 Consumer<? super U> action) {
5864 dl 1.146 super(m, p, b);
5865     this.transformer = transformer; this.action = action;
5866 dl 1.119 }
5867 jsr166 1.168 public final void compute() {
5868 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5869 dl 1.171 final Consumer<? super U> action;
5870 dl 1.149 if ((transformer = this.transformer) != null &&
5871     (action = this.action) != null) {
5872     for (int b; (b = preSplit()) > 0;)
5873     new ForEachTransformedMappingTask<K,V,U>
5874     (map, this, b, transformer, action).fork();
5875 dl 1.151 V v; U u;
5876 dl 1.191 while ((v = advanceValue()) != null) {
5877 jsr166 1.168 if ((u = transformer.apply(nextKey, v)) != null)
5878 dl 1.153 action.accept(u);
5879 dl 1.149 }
5880     propagateCompletion();
5881 dl 1.119 }
5882     }
5883 tim 1.1 }
5884    
5885 dl 1.128 @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5886 dl 1.146 extends Traverser<K,V,U> {
5887 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5888 dl 1.119 final AtomicReference<U> result;
5889     SearchKeysTask
5890 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5891 dl 1.153 Function<? super K, ? extends U> searchFunction,
5892 dl 1.119 AtomicReference<U> result) {
5893 dl 1.146 super(m, p, b);
5894 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5895     }
5896 dl 1.146 public final U getRawResult() { return result.get(); }
5897 jsr166 1.168 public final void compute() {
5898 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5899 dl 1.146 final AtomicReference<U> result;
5900 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5901     (result = this.result) != null) {
5902     for (int b;;) {
5903     if (result.get() != null)
5904     return;
5905     if ((b = preSplit()) <= 0)
5906     break;
5907     new SearchKeysTask<K,V,U>
5908     (map, this, b, searchFunction, result).fork();
5909 dl 1.128 }
5910 dl 1.149 while (result.get() == null) {
5911 dl 1.191 K k; U u;
5912     if ((k = advanceKey()) == null) {
5913 dl 1.149 propagateCompletion();
5914     break;
5915     }
5916 dl 1.191 if ((u = searchFunction.apply(k)) != null) {
5917 dl 1.149 if (result.compareAndSet(null, u))
5918     quietlyCompleteRoot();
5919     break;
5920     }
5921 dl 1.119 }
5922     }
5923     }
5924 tim 1.1 }
5925    
5926 dl 1.128 @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5927 dl 1.146 extends Traverser<K,V,U> {
5928 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5929 dl 1.119 final AtomicReference<U> result;
5930     SearchValuesTask
5931 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5932 dl 1.153 Function<? super V, ? extends U> searchFunction,
5933 dl 1.119 AtomicReference<U> result) {
5934 dl 1.146 super(m, p, b);
5935 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5936     }
5937 dl 1.146 public final U getRawResult() { return result.get(); }
5938 jsr166 1.168 public final void compute() {
5939 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5940 dl 1.146 final AtomicReference<U> result;
5941 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5942     (result = this.result) != null) {
5943     for (int b;;) {
5944     if (result.get() != null)
5945     return;
5946     if ((b = preSplit()) <= 0)
5947     break;
5948     new SearchValuesTask<K,V,U>
5949     (map, this, b, searchFunction, result).fork();
5950 dl 1.128 }
5951 dl 1.149 while (result.get() == null) {
5952 dl 1.151 V v; U u;
5953 dl 1.191 if ((v = advanceValue()) == null) {
5954 dl 1.149 propagateCompletion();
5955     break;
5956     }
5957 dl 1.151 if ((u = searchFunction.apply(v)) != null) {
5958 dl 1.149 if (result.compareAndSet(null, u))
5959     quietlyCompleteRoot();
5960     break;
5961     }
5962 dl 1.119 }
5963     }
5964     }
5965     }
5966 tim 1.11
5967 dl 1.128 @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5968 dl 1.146 extends Traverser<K,V,U> {
5969 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5970 dl 1.119 final AtomicReference<U> result;
5971     SearchEntriesTask
5972 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5973 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
5974 dl 1.119 AtomicReference<U> result) {
5975 dl 1.146 super(m, p, b);
5976 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5977     }
5978 dl 1.146 public final U getRawResult() { return result.get(); }
5979 jsr166 1.168 public final void compute() {
5980 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5981 dl 1.146 final AtomicReference<U> result;
5982 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5983     (result = this.result) != null) {
5984     for (int b;;) {
5985     if (result.get() != null)
5986     return;
5987     if ((b = preSplit()) <= 0)
5988     break;
5989     new SearchEntriesTask<K,V,U>
5990     (map, this, b, searchFunction, result).fork();
5991 dl 1.128 }
5992 dl 1.149 while (result.get() == null) {
5993 dl 1.151 V v; U u;
5994 dl 1.191 if ((v = advanceValue()) == null) {
5995 dl 1.149 propagateCompletion();
5996     break;
5997     }
5998 jsr166 1.168 if ((u = searchFunction.apply(entryFor(nextKey,
5999 dl 1.151 v))) != null) {
6000 dl 1.149 if (result.compareAndSet(null, u))
6001     quietlyCompleteRoot();
6002     return;
6003     }
6004 dl 1.119 }
6005     }
6006     }
6007     }
6008 tim 1.1
6009 dl 1.128 @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
6010 dl 1.146 extends Traverser<K,V,U> {
6011 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
6012 dl 1.119 final AtomicReference<U> result;
6013     SearchMappingsTask
6014 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6015 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
6016 dl 1.119 AtomicReference<U> result) {
6017 dl 1.146 super(m, p, b);
6018 dl 1.119 this.searchFunction = searchFunction; this.result = result;
6019     }
6020 dl 1.146 public final U getRawResult() { return result.get(); }
6021 jsr166 1.168 public final void compute() {
6022 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
6023 dl 1.146 final AtomicReference<U> result;
6024 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
6025     (result = this.result) != null) {
6026     for (int b;;) {
6027     if (result.get() != null)
6028     return;
6029     if ((b = preSplit()) <= 0)
6030     break;
6031     new SearchMappingsTask<K,V,U>
6032     (map, this, b, searchFunction, result).fork();
6033 dl 1.128 }
6034 dl 1.149 while (result.get() == null) {
6035 dl 1.151 V v; U u;
6036 dl 1.191 if ((v = advanceValue()) == null) {
6037 dl 1.149 propagateCompletion();
6038     break;
6039     }
6040 jsr166 1.168 if ((u = searchFunction.apply(nextKey, v)) != null) {
6041 dl 1.149 if (result.compareAndSet(null, u))
6042     quietlyCompleteRoot();
6043     break;
6044     }
6045 dl 1.119 }
6046     }
6047 tim 1.1 }
6048 dl 1.119 }
6049 tim 1.1
6050 dl 1.128 @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
6051 dl 1.146 extends Traverser<K,V,K> {
6052 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
6053 dl 1.119 K result;
6054 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
6055 dl 1.119 ReduceKeysTask
6056 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6057 dl 1.128 ReduceKeysTask<K,V> nextRight,
6058 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
6059 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6060 dl 1.119 this.reducer = reducer;
6061     }
6062 dl 1.146 public final K getRawResult() { return result; }
6063     @SuppressWarnings("unchecked") public final void compute() {
6064 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
6065 dl 1.149 if ((reducer = this.reducer) != null) {
6066     for (int b; (b = preSplit()) > 0;)
6067     (rights = new ReduceKeysTask<K,V>
6068     (map, this, b, rights, reducer)).fork();
6069 dl 1.191 K u, r = null;
6070     while ((u = advanceKey()) != null) {
6071 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
6072 dl 1.149 }
6073     result = r;
6074     CountedCompleter<?> c;
6075     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6076     ReduceKeysTask<K,V>
6077     t = (ReduceKeysTask<K,V>)c,
6078     s = t.rights;
6079     while (s != null) {
6080     K tr, sr;
6081     if ((sr = s.result) != null)
6082     t.result = (((tr = t.result) == null) ? sr :
6083     reducer.apply(tr, sr));
6084     s = t.rights = s.nextRight;
6085     }
6086 dl 1.99 }
6087 dl 1.138 }
6088 tim 1.1 }
6089 dl 1.119 }
6090 tim 1.1
6091 dl 1.128 @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
6092 dl 1.146 extends Traverser<K,V,V> {
6093 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
6094 dl 1.119 V result;
6095 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
6096 dl 1.119 ReduceValuesTask
6097 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6098 dl 1.128 ReduceValuesTask<K,V> nextRight,
6099 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
6100 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6101 dl 1.119 this.reducer = reducer;
6102     }
6103 dl 1.146 public final V getRawResult() { return result; }
6104     @SuppressWarnings("unchecked") public final void compute() {
6105 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
6106 dl 1.149 if ((reducer = this.reducer) != null) {
6107     for (int b; (b = preSplit()) > 0;)
6108     (rights = new ReduceValuesTask<K,V>
6109     (map, this, b, rights, reducer)).fork();
6110 dl 1.153 V r = null, v;
6111 dl 1.191 while ((v = advanceValue()) != null)
6112 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
6113 dl 1.149 result = r;
6114     CountedCompleter<?> c;
6115     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6116     ReduceValuesTask<K,V>
6117     t = (ReduceValuesTask<K,V>)c,
6118     s = t.rights;
6119     while (s != null) {
6120     V tr, sr;
6121     if ((sr = s.result) != null)
6122     t.result = (((tr = t.result) == null) ? sr :
6123     reducer.apply(tr, sr));
6124     s = t.rights = s.nextRight;
6125     }
6126 dl 1.119 }
6127     }
6128 tim 1.1 }
6129 dl 1.119 }
6130 tim 1.1
6131 dl 1.128 @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6132 dl 1.146 extends Traverser<K,V,Map.Entry<K,V>> {
6133 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6134 dl 1.119 Map.Entry<K,V> result;
6135 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
6136 dl 1.119 ReduceEntriesTask
6137 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6138 dl 1.130 ReduceEntriesTask<K,V> nextRight,
6139 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6140 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6141 dl 1.119 this.reducer = reducer;
6142     }
6143 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
6144     @SuppressWarnings("unchecked") public final void compute() {
6145 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6146 dl 1.149 if ((reducer = this.reducer) != null) {
6147     for (int b; (b = preSplit()) > 0;)
6148     (rights = new ReduceEntriesTask<K,V>
6149     (map, this, b, rights, reducer)).fork();
6150     Map.Entry<K,V> r = null;
6151 dl 1.151 V v;
6152 dl 1.191 while ((v = advanceValue()) != null) {
6153 jsr166 1.168 Map.Entry<K,V> u = entryFor(nextKey, v);
6154 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6155     }
6156     result = r;
6157     CountedCompleter<?> c;
6158     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6159     ReduceEntriesTask<K,V>
6160     t = (ReduceEntriesTask<K,V>)c,
6161     s = t.rights;
6162     while (s != null) {
6163     Map.Entry<K,V> tr, sr;
6164     if ((sr = s.result) != null)
6165     t.result = (((tr = t.result) == null) ? sr :
6166     reducer.apply(tr, sr));
6167     s = t.rights = s.nextRight;
6168     }
6169 dl 1.119 }
6170 dl 1.138 }
6171 dl 1.119 }
6172     }
6173 dl 1.99
6174 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6175 dl 1.146 extends Traverser<K,V,U> {
6176 dl 1.153 final Function<? super K, ? extends U> transformer;
6177     final BiFunction<? super U, ? super U, ? extends U> reducer;
6178 dl 1.119 U result;
6179 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
6180 dl 1.119 MapReduceKeysTask
6181 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6182 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
6183 dl 1.153 Function<? super K, ? extends U> transformer,
6184     BiFunction<? super U, ? super U, ? extends U> reducer) {
6185 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6186 dl 1.119 this.transformer = transformer;
6187     this.reducer = reducer;
6188     }
6189 dl 1.146 public final U getRawResult() { return result; }
6190     @SuppressWarnings("unchecked") public final void compute() {
6191 dl 1.153 final Function<? super K, ? extends U> transformer;
6192     final BiFunction<? super U, ? super U, ? extends U> reducer;
6193 dl 1.149 if ((transformer = this.transformer) != null &&
6194     (reducer = this.reducer) != null) {
6195     for (int b; (b = preSplit()) > 0;)
6196     (rights = new MapReduceKeysTask<K,V,U>
6197     (map, this, b, rights, transformer, reducer)).fork();
6198 dl 1.191 K k; U r = null, u;
6199     while ((k = advanceKey()) != null) {
6200     if ((u = transformer.apply(k)) != null)
6201 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6202     }
6203     result = r;
6204     CountedCompleter<?> c;
6205     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6206     MapReduceKeysTask<K,V,U>
6207     t = (MapReduceKeysTask<K,V,U>)c,
6208     s = t.rights;
6209     while (s != null) {
6210     U tr, sr;
6211     if ((sr = s.result) != null)
6212     t.result = (((tr = t.result) == null) ? sr :
6213     reducer.apply(tr, sr));
6214     s = t.rights = s.nextRight;
6215     }
6216 dl 1.119 }
6217 dl 1.138 }
6218 tim 1.1 }
6219 dl 1.4 }
6220    
6221 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6222 dl 1.146 extends Traverser<K,V,U> {
6223 dl 1.153 final Function<? super V, ? extends U> transformer;
6224     final BiFunction<? super U, ? super U, ? extends U> reducer;
6225 dl 1.119 U result;
6226 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
6227 dl 1.119 MapReduceValuesTask
6228 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6229 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
6230 dl 1.153 Function<? super V, ? extends U> transformer,
6231     BiFunction<? super U, ? super U, ? extends U> reducer) {
6232 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6233 dl 1.119 this.transformer = transformer;
6234     this.reducer = reducer;
6235     }
6236 dl 1.146 public final U getRawResult() { return result; }
6237     @SuppressWarnings("unchecked") public final void compute() {
6238 dl 1.153 final Function<? super V, ? extends U> transformer;
6239     final BiFunction<? super U, ? super U, ? extends U> reducer;
6240 dl 1.149 if ((transformer = this.transformer) != null &&
6241     (reducer = this.reducer) != null) {
6242     for (int b; (b = preSplit()) > 0;)
6243     (rights = new MapReduceValuesTask<K,V,U>
6244     (map, this, b, rights, transformer, reducer)).fork();
6245     U r = null, u;
6246 dl 1.151 V v;
6247 dl 1.191 while ((v = advanceValue()) != null) {
6248 dl 1.151 if ((u = transformer.apply(v)) != null)
6249 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6250     }
6251     result = r;
6252     CountedCompleter<?> c;
6253     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6254     MapReduceValuesTask<K,V,U>
6255     t = (MapReduceValuesTask<K,V,U>)c,
6256     s = t.rights;
6257     while (s != null) {
6258     U tr, sr;
6259     if ((sr = s.result) != null)
6260     t.result = (((tr = t.result) == null) ? sr :
6261     reducer.apply(tr, sr));
6262     s = t.rights = s.nextRight;
6263     }
6264 dl 1.119 }
6265     }
6266     }
6267 dl 1.4 }
6268    
6269 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6270 dl 1.146 extends Traverser<K,V,U> {
6271 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
6272     final BiFunction<? super U, ? super U, ? extends U> reducer;
6273 dl 1.119 U result;
6274 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
6275 dl 1.119 MapReduceEntriesTask
6276 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6277 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
6278 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
6279     BiFunction<? super U, ? super U, ? extends U> reducer) {
6280 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6281 dl 1.119 this.transformer = transformer;
6282     this.reducer = reducer;
6283     }
6284 dl 1.146 public final U getRawResult() { return result; }
6285     @SuppressWarnings("unchecked") public final void compute() {
6286 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
6287     final BiFunction<? super U, ? super U, ? extends U> reducer;
6288 dl 1.149 if ((transformer = this.transformer) != null &&
6289     (reducer = this.reducer) != null) {
6290     for (int b; (b = preSplit()) > 0;)
6291     (rights = new MapReduceEntriesTask<K,V,U>
6292     (map, this, b, rights, transformer, reducer)).fork();
6293     U r = null, u;
6294 dl 1.151 V v;
6295 dl 1.191 while ((v = advanceValue()) != null) {
6296 jsr166 1.168 if ((u = transformer.apply(entryFor(nextKey,
6297 dl 1.151 v))) != null)
6298 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6299     }
6300     result = r;
6301     CountedCompleter<?> c;
6302     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6303     MapReduceEntriesTask<K,V,U>
6304     t = (MapReduceEntriesTask<K,V,U>)c,
6305     s = t.rights;
6306     while (s != null) {
6307     U tr, sr;
6308     if ((sr = s.result) != null)
6309     t.result = (((tr = t.result) == null) ? sr :
6310     reducer.apply(tr, sr));
6311     s = t.rights = s.nextRight;
6312     }
6313 dl 1.119 }
6314 dl 1.138 }
6315 dl 1.119 }
6316 dl 1.4 }
6317 tim 1.1
6318 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6319 dl 1.146 extends Traverser<K,V,U> {
6320 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
6321     final BiFunction<? super U, ? super U, ? extends U> reducer;
6322 dl 1.119 U result;
6323 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
6324 dl 1.119 MapReduceMappingsTask
6325 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6326 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
6327 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
6328     BiFunction<? super U, ? super U, ? extends U> reducer) {
6329 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6330 dl 1.119 this.transformer = transformer;
6331     this.reducer = reducer;
6332     }
6333 dl 1.146 public final U getRawResult() { return result; }
6334     @SuppressWarnings("unchecked") public final void compute() {
6335 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
6336     final BiFunction<? super U, ? super U, ? extends U> reducer;
6337 dl 1.149 if ((transformer = this.transformer) != null &&
6338     (reducer = this.reducer) != null) {
6339     for (int b; (b = preSplit()) > 0;)
6340     (rights = new MapReduceMappingsTask<K,V,U>
6341     (map, this, b, rights, transformer, reducer)).fork();
6342     U r = null, u;
6343 dl 1.151 V v;
6344 dl 1.191 while ((v = advanceValue()) != null) {
6345 jsr166 1.168 if ((u = transformer.apply(nextKey, v)) != null)
6346 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6347     }
6348     result = r;
6349     CountedCompleter<?> c;
6350     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6351     MapReduceMappingsTask<K,V,U>
6352     t = (MapReduceMappingsTask<K,V,U>)c,
6353     s = t.rights;
6354     while (s != null) {
6355     U tr, sr;
6356     if ((sr = s.result) != null)
6357     t.result = (((tr = t.result) == null) ? sr :
6358     reducer.apply(tr, sr));
6359     s = t.rights = s.nextRight;
6360     }
6361 dl 1.119 }
6362     }
6363     }
6364     }
6365 jsr166 1.114
6366 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6367 dl 1.146 extends Traverser<K,V,Double> {
6368 dl 1.171 final ToDoubleFunction<? super K> transformer;
6369 dl 1.153 final DoubleBinaryOperator reducer;
6370 dl 1.119 final double basis;
6371     double result;
6372 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6373 dl 1.119 MapReduceKeysToDoubleTask
6374 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6375 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
6376 dl 1.171 ToDoubleFunction<? super K> transformer,
6377 dl 1.119 double basis,
6378 dl 1.153 DoubleBinaryOperator reducer) {
6379 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6380 dl 1.119 this.transformer = transformer;
6381     this.basis = basis; this.reducer = reducer;
6382     }
6383 dl 1.146 public final Double getRawResult() { return result; }
6384     @SuppressWarnings("unchecked") public final void compute() {
6385 dl 1.171 final ToDoubleFunction<? super K> transformer;
6386 dl 1.153 final DoubleBinaryOperator reducer;
6387 dl 1.149 if ((transformer = this.transformer) != null &&
6388     (reducer = this.reducer) != null) {
6389     double r = this.basis;
6390     for (int b; (b = preSplit()) > 0;)
6391     (rights = new MapReduceKeysToDoubleTask<K,V>
6392     (map, this, b, rights, transformer, r, reducer)).fork();
6393 dl 1.191 K k;
6394     while ((k = advanceKey()) != null)
6395     r = reducer.applyAsDouble(r, transformer.applyAsDouble(k));
6396 dl 1.149 result = r;
6397     CountedCompleter<?> c;
6398     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6399     MapReduceKeysToDoubleTask<K,V>
6400     t = (MapReduceKeysToDoubleTask<K,V>)c,
6401     s = t.rights;
6402     while (s != null) {
6403 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6404 dl 1.149 s = t.rights = s.nextRight;
6405     }
6406 dl 1.119 }
6407 dl 1.138 }
6408 dl 1.79 }
6409 dl 1.119 }
6410 dl 1.79
6411 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6412 dl 1.146 extends Traverser<K,V,Double> {
6413 dl 1.171 final ToDoubleFunction<? super V> transformer;
6414 dl 1.153 final DoubleBinaryOperator reducer;
6415 dl 1.119 final double basis;
6416     double result;
6417 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6418 dl 1.119 MapReduceValuesToDoubleTask
6419 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6420 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
6421 dl 1.171 ToDoubleFunction<? super V> transformer,
6422 dl 1.119 double basis,
6423 dl 1.153 DoubleBinaryOperator reducer) {
6424 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6425 dl 1.119 this.transformer = transformer;
6426     this.basis = basis; this.reducer = reducer;
6427     }
6428 dl 1.146 public final Double getRawResult() { return result; }
6429     @SuppressWarnings("unchecked") public final void compute() {
6430 dl 1.171 final ToDoubleFunction<? super V> transformer;
6431 dl 1.153 final DoubleBinaryOperator reducer;
6432 dl 1.149 if ((transformer = this.transformer) != null &&
6433     (reducer = this.reducer) != null) {
6434     double r = this.basis;
6435     for (int b; (b = preSplit()) > 0;)
6436     (rights = new MapReduceValuesToDoubleTask<K,V>
6437     (map, this, b, rights, transformer, r, reducer)).fork();
6438 dl 1.151 V v;
6439 dl 1.191 while ((v = advanceValue()) != null)
6440 dl 1.153 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
6441 dl 1.149 result = r;
6442     CountedCompleter<?> c;
6443     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6444     MapReduceValuesToDoubleTask<K,V>
6445     t = (MapReduceValuesToDoubleTask<K,V>)c,
6446     s = t.rights;
6447     while (s != null) {
6448 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6449 dl 1.149 s = t.rights = s.nextRight;
6450     }
6451 dl 1.119 }
6452     }
6453 dl 1.30 }
6454 dl 1.79 }
6455 dl 1.30
6456 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6457 dl 1.146 extends Traverser<K,V,Double> {
6458 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6459 dl 1.153 final DoubleBinaryOperator reducer;
6460 dl 1.119 final double basis;
6461     double result;
6462 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6463 dl 1.119 MapReduceEntriesToDoubleTask
6464 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6465 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
6466 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
6467 dl 1.119 double basis,
6468 dl 1.153 DoubleBinaryOperator reducer) {
6469 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6470 dl 1.119 this.transformer = transformer;
6471     this.basis = basis; this.reducer = reducer;
6472     }
6473 dl 1.146 public final Double getRawResult() { return result; }
6474     @SuppressWarnings("unchecked") public final void compute() {
6475 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6476 dl 1.153 final DoubleBinaryOperator reducer;
6477 dl 1.149 if ((transformer = this.transformer) != null &&
6478     (reducer = this.reducer) != null) {
6479     double r = this.basis;
6480     for (int b; (b = preSplit()) > 0;)
6481     (rights = new MapReduceEntriesToDoubleTask<K,V>
6482     (map, this, b, rights, transformer, r, reducer)).fork();
6483 dl 1.151 V v;
6484 dl 1.191 while ((v = advanceValue()) != null)
6485 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
6486 dl 1.151 v)));
6487 dl 1.149 result = r;
6488     CountedCompleter<?> c;
6489     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6490     MapReduceEntriesToDoubleTask<K,V>
6491     t = (MapReduceEntriesToDoubleTask<K,V>)c,
6492     s = t.rights;
6493     while (s != null) {
6494 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6495 dl 1.149 s = t.rights = s.nextRight;
6496     }
6497 dl 1.119 }
6498 dl 1.138 }
6499 dl 1.30 }
6500 tim 1.1 }
6501    
6502 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6503 dl 1.146 extends Traverser<K,V,Double> {
6504 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
6505 dl 1.153 final DoubleBinaryOperator reducer;
6506 dl 1.119 final double basis;
6507     double result;
6508 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6509 dl 1.119 MapReduceMappingsToDoubleTask
6510 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6511 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
6512 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
6513 dl 1.119 double basis,
6514 dl 1.153 DoubleBinaryOperator reducer) {
6515 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6516 dl 1.119 this.transformer = transformer;
6517     this.basis = basis; this.reducer = reducer;
6518     }
6519 dl 1.146 public final Double getRawResult() { return result; }
6520     @SuppressWarnings("unchecked") public final void compute() {
6521 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
6522 dl 1.153 final DoubleBinaryOperator reducer;
6523 dl 1.149 if ((transformer = this.transformer) != null &&
6524     (reducer = this.reducer) != null) {
6525     double r = this.basis;
6526     for (int b; (b = preSplit()) > 0;)
6527     (rights = new MapReduceMappingsToDoubleTask<K,V>
6528     (map, this, b, rights, transformer, r, reducer)).fork();
6529 dl 1.151 V v;
6530 dl 1.191 while ((v = advanceValue()) != null)
6531 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
6532 dl 1.149 result = r;
6533     CountedCompleter<?> c;
6534     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6535     MapReduceMappingsToDoubleTask<K,V>
6536     t = (MapReduceMappingsToDoubleTask<K,V>)c,
6537     s = t.rights;
6538     while (s != null) {
6539 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6540 dl 1.149 s = t.rights = s.nextRight;
6541     }
6542 dl 1.119 }
6543     }
6544 dl 1.4 }
6545 dl 1.119 }
6546    
6547 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6548 dl 1.146 extends Traverser<K,V,Long> {
6549 dl 1.171 final ToLongFunction<? super K> transformer;
6550 dl 1.153 final LongBinaryOperator reducer;
6551 dl 1.119 final long basis;
6552     long result;
6553 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
6554 dl 1.119 MapReduceKeysToLongTask
6555 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6556 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
6557 dl 1.171 ToLongFunction<? super K> transformer,
6558 dl 1.119 long basis,
6559 dl 1.153 LongBinaryOperator reducer) {
6560 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6561 dl 1.119 this.transformer = transformer;
6562     this.basis = basis; this.reducer = reducer;
6563     }
6564 dl 1.146 public final Long getRawResult() { return result; }
6565     @SuppressWarnings("unchecked") public final void compute() {
6566 dl 1.171 final ToLongFunction<? super K> transformer;
6567 dl 1.153 final LongBinaryOperator reducer;
6568 dl 1.149 if ((transformer = this.transformer) != null &&
6569     (reducer = this.reducer) != null) {
6570     long r = this.basis;
6571     for (int b; (b = preSplit()) > 0;)
6572     (rights = new MapReduceKeysToLongTask<K,V>
6573     (map, this, b, rights, transformer, r, reducer)).fork();
6574 dl 1.191 K k;
6575     while ((k = advanceKey()) != null)
6576     r = reducer.applyAsLong(r, transformer.applyAsLong(k));
6577 dl 1.149 result = r;
6578     CountedCompleter<?> c;
6579     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6580     MapReduceKeysToLongTask<K,V>
6581     t = (MapReduceKeysToLongTask<K,V>)c,
6582     s = t.rights;
6583     while (s != null) {
6584 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6585 dl 1.149 s = t.rights = s.nextRight;
6586     }
6587 dl 1.119 }
6588 dl 1.138 }
6589 dl 1.4 }
6590 dl 1.119 }
6591    
6592 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6593 dl 1.146 extends Traverser<K,V,Long> {
6594 dl 1.171 final ToLongFunction<? super V> transformer;
6595 dl 1.153 final LongBinaryOperator reducer;
6596 dl 1.119 final long basis;
6597     long result;
6598 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
6599 dl 1.119 MapReduceValuesToLongTask
6600 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6601 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
6602 dl 1.171 ToLongFunction<? super V> transformer,
6603 dl 1.119 long basis,
6604 dl 1.153 LongBinaryOperator reducer) {
6605 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6606 dl 1.119 this.transformer = transformer;
6607     this.basis = basis; this.reducer = reducer;
6608     }
6609 dl 1.146 public final Long getRawResult() { return result; }
6610     @SuppressWarnings("unchecked") public final void compute() {
6611 dl 1.171 final ToLongFunction<? super V> transformer;
6612 dl 1.153 final LongBinaryOperator reducer;
6613 dl 1.149 if ((transformer = this.transformer) != null &&
6614     (reducer = this.reducer) != null) {
6615     long r = this.basis;
6616     for (int b; (b = preSplit()) > 0;)
6617     (rights = new MapReduceValuesToLongTask<K,V>
6618     (map, this, b, rights, transformer, r, reducer)).fork();
6619 dl 1.151 V v;
6620 dl 1.191 while ((v = advanceValue()) != null)
6621 dl 1.153 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6622 dl 1.149 result = r;
6623     CountedCompleter<?> c;
6624     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6625     MapReduceValuesToLongTask<K,V>
6626     t = (MapReduceValuesToLongTask<K,V>)c,
6627     s = t.rights;
6628     while (s != null) {
6629 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6630 dl 1.149 s = t.rights = s.nextRight;
6631     }
6632 dl 1.119 }
6633     }
6634 jsr166 1.95 }
6635 dl 1.119 }
6636    
6637 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6638 dl 1.146 extends Traverser<K,V,Long> {
6639 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6640 dl 1.153 final LongBinaryOperator reducer;
6641 dl 1.119 final long basis;
6642     long result;
6643 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
6644 dl 1.119 MapReduceEntriesToLongTask
6645 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6646 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
6647 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
6648 dl 1.119 long basis,
6649 dl 1.153 LongBinaryOperator reducer) {
6650 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6651 dl 1.119 this.transformer = transformer;
6652     this.basis = basis; this.reducer = reducer;
6653     }
6654 dl 1.146 public final Long getRawResult() { return result; }
6655     @SuppressWarnings("unchecked") public final void compute() {
6656 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6657 dl 1.153 final LongBinaryOperator reducer;
6658 dl 1.149 if ((transformer = this.transformer) != null &&
6659     (reducer = this.reducer) != null) {
6660     long r = this.basis;
6661     for (int b; (b = preSplit()) > 0;)
6662     (rights = new MapReduceEntriesToLongTask<K,V>
6663     (map, this, b, rights, transformer, r, reducer)).fork();
6664 dl 1.151 V v;
6665 dl 1.191 while ((v = advanceValue()) != null)
6666 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6667 dl 1.149 result = r;
6668     CountedCompleter<?> c;
6669     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6670     MapReduceEntriesToLongTask<K,V>
6671     t = (MapReduceEntriesToLongTask<K,V>)c,
6672     s = t.rights;
6673     while (s != null) {
6674 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6675 dl 1.149 s = t.rights = s.nextRight;
6676     }
6677 dl 1.119 }
6678 dl 1.138 }
6679 dl 1.4 }
6680 tim 1.1 }
6681    
6682 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6683 dl 1.146 extends Traverser<K,V,Long> {
6684 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6685 dl 1.153 final LongBinaryOperator reducer;
6686 dl 1.119 final long basis;
6687     long result;
6688 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6689 dl 1.119 MapReduceMappingsToLongTask
6690 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6691 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
6692 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
6693 dl 1.119 long basis,
6694 dl 1.153 LongBinaryOperator reducer) {
6695 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6696 dl 1.119 this.transformer = transformer;
6697     this.basis = basis; this.reducer = reducer;
6698     }
6699 dl 1.146 public final Long getRawResult() { return result; }
6700     @SuppressWarnings("unchecked") public final void compute() {
6701 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6702 dl 1.153 final LongBinaryOperator reducer;
6703 dl 1.149 if ((transformer = this.transformer) != null &&
6704     (reducer = this.reducer) != null) {
6705     long r = this.basis;
6706     for (int b; (b = preSplit()) > 0;)
6707     (rights = new MapReduceMappingsToLongTask<K,V>
6708     (map, this, b, rights, transformer, r, reducer)).fork();
6709 dl 1.151 V v;
6710 dl 1.191 while ((v = advanceValue()) != null)
6711 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6712 dl 1.149 result = r;
6713     CountedCompleter<?> c;
6714     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6715     MapReduceMappingsToLongTask<K,V>
6716     t = (MapReduceMappingsToLongTask<K,V>)c,
6717     s = t.rights;
6718     while (s != null) {
6719 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6720 dl 1.149 s = t.rights = s.nextRight;
6721     }
6722 dl 1.119 }
6723     }
6724 dl 1.4 }
6725 tim 1.1 }
6726    
6727 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6728 dl 1.146 extends Traverser<K,V,Integer> {
6729 dl 1.171 final ToIntFunction<? super K> transformer;
6730 dl 1.153 final IntBinaryOperator reducer;
6731 dl 1.119 final int basis;
6732     int result;
6733 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
6734 dl 1.119 MapReduceKeysToIntTask
6735 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6736 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
6737 dl 1.171 ToIntFunction<? super K> transformer,
6738 dl 1.119 int basis,
6739 dl 1.153 IntBinaryOperator reducer) {
6740 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6741 dl 1.119 this.transformer = transformer;
6742     this.basis = basis; this.reducer = reducer;
6743     }
6744 dl 1.146 public final Integer getRawResult() { return result; }
6745     @SuppressWarnings("unchecked") public final void compute() {
6746 dl 1.171 final ToIntFunction<? super K> transformer;
6747 dl 1.153 final IntBinaryOperator reducer;
6748 dl 1.149 if ((transformer = this.transformer) != null &&
6749     (reducer = this.reducer) != null) {
6750     int r = this.basis;
6751     for (int b; (b = preSplit()) > 0;)
6752     (rights = new MapReduceKeysToIntTask<K,V>
6753     (map, this, b, rights, transformer, r, reducer)).fork();
6754 dl 1.191 K k;
6755     while ((k = advanceKey()) != null)
6756     r = reducer.applyAsInt(r, transformer.applyAsInt(k));
6757 dl 1.149 result = r;
6758     CountedCompleter<?> c;
6759     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6760     MapReduceKeysToIntTask<K,V>
6761     t = (MapReduceKeysToIntTask<K,V>)c,
6762     s = t.rights;
6763     while (s != null) {
6764 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6765 dl 1.149 s = t.rights = s.nextRight;
6766     }
6767 dl 1.119 }
6768 dl 1.138 }
6769 dl 1.30 }
6770     }
6771    
6772 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6773 dl 1.146 extends Traverser<K,V,Integer> {
6774 dl 1.171 final ToIntFunction<? super V> transformer;
6775 dl 1.153 final IntBinaryOperator reducer;
6776 dl 1.119 final int basis;
6777     int result;
6778 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
6779 dl 1.119 MapReduceValuesToIntTask
6780 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6781 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
6782 dl 1.171 ToIntFunction<? super V> transformer,
6783 dl 1.119 int basis,
6784 dl 1.153 IntBinaryOperator reducer) {
6785 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6786 dl 1.119 this.transformer = transformer;
6787     this.basis = basis; this.reducer = reducer;
6788     }
6789 dl 1.146 public final Integer getRawResult() { return result; }
6790     @SuppressWarnings("unchecked") public final void compute() {
6791 dl 1.171 final ToIntFunction<? super V> transformer;
6792 dl 1.153 final IntBinaryOperator reducer;
6793 dl 1.149 if ((transformer = this.transformer) != null &&
6794     (reducer = this.reducer) != null) {
6795     int r = this.basis;
6796     for (int b; (b = preSplit()) > 0;)
6797     (rights = new MapReduceValuesToIntTask<K,V>
6798     (map, this, b, rights, transformer, r, reducer)).fork();
6799 dl 1.151 V v;
6800 dl 1.191 while ((v = advanceValue()) != null)
6801 dl 1.153 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6802 dl 1.149 result = r;
6803     CountedCompleter<?> c;
6804     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6805     MapReduceValuesToIntTask<K,V>
6806     t = (MapReduceValuesToIntTask<K,V>)c,
6807     s = t.rights;
6808     while (s != null) {
6809 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6810 dl 1.149 s = t.rights = s.nextRight;
6811     }
6812 dl 1.119 }
6813 dl 1.2 }
6814 tim 1.1 }
6815     }
6816    
6817 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6818 dl 1.146 extends Traverser<K,V,Integer> {
6819 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6820 dl 1.153 final IntBinaryOperator reducer;
6821 dl 1.119 final int basis;
6822     int result;
6823 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6824 dl 1.119 MapReduceEntriesToIntTask
6825 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6826 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
6827 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
6828 dl 1.119 int basis,
6829 dl 1.153 IntBinaryOperator reducer) {
6830 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6831 dl 1.119 this.transformer = transformer;
6832     this.basis = basis; this.reducer = reducer;
6833     }
6834 dl 1.146 public final Integer getRawResult() { return result; }
6835     @SuppressWarnings("unchecked") public final void compute() {
6836 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6837 dl 1.153 final IntBinaryOperator reducer;
6838 dl 1.149 if ((transformer = this.transformer) != null &&
6839     (reducer = this.reducer) != null) {
6840     int r = this.basis;
6841     for (int b; (b = preSplit()) > 0;)
6842     (rights = new MapReduceEntriesToIntTask<K,V>
6843     (map, this, b, rights, transformer, r, reducer)).fork();
6844 dl 1.151 V v;
6845 dl 1.191 while ((v = advanceValue()) != null)
6846 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6847 dl 1.151 v)));
6848 dl 1.149 result = r;
6849     CountedCompleter<?> c;
6850     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6851     MapReduceEntriesToIntTask<K,V>
6852     t = (MapReduceEntriesToIntTask<K,V>)c,
6853     s = t.rights;
6854     while (s != null) {
6855 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6856 dl 1.149 s = t.rights = s.nextRight;
6857     }
6858 dl 1.119 }
6859 dl 1.138 }
6860 dl 1.4 }
6861 dl 1.119 }
6862 tim 1.1
6863 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6864 dl 1.146 extends Traverser<K,V,Integer> {
6865 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6866 dl 1.153 final IntBinaryOperator reducer;
6867 dl 1.119 final int basis;
6868     int result;
6869 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6870 dl 1.119 MapReduceMappingsToIntTask
6871 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6872     MapReduceMappingsToIntTask<K,V> nextRight,
6873 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
6874 dl 1.119 int basis,
6875 dl 1.153 IntBinaryOperator reducer) {
6876 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6877 dl 1.119 this.transformer = transformer;
6878     this.basis = basis; this.reducer = reducer;
6879     }
6880 dl 1.146 public final Integer getRawResult() { return result; }
6881     @SuppressWarnings("unchecked") public final void compute() {
6882 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6883 dl 1.153 final IntBinaryOperator reducer;
6884 dl 1.149 if ((transformer = this.transformer) != null &&
6885     (reducer = this.reducer) != null) {
6886     int r = this.basis;
6887     for (int b; (b = preSplit()) > 0;)
6888     (rights = new MapReduceMappingsToIntTask<K,V>
6889     (map, this, b, rights, transformer, r, reducer)).fork();
6890 dl 1.151 V v;
6891 dl 1.191 while ((v = advanceValue()) != null)
6892 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6893 dl 1.149 result = r;
6894     CountedCompleter<?> c;
6895     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6896     MapReduceMappingsToIntTask<K,V>
6897     t = (MapReduceMappingsToIntTask<K,V>)c,
6898     s = t.rights;
6899     while (s != null) {
6900 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6901 dl 1.149 s = t.rights = s.nextRight;
6902     }
6903 dl 1.119 }
6904 dl 1.138 }
6905 tim 1.1 }
6906     }
6907 dl 1.99
6908     // Unsafe mechanics
6909 dl 1.149 private static final sun.misc.Unsafe U;
6910     private static final long SIZECTL;
6911     private static final long TRANSFERINDEX;
6912     private static final long TRANSFERORIGIN;
6913     private static final long BASECOUNT;
6914 dl 1.153 private static final long CELLSBUSY;
6915 dl 1.149 private static final long CELLVALUE;
6916 dl 1.119 private static final long ABASE;
6917     private static final int ASHIFT;
6918 dl 1.99
6919     static {
6920     try {
6921 dl 1.149 U = sun.misc.Unsafe.getUnsafe();
6922 dl 1.119 Class<?> k = ConcurrentHashMap.class;
6923 dl 1.149 SIZECTL = U.objectFieldOffset
6924 dl 1.119 (k.getDeclaredField("sizeCtl"));
6925 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
6926     (k.getDeclaredField("transferIndex"));
6927     TRANSFERORIGIN = U.objectFieldOffset
6928     (k.getDeclaredField("transferOrigin"));
6929     BASECOUNT = U.objectFieldOffset
6930     (k.getDeclaredField("baseCount"));
6931 dl 1.153 CELLSBUSY = U.objectFieldOffset
6932     (k.getDeclaredField("cellsBusy"));
6933     Class<?> ck = Cell.class;
6934 dl 1.149 CELLVALUE = U.objectFieldOffset
6935     (ck.getDeclaredField("value"));
6936 dl 1.119 Class<?> sc = Node[].class;
6937 dl 1.149 ABASE = U.arrayBaseOffset(sc);
6938 jsr166 1.167 int scale = U.arrayIndexScale(sc);
6939     if ((scale & (scale - 1)) != 0)
6940     throw new Error("data type scale not a power of two");
6941     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6942 dl 1.99 } catch (Exception e) {
6943     throw new Error(e);
6944     }
6945     }
6946 jsr166 1.152
6947     }