ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.194
Committed: Wed Mar 13 12:39:01 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.193: +3 -24 lines
Log Message:
Synch with lambda Spliterator API

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