ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.188
Committed: Sun Feb 17 23:36:34 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.187: +19 -17 lines
Log Message:
Spliterator sync

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     * Internal traversals directly access these fields, as in:
2148     * {@code while (it.advance() != null) { process(it.nextKey); }}
2149     *
2150     * Exported iterators must track whether the iterator has advanced
2151     * (in hasNext vs next) (by setting/checking/nulling field
2152     * nextVal), and then extract key, value, or key-value pairs as
2153     * return values of next().
2154     *
2155     * The iterator visits once each still-valid node that was
2156     * reachable upon iterator construction. It might miss some that
2157     * were added to a bin after the bin was visited, which is OK wrt
2158     * consistency guarantees. Maintaining this property in the face
2159     * of possible ongoing resizes requires a fair amount of
2160     * bookkeeping state that is difficult to optimize away amidst
2161     * volatile accesses. Even so, traversal maintains reasonable
2162     * throughput.
2163     *
2164     * Normally, iteration proceeds bin-by-bin traversing lists.
2165     * However, if the table has been resized, then all future steps
2166     * must traverse both the bin at the current index as well as at
2167     * (index + baseSize); and so on for further resizings. To
2168     * paranoically cope with potential sharing by users of iterators
2169     * across threads, iteration terminates if a bounds checks fails
2170     * for a table read.
2171     *
2172 dl 1.153 * This class supports both Spliterator-based traversal and
2173     * CountedCompleter-based bulk tasks. The same "batch" field is
2174     * used, but in slightly different ways, in the two cases. For
2175     * Spliterators, it is a saturating (at Integer.MAX_VALUE)
2176     * estimate of element coverage. For CHM tasks, it is a pre-scaled
2177     * size that halves down to zero for leaf tasks, that is only
2178     * computed upon execution of the task. (Tasks can be submitted to
2179     * any pool, of any size, so we don't know scale factors until
2180     * running.)
2181     *
2182 dl 1.146 * This class extends CountedCompleter to streamline parallel
2183     * iteration in bulk operations. This adds only a few fields of
2184     * space overhead, which is small enough in cases where it is not
2185     * needed to not worry about it. Because CountedCompleter is
2186     * Serializable, but iterators need not be, we need to add warning
2187     * suppressions.
2188 dl 1.119 */
2189 dl 1.149 @SuppressWarnings("serial") static class Traverser<K,V,R>
2190     extends CountedCompleter<R> {
2191 jsr166 1.186 final ConcurrentHashMap<K,V> map;
2192 dl 1.151 Node<V> next; // the next entry to use
2193 jsr166 1.168 K nextKey; // cached key field of next
2194 dl 1.151 V nextVal; // cached val field of next
2195     Node<V>[] tab; // current table; updated if resized
2196 dl 1.119 int index; // index of bin to use next
2197     int baseIndex; // current index of initial table
2198     int baseLimit; // index bound for initial table
2199 dl 1.130 int baseSize; // initial table size
2200 dl 1.146 int batch; // split control
2201 dl 1.119 /** Creates iterator for all entries in the table. */
2202 jsr166 1.186 Traverser(ConcurrentHashMap<K,V> map) {
2203 dl 1.130 this.map = map;
2204 dl 1.153 Node<V>[] t;
2205     if ((t = tab = map.table) != null)
2206     baseLimit = baseSize = t.length;
2207 dl 1.119 }
2208    
2209 dl 1.153 /** Task constructor */
2210 dl 1.146 Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it, int batch) {
2211     super(it);
2212 dl 1.153 this.map = map;
2213     this.batch = batch; // -1 if unknown
2214     if (it == null) {
2215 dl 1.151 Node<V>[] t;
2216 dl 1.153 if ((t = tab = map.table) != null)
2217     baseLimit = baseSize = t.length;
2218     }
2219     else { // split parent
2220     this.tab = it.tab;
2221 dl 1.146 this.baseSize = it.baseSize;
2222     int hi = this.baseLimit = it.baseLimit;
2223     it.baseLimit = this.index = this.baseIndex =
2224     (hi + it.baseIndex + 1) >>> 1;
2225     }
2226 dl 1.119 }
2227    
2228 dl 1.153 /** Spliterator constructor */
2229     Traverser(ConcurrentHashMap<K,V> map, Traverser<K,V,?> it) {
2230     super(it);
2231     this.map = map;
2232     if (it == null) {
2233     Node<V>[] t;
2234     if ((t = tab = map.table) != null)
2235     baseLimit = baseSize = t.length;
2236     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 dl 1.119 /**
2251     * Advances next; returns nextVal or null if terminated.
2252     * See above for explanation.
2253     */
2254 dl 1.151 @SuppressWarnings("unchecked") final V advance() {
2255     Node<V> e = next;
2256     V ev = null;
2257 dl 1.119 outer: do {
2258     if (e != null) // advance past used/skipped node
2259     e = e.next;
2260     while (e == null) { // get to next non-null bin
2261 jsr166 1.186 ConcurrentHashMap<K,V> m;
2262 dl 1.151 Node<V>[] t; int b, i, n; Object ek; // must use locals
2263 dl 1.130 if ((t = tab) != null)
2264     n = t.length;
2265     else if ((m = map) != null && (t = tab = m.table) != null)
2266     n = baseLimit = baseSize = t.length;
2267     else
2268 dl 1.119 break outer;
2269 dl 1.130 if ((b = baseIndex) >= baseLimit ||
2270     (i = index) < 0 || i >= n)
2271     break outer;
2272 dl 1.149 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2273 dl 1.119 if ((ek = e.key) instanceof TreeBin)
2274 dl 1.151 e = ((TreeBin<V>)ek).first;
2275 dl 1.119 else {
2276 dl 1.151 tab = (Node<V>[])ek;
2277 dl 1.119 continue; // restarts due to null val
2278     }
2279     } // visit upper slots if present
2280     index = (i += baseSize) < n ? i : (baseIndex = b + 1);
2281     }
2282 jsr166 1.168 nextKey = (K)e.key;
2283 dl 1.119 } while ((ev = e.val) == null); // skip deleted or special nodes
2284     next = e;
2285     return nextVal = ev;
2286     }
2287    
2288     public final void remove() {
2289 jsr166 1.168 K k = nextKey;
2290 dl 1.137 if (k == null && (advance() == null || (k = nextKey) == null))
2291 dl 1.119 throw new IllegalStateException();
2292 dl 1.137 map.internalReplace(k, null, null);
2293 dl 1.119 }
2294    
2295     public final boolean hasNext() {
2296     return nextVal != null || advance() != null;
2297     }
2298    
2299     public final boolean hasMoreElements() { return hasNext(); }
2300 dl 1.146
2301     public void compute() { } // default no-op CountedCompleter body
2302    
2303     /**
2304     * Returns a batch value > 0 if this task should (and must) be
2305     * split, if so, adding to pending count, and in any case
2306     * updating batch value. The initial batch value is approx
2307     * exp2 of the number of times (minus one) to split task by
2308     * two before executing leaf action. This value is faster to
2309     * compute and more convenient to use as a guide to splitting
2310     * than is the depth, since it is used while dividing by two
2311     * anyway.
2312     */
2313     final int preSplit() {
2314 dl 1.153 int b; ForkJoinPool pool;
2315     if ((b = batch) < 0) { // force initialization
2316     int sp = (((pool = getPool()) == null) ?
2317     ForkJoinPool.getCommonPoolParallelism() :
2318     pool.getParallelism()) << 3; // slack of 8
2319     long n = map.sumCount();
2320     b = (n <= 0L) ? 0 : (n < (long)sp) ? (int)n : sp;
2321 dl 1.146 }
2322 jsr166 1.147 b = (b <= 1 || baseIndex == baseLimit) ? 0 : (b >>> 1);
2323 dl 1.146 if ((batch = b) > 0)
2324     addToPendingCount(1);
2325     return b;
2326     }
2327    
2328 dl 1.153 // spliterator support
2329    
2330     public long estimateSize() {
2331     return batch;
2332     }
2333 dl 1.119 }
2334    
2335     /* ---------------- Public operations -------------- */
2336    
2337     /**
2338     * Creates a new, empty map with the default initial table size (16).
2339     */
2340     public ConcurrentHashMap() {
2341     }
2342    
2343     /**
2344     * Creates a new, empty map with an initial table size
2345     * accommodating the specified number of elements without the need
2346     * to dynamically resize.
2347     *
2348     * @param initialCapacity The implementation performs internal
2349     * sizing to accommodate this many elements.
2350     * @throws IllegalArgumentException if the initial capacity of
2351     * elements is negative
2352     */
2353     public ConcurrentHashMap(int initialCapacity) {
2354     if (initialCapacity < 0)
2355     throw new IllegalArgumentException();
2356     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
2357     MAXIMUM_CAPACITY :
2358     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
2359     this.sizeCtl = cap;
2360     }
2361    
2362     /**
2363     * Creates a new map with the same mappings as the given map.
2364     *
2365     * @param m the map
2366     */
2367     public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
2368     this.sizeCtl = DEFAULT_CAPACITY;
2369     internalPutAll(m);
2370     }
2371    
2372     /**
2373     * Creates a new, empty map with an initial table size based on
2374     * the given number of elements ({@code initialCapacity}) and
2375     * initial table density ({@code loadFactor}).
2376     *
2377     * @param initialCapacity the initial capacity. The implementation
2378     * performs internal sizing to accommodate this many elements,
2379     * given the specified load factor.
2380     * @param loadFactor the load factor (table density) for
2381     * establishing the initial table size
2382     * @throws IllegalArgumentException if the initial capacity of
2383     * elements is negative or the load factor is nonpositive
2384     *
2385     * @since 1.6
2386     */
2387     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
2388     this(initialCapacity, loadFactor, 1);
2389     }
2390    
2391     /**
2392     * Creates a new, empty map with an initial table size based on
2393     * the given number of elements ({@code initialCapacity}), table
2394     * density ({@code loadFactor}), and number of concurrently
2395     * updating threads ({@code concurrencyLevel}).
2396     *
2397     * @param initialCapacity the initial capacity. The implementation
2398     * performs internal sizing to accommodate this many elements,
2399     * given the specified load factor.
2400     * @param loadFactor the load factor (table density) for
2401     * establishing the initial table size
2402     * @param concurrencyLevel the estimated number of concurrently
2403     * updating threads. The implementation may use this value as
2404     * a sizing hint.
2405     * @throws IllegalArgumentException if the initial capacity is
2406     * negative or the load factor or concurrencyLevel are
2407     * nonpositive
2408     */
2409     public ConcurrentHashMap(int initialCapacity,
2410     float loadFactor, int concurrencyLevel) {
2411     if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
2412     throw new IllegalArgumentException();
2413     if (initialCapacity < concurrencyLevel) // Use at least as many bins
2414     initialCapacity = concurrencyLevel; // as estimated threads
2415     long size = (long)(1.0 + (long)initialCapacity / loadFactor);
2416     int cap = (size >= (long)MAXIMUM_CAPACITY) ?
2417     MAXIMUM_CAPACITY : tableSizeFor((int)size);
2418     this.sizeCtl = cap;
2419     }
2420    
2421     /**
2422 dl 1.137 * Creates a new {@link Set} backed by a ConcurrentHashMap
2423     * from the given type to {@code Boolean.TRUE}.
2424     *
2425     * @return the new set
2426     */
2427     public static <K> KeySetView<K,Boolean> newKeySet() {
2428 jsr166 1.184 return new KeySetView<K,Boolean>
2429     (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
2430 dl 1.137 }
2431    
2432     /**
2433     * Creates a new {@link Set} backed by a ConcurrentHashMap
2434     * from the given type to {@code Boolean.TRUE}.
2435     *
2436     * @param initialCapacity The implementation performs internal
2437     * sizing to accommodate this many elements.
2438     * @throws IllegalArgumentException if the initial capacity of
2439     * elements is negative
2440     * @return the new set
2441     */
2442     public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
2443 dl 1.149 return new KeySetView<K,Boolean>
2444     (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
2445 dl 1.137 }
2446    
2447     /**
2448 dl 1.119 * {@inheritDoc}
2449     */
2450     public boolean isEmpty() {
2451 dl 1.149 return sumCount() <= 0L; // ignore transient negative values
2452 dl 1.119 }
2453    
2454     /**
2455     * {@inheritDoc}
2456     */
2457     public int size() {
2458 dl 1.149 long n = sumCount();
2459 dl 1.119 return ((n < 0L) ? 0 :
2460     (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
2461     (int)n);
2462     }
2463    
2464     /**
2465     * Returns the number of mappings. This method should be used
2466     * instead of {@link #size} because a ConcurrentHashMap may
2467     * contain more mappings than can be represented as an int. The
2468 dl 1.146 * value returned is an estimate; the actual count may differ if
2469     * there are concurrent insertions or removals.
2470 dl 1.119 *
2471     * @return the number of mappings
2472     */
2473     public long mappingCount() {
2474 dl 1.149 long n = sumCount();
2475 dl 1.126 return (n < 0L) ? 0L : n; // ignore transient negative values
2476 dl 1.119 }
2477    
2478     /**
2479     * Returns the value to which the specified key is mapped,
2480     * or {@code null} if this map contains no mapping for the key.
2481     *
2482     * <p>More formally, if this map contains a mapping from a key
2483     * {@code k} to a value {@code v} such that {@code key.equals(k)},
2484     * then this method returns {@code v}; otherwise it returns
2485     * {@code null}. (There can be at most one such mapping.)
2486     *
2487     * @throws NullPointerException if the specified key is null
2488     */
2489 dl 1.149 public V get(Object key) {
2490     return internalGet(key);
2491 dl 1.119 }
2492    
2493     /**
2494 dl 1.129 * Returns the value to which the specified key is mapped,
2495 jsr166 1.133 * or the given defaultValue if this map contains no mapping for the key.
2496 dl 1.129 *
2497     * @param key the key
2498     * @param defaultValue the value to return if this map contains
2499 jsr166 1.134 * no mapping for the given key
2500 dl 1.129 * @return the mapping for the key, if present; else the defaultValue
2501     * @throws NullPointerException if the specified key is null
2502     */
2503 dl 1.149 public V getValueOrDefault(Object key, V defaultValue) {
2504     V v;
2505     return (v = internalGet(key)) == null ? defaultValue : v;
2506 dl 1.129 }
2507    
2508     /**
2509 dl 1.119 * Tests if the specified object is a key in this table.
2510     *
2511     * @param key possible key
2512     * @return {@code true} if and only if the specified object
2513     * is a key in this table, as determined by the
2514     * {@code equals} method; {@code false} otherwise
2515     * @throws NullPointerException if the specified key is null
2516     */
2517     public boolean containsKey(Object key) {
2518     return internalGet(key) != null;
2519     }
2520    
2521     /**
2522     * Returns {@code true} if this map maps one or more keys to the
2523     * specified value. Note: This method may require a full traversal
2524     * of the map, and is much slower than method {@code containsKey}.
2525     *
2526     * @param value value whose presence in this map is to be tested
2527     * @return {@code true} if this map maps one or more keys to the
2528     * specified value
2529     * @throws NullPointerException if the specified value is null
2530     */
2531     public boolean containsValue(Object value) {
2532     if (value == null)
2533     throw new NullPointerException();
2534 dl 1.151 V v;
2535 dl 1.119 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2536     while ((v = it.advance()) != null) {
2537     if (v == value || value.equals(v))
2538     return true;
2539     }
2540     return false;
2541     }
2542    
2543     /**
2544     * Legacy method testing if some key maps into the specified value
2545     * in this table. This method is identical in functionality to
2546 jsr166 1.176 * {@link #containsValue(Object)}, and exists solely to ensure
2547 dl 1.119 * full compatibility with class {@link java.util.Hashtable},
2548     * which supported this method prior to introduction of the
2549     * Java Collections framework.
2550     *
2551     * @param value a value to search for
2552     * @return {@code true} if and only if some key maps to the
2553     * {@code value} argument in this table as
2554     * determined by the {@code equals} method;
2555     * {@code false} otherwise
2556     * @throws NullPointerException if the specified value is null
2557     */
2558 dl 1.151 @Deprecated public boolean contains(Object value) {
2559 dl 1.119 return containsValue(value);
2560     }
2561    
2562     /**
2563     * Maps the specified key to the specified value in this table.
2564     * Neither the key nor the value can be null.
2565     *
2566 jsr166 1.145 * <p>The value can be retrieved by calling the {@code get} method
2567 dl 1.119 * with a key that is equal to the original key.
2568     *
2569     * @param key key with which the specified value is to be associated
2570     * @param value value to be associated with the specified key
2571     * @return the previous value associated with {@code key}, or
2572     * {@code null} if there was no mapping for {@code key}
2573     * @throws NullPointerException if the specified key or value is null
2574     */
2575 dl 1.149 public V put(K key, V value) {
2576     return internalPut(key, value, false);
2577 dl 1.119 }
2578    
2579     /**
2580     * {@inheritDoc}
2581     *
2582     * @return the previous value associated with the specified key,
2583     * or {@code null} if there was no mapping for the key
2584     * @throws NullPointerException if the specified key or value is null
2585     */
2586 dl 1.149 public V putIfAbsent(K key, V value) {
2587     return internalPut(key, value, true);
2588 dl 1.119 }
2589    
2590     /**
2591     * Copies all of the mappings from the specified map to this one.
2592     * These mappings replace any mappings that this map had for any of the
2593     * keys currently in the specified map.
2594     *
2595     * @param m mappings to be stored in this map
2596     */
2597     public void putAll(Map<? extends K, ? extends V> m) {
2598     internalPutAll(m);
2599     }
2600    
2601     /**
2602 dl 1.153 * If the specified key is not already associated with a value (or
2603     * is mapped to {@code null}), attempts to compute its value using
2604     * the given mapping function and enters it into this map unless
2605     * {@code null}. The entire method invocation is performed
2606     * atomically, so the function is applied at most once per key.
2607     * Some attempted update operations on this map by other threads
2608     * may be blocked while computation is in progress, so the
2609     * computation should be short and simple, and must not attempt to
2610     * update any other mappings of this Map.
2611 dl 1.119 *
2612     * @param key key with which the specified value is to be associated
2613     * @param mappingFunction the function to compute a value
2614     * @return the current (existing or computed) value associated with
2615 jsr166 1.134 * the specified key, or null if the computed value is null
2616 dl 1.119 * @throws NullPointerException if the specified key or mappingFunction
2617     * is null
2618     * @throws IllegalStateException if the computation detectably
2619     * attempts a recursive update to this map that would
2620     * otherwise never complete
2621     * @throws RuntimeException or Error if the mappingFunction does so,
2622     * in which case the mapping is left unestablished
2623     */
2624 dl 1.149 public V computeIfAbsent
2625 dl 1.153 (K key, Function<? super K, ? extends V> mappingFunction) {
2626 dl 1.149 return internalComputeIfAbsent(key, mappingFunction);
2627 dl 1.119 }
2628    
2629     /**
2630 dl 1.153 * If the value for the specified key is present and non-null,
2631     * attempts to compute a new mapping given the key and its current
2632     * mapped value. The entire method invocation is performed
2633     * atomically. Some attempted update operations on this map by
2634 dl 1.119 * other threads may be blocked while computation is in progress,
2635     * so the computation should be short and simple, and must not
2636 dl 1.153 * attempt to update any other mappings of this Map.
2637 dl 1.119 *
2638     * @param key key with which the specified value is to be associated
2639     * @param remappingFunction the function to compute a value
2640 jsr166 1.123 * @return the new value associated with the specified key, or null if none
2641 dl 1.119 * @throws NullPointerException if the specified key or remappingFunction
2642     * is null
2643     * @throws IllegalStateException if the computation detectably
2644     * attempts a recursive update to this map that would
2645     * otherwise never complete
2646     * @throws RuntimeException or Error if the remappingFunction does so,
2647     * in which case the mapping is unchanged
2648     */
2649 dl 1.149 public V computeIfPresent
2650 dl 1.153 (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2651 dl 1.149 return internalCompute(key, true, remappingFunction);
2652 dl 1.119 }
2653    
2654     /**
2655 dl 1.153 * Attempts to compute a mapping for the specified key and its
2656     * current mapped value (or {@code null} if there is no current
2657     * mapping). The entire method invocation is performed atomically.
2658     * Some attempted update operations on this map by other threads
2659     * may be blocked while computation is in progress, so the
2660     * computation should be short and simple, and must not attempt to
2661     * update any other mappings of this Map.
2662 dl 1.119 *
2663     * @param key key with which the specified value is to be associated
2664     * @param remappingFunction the function to compute a value
2665 jsr166 1.123 * @return the new value associated with the specified key, or null if none
2666 dl 1.119 * @throws NullPointerException if the specified key or remappingFunction
2667     * is null
2668     * @throws IllegalStateException if the computation detectably
2669     * attempts a recursive update to this map that would
2670     * otherwise never complete
2671     * @throws RuntimeException or Error if the remappingFunction does so,
2672     * in which case the mapping is unchanged
2673     */
2674 dl 1.149 public V compute
2675 dl 1.153 (K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2676 dl 1.149 return internalCompute(key, false, remappingFunction);
2677 dl 1.119 }
2678    
2679     /**
2680 dl 1.153 * If the specified key is not already associated with a
2681     * (non-null) value, associates it with the given value.
2682     * Otherwise, replaces the value with the results of the given
2683     * remapping function, or removes if {@code null}. The entire
2684     * method invocation is performed atomically. Some attempted
2685     * update operations on this map by other threads may be blocked
2686     * while computation is in progress, so the computation should be
2687     * short and simple, and must not attempt to update any other
2688     * mappings of this Map.
2689     *
2690     * @param key key with which the specified value is to be associated
2691     * @param value the value to use if absent
2692     * @param remappingFunction the function to recompute a value if present
2693     * @return the new value associated with the specified key, or null if none
2694     * @throws NullPointerException if the specified key or the
2695     * remappingFunction is null
2696     * @throws RuntimeException or Error if the remappingFunction does so,
2697     * in which case the mapping is unchanged
2698 dl 1.119 */
2699 dl 1.149 public V merge
2700     (K key, V value,
2701 dl 1.153 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2702 dl 1.149 return internalMerge(key, value, remappingFunction);
2703 dl 1.119 }
2704    
2705     /**
2706     * Removes the key (and its corresponding value) from this map.
2707     * This method does nothing if the key is not in the map.
2708     *
2709     * @param key the key that needs to be removed
2710     * @return the previous value associated with {@code key}, or
2711     * {@code null} if there was no mapping for {@code key}
2712     * @throws NullPointerException if the specified key is null
2713     */
2714 dl 1.149 public V remove(Object key) {
2715     return internalReplace(key, null, null);
2716 dl 1.119 }
2717    
2718     /**
2719     * {@inheritDoc}
2720     *
2721     * @throws NullPointerException if the specified key is null
2722     */
2723     public boolean remove(Object key, Object value) {
2724 dl 1.163 if (key == null)
2725     throw new NullPointerException();
2726 dl 1.149 return value != null && internalReplace(key, null, value) != null;
2727 tim 1.1 }
2728 dl 1.31
2729     /**
2730 jsr166 1.68 * {@inheritDoc}
2731     *
2732     * @throws NullPointerException if any of the arguments are null
2733 dl 1.31 */
2734     public boolean replace(K key, V oldValue, V newValue) {
2735 dl 1.119 if (key == null || oldValue == null || newValue == null)
2736 dl 1.31 throw new NullPointerException();
2737 dl 1.119 return internalReplace(key, newValue, oldValue) != null;
2738 dl 1.32 }
2739    
2740     /**
2741 jsr166 1.68 * {@inheritDoc}
2742     *
2743     * @return the previous value associated with the specified key,
2744 dl 1.119 * or {@code null} if there was no mapping for the key
2745 jsr166 1.68 * @throws NullPointerException if the specified key or value is null
2746 dl 1.32 */
2747 dl 1.149 public V replace(K key, V value) {
2748 dl 1.119 if (key == null || value == null)
2749 dl 1.32 throw new NullPointerException();
2750 dl 1.149 return internalReplace(key, value, null);
2751 dl 1.31 }
2752    
2753 tim 1.1 /**
2754 jsr166 1.68 * Removes all of the mappings from this map.
2755 tim 1.1 */
2756     public void clear() {
2757 dl 1.119 internalClear();
2758 tim 1.1 }
2759    
2760     /**
2761 jsr166 1.68 * Returns a {@link Set} view of the keys contained in this map.
2762     * The set is backed by the map, so changes to the map are
2763 dl 1.137 * reflected in the set, and vice-versa.
2764     *
2765     * @return the set view
2766     */
2767     public KeySetView<K,V> keySet() {
2768     KeySetView<K,V> ks = keySet;
2769     return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
2770     }
2771    
2772     /**
2773     * Returns a {@link Set} view of the keys in this map, using the
2774     * given common mapped value for any additions (i.e., {@link
2775 jsr166 1.174 * Collection#add} and {@link Collection#addAll(Collection)}).
2776     * This is of course only appropriate if it is acceptable to use
2777     * the same value for all additions from this view.
2778 jsr166 1.68 *
2779 jsr166 1.172 * @param mappedValue the mapped value to use for any additions
2780 dl 1.137 * @return the set view
2781     * @throws NullPointerException if the mappedValue is null
2782 tim 1.1 */
2783 dl 1.137 public KeySetView<K,V> keySet(V mappedValue) {
2784     if (mappedValue == null)
2785     throw new NullPointerException();
2786     return new KeySetView<K,V>(this, mappedValue);
2787 tim 1.1 }
2788    
2789     /**
2790 jsr166 1.68 * Returns a {@link Collection} view of the values contained in this map.
2791     * The collection is backed by the map, so changes to the map are
2792 jsr166 1.143 * reflected in the collection, and vice-versa.
2793 jsr166 1.184 *
2794     * @return the collection view
2795 tim 1.1 */
2796 dl 1.142 public ValuesView<K,V> values() {
2797     ValuesView<K,V> vs = values;
2798     return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
2799 dl 1.119 }
2800    
2801     /**
2802     * Returns a {@link Set} view of the mappings contained in this map.
2803     * The set is backed by the map, so changes to the map are
2804     * reflected in the set, and vice-versa. The set supports element
2805     * removal, which removes the corresponding mapping from the map,
2806     * via the {@code Iterator.remove}, {@code Set.remove},
2807     * {@code removeAll}, {@code retainAll}, and {@code clear}
2808     * operations. It does not support the {@code add} or
2809     * {@code addAll} operations.
2810     *
2811     * <p>The view's {@code iterator} is a "weakly consistent" iterator
2812     * that will never throw {@link ConcurrentModificationException},
2813     * and guarantees to traverse elements as they existed upon
2814     * construction of the iterator, and may (but is not guaranteed to)
2815     * reflect any modifications subsequent to construction.
2816 jsr166 1.184 *
2817     * @return the set view
2818 dl 1.119 */
2819     public Set<Map.Entry<K,V>> entrySet() {
2820 dl 1.142 EntrySetView<K,V> es = entrySet;
2821     return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
2822 dl 1.119 }
2823    
2824     /**
2825     * Returns an enumeration of the keys in this table.
2826     *
2827     * @return an enumeration of the keys in this table
2828     * @see #keySet()
2829     */
2830     public Enumeration<K> keys() {
2831     return new KeyIterator<K,V>(this);
2832     }
2833    
2834     /**
2835     * Returns an enumeration of the values in this table.
2836     *
2837     * @return an enumeration of the values in this table
2838     * @see #values()
2839     */
2840     public Enumeration<V> elements() {
2841     return new ValueIterator<K,V>(this);
2842     }
2843    
2844     /**
2845     * Returns the hash code value for this {@link Map}, i.e.,
2846     * the sum of, for each key-value pair in the map,
2847     * {@code key.hashCode() ^ value.hashCode()}.
2848     *
2849     * @return the hash code value for this map
2850     */
2851     public int hashCode() {
2852     int h = 0;
2853     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2854 dl 1.151 V v;
2855 dl 1.119 while ((v = it.advance()) != null) {
2856     h += it.nextKey.hashCode() ^ v.hashCode();
2857     }
2858     return h;
2859     }
2860    
2861     /**
2862     * Returns a string representation of this map. The string
2863     * representation consists of a list of key-value mappings (in no
2864     * particular order) enclosed in braces ("{@code {}}"). Adjacent
2865     * mappings are separated by the characters {@code ", "} (comma
2866     * and space). Each key-value mapping is rendered as the key
2867     * followed by an equals sign ("{@code =}") followed by the
2868     * associated value.
2869     *
2870     * @return a string representation of this map
2871     */
2872     public String toString() {
2873     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2874     StringBuilder sb = new StringBuilder();
2875     sb.append('{');
2876 dl 1.151 V v;
2877 dl 1.119 if ((v = it.advance()) != null) {
2878     for (;;) {
2879 jsr166 1.168 K k = it.nextKey;
2880 dl 1.119 sb.append(k == this ? "(this Map)" : k);
2881     sb.append('=');
2882     sb.append(v == this ? "(this Map)" : v);
2883     if ((v = it.advance()) == null)
2884     break;
2885     sb.append(',').append(' ');
2886     }
2887     }
2888     return sb.append('}').toString();
2889     }
2890    
2891     /**
2892     * Compares the specified object with this map for equality.
2893     * Returns {@code true} if the given object is a map with the same
2894     * mappings as this map. This operation may return misleading
2895     * results if either map is concurrently modified during execution
2896     * of this method.
2897     *
2898     * @param o object to be compared for equality with this map
2899     * @return {@code true} if the specified object is equal to this map
2900     */
2901     public boolean equals(Object o) {
2902     if (o != this) {
2903     if (!(o instanceof Map))
2904     return false;
2905     Map<?,?> m = (Map<?,?>) o;
2906     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
2907 dl 1.151 V val;
2908 dl 1.119 while ((val = it.advance()) != null) {
2909     Object v = m.get(it.nextKey);
2910     if (v == null || (v != val && !v.equals(val)))
2911     return false;
2912     }
2913     for (Map.Entry<?,?> e : m.entrySet()) {
2914     Object mk, mv, v;
2915     if ((mk = e.getKey()) == null ||
2916     (mv = e.getValue()) == null ||
2917     (v = internalGet(mk)) == null ||
2918     (mv != v && !mv.equals(v)))
2919     return false;
2920     }
2921     }
2922     return true;
2923     }
2924    
2925     /* ----------------Iterators -------------- */
2926    
2927 dl 1.149 @SuppressWarnings("serial") static final class KeyIterator<K,V>
2928     extends Traverser<K,V,Object>
2929 dl 1.153 implements Spliterator<K>, Iterator<K>, Enumeration<K> {
2930 jsr166 1.186 KeyIterator(ConcurrentHashMap<K,V> map) { super(map); }
2931     KeyIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2932 dl 1.153 super(map, it);
2933 dl 1.119 }
2934 dl 1.155 public KeyIterator<K,V> trySplit() {
2935     if (tab != null && baseIndex == baseLimit)
2936     return null;
2937 dl 1.146 return new KeyIterator<K,V>(map, this);
2938 dl 1.119 }
2939 jsr166 1.168 public final K next() {
2940 dl 1.119 if (nextVal == null && advance() == null)
2941     throw new NoSuchElementException();
2942 jsr166 1.168 K k = nextKey;
2943 dl 1.119 nextVal = null;
2944 jsr166 1.168 return k;
2945 dl 1.119 }
2946    
2947     public final K nextElement() { return next(); }
2948 dl 1.153
2949 dl 1.162 public Iterator<K> iterator() { return this; }
2950 dl 1.153
2951 dl 1.171 public void forEach(Consumer<? super K> action) {
2952 dl 1.153 if (action == null) throw new NullPointerException();
2953     while (advance() != null)
2954 jsr166 1.168 action.accept(nextKey);
2955 dl 1.153 }
2956 dl 1.160
2957 dl 1.171 public boolean tryAdvance(Consumer<? super K> block) {
2958 dl 1.160 if (block == null) throw new NullPointerException();
2959     if (advance() == null)
2960     return false;
2961 jsr166 1.168 block.accept(nextKey);
2962 dl 1.160 return true;
2963     }
2964 dl 1.188
2965     public int characteristics() {
2966     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
2967     Spliterator.NONNULL;
2968     }
2969    
2970 dl 1.119 }
2971    
2972 dl 1.149 @SuppressWarnings("serial") static final class ValueIterator<K,V>
2973     extends Traverser<K,V,Object>
2974 dl 1.153 implements Spliterator<V>, Iterator<V>, Enumeration<V> {
2975 jsr166 1.186 ValueIterator(ConcurrentHashMap<K,V> map) { super(map); }
2976     ValueIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
2977 dl 1.153 super(map, it);
2978 dl 1.119 }
2979 dl 1.155 public ValueIterator<K,V> trySplit() {
2980     if (tab != null && baseIndex == baseLimit)
2981     return null;
2982 dl 1.146 return new ValueIterator<K,V>(map, this);
2983 dl 1.119 }
2984    
2985 dl 1.151 public final V next() {
2986     V v;
2987 dl 1.119 if ((v = nextVal) == null && (v = advance()) == null)
2988     throw new NoSuchElementException();
2989     nextVal = null;
2990 dl 1.151 return v;
2991 dl 1.119 }
2992    
2993     public final V nextElement() { return next(); }
2994 dl 1.153
2995 dl 1.162 public Iterator<V> iterator() { return this; }
2996 dl 1.153
2997 dl 1.171 public void forEach(Consumer<? super V> action) {
2998 dl 1.153 if (action == null) throw new NullPointerException();
2999     V v;
3000     while ((v = advance()) != null)
3001     action.accept(v);
3002     }
3003 dl 1.160
3004 dl 1.171 public boolean tryAdvance(Consumer<? super V> block) {
3005 dl 1.160 V v;
3006     if (block == null) throw new NullPointerException();
3007     if ((v = advance()) == null)
3008     return false;
3009     block.accept(v);
3010     return true;
3011     }
3012 jsr166 1.161
3013 dl 1.188 public int characteristics() {
3014     return Spliterator.CONCURRENT | Spliterator.NONNULL;
3015     }
3016 dl 1.119 }
3017    
3018 dl 1.149 @SuppressWarnings("serial") static final class EntryIterator<K,V>
3019     extends Traverser<K,V,Object>
3020 dl 1.153 implements Spliterator<Map.Entry<K,V>>, Iterator<Map.Entry<K,V>> {
3021 jsr166 1.186 EntryIterator(ConcurrentHashMap<K,V> map) { super(map); }
3022     EntryIterator(ConcurrentHashMap<K,V> map, Traverser<K,V,Object> it) {
3023 dl 1.153 super(map, it);
3024 dl 1.119 }
3025 dl 1.155 public EntryIterator<K,V> trySplit() {
3026     if (tab != null && baseIndex == baseLimit)
3027     return null;
3028 dl 1.146 return new EntryIterator<K,V>(map, this);
3029 dl 1.119 }
3030    
3031 jsr166 1.168 public final Map.Entry<K,V> next() {
3032 dl 1.151 V v;
3033 dl 1.119 if ((v = nextVal) == null && (v = advance()) == null)
3034     throw new NoSuchElementException();
3035 jsr166 1.168 K k = nextKey;
3036 dl 1.119 nextVal = null;
3037 jsr166 1.168 return new MapEntry<K,V>(k, v, map);
3038 dl 1.119 }
3039 dl 1.153
3040 dl 1.162 public Iterator<Map.Entry<K,V>> iterator() { return this; }
3041 dl 1.153
3042 dl 1.171 public void forEach(Consumer<? super Map.Entry<K,V>> action) {
3043 dl 1.153 if (action == null) throw new NullPointerException();
3044     V v;
3045     while ((v = advance()) != null)
3046 jsr166 1.168 action.accept(entryFor(nextKey, v));
3047 dl 1.153 }
3048 dl 1.160
3049 dl 1.171 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) {
3050 dl 1.160 V v;
3051     if (block == null) throw new NullPointerException();
3052     if ((v = advance()) == null)
3053     return false;
3054 jsr166 1.168 block.accept(entryFor(nextKey, v));
3055 dl 1.160 return true;
3056     }
3057    
3058 dl 1.188 public int characteristics() {
3059     return Spliterator.DISTINCT | Spliterator.CONCURRENT |
3060     Spliterator.NONNULL;
3061     }
3062 dl 1.119 }
3063    
3064     /**
3065     * Exported Entry for iterators
3066     */
3067 jsr166 1.186 static final class MapEntry<K,V> implements Map.Entry<K,V> {
3068 dl 1.119 final K key; // non-null
3069     V val; // non-null
3070 jsr166 1.186 final ConcurrentHashMap<K,V> map;
3071     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
3072 dl 1.119 this.key = key;
3073     this.val = val;
3074     this.map = map;
3075     }
3076     public final K getKey() { return key; }
3077     public final V getValue() { return val; }
3078     public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
3079     public final String toString(){ return key + "=" + val; }
3080    
3081     public final boolean equals(Object o) {
3082     Object k, v; Map.Entry<?,?> e;
3083     return ((o instanceof Map.Entry) &&
3084     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3085     (v = e.getValue()) != null &&
3086     (k == key || k.equals(key)) &&
3087     (v == val || v.equals(val)));
3088     }
3089    
3090     /**
3091     * Sets our entry's value and writes through to the map. The
3092     * value to return is somewhat arbitrary here. Since we do not
3093     * necessarily track asynchronous changes, the most recent
3094     * "previous" value could be different from what we return (or
3095     * could even have been removed in which case the put will
3096     * re-establish). We do not and cannot guarantee more.
3097     */
3098     public final V setValue(V value) {
3099     if (value == null) throw new NullPointerException();
3100     V v = val;
3101     val = value;
3102     map.put(key, value);
3103     return v;
3104     }
3105     }
3106    
3107 dl 1.146 /**
3108     * Returns exportable snapshot entry for the given key and value
3109     * when write-through can't or shouldn't be used.
3110     */
3111     static <K,V> AbstractMap.SimpleEntry<K,V> entryFor(K k, V v) {
3112     return new AbstractMap.SimpleEntry<K,V>(k, v);
3113     }
3114    
3115 dl 1.142 /* ---------------- Serialization Support -------------- */
3116 dl 1.119
3117     /**
3118 dl 1.142 * Stripped-down version of helper class used in previous version,
3119     * declared for the sake of serialization compatibility
3120 dl 1.119 */
3121 dl 1.142 static class Segment<K,V> implements Serializable {
3122     private static final long serialVersionUID = 2249069246763182397L;
3123     final float loadFactor;
3124     Segment(float lf) { this.loadFactor = lf; }
3125     }
3126 dl 1.119
3127 dl 1.142 /**
3128     * Saves the state of the {@code ConcurrentHashMap} instance to a
3129     * stream (i.e., serializes it).
3130     * @param s the stream
3131     * @serialData
3132     * the key (Object) and value (Object)
3133     * for each key-value mapping, followed by a null pair.
3134     * The key-value mappings are emitted in no particular order.
3135     */
3136 dl 1.149 @SuppressWarnings("unchecked") private void writeObject
3137     (java.io.ObjectOutputStream s)
3138 dl 1.142 throws java.io.IOException {
3139     if (segments == null) { // for serialization compatibility
3140     segments = (Segment<K,V>[])
3141     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
3142     for (int i = 0; i < segments.length; ++i)
3143     segments[i] = new Segment<K,V>(LOAD_FACTOR);
3144     }
3145     s.defaultWriteObject();
3146     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3147 dl 1.151 V v;
3148 dl 1.142 while ((v = it.advance()) != null) {
3149     s.writeObject(it.nextKey);
3150     s.writeObject(v);
3151     }
3152     s.writeObject(null);
3153     s.writeObject(null);
3154     segments = null; // throw away
3155     }
3156 dl 1.119
3157 dl 1.142 /**
3158     * Reconstitutes the instance from a stream (that is, deserializes it).
3159     * @param s the stream
3160     */
3161 dl 1.149 @SuppressWarnings("unchecked") private void readObject
3162     (java.io.ObjectInputStream s)
3163 dl 1.142 throws java.io.IOException, ClassNotFoundException {
3164     s.defaultReadObject();
3165     this.segments = null; // unneeded
3166 dl 1.119
3167 dl 1.142 // Create all nodes, then place in table once size is known
3168     long size = 0L;
3169 dl 1.151 Node<V> p = null;
3170 dl 1.142 for (;;) {
3171     K k = (K) s.readObject();
3172     V v = (V) s.readObject();
3173     if (k != null && v != null) {
3174     int h = spread(k.hashCode());
3175 dl 1.151 p = new Node<V>(h, k, v, p);
3176 dl 1.142 ++size;
3177 dl 1.119 }
3178 dl 1.142 else
3179     break;
3180 dl 1.119 }
3181 dl 1.142 if (p != null) {
3182     boolean init = false;
3183     int n;
3184     if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
3185     n = MAXIMUM_CAPACITY;
3186     else {
3187     int sz = (int)size;
3188     n = tableSizeFor(sz + (sz >>> 1) + 1);
3189     }
3190     int sc = sizeCtl;
3191     boolean collide = false;
3192     if (n > sc &&
3193 dl 1.149 U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
3194 dl 1.142 try {
3195     if (table == null) {
3196     init = true;
3197 dl 1.151 @SuppressWarnings("rawtypes") Node[] rt = new Node[n];
3198     Node<V>[] tab = (Node<V>[])rt;
3199 dl 1.142 int mask = n - 1;
3200     while (p != null) {
3201     int j = p.hash & mask;
3202 dl 1.151 Node<V> next = p.next;
3203     Node<V> q = p.next = tabAt(tab, j);
3204 dl 1.142 setTabAt(tab, j, p);
3205     if (!collide && q != null && q.hash == p.hash)
3206     collide = true;
3207     p = next;
3208     }
3209     table = tab;
3210 dl 1.149 addCount(size, -1);
3211 dl 1.142 sc = n - (n >>> 2);
3212     }
3213     } finally {
3214     sizeCtl = sc;
3215     }
3216     if (collide) { // rescan and convert to TreeBins
3217 dl 1.151 Node<V>[] tab = table;
3218 dl 1.142 for (int i = 0; i < tab.length; ++i) {
3219     int c = 0;
3220 dl 1.151 for (Node<V> e = tabAt(tab, i); e != null; e = e.next) {
3221 dl 1.142 if (++c > TREE_THRESHOLD &&
3222     (e.key instanceof Comparable)) {
3223     replaceWithTreeBin(tab, i, e.key);
3224     break;
3225     }
3226     }
3227     }
3228 dl 1.119 }
3229     }
3230 dl 1.142 if (!init) { // Can only happen if unsafely published.
3231     while (p != null) {
3232 dl 1.151 internalPut((K)p.key, p.val, false);
3233 dl 1.142 p = p.next;
3234     }
3235 dl 1.119 }
3236     }
3237 dl 1.142 }
3238 dl 1.119
3239 dl 1.142 // -------------------------------------------------------
3240    
3241 dl 1.151 // Sequential bulk operations
3242    
3243 dl 1.119 /**
3244 dl 1.137 * Performs the given action for each (key, value).
3245 dl 1.119 *
3246 dl 1.137 * @param action the action
3247 dl 1.119 */
3248 jsr166 1.168 public void forEachSequentially
3249 dl 1.171 (BiConsumer<? super K, ? super V> action) {
3250 dl 1.151 if (action == null) throw new NullPointerException();
3251     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3252     V v;
3253     while ((v = it.advance()) != null)
3254 jsr166 1.168 action.accept(it.nextKey, v);
3255 dl 1.119 }
3256    
3257     /**
3258 dl 1.137 * Performs the given action for each non-null transformation
3259     * of each (key, value).
3260     *
3261     * @param transformer a function returning the transformation
3262 jsr166 1.169 * for an element, or null if there is no transformation (in
3263 jsr166 1.172 * which case the action is not applied)
3264 dl 1.137 * @param action the action
3265 dl 1.119 */
3266 jsr166 1.168 public <U> void forEachSequentially
3267 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
3268 dl 1.171 Consumer<? super U> action) {
3269 dl 1.151 if (transformer == null || action == null)
3270     throw new NullPointerException();
3271     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3272     V v; U u;
3273     while ((v = it.advance()) != null) {
3274 jsr166 1.168 if ((u = transformer.apply(it.nextKey, v)) != null)
3275 dl 1.153 action.accept(u);
3276 dl 1.151 }
3277 dl 1.137 }
3278    
3279     /**
3280     * Returns a non-null result from applying the given search
3281 dl 1.151 * function on each (key, value), or null if none.
3282 dl 1.137 *
3283     * @param searchFunction a function returning a non-null
3284     * result on success, else null
3285     * @return a non-null result from applying the given search
3286     * function on each (key, value), or null if none
3287     */
3288 jsr166 1.168 public <U> U searchSequentially
3289 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3290 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3291     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3292     V v; U u;
3293     while ((v = it.advance()) != null) {
3294 jsr166 1.168 if ((u = searchFunction.apply(it.nextKey, v)) != null)
3295 dl 1.151 return u;
3296     }
3297     return null;
3298 dl 1.137 }
3299    
3300     /**
3301     * Returns the result of accumulating the given transformation
3302     * of all (key, value) pairs using the given reducer to
3303     * combine values, or null if none.
3304     *
3305     * @param transformer a function returning the transformation
3306 jsr166 1.169 * for an element, or null if there is no transformation (in
3307 jsr166 1.172 * which case it is not combined)
3308 dl 1.137 * @param reducer a commutative associative combining function
3309     * @return the result of accumulating the given transformation
3310     * of all (key, value) pairs
3311     */
3312 jsr166 1.168 public <U> U reduceSequentially
3313 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
3314     BiFunction<? super U, ? super U, ? extends U> reducer) {
3315 dl 1.151 if (transformer == null || reducer == null)
3316     throw new NullPointerException();
3317     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3318     U r = null, u; V v;
3319     while ((v = it.advance()) != null) {
3320 jsr166 1.168 if ((u = transformer.apply(it.nextKey, v)) != null)
3321 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3322     }
3323     return r;
3324 dl 1.137 }
3325    
3326     /**
3327     * Returns the result of accumulating the given transformation
3328     * of all (key, value) pairs using the given reducer to
3329     * combine values, and the given basis as an identity value.
3330     *
3331     * @param transformer a function returning the transformation
3332     * for an element
3333     * @param basis the identity (initial default value) for the reduction
3334     * @param reducer a commutative associative combining function
3335     * @return the result of accumulating the given transformation
3336     * of all (key, value) pairs
3337     */
3338 jsr166 1.168 public double reduceToDoubleSequentially
3339 dl 1.171 (ToDoubleBiFunction<? super K, ? super V> transformer,
3340 dl 1.151 double basis,
3341 dl 1.153 DoubleBinaryOperator reducer) {
3342 dl 1.151 if (transformer == null || reducer == null)
3343     throw new NullPointerException();
3344     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3345     double r = basis; V v;
3346     while ((v = it.advance()) != null)
3347 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey, v));
3348 dl 1.151 return r;
3349 dl 1.137 }
3350 dl 1.119
3351 dl 1.137 /**
3352     * Returns the result of accumulating the given transformation
3353     * of all (key, value) pairs using the given reducer to
3354     * combine values, and the given basis as an identity value.
3355     *
3356     * @param transformer a function returning the transformation
3357     * for an element
3358     * @param basis the identity (initial default value) for the reduction
3359     * @param reducer a commutative associative combining function
3360     * @return the result of accumulating the given transformation
3361     * of all (key, value) pairs
3362     */
3363 jsr166 1.168 public long reduceToLongSequentially
3364 dl 1.171 (ToLongBiFunction<? super K, ? super V> transformer,
3365 dl 1.151 long basis,
3366 dl 1.153 LongBinaryOperator reducer) {
3367 dl 1.151 if (transformer == null || reducer == null)
3368     throw new NullPointerException();
3369     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3370     long r = basis; V v;
3371     while ((v = it.advance()) != null)
3372 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey, v));
3373 dl 1.151 return r;
3374 dl 1.137 }
3375    
3376     /**
3377     * Returns the result of accumulating the given transformation
3378     * of all (key, value) pairs using the given reducer to
3379     * combine values, and the given basis as an identity value.
3380     *
3381     * @param transformer a function returning the transformation
3382     * for an element
3383     * @param basis the identity (initial default value) for the reduction
3384     * @param reducer a commutative associative combining function
3385     * @return the result of accumulating the given transformation
3386     * of all (key, value) pairs
3387     */
3388 jsr166 1.168 public int reduceToIntSequentially
3389 dl 1.171 (ToIntBiFunction<? super K, ? super V> transformer,
3390 dl 1.151 int basis,
3391 dl 1.153 IntBinaryOperator reducer) {
3392 dl 1.151 if (transformer == null || reducer == null)
3393     throw new NullPointerException();
3394     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3395     int r = basis; V v;
3396     while ((v = it.advance()) != null)
3397 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey, v));
3398 dl 1.151 return r;
3399 dl 1.137 }
3400    
3401     /**
3402     * Performs the given action for each key.
3403     *
3404     * @param action the action
3405     */
3406 jsr166 1.168 public void forEachKeySequentially
3407 dl 1.171 (Consumer<? super K> action) {
3408 dl 1.151 if (action == null) throw new NullPointerException();
3409     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3410     while (it.advance() != null)
3411 jsr166 1.168 action.accept(it.nextKey);
3412 dl 1.137 }
3413 dl 1.119
3414 dl 1.137 /**
3415     * Performs the given action for each non-null transformation
3416     * of each key.
3417     *
3418     * @param transformer a function returning the transformation
3419 jsr166 1.169 * for an element, or null if there is no transformation (in
3420 jsr166 1.172 * which case the action is not applied)
3421 dl 1.137 * @param action the action
3422     */
3423 jsr166 1.168 public <U> void forEachKeySequentially
3424 dl 1.153 (Function<? super K, ? extends U> transformer,
3425 dl 1.171 Consumer<? super U> action) {
3426 dl 1.151 if (transformer == null || action == null)
3427     throw new NullPointerException();
3428     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3429     U u;
3430     while (it.advance() != null) {
3431 jsr166 1.168 if ((u = transformer.apply(it.nextKey)) != null)
3432 dl 1.153 action.accept(u);
3433 dl 1.151 }
3434 dl 1.137 ForkJoinTasks.forEachKey
3435     (this, transformer, action).invoke();
3436     }
3437 dl 1.119
3438 dl 1.137 /**
3439     * Returns a non-null result from applying the given search
3440 dl 1.151 * function on each key, or null if none.
3441 dl 1.137 *
3442     * @param searchFunction a function returning a non-null
3443     * result on success, else null
3444     * @return a non-null result from applying the given search
3445     * function on each key, or null if none
3446     */
3447 jsr166 1.168 public <U> U searchKeysSequentially
3448 dl 1.153 (Function<? super K, ? extends U> searchFunction) {
3449 dl 1.151 Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3450     U u;
3451     while (it.advance() != null) {
3452 jsr166 1.168 if ((u = searchFunction.apply(it.nextKey)) != null)
3453 dl 1.151 return u;
3454     }
3455     return null;
3456 dl 1.137 }
3457 dl 1.119
3458 dl 1.137 /**
3459     * Returns the result of accumulating all keys using the given
3460     * reducer to combine values, or null if none.
3461     *
3462     * @param reducer a commutative associative combining function
3463     * @return the result of accumulating all keys using the given
3464     * reducer to combine values, or null if none
3465     */
3466 jsr166 1.168 public K reduceKeysSequentially
3467 dl 1.153 (BiFunction<? super K, ? super K, ? extends K> reducer) {
3468 dl 1.151 if (reducer == null) throw new NullPointerException();
3469     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3470     K r = null;
3471     while (it.advance() != null) {
3472 jsr166 1.168 K u = it.nextKey;
3473 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3474     }
3475     return r;
3476 dl 1.137 }
3477 dl 1.119
3478 dl 1.137 /**
3479     * Returns the result of accumulating the given transformation
3480     * of all keys using the given reducer to combine values, or
3481     * null if none.
3482     *
3483     * @param transformer a function returning the transformation
3484 jsr166 1.169 * for an element, or null if there is no transformation (in
3485 jsr166 1.172 * which case it is not combined)
3486 dl 1.137 * @param reducer a commutative associative combining function
3487     * @return the result of accumulating the given transformation
3488     * of all keys
3489     */
3490 jsr166 1.168 public <U> U reduceKeysSequentially
3491 dl 1.153 (Function<? super K, ? extends U> transformer,
3492     BiFunction<? super U, ? super U, ? extends U> reducer) {
3493 dl 1.151 if (transformer == null || reducer == null)
3494     throw new NullPointerException();
3495     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3496     U r = null, u;
3497     while (it.advance() != null) {
3498 jsr166 1.168 if ((u = transformer.apply(it.nextKey)) != null)
3499 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3500     }
3501     return r;
3502 dl 1.137 }
3503 dl 1.119
3504 dl 1.137 /**
3505     * Returns the result of accumulating the given transformation
3506     * of all keys using the given reducer to combine values, and
3507     * the given basis as an identity value.
3508     *
3509     * @param transformer a function returning the transformation
3510     * for an element
3511     * @param basis the identity (initial default value) for the reduction
3512     * @param reducer a commutative associative combining function
3513 jsr166 1.157 * @return the result of accumulating the given transformation
3514 dl 1.137 * of all keys
3515     */
3516 jsr166 1.168 public double reduceKeysToDoubleSequentially
3517 dl 1.171 (ToDoubleFunction<? super K> transformer,
3518 dl 1.151 double basis,
3519 dl 1.153 DoubleBinaryOperator reducer) {
3520 dl 1.151 if (transformer == null || reducer == null)
3521     throw new NullPointerException();
3522     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3523     double r = basis;
3524     while (it.advance() != null)
3525 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(it.nextKey));
3526 dl 1.151 return r;
3527 dl 1.137 }
3528 dl 1.119
3529 dl 1.137 /**
3530     * Returns the result of accumulating the given transformation
3531     * of all keys using the given reducer to combine values, and
3532     * the given basis as an identity value.
3533     *
3534     * @param transformer a function returning the transformation
3535     * for an element
3536     * @param basis the identity (initial default value) for the reduction
3537     * @param reducer a commutative associative combining function
3538     * @return the result of accumulating the given transformation
3539     * of all keys
3540     */
3541 jsr166 1.168 public long reduceKeysToLongSequentially
3542 dl 1.171 (ToLongFunction<? super K> transformer,
3543 dl 1.151 long basis,
3544 dl 1.153 LongBinaryOperator reducer) {
3545 dl 1.151 if (transformer == null || reducer == null)
3546     throw new NullPointerException();
3547     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3548     long r = basis;
3549     while (it.advance() != null)
3550 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(it.nextKey));
3551 dl 1.151 return r;
3552 dl 1.137 }
3553 dl 1.119
3554 dl 1.137 /**
3555     * Returns the result of accumulating the given transformation
3556     * of all keys using the given reducer to combine values, and
3557     * the given basis as an identity value.
3558     *
3559     * @param transformer a function returning the transformation
3560     * for an element
3561     * @param basis the identity (initial default value) for the reduction
3562     * @param reducer a commutative associative combining function
3563     * @return the result of accumulating the given transformation
3564     * of all keys
3565     */
3566 jsr166 1.168 public int reduceKeysToIntSequentially
3567 dl 1.171 (ToIntFunction<? super K> transformer,
3568 dl 1.151 int basis,
3569 dl 1.153 IntBinaryOperator reducer) {
3570 dl 1.151 if (transformer == null || reducer == null)
3571     throw new NullPointerException();
3572     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3573     int r = basis;
3574     while (it.advance() != null)
3575 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(it.nextKey));
3576 dl 1.151 return r;
3577 dl 1.137 }
3578 dl 1.119
3579 dl 1.137 /**
3580     * Performs the given action for each value.
3581     *
3582     * @param action the action
3583     */
3584 dl 1.171 public void forEachValueSequentially(Consumer<? super V> action) {
3585 dl 1.151 if (action == null) throw new NullPointerException();
3586     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3587     V v;
3588     while ((v = it.advance()) != null)
3589 dl 1.153 action.accept(v);
3590 dl 1.137 }
3591 dl 1.119
3592 dl 1.137 /**
3593     * Performs the given action for each non-null transformation
3594     * of each value.
3595     *
3596     * @param transformer a function returning the transformation
3597 jsr166 1.169 * for an element, or null if there is no transformation (in
3598 jsr166 1.172 * which case the action is not applied)
3599 jsr166 1.179 * @param action the action
3600 dl 1.137 */
3601 dl 1.151 public <U> void forEachValueSequentially
3602 dl 1.153 (Function<? super V, ? extends U> transformer,
3603 dl 1.171 Consumer<? super U> action) {
3604 dl 1.151 if (transformer == null || action == null)
3605     throw new NullPointerException();
3606     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3607     V v; U u;
3608     while ((v = it.advance()) != null) {
3609     if ((u = transformer.apply(v)) != null)
3610 dl 1.153 action.accept(u);
3611 dl 1.151 }
3612 dl 1.137 }
3613 dl 1.119
3614 dl 1.137 /**
3615     * Returns a non-null result from applying the given search
3616 dl 1.151 * function on each value, or null if none.
3617 dl 1.137 *
3618     * @param searchFunction a function returning a non-null
3619     * result on success, else null
3620     * @return a non-null result from applying the given search
3621     * function on each value, or null if none
3622     */
3623 dl 1.151 public <U> U searchValuesSequentially
3624 dl 1.153 (Function<? super V, ? extends U> searchFunction) {
3625 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3626     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3627     V v; U u;
3628     while ((v = it.advance()) != null) {
3629     if ((u = searchFunction.apply(v)) != null)
3630     return u;
3631     }
3632     return null;
3633 dl 1.137 }
3634 dl 1.119
3635 dl 1.137 /**
3636     * Returns the result of accumulating all values using the
3637     * given reducer to combine values, or null if none.
3638     *
3639     * @param reducer a commutative associative combining function
3640 jsr166 1.157 * @return the result of accumulating all values
3641 dl 1.137 */
3642 dl 1.151 public V reduceValuesSequentially
3643 dl 1.153 (BiFunction<? super V, ? super V, ? extends V> reducer) {
3644 dl 1.151 if (reducer == null) throw new NullPointerException();
3645     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3646     V r = null; V v;
3647     while ((v = it.advance()) != null)
3648     r = (r == null) ? v : reducer.apply(r, v);
3649     return r;
3650 dl 1.137 }
3651 dl 1.119
3652 dl 1.137 /**
3653     * Returns the result of accumulating the given transformation
3654     * of all values using the given reducer to combine values, or
3655     * null if none.
3656     *
3657     * @param transformer a function returning the transformation
3658 jsr166 1.169 * for an element, or null if there is no transformation (in
3659 jsr166 1.172 * which case it is not combined)
3660 dl 1.137 * @param reducer a commutative associative combining function
3661     * @return the result of accumulating the given transformation
3662     * of all values
3663     */
3664 dl 1.151 public <U> U reduceValuesSequentially
3665 dl 1.153 (Function<? super V, ? extends U> transformer,
3666     BiFunction<? super U, ? super U, ? extends U> reducer) {
3667 dl 1.151 if (transformer == null || reducer == null)
3668     throw new NullPointerException();
3669     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3670     U r = null, u; V v;
3671     while ((v = it.advance()) != null) {
3672     if ((u = transformer.apply(v)) != null)
3673     r = (r == null) ? u : reducer.apply(r, u);
3674     }
3675     return r;
3676 dl 1.137 }
3677 dl 1.119
3678 dl 1.137 /**
3679     * Returns the result of accumulating the given transformation
3680     * of all values using the given reducer to combine values,
3681     * and the given basis as an identity value.
3682     *
3683     * @param transformer a function returning the transformation
3684     * for an element
3685     * @param basis the identity (initial default value) for the reduction
3686     * @param reducer a commutative associative combining function
3687     * @return the result of accumulating the given transformation
3688     * of all values
3689     */
3690 dl 1.151 public double reduceValuesToDoubleSequentially
3691 dl 1.171 (ToDoubleFunction<? super V> transformer,
3692 dl 1.151 double basis,
3693 dl 1.153 DoubleBinaryOperator reducer) {
3694 dl 1.151 if (transformer == null || reducer == null)
3695     throw new NullPointerException();
3696     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3697     double r = basis; V v;
3698     while ((v = it.advance()) != null)
3699 dl 1.153 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
3700 dl 1.151 return r;
3701 dl 1.137 }
3702 dl 1.119
3703 dl 1.137 /**
3704     * Returns the result of accumulating the given transformation
3705     * of all values using the given reducer to combine values,
3706     * and the given basis as an identity value.
3707     *
3708     * @param transformer a function returning the transformation
3709     * for an element
3710     * @param basis the identity (initial default value) for the reduction
3711     * @param reducer a commutative associative combining function
3712     * @return the result of accumulating the given transformation
3713     * of all values
3714     */
3715 dl 1.151 public long reduceValuesToLongSequentially
3716 dl 1.171 (ToLongFunction<? super V> transformer,
3717 dl 1.151 long basis,
3718 dl 1.153 LongBinaryOperator reducer) {
3719 dl 1.151 if (transformer == null || reducer == null)
3720     throw new NullPointerException();
3721     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3722     long r = basis; V v;
3723     while ((v = it.advance()) != null)
3724 dl 1.153 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
3725 dl 1.151 return r;
3726 dl 1.137 }
3727 dl 1.119
3728 dl 1.137 /**
3729     * Returns the result of accumulating the given transformation
3730     * of all values using the given reducer to combine values,
3731     * and the given basis as an identity value.
3732     *
3733     * @param transformer a function returning the transformation
3734     * for an element
3735     * @param basis the identity (initial default value) for the reduction
3736     * @param reducer a commutative associative combining function
3737     * @return the result of accumulating the given transformation
3738     * of all values
3739     */
3740 dl 1.151 public int reduceValuesToIntSequentially
3741 dl 1.171 (ToIntFunction<? super V> transformer,
3742 dl 1.151 int basis,
3743 dl 1.153 IntBinaryOperator reducer) {
3744 dl 1.151 if (transformer == null || reducer == null)
3745     throw new NullPointerException();
3746     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3747     int r = basis; V v;
3748     while ((v = it.advance()) != null)
3749 dl 1.153 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
3750 dl 1.151 return r;
3751 dl 1.137 }
3752 dl 1.119
3753 dl 1.137 /**
3754     * Performs the given action for each entry.
3755     *
3756     * @param action the action
3757     */
3758 jsr166 1.168 public void forEachEntrySequentially
3759 dl 1.171 (Consumer<? super Map.Entry<K,V>> action) {
3760 dl 1.151 if (action == null) throw new NullPointerException();
3761     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3762     V v;
3763     while ((v = it.advance()) != null)
3764 jsr166 1.168 action.accept(entryFor(it.nextKey, v));
3765 dl 1.137 }
3766 dl 1.119
3767 dl 1.137 /**
3768     * Performs the given action for each non-null transformation
3769     * of each entry.
3770     *
3771     * @param transformer a function returning the transformation
3772 jsr166 1.169 * for an element, or null if there is no transformation (in
3773 jsr166 1.172 * which case the action is not applied)
3774 dl 1.137 * @param action the action
3775     */
3776 jsr166 1.168 public <U> void forEachEntrySequentially
3777 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
3778 dl 1.171 Consumer<? super U> action) {
3779 dl 1.151 if (transformer == null || action == null)
3780     throw new NullPointerException();
3781     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3782     V v; U u;
3783     while ((v = it.advance()) != null) {
3784 jsr166 1.168 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3785 dl 1.153 action.accept(u);
3786 dl 1.151 }
3787 dl 1.137 }
3788 dl 1.119
3789 dl 1.137 /**
3790     * Returns a non-null result from applying the given search
3791 dl 1.151 * function on each entry, or null if none.
3792 dl 1.137 *
3793     * @param searchFunction a function returning a non-null
3794     * result on success, else null
3795     * @return a non-null result from applying the given search
3796     * function on each entry, or null if none
3797     */
3798 jsr166 1.168 public <U> U searchEntriesSequentially
3799 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
3800 dl 1.151 if (searchFunction == null) throw new NullPointerException();
3801     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3802     V v; U u;
3803     while ((v = it.advance()) != null) {
3804 jsr166 1.168 if ((u = searchFunction.apply(entryFor(it.nextKey, v))) != null)
3805 dl 1.151 return u;
3806     }
3807     return null;
3808 dl 1.137 }
3809 dl 1.119
3810 dl 1.137 /**
3811     * Returns the result of accumulating all entries using the
3812     * given reducer to combine values, or null if none.
3813     *
3814     * @param reducer a commutative associative combining function
3815     * @return the result of accumulating all entries
3816     */
3817 jsr166 1.168 public Map.Entry<K,V> reduceEntriesSequentially
3818 dl 1.153 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
3819 dl 1.151 if (reducer == null) throw new NullPointerException();
3820     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3821     Map.Entry<K,V> r = null; V v;
3822     while ((v = it.advance()) != null) {
3823 jsr166 1.168 Map.Entry<K,V> u = entryFor(it.nextKey, v);
3824 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3825     }
3826     return r;
3827 dl 1.137 }
3828 dl 1.119
3829 dl 1.137 /**
3830     * Returns the result of accumulating the given transformation
3831     * of all entries using the given reducer to combine values,
3832     * or null if none.
3833     *
3834     * @param transformer a function returning the transformation
3835 jsr166 1.169 * for an element, or null if there is no transformation (in
3836 jsr166 1.172 * which case it is not combined)
3837 dl 1.137 * @param reducer a commutative associative combining function
3838     * @return the result of accumulating the given transformation
3839     * of all entries
3840     */
3841 jsr166 1.168 public <U> U reduceEntriesSequentially
3842 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
3843     BiFunction<? super U, ? super U, ? extends U> reducer) {
3844 dl 1.151 if (transformer == null || reducer == null)
3845     throw new NullPointerException();
3846     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3847     U r = null, u; V v;
3848     while ((v = it.advance()) != null) {
3849 jsr166 1.168 if ((u = transformer.apply(entryFor(it.nextKey, v))) != null)
3850 dl 1.151 r = (r == null) ? u : reducer.apply(r, u);
3851     }
3852     return r;
3853 dl 1.137 }
3854 dl 1.119
3855 dl 1.137 /**
3856     * Returns the result of accumulating the given transformation
3857     * of all entries using the given reducer to combine values,
3858     * and the given basis as an identity value.
3859     *
3860     * @param transformer a function returning the transformation
3861     * for an element
3862     * @param basis the identity (initial default value) for the reduction
3863     * @param reducer a commutative associative combining function
3864     * @return the result of accumulating the given transformation
3865     * of all entries
3866     */
3867 jsr166 1.168 public double reduceEntriesToDoubleSequentially
3868 dl 1.171 (ToDoubleFunction<Map.Entry<K,V>> transformer,
3869 dl 1.151 double basis,
3870 dl 1.153 DoubleBinaryOperator reducer) {
3871 dl 1.151 if (transformer == null || reducer == null)
3872     throw new NullPointerException();
3873     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3874     double r = basis; V v;
3875     while ((v = it.advance()) != null)
3876 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(it.nextKey, v)));
3877 dl 1.151 return r;
3878 dl 1.137 }
3879 dl 1.119
3880 dl 1.137 /**
3881     * Returns the result of accumulating the given transformation
3882     * of all entries using the given reducer to combine values,
3883     * and the given basis as an identity value.
3884     *
3885     * @param transformer a function returning the transformation
3886     * for an element
3887     * @param basis the identity (initial default value) for the reduction
3888     * @param reducer a commutative associative combining function
3889 jsr166 1.157 * @return the result of accumulating the given transformation
3890 dl 1.137 * of all entries
3891     */
3892 jsr166 1.168 public long reduceEntriesToLongSequentially
3893 dl 1.171 (ToLongFunction<Map.Entry<K,V>> transformer,
3894 dl 1.151 long basis,
3895 dl 1.153 LongBinaryOperator reducer) {
3896 dl 1.151 if (transformer == null || reducer == null)
3897     throw new NullPointerException();
3898     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3899     long r = basis; V v;
3900     while ((v = it.advance()) != null)
3901 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(it.nextKey, v)));
3902 dl 1.151 return r;
3903 dl 1.137 }
3904 dl 1.119
3905 dl 1.137 /**
3906     * Returns the result of accumulating the given transformation
3907     * of all entries using the given reducer to combine values,
3908     * and the given basis as an identity value.
3909     *
3910     * @param transformer a function returning the transformation
3911     * for an element
3912     * @param basis the identity (initial default value) for the reduction
3913     * @param reducer a commutative associative combining function
3914     * @return the result of accumulating the given transformation
3915     * of all entries
3916     */
3917 jsr166 1.168 public int reduceEntriesToIntSequentially
3918 dl 1.171 (ToIntFunction<Map.Entry<K,V>> transformer,
3919 dl 1.151 int basis,
3920 dl 1.153 IntBinaryOperator reducer) {
3921 dl 1.151 if (transformer == null || reducer == null)
3922     throw new NullPointerException();
3923     Traverser<K,V,Object> it = new Traverser<K,V,Object>(this);
3924     int r = basis; V v;
3925     while ((v = it.advance()) != null)
3926 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(it.nextKey, v)));
3927 dl 1.151 return r;
3928 dl 1.119 }
3929    
3930 dl 1.151 // Parallel bulk operations
3931 dl 1.142
3932     /**
3933 dl 1.151 * Performs the given action for each (key, value).
3934     *
3935     * @param action the action
3936 dl 1.142 */
3937 dl 1.171 public void forEachInParallel(BiConsumer<? super K,? super V> action) {
3938 dl 1.151 ForkJoinTasks.forEach
3939     (this, action).invoke();
3940     }
3941 dl 1.142
3942 dl 1.151 /**
3943     * Performs the given action for each non-null transformation
3944     * of each (key, value).
3945     *
3946     * @param transformer a function returning the transformation
3947 jsr166 1.169 * for an element, or null if there is no transformation (in
3948 jsr166 1.172 * which case the action is not applied)
3949 dl 1.151 * @param action the action
3950     */
3951     public <U> void forEachInParallel
3952 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
3953 dl 1.171 Consumer<? super U> action) {
3954 dl 1.151 ForkJoinTasks.forEach
3955     (this, transformer, action).invoke();
3956     }
3957 dl 1.142
3958 dl 1.151 /**
3959     * Returns a non-null result from applying the given search
3960     * function on each (key, value), or null if none. Upon
3961     * success, further element processing is suppressed and the
3962     * results of any other parallel invocations of the search
3963     * function are ignored.
3964     *
3965     * @param searchFunction a function returning a non-null
3966     * result on success, else null
3967     * @return a non-null result from applying the given search
3968     * function on each (key, value), or null if none
3969     */
3970     public <U> U searchInParallel
3971 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> searchFunction) {
3972 dl 1.151 return ForkJoinTasks.search
3973     (this, searchFunction).invoke();
3974     }
3975 dl 1.142
3976 dl 1.151 /**
3977     * Returns the result of accumulating the given transformation
3978     * of all (key, value) pairs using the given reducer to
3979     * combine values, or null if none.
3980     *
3981     * @param transformer a function returning the transformation
3982 jsr166 1.169 * for an element, or null if there is no transformation (in
3983 jsr166 1.172 * which case it is not combined)
3984 dl 1.151 * @param reducer a commutative associative combining function
3985     * @return the result of accumulating the given transformation
3986     * of all (key, value) pairs
3987     */
3988     public <U> U reduceInParallel
3989 dl 1.153 (BiFunction<? super K, ? super V, ? extends U> transformer,
3990     BiFunction<? super U, ? super U, ? extends U> reducer) {
3991 dl 1.151 return ForkJoinTasks.reduce
3992     (this, transformer, reducer).invoke();
3993     }
3994 dl 1.142
3995 dl 1.151 /**
3996     * Returns the result of accumulating the given transformation
3997     * of all (key, value) pairs using the given reducer to
3998     * combine values, and the given basis as an identity value.
3999     *
4000     * @param transformer a function returning the transformation
4001     * for an element
4002     * @param basis the identity (initial default value) for the reduction
4003     * @param reducer a commutative associative combining function
4004     * @return the result of accumulating the given transformation
4005     * of all (key, value) pairs
4006     */
4007     public double reduceToDoubleInParallel
4008 dl 1.171 (ToDoubleBiFunction<? super K, ? super V> transformer,
4009 dl 1.151 double basis,
4010 dl 1.153 DoubleBinaryOperator reducer) {
4011 dl 1.151 return ForkJoinTasks.reduceToDouble
4012     (this, transformer, basis, reducer).invoke();
4013     }
4014    
4015     /**
4016     * Returns the result of accumulating the given transformation
4017     * of all (key, value) pairs using the given reducer to
4018     * combine values, and the given basis as an identity value.
4019     *
4020     * @param transformer a function returning the transformation
4021     * for an element
4022     * @param basis the identity (initial default value) for the reduction
4023     * @param reducer a commutative associative combining function
4024     * @return the result of accumulating the given transformation
4025     * of all (key, value) pairs
4026     */
4027     public long reduceToLongInParallel
4028 dl 1.171 (ToLongBiFunction<? super K, ? super V> transformer,
4029 dl 1.151 long basis,
4030 dl 1.153 LongBinaryOperator reducer) {
4031 dl 1.151 return ForkJoinTasks.reduceToLong
4032     (this, transformer, basis, reducer).invoke();
4033     }
4034    
4035     /**
4036     * Returns the result of accumulating the given transformation
4037     * of all (key, value) pairs using the given reducer to
4038     * combine values, and the given basis as an identity value.
4039     *
4040     * @param transformer a function returning the transformation
4041     * for an element
4042     * @param basis the identity (initial default value) for the reduction
4043     * @param reducer a commutative associative combining function
4044     * @return the result of accumulating the given transformation
4045     * of all (key, value) pairs
4046     */
4047     public int reduceToIntInParallel
4048 dl 1.171 (ToIntBiFunction<? super K, ? super V> transformer,
4049 dl 1.151 int basis,
4050 dl 1.153 IntBinaryOperator reducer) {
4051 dl 1.151 return ForkJoinTasks.reduceToInt
4052     (this, transformer, basis, reducer).invoke();
4053     }
4054    
4055     /**
4056     * Performs the given action for each key.
4057     *
4058     * @param action the action
4059     */
4060 dl 1.171 public void forEachKeyInParallel(Consumer<? super K> action) {
4061 dl 1.151 ForkJoinTasks.forEachKey
4062     (this, action).invoke();
4063     }
4064    
4065     /**
4066     * Performs the given action for each non-null transformation
4067     * of each key.
4068     *
4069     * @param transformer a function returning the transformation
4070 jsr166 1.169 * for an element, or null if there is no transformation (in
4071 jsr166 1.172 * which case the action is not applied)
4072 dl 1.151 * @param action the action
4073     */
4074     public <U> void forEachKeyInParallel
4075 dl 1.153 (Function<? super K, ? extends U> transformer,
4076 dl 1.171 Consumer<? super U> action) {
4077 dl 1.151 ForkJoinTasks.forEachKey
4078     (this, transformer, action).invoke();
4079     }
4080    
4081     /**
4082     * Returns a non-null result from applying the given search
4083     * function on each key, or null if none. Upon success,
4084     * further element processing is suppressed and the results of
4085     * any other parallel invocations of the search function are
4086     * ignored.
4087     *
4088     * @param searchFunction a function returning a non-null
4089     * result on success, else null
4090     * @return a non-null result from applying the given search
4091     * function on each key, or null if none
4092     */
4093     public <U> U searchKeysInParallel
4094 dl 1.153 (Function<? super K, ? extends U> searchFunction) {
4095 dl 1.151 return ForkJoinTasks.searchKeys
4096     (this, searchFunction).invoke();
4097     }
4098    
4099     /**
4100     * Returns the result of accumulating all keys using the given
4101     * reducer to combine values, or null if none.
4102     *
4103     * @param reducer a commutative associative combining function
4104     * @return the result of accumulating all keys using the given
4105     * reducer to combine values, or null if none
4106     */
4107     public K reduceKeysInParallel
4108 dl 1.153 (BiFunction<? super K, ? super K, ? extends K> reducer) {
4109 dl 1.151 return ForkJoinTasks.reduceKeys
4110     (this, reducer).invoke();
4111     }
4112    
4113     /**
4114     * Returns the result of accumulating the given transformation
4115     * of all keys using the given reducer to combine values, or
4116     * null if none.
4117     *
4118     * @param transformer a function returning the transformation
4119 jsr166 1.169 * for an element, or null if there is no transformation (in
4120 jsr166 1.172 * which case it is not combined)
4121 dl 1.151 * @param reducer a commutative associative combining function
4122     * @return the result of accumulating the given transformation
4123     * of all keys
4124     */
4125     public <U> U reduceKeysInParallel
4126 dl 1.153 (Function<? super K, ? extends U> transformer,
4127     BiFunction<? super U, ? super U, ? extends U> reducer) {
4128 dl 1.151 return ForkJoinTasks.reduceKeys
4129     (this, transformer, reducer).invoke();
4130     }
4131    
4132     /**
4133     * Returns the result of accumulating the given transformation
4134     * of all keys using the given reducer to combine values, and
4135     * the given basis as an identity value.
4136     *
4137     * @param transformer a function returning the transformation
4138     * for an element
4139     * @param basis the identity (initial default value) for the reduction
4140     * @param reducer a commutative associative combining function
4141 jsr166 1.157 * @return the result of accumulating the given transformation
4142 dl 1.151 * of all keys
4143     */
4144     public double reduceKeysToDoubleInParallel
4145 dl 1.171 (ToDoubleFunction<? super K> transformer,
4146 dl 1.151 double basis,
4147 dl 1.153 DoubleBinaryOperator reducer) {
4148 dl 1.151 return ForkJoinTasks.reduceKeysToDouble
4149     (this, transformer, basis, reducer).invoke();
4150     }
4151    
4152     /**
4153     * Returns the result of accumulating the given transformation
4154     * of all keys using the given reducer to combine values, and
4155     * the given basis as an identity value.
4156     *
4157     * @param transformer a function returning the transformation
4158     * for an element
4159     * @param basis the identity (initial default value) for the reduction
4160     * @param reducer a commutative associative combining function
4161     * @return the result of accumulating the given transformation
4162     * of all keys
4163     */
4164     public long reduceKeysToLongInParallel
4165 dl 1.171 (ToLongFunction<? super K> transformer,
4166 dl 1.151 long basis,
4167 dl 1.153 LongBinaryOperator reducer) {
4168 dl 1.151 return ForkJoinTasks.reduceKeysToLong
4169     (this, transformer, basis, reducer).invoke();
4170     }
4171    
4172     /**
4173     * Returns the result of accumulating the given transformation
4174     * of all keys using the given reducer to combine values, and
4175     * the given basis as an identity value.
4176     *
4177     * @param transformer a function returning the transformation
4178     * for an element
4179     * @param basis the identity (initial default value) for the reduction
4180     * @param reducer a commutative associative combining function
4181     * @return the result of accumulating the given transformation
4182     * of all keys
4183     */
4184     public int reduceKeysToIntInParallel
4185 dl 1.171 (ToIntFunction<? super K> transformer,
4186 dl 1.151 int basis,
4187 dl 1.153 IntBinaryOperator reducer) {
4188 dl 1.151 return ForkJoinTasks.reduceKeysToInt
4189     (this, transformer, basis, reducer).invoke();
4190     }
4191    
4192     /**
4193     * Performs the given action for each value.
4194     *
4195     * @param action the action
4196     */
4197 dl 1.171 public void forEachValueInParallel(Consumer<? super V> action) {
4198 dl 1.151 ForkJoinTasks.forEachValue
4199     (this, action).invoke();
4200     }
4201    
4202     /**
4203     * Performs the given action for each non-null transformation
4204     * of each value.
4205     *
4206     * @param transformer a function returning the transformation
4207 jsr166 1.169 * for an element, or null if there is no transformation (in
4208 jsr166 1.172 * which case the action is not applied)
4209 jsr166 1.179 * @param action the action
4210 dl 1.151 */
4211     public <U> void forEachValueInParallel
4212 dl 1.153 (Function<? super V, ? extends U> transformer,
4213 dl 1.171 Consumer<? super U> action) {
4214 dl 1.151 ForkJoinTasks.forEachValue
4215     (this, transformer, action).invoke();
4216     }
4217    
4218     /**
4219     * Returns a non-null result from applying the given search
4220     * function on each value, or null if none. Upon success,
4221     * further element processing is suppressed and the results of
4222     * any other parallel invocations of the search function are
4223     * ignored.
4224     *
4225     * @param searchFunction a function returning a non-null
4226     * result on success, else null
4227     * @return a non-null result from applying the given search
4228     * function on each value, or null if none
4229     */
4230     public <U> U searchValuesInParallel
4231 dl 1.153 (Function<? super V, ? extends U> searchFunction) {
4232 dl 1.151 return ForkJoinTasks.searchValues
4233     (this, searchFunction).invoke();
4234     }
4235    
4236     /**
4237     * Returns the result of accumulating all values using the
4238     * given reducer to combine values, or null if none.
4239     *
4240     * @param reducer a commutative associative combining function
4241 jsr166 1.157 * @return the result of accumulating all values
4242 dl 1.151 */
4243     public V reduceValuesInParallel
4244 dl 1.153 (BiFunction<? super V, ? super V, ? extends V> reducer) {
4245 dl 1.151 return ForkJoinTasks.reduceValues
4246     (this, reducer).invoke();
4247     }
4248    
4249     /**
4250     * Returns the result of accumulating the given transformation
4251     * of all values using the given reducer to combine values, or
4252     * null if none.
4253     *
4254     * @param transformer a function returning the transformation
4255 jsr166 1.169 * for an element, or null if there is no transformation (in
4256 jsr166 1.172 * which case it is not combined)
4257 dl 1.151 * @param reducer a commutative associative combining function
4258     * @return the result of accumulating the given transformation
4259     * of all values
4260     */
4261     public <U> U reduceValuesInParallel
4262 dl 1.153 (Function<? super V, ? extends U> transformer,
4263     BiFunction<? super U, ? super U, ? extends U> reducer) {
4264 dl 1.151 return ForkJoinTasks.reduceValues
4265     (this, transformer, reducer).invoke();
4266     }
4267    
4268     /**
4269     * Returns the result of accumulating the given transformation
4270     * of all values using the given reducer to combine values,
4271     * and the given basis as an identity value.
4272     *
4273     * @param transformer a function returning the transformation
4274     * for an element
4275     * @param basis the identity (initial default value) for the reduction
4276     * @param reducer a commutative associative combining function
4277     * @return the result of accumulating the given transformation
4278     * of all values
4279     */
4280     public double reduceValuesToDoubleInParallel
4281 dl 1.171 (ToDoubleFunction<? super V> transformer,
4282 dl 1.151 double basis,
4283 dl 1.153 DoubleBinaryOperator reducer) {
4284 dl 1.151 return ForkJoinTasks.reduceValuesToDouble
4285     (this, transformer, basis, reducer).invoke();
4286     }
4287    
4288     /**
4289     * Returns the result of accumulating the given transformation
4290     * of all values using the given reducer to combine values,
4291     * and the given basis as an identity value.
4292     *
4293     * @param transformer a function returning the transformation
4294     * for an element
4295     * @param basis the identity (initial default value) for the reduction
4296     * @param reducer a commutative associative combining function
4297     * @return the result of accumulating the given transformation
4298     * of all values
4299     */
4300     public long reduceValuesToLongInParallel
4301 dl 1.171 (ToLongFunction<? super V> transformer,
4302 dl 1.151 long basis,
4303 dl 1.153 LongBinaryOperator reducer) {
4304 dl 1.151 return ForkJoinTasks.reduceValuesToLong
4305     (this, transformer, basis, reducer).invoke();
4306     }
4307    
4308     /**
4309     * Returns the result of accumulating the given transformation
4310     * of all values using the given reducer to combine values,
4311     * and the given basis as an identity value.
4312     *
4313     * @param transformer a function returning the transformation
4314     * for an element
4315     * @param basis the identity (initial default value) for the reduction
4316     * @param reducer a commutative associative combining function
4317     * @return the result of accumulating the given transformation
4318     * of all values
4319     */
4320     public int reduceValuesToIntInParallel
4321 dl 1.171 (ToIntFunction<? super V> transformer,
4322 dl 1.151 int basis,
4323 dl 1.153 IntBinaryOperator reducer) {
4324 dl 1.151 return ForkJoinTasks.reduceValuesToInt
4325     (this, transformer, basis, reducer).invoke();
4326     }
4327    
4328     /**
4329     * Performs the given action for each entry.
4330     *
4331     * @param action the action
4332     */
4333 dl 1.171 public void forEachEntryInParallel(Consumer<? super Map.Entry<K,V>> action) {
4334 dl 1.151 ForkJoinTasks.forEachEntry
4335     (this, action).invoke();
4336     }
4337    
4338     /**
4339     * Performs the given action for each non-null transformation
4340     * of each entry.
4341     *
4342     * @param transformer a function returning the transformation
4343 jsr166 1.169 * for an element, or null if there is no transformation (in
4344 jsr166 1.172 * which case the action is not applied)
4345 dl 1.151 * @param action the action
4346     */
4347     public <U> void forEachEntryInParallel
4348 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
4349 dl 1.171 Consumer<? super U> action) {
4350 dl 1.151 ForkJoinTasks.forEachEntry
4351     (this, transformer, action).invoke();
4352     }
4353    
4354     /**
4355     * Returns a non-null result from applying the given search
4356     * function on each entry, or null if none. Upon success,
4357     * further element processing is suppressed and the results of
4358     * any other parallel invocations of the search function are
4359     * ignored.
4360     *
4361     * @param searchFunction a function returning a non-null
4362     * result on success, else null
4363     * @return a non-null result from applying the given search
4364     * function on each entry, or null if none
4365     */
4366     public <U> U searchEntriesInParallel
4367 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> searchFunction) {
4368 dl 1.151 return ForkJoinTasks.searchEntries
4369     (this, searchFunction).invoke();
4370     }
4371    
4372     /**
4373     * Returns the result of accumulating all entries using the
4374     * given reducer to combine values, or null if none.
4375     *
4376     * @param reducer a commutative associative combining function
4377     * @return the result of accumulating all entries
4378     */
4379     public Map.Entry<K,V> reduceEntriesInParallel
4380 dl 1.153 (BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
4381 dl 1.151 return ForkJoinTasks.reduceEntries
4382     (this, reducer).invoke();
4383     }
4384    
4385     /**
4386     * Returns the result of accumulating the given transformation
4387     * of all entries using the given reducer to combine values,
4388     * or null if none.
4389     *
4390     * @param transformer a function returning the transformation
4391 jsr166 1.169 * for an element, or null if there is no transformation (in
4392 jsr166 1.172 * which case it is not combined)
4393 dl 1.151 * @param reducer a commutative associative combining function
4394     * @return the result of accumulating the given transformation
4395     * of all entries
4396     */
4397     public <U> U reduceEntriesInParallel
4398 dl 1.153 (Function<Map.Entry<K,V>, ? extends U> transformer,
4399     BiFunction<? super U, ? super U, ? extends U> reducer) {
4400 dl 1.151 return ForkJoinTasks.reduceEntries
4401     (this, transformer, reducer).invoke();
4402     }
4403    
4404     /**
4405     * Returns the result of accumulating the given transformation
4406     * of all entries using the given reducer to combine values,
4407     * and the given basis as an identity value.
4408     *
4409     * @param transformer a function returning the transformation
4410     * for an element
4411     * @param basis the identity (initial default value) for the reduction
4412     * @param reducer a commutative associative combining function
4413     * @return the result of accumulating the given transformation
4414     * of all entries
4415     */
4416     public double reduceEntriesToDoubleInParallel
4417 dl 1.171 (ToDoubleFunction<Map.Entry<K,V>> transformer,
4418 dl 1.151 double basis,
4419 dl 1.153 DoubleBinaryOperator reducer) {
4420 dl 1.151 return ForkJoinTasks.reduceEntriesToDouble
4421     (this, transformer, basis, reducer).invoke();
4422     }
4423    
4424     /**
4425     * Returns the result of accumulating the given transformation
4426     * of all entries using the given reducer to combine values,
4427     * and the given basis as an identity value.
4428     *
4429     * @param transformer a function returning the transformation
4430     * for an element
4431     * @param basis the identity (initial default value) for the reduction
4432     * @param reducer a commutative associative combining function
4433 jsr166 1.157 * @return the result of accumulating the given transformation
4434 dl 1.151 * of all entries
4435     */
4436     public long reduceEntriesToLongInParallel
4437 dl 1.171 (ToLongFunction<Map.Entry<K,V>> transformer,
4438 dl 1.151 long basis,
4439 dl 1.153 LongBinaryOperator reducer) {
4440 dl 1.151 return ForkJoinTasks.reduceEntriesToLong
4441     (this, transformer, basis, reducer).invoke();
4442     }
4443    
4444     /**
4445     * Returns the result of accumulating the given transformation
4446     * of all entries using the given reducer to combine values,
4447     * and the given basis as an identity value.
4448     *
4449     * @param transformer a function returning the transformation
4450     * for an element
4451     * @param basis the identity (initial default value) for the reduction
4452     * @param reducer a commutative associative combining function
4453     * @return the result of accumulating the given transformation
4454     * of all entries
4455     */
4456     public int reduceEntriesToIntInParallel
4457 dl 1.171 (ToIntFunction<Map.Entry<K,V>> transformer,
4458 dl 1.151 int basis,
4459 dl 1.153 IntBinaryOperator reducer) {
4460 dl 1.151 return ForkJoinTasks.reduceEntriesToInt
4461     (this, transformer, basis, reducer).invoke();
4462     }
4463    
4464    
4465     /* ----------------Views -------------- */
4466    
4467     /**
4468     * Base class for views.
4469     */
4470 jsr166 1.187 abstract static class CHMCollectionView<K,V,E>
4471 jsr166 1.184 implements Collection<E>, java.io.Serializable {
4472 dl 1.163 private static final long serialVersionUID = 7249069246763182397L;
4473 jsr166 1.186 final ConcurrentHashMap<K,V> map;
4474     CHMCollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
4475 dl 1.151
4476     /**
4477     * Returns the map backing this view.
4478     *
4479     * @return the map backing this view
4480     */
4481     public ConcurrentHashMap<K,V> getMap() { return map; }
4482    
4483 jsr166 1.184 /**
4484     * Removes all of the elements from this view, by removing all
4485     * the mappings from the map backing this view.
4486     */
4487     public final void clear() { map.clear(); }
4488     public final int size() { return map.size(); }
4489     public final boolean isEmpty() { return map.isEmpty(); }
4490 dl 1.151
4491     // implementations below rely on concrete classes supplying these
4492 jsr166 1.184 // abstract methods
4493     /**
4494     * Returns a "weakly consistent" iterator that will never
4495     * throw {@link ConcurrentModificationException}, and
4496     * guarantees to traverse elements as they existed upon
4497     * construction of the iterator, and may (but is not
4498     * guaranteed to) reflect any modifications subsequent to
4499     * construction.
4500     */
4501     public abstract Iterator<E> iterator();
4502 jsr166 1.165 public abstract boolean contains(Object o);
4503     public abstract boolean remove(Object o);
4504 dl 1.151
4505     private static final String oomeMsg = "Required array size too large";
4506 dl 1.142
4507     public final Object[] toArray() {
4508     long sz = map.mappingCount();
4509 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4510 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4511     int n = (int)sz;
4512     Object[] r = new Object[n];
4513     int i = 0;
4514 jsr166 1.184 for (E e : this) {
4515 dl 1.142 if (i == n) {
4516     if (n >= MAX_ARRAY_SIZE)
4517     throw new OutOfMemoryError(oomeMsg);
4518     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4519     n = MAX_ARRAY_SIZE;
4520     else
4521     n += (n >>> 1) + 1;
4522     r = Arrays.copyOf(r, n);
4523     }
4524 jsr166 1.184 r[i++] = e;
4525 dl 1.142 }
4526     return (i == n) ? r : Arrays.copyOf(r, i);
4527     }
4528    
4529 jsr166 1.184 @SuppressWarnings("unchecked")
4530     public final <T> T[] toArray(T[] a) {
4531 dl 1.142 long sz = map.mappingCount();
4532 jsr166 1.184 if (sz > MAX_ARRAY_SIZE)
4533 dl 1.142 throw new OutOfMemoryError(oomeMsg);
4534     int m = (int)sz;
4535     T[] r = (a.length >= m) ? a :
4536     (T[])java.lang.reflect.Array
4537     .newInstance(a.getClass().getComponentType(), m);
4538     int n = r.length;
4539     int i = 0;
4540 jsr166 1.184 for (E e : this) {
4541 dl 1.142 if (i == n) {
4542     if (n >= MAX_ARRAY_SIZE)
4543     throw new OutOfMemoryError(oomeMsg);
4544     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
4545     n = MAX_ARRAY_SIZE;
4546     else
4547     n += (n >>> 1) + 1;
4548     r = Arrays.copyOf(r, n);
4549     }
4550 jsr166 1.184 r[i++] = (T)e;
4551 dl 1.142 }
4552     if (a == r && i < n) {
4553     r[i] = null; // null-terminate
4554     return r;
4555     }
4556     return (i == n) ? r : Arrays.copyOf(r, i);
4557     }
4558    
4559 jsr166 1.184 /**
4560     * Returns a string representation of this collection.
4561     * The string representation consists of the string representations
4562     * of the collection's elements in the order they are returned by
4563     * its iterator, enclosed in square brackets ({@code "[]"}).
4564     * Adjacent elements are separated by the characters {@code ", "}
4565     * (comma and space). Elements are converted to strings as by
4566     * {@link String#valueOf(Object)}.
4567     *
4568     * @return a string representation of this collection
4569     */
4570 dl 1.142 public final String toString() {
4571     StringBuilder sb = new StringBuilder();
4572     sb.append('[');
4573 jsr166 1.184 Iterator<E> it = iterator();
4574 dl 1.142 if (it.hasNext()) {
4575     for (;;) {
4576     Object e = it.next();
4577     sb.append(e == this ? "(this Collection)" : e);
4578     if (!it.hasNext())
4579     break;
4580     sb.append(',').append(' ');
4581     }
4582     }
4583     return sb.append(']').toString();
4584     }
4585    
4586     public final boolean containsAll(Collection<?> c) {
4587     if (c != this) {
4588 jsr166 1.184 for (Object e : c) {
4589 dl 1.142 if (e == null || !contains(e))
4590     return false;
4591     }
4592     }
4593     return true;
4594     }
4595    
4596     public final boolean removeAll(Collection<?> c) {
4597     boolean modified = false;
4598 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4599 dl 1.142 if (c.contains(it.next())) {
4600     it.remove();
4601     modified = true;
4602     }
4603     }
4604     return modified;
4605     }
4606    
4607     public final boolean retainAll(Collection<?> c) {
4608     boolean modified = false;
4609 jsr166 1.184 for (Iterator<E> it = iterator(); it.hasNext();) {
4610 dl 1.142 if (!c.contains(it.next())) {
4611     it.remove();
4612     modified = true;
4613     }
4614     }
4615     return modified;
4616     }
4617    
4618     }
4619    
4620 jsr166 1.187 abstract static class CHMSetView<K,V,E>
4621     extends CHMCollectionView<K,V,E>
4622 jsr166 1.184 implements Set<E>, java.io.Serializable {
4623     private static final long serialVersionUID = 7249069246763182397L;
4624 jsr166 1.186 CHMSetView(ConcurrentHashMap<K,V> map) { super(map); }
4625 jsr166 1.184
4626     // Implement Set API
4627    
4628     /**
4629     * Implements {@link Set#hashCode()}.
4630     * @return the hash code value for this set
4631     */
4632     public final int hashCode() {
4633     int h = 0;
4634     for (E e : this)
4635     h += e.hashCode();
4636     return h;
4637     }
4638    
4639     /**
4640     * Implements {@link Set#equals(Object)}.
4641     * @param o object to be compared for equality with this set
4642     * @return {@code true} if the specified object is equal to this set
4643     */
4644     public final boolean equals(Object o) {
4645     Set<?> c;
4646     return ((o instanceof Set) &&
4647     ((c = (Set<?>)o) == this ||
4648     (containsAll(c) && c.containsAll(this))));
4649     }
4650     }
4651    
4652 dl 1.142 /**
4653     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
4654     * which additions may optionally be enabled by mapping to a
4655 jsr166 1.185 * common value. This class cannot be directly instantiated.
4656     * See {@link #keySet() keySet()},
4657     * {@link #keySet(Object) keySet(V)},
4658     * {@link #newKeySet() newKeySet()},
4659     * {@link #newKeySet(int) newKeySet(int)}.
4660 dl 1.142 */
4661 jsr166 1.184 public static class KeySetView<K,V>
4662     extends CHMSetView<K,V,K>
4663     implements Set<K>, java.io.Serializable {
4664 dl 1.142 private static final long serialVersionUID = 7249069246763182397L;
4665     private final V value;
4666 jsr166 1.186 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
4667 dl 1.142 super(map);
4668     this.value = value;
4669     }
4670    
4671     /**
4672     * Returns the default mapped value for additions,
4673     * or {@code null} if additions are not supported.
4674     *
4675     * @return the default mapped value for additions, or {@code null}
4676 jsr166 1.172 * if not supported
4677 dl 1.142 */
4678     public V getMappedValue() { return value; }
4679    
4680 jsr166 1.184 /**
4681     * {@inheritDoc}
4682     * @throws NullPointerException if the specified key is null
4683     */
4684     public boolean contains(Object o) { return map.containsKey(o); }
4685 dl 1.142
4686 jsr166 1.184 /**
4687     * Removes the key from this map view, by removing the key (and its
4688     * corresponding value) from the backing map. This method does
4689     * nothing if the key is not in the map.
4690     *
4691     * @param o the key to be removed from the backing map
4692     * @return {@code true} if the backing map contained the specified key
4693     * @throws NullPointerException if the specified key is null
4694     */
4695     public boolean remove(Object o) { return map.remove(o) != null; }
4696    
4697     /**
4698     * @return an iterator over the keys of the backing map
4699     */
4700     public Iterator<K> iterator() { return new KeyIterator<K,V>(map); }
4701 dl 1.142
4702     /**
4703 jsr166 1.184 * Adds the specified key to this set view by mapping the key to
4704     * the default mapped value in the backing map, if defined.
4705 dl 1.142 *
4706 jsr166 1.184 * @param e key to be added
4707     * @return {@code true} if this set changed as a result of the call
4708     * @throws NullPointerException if the specified key is null
4709     * @throws UnsupportedOperationException if no default mapped value
4710     * for additions was provided
4711 dl 1.142 */
4712     public boolean add(K e) {
4713     V v;
4714     if ((v = value) == null)
4715     throw new UnsupportedOperationException();
4716 dl 1.149 return map.internalPut(e, v, true) == null;
4717 dl 1.142 }
4718 jsr166 1.184
4719     /**
4720     * Adds all of the elements in the specified collection to this set,
4721     * as if by calling {@link #add} on each one.
4722     *
4723     * @param c the elements to be inserted into this set
4724     * @return {@code true} if this set changed as a result of the call
4725     * @throws NullPointerException if the collection or any of its
4726     * elements are {@code null}
4727     * @throws UnsupportedOperationException if no default mapped value
4728     * for additions was provided
4729     */
4730 dl 1.142 public boolean addAll(Collection<? extends K> c) {
4731     boolean added = false;
4732     V v;
4733     if ((v = value) == null)
4734     throw new UnsupportedOperationException();
4735     for (K e : c) {
4736 dl 1.149 if (map.internalPut(e, v, true) == null)
4737 dl 1.142 added = true;
4738     }
4739     return added;
4740     }
4741 dl 1.153
4742     public Stream<K> stream() {
4743 dl 1.188 return Streams.stream(new KeyIterator<>(map, null));
4744 dl 1.153 }
4745     public Stream<K> parallelStream() {
4746 dl 1.188 return Streams.parallelStream(new KeyIterator<K,V>(map, null));
4747 dl 1.153 }
4748 dl 1.142 }
4749    
4750     /**
4751     * A view of a ConcurrentHashMap as a {@link Collection} of
4752     * values, in which additions are disabled. This class cannot be
4753 jsr166 1.181 * directly instantiated. See {@link #values()}.
4754 dl 1.142 *
4755     * <p>The view's {@code iterator} is a "weakly consistent" iterator
4756     * that will never throw {@link ConcurrentModificationException},
4757     * and guarantees to traverse elements as they existed upon
4758     * construction of the iterator, and may (but is not guaranteed to)
4759     * reflect any modifications subsequent to construction.
4760     */
4761 jsr166 1.184 public static final class ValuesView<K,V>
4762     extends CHMCollectionView<K,V,V>
4763     implements Collection<V>, java.io.Serializable {
4764 jsr166 1.166 private static final long serialVersionUID = 2249069246763182397L;
4765 jsr166 1.186 ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
4766 jsr166 1.184 public final boolean contains(Object o) {
4767     return map.containsValue(o);
4768     }
4769 dl 1.142 public final boolean remove(Object o) {
4770     if (o != null) {
4771 jsr166 1.184 for (Iterator<V> it = iterator(); it.hasNext();) {
4772 dl 1.142 if (o.equals(it.next())) {
4773     it.remove();
4774     return true;
4775     }
4776     }
4777     }
4778     return false;
4779     }
4780    
4781     /**
4782 jsr166 1.184 * @return an iterator over the values of the backing map
4783 dl 1.142 */
4784     public final Iterator<V> iterator() {
4785     return new ValueIterator<K,V>(map);
4786     }
4787 jsr166 1.184
4788     /** Always throws {@link UnsupportedOperationException}. */
4789 dl 1.142 public final boolean add(V e) {
4790     throw new UnsupportedOperationException();
4791     }
4792 jsr166 1.184 /** Always throws {@link UnsupportedOperationException}. */
4793 dl 1.142 public final boolean addAll(Collection<? extends V> c) {
4794     throw new UnsupportedOperationException();
4795     }
4796    
4797 dl 1.153 public Stream<V> stream() {
4798 dl 1.188 return Streams.stream(new ValueIterator<K,V>(map, null));
4799 dl 1.153 }
4800    
4801     public Stream<V> parallelStream() {
4802 dl 1.188 return Streams.parallelStream(new ValueIterator<K,V>(map, null));
4803 dl 1.153 }
4804    
4805 dl 1.142 }
4806    
4807     /**
4808     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
4809     * entries. This class cannot be directly instantiated. See
4810 jsr166 1.180 * {@link #entrySet()}.
4811 dl 1.142 */
4812 jsr166 1.184 public static final class EntrySetView<K,V>
4813     extends CHMSetView<K,V,Map.Entry<K,V>>
4814     implements Set<Map.Entry<K,V>>, java.io.Serializable {
4815 jsr166 1.166 private static final long serialVersionUID = 2249069246763182397L;
4816 jsr166 1.186 EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
4817 jsr166 1.184
4818 dl 1.142 public final boolean contains(Object o) {
4819     Object k, v, r; Map.Entry<?,?> e;
4820     return ((o instanceof Map.Entry) &&
4821     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4822     (r = map.get(k)) != null &&
4823     (v = e.getValue()) != null &&
4824     (v == r || v.equals(r)));
4825     }
4826     public final boolean remove(Object o) {
4827     Object k, v; Map.Entry<?,?> e;
4828     return ((o instanceof Map.Entry) &&
4829     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
4830     (v = e.getValue()) != null &&
4831     map.remove(k, v));
4832     }
4833    
4834     /**
4835 jsr166 1.184 * @return an iterator over the entries of the backing map
4836 dl 1.142 */
4837     public final Iterator<Map.Entry<K,V>> iterator() {
4838     return new EntryIterator<K,V>(map);
4839     }
4840    
4841 jsr166 1.184 /**
4842     * Adds the specified mapping to this view.
4843     *
4844     * @param e mapping to be added
4845     * @return {@code true} if this set changed as a result of the call
4846     * @throws NullPointerException if the entry, its key, or its
4847     * value is null
4848     */
4849 dl 1.142 public final boolean add(Entry<K,V> e) {
4850 jsr166 1.182 return map.internalPut(e.getKey(), e.getValue(), false) == null;
4851 dl 1.142 }
4852 jsr166 1.184 /**
4853     * Adds all of the mappings in the specified collection to this
4854     * set, as if by calling {@link #add(Map.Entry)} on each one.
4855     * @param c the mappings to be inserted into this set
4856     * @return {@code true} if this set changed as a result of the call
4857     * @throws NullPointerException if the collection or any of its
4858     * entries, keys, or values are null
4859     */
4860 dl 1.142 public final boolean addAll(Collection<? extends Entry<K,V>> c) {
4861     boolean added = false;
4862     for (Entry<K,V> e : c) {
4863     if (add(e))
4864     added = true;
4865     }
4866     return added;
4867     }
4868 dl 1.153
4869     public Stream<Map.Entry<K,V>> stream() {
4870 dl 1.188 return Streams.stream(new EntryIterator<K,V>(map, null));
4871 dl 1.153 }
4872    
4873     public Stream<Map.Entry<K,V>> parallelStream() {
4874 dl 1.188 return Streams.parallelStream(new EntryIterator<K,V>(map, null));
4875 dl 1.153 }
4876 dl 1.142 }
4877    
4878 dl 1.119 // ---------------------------------------------------------------------
4879    
4880     /**
4881     * Predefined tasks for performing bulk parallel operations on
4882     * ConcurrentHashMaps. These tasks follow the forms and rules used
4883 dl 1.137 * for bulk operations. Each method has the same name, but returns
4884     * a task rather than invoking it. These methods may be useful in
4885     * custom applications such as submitting a task without waiting
4886     * for completion, using a custom pool, or combining with other
4887     * tasks.
4888 dl 1.119 */
4889     public static class ForkJoinTasks {
4890     private ForkJoinTasks() {}
4891    
4892     /**
4893     * Returns a task that when invoked, performs the given
4894     * action for each (key, value)
4895     *
4896     * @param map the map
4897     * @param action the action
4898     * @return the task
4899     */
4900 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEach
4901 dl 1.119 (ConcurrentHashMap<K,V> map,
4902 dl 1.171 BiConsumer<? super K, ? super V> action) {
4903 dl 1.119 if (action == null) throw new NullPointerException();
4904 dl 1.146 return new ForEachMappingTask<K,V>(map, null, -1, action);
4905 dl 1.119 }
4906    
4907     /**
4908     * Returns a task that when invoked, performs the given
4909     * action for each non-null transformation of each (key, value)
4910     *
4911     * @param map the map
4912     * @param transformer a function returning the transformation
4913 jsr166 1.135 * for an element, or null if there is no transformation (in
4914 jsr166 1.134 * which case the action is not applied)
4915 dl 1.119 * @param action the action
4916     * @return the task
4917     */
4918 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEach
4919 dl 1.119 (ConcurrentHashMap<K,V> map,
4920 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
4921 dl 1.171 Consumer<? super U> action) {
4922 dl 1.119 if (transformer == null || action == null)
4923     throw new NullPointerException();
4924     return new ForEachTransformedMappingTask<K,V,U>
4925 dl 1.146 (map, null, -1, transformer, action);
4926 dl 1.119 }
4927    
4928     /**
4929 dl 1.126 * Returns a task that when invoked, returns a non-null result
4930     * from applying the given search function on each (key,
4931     * value), or null if none. Upon success, further element
4932     * processing is suppressed and the results of any other
4933     * parallel invocations of the search function are ignored.
4934 dl 1.119 *
4935     * @param map the map
4936     * @param searchFunction a function returning a non-null
4937     * result on success, else null
4938     * @return the task
4939     */
4940     public static <K,V,U> ForkJoinTask<U> search
4941     (ConcurrentHashMap<K,V> map,
4942 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction) {
4943 dl 1.119 if (searchFunction == null) throw new NullPointerException();
4944     return new SearchMappingsTask<K,V,U>
4945 dl 1.146 (map, null, -1, searchFunction,
4946 dl 1.119 new AtomicReference<U>());
4947     }
4948    
4949     /**
4950     * Returns a task that when invoked, returns the result of
4951     * accumulating the given transformation of all (key, value) pairs
4952     * using the given reducer to combine values, or null if none.
4953     *
4954     * @param map the map
4955     * @param transformer a function returning the transformation
4956 jsr166 1.135 * for an element, or null if there is no transformation (in
4957 jsr166 1.172 * which case it is not combined)
4958 dl 1.119 * @param reducer a commutative associative combining function
4959     * @return the task
4960     */
4961     public static <K,V,U> ForkJoinTask<U> reduce
4962     (ConcurrentHashMap<K,V> map,
4963 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
4964     BiFunction<? super U, ? super U, ? extends U> reducer) {
4965 dl 1.119 if (transformer == null || reducer == null)
4966     throw new NullPointerException();
4967     return new MapReduceMappingsTask<K,V,U>
4968 dl 1.130 (map, null, -1, null, transformer, reducer);
4969 dl 1.119 }
4970    
4971     /**
4972     * Returns a task that when invoked, returns the result of
4973     * accumulating the given transformation of all (key, value) pairs
4974     * using the given reducer to combine values, and the given
4975     * basis as an identity value.
4976     *
4977     * @param map the map
4978     * @param transformer a function returning the transformation
4979     * for an element
4980     * @param basis the identity (initial default value) for the reduction
4981     * @param reducer a commutative associative combining function
4982     * @return the task
4983     */
4984     public static <K,V> ForkJoinTask<Double> reduceToDouble
4985     (ConcurrentHashMap<K,V> map,
4986 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
4987 dl 1.119 double basis,
4988 dl 1.153 DoubleBinaryOperator reducer) {
4989 dl 1.119 if (transformer == null || reducer == null)
4990     throw new NullPointerException();
4991     return new MapReduceMappingsToDoubleTask<K,V>
4992 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
4993 dl 1.119 }
4994    
4995     /**
4996     * Returns a task that when invoked, returns the result of
4997     * accumulating the given transformation of all (key, value) pairs
4998     * using the given reducer to combine values, and the given
4999     * basis as an identity value.
5000     *
5001     * @param map the map
5002     * @param transformer a function returning the transformation
5003     * for an element
5004     * @param basis the identity (initial default value) for the reduction
5005     * @param reducer a commutative associative combining function
5006     * @return the task
5007     */
5008     public static <K,V> ForkJoinTask<Long> reduceToLong
5009     (ConcurrentHashMap<K,V> map,
5010 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
5011 dl 1.119 long basis,
5012 dl 1.153 LongBinaryOperator reducer) {
5013 dl 1.119 if (transformer == null || reducer == null)
5014     throw new NullPointerException();
5015     return new MapReduceMappingsToLongTask<K,V>
5016 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5017 dl 1.119 }
5018    
5019     /**
5020     * Returns a task that when invoked, returns the result of
5021     * accumulating the given transformation of all (key, value) pairs
5022     * using the given reducer to combine values, and the given
5023     * basis as an identity value.
5024     *
5025 jsr166 1.179 * @param map the map
5026 dl 1.119 * @param transformer a function returning the transformation
5027     * for an element
5028     * @param basis the identity (initial default value) for the reduction
5029     * @param reducer a commutative associative combining function
5030     * @return the task
5031     */
5032     public static <K,V> ForkJoinTask<Integer> reduceToInt
5033     (ConcurrentHashMap<K,V> map,
5034 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
5035 dl 1.119 int basis,
5036 dl 1.153 IntBinaryOperator reducer) {
5037 dl 1.119 if (transformer == null || reducer == null)
5038     throw new NullPointerException();
5039     return new MapReduceMappingsToIntTask<K,V>
5040 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5041 dl 1.119 }
5042    
5043     /**
5044     * Returns a task that when invoked, performs the given action
5045 jsr166 1.123 * for each key.
5046 dl 1.119 *
5047     * @param map the map
5048     * @param action the action
5049     * @return the task
5050     */
5051 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachKey
5052 dl 1.119 (ConcurrentHashMap<K,V> map,
5053 dl 1.171 Consumer<? super K> action) {
5054 dl 1.119 if (action == null) throw new NullPointerException();
5055 dl 1.146 return new ForEachKeyTask<K,V>(map, null, -1, action);
5056 dl 1.119 }
5057    
5058     /**
5059     * Returns a task that when invoked, performs the given action
5060 jsr166 1.123 * for each non-null transformation of each key.
5061 dl 1.119 *
5062     * @param map the map
5063     * @param transformer a function returning the transformation
5064 jsr166 1.135 * for an element, or null if there is no transformation (in
5065 jsr166 1.134 * which case the action is not applied)
5066 dl 1.119 * @param action the action
5067     * @return the task
5068     */
5069 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachKey
5070 dl 1.119 (ConcurrentHashMap<K,V> map,
5071 dl 1.153 Function<? super K, ? extends U> transformer,
5072 dl 1.171 Consumer<? super U> action) {
5073 dl 1.119 if (transformer == null || action == null)
5074     throw new NullPointerException();
5075     return new ForEachTransformedKeyTask<K,V,U>
5076 dl 1.146 (map, null, -1, transformer, action);
5077 dl 1.119 }
5078    
5079     /**
5080     * Returns a task that when invoked, returns a non-null result
5081     * from applying the given search function on each key, or
5082 dl 1.126 * null if none. Upon success, further element processing is
5083     * suppressed and the results of any other parallel
5084     * invocations of the search function are ignored.
5085 dl 1.119 *
5086     * @param map the map
5087     * @param searchFunction a function returning a non-null
5088     * result on success, else null
5089     * @return the task
5090     */
5091     public static <K,V,U> ForkJoinTask<U> searchKeys
5092     (ConcurrentHashMap<K,V> map,
5093 dl 1.153 Function<? super K, ? extends U> searchFunction) {
5094 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5095     return new SearchKeysTask<K,V,U>
5096 dl 1.146 (map, null, -1, searchFunction,
5097 dl 1.119 new AtomicReference<U>());
5098     }
5099    
5100     /**
5101     * Returns a task that when invoked, returns the result of
5102     * accumulating all keys using the given reducer to combine
5103     * values, or null if none.
5104     *
5105     * @param map the map
5106     * @param reducer a commutative associative combining function
5107     * @return the task
5108     */
5109     public static <K,V> ForkJoinTask<K> reduceKeys
5110     (ConcurrentHashMap<K,V> map,
5111 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5112 dl 1.119 if (reducer == null) throw new NullPointerException();
5113     return new ReduceKeysTask<K,V>
5114 dl 1.130 (map, null, -1, null, reducer);
5115 dl 1.119 }
5116 jsr166 1.125
5117 dl 1.119 /**
5118     * Returns a task that when invoked, returns the result of
5119     * accumulating the given transformation of all keys using the given
5120     * reducer to combine values, or null if none.
5121     *
5122     * @param map the map
5123     * @param transformer a function returning the transformation
5124 jsr166 1.135 * for an element, or null if there is no transformation (in
5125 jsr166 1.172 * which case it is not combined)
5126 dl 1.119 * @param reducer a commutative associative combining function
5127     * @return the task
5128     */
5129     public static <K,V,U> ForkJoinTask<U> reduceKeys
5130     (ConcurrentHashMap<K,V> map,
5131 dl 1.153 Function<? super K, ? extends U> transformer,
5132     BiFunction<? super U, ? super U, ? extends U> reducer) {
5133 dl 1.119 if (transformer == null || reducer == null)
5134     throw new NullPointerException();
5135     return new MapReduceKeysTask<K,V,U>
5136 dl 1.130 (map, null, -1, null, transformer, reducer);
5137 dl 1.119 }
5138    
5139     /**
5140     * Returns a task that when invoked, returns the result of
5141     * accumulating the given transformation of all keys using the given
5142     * reducer to combine values, and the given basis as an
5143     * identity value.
5144     *
5145     * @param map the map
5146     * @param transformer a function returning the transformation
5147     * for an element
5148     * @param basis the identity (initial default value) for the reduction
5149     * @param reducer a commutative associative combining function
5150     * @return the task
5151     */
5152     public static <K,V> ForkJoinTask<Double> reduceKeysToDouble
5153     (ConcurrentHashMap<K,V> map,
5154 dl 1.171 ToDoubleFunction<? super K> transformer,
5155 dl 1.119 double basis,
5156 dl 1.153 DoubleBinaryOperator reducer) {
5157 dl 1.119 if (transformer == null || reducer == null)
5158     throw new NullPointerException();
5159     return new MapReduceKeysToDoubleTask<K,V>
5160 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5161 dl 1.119 }
5162    
5163     /**
5164     * Returns a task that when invoked, returns the result of
5165     * accumulating the given transformation of all keys using the given
5166     * reducer to combine values, and the given basis as an
5167     * identity value.
5168     *
5169     * @param map the map
5170     * @param transformer a function returning the transformation
5171     * for an element
5172     * @param basis the identity (initial default value) for the reduction
5173     * @param reducer a commutative associative combining function
5174     * @return the task
5175     */
5176     public static <K,V> ForkJoinTask<Long> reduceKeysToLong
5177     (ConcurrentHashMap<K,V> map,
5178 dl 1.171 ToLongFunction<? super K> transformer,
5179 dl 1.119 long basis,
5180 dl 1.153 LongBinaryOperator reducer) {
5181 dl 1.119 if (transformer == null || reducer == null)
5182     throw new NullPointerException();
5183     return new MapReduceKeysToLongTask<K,V>
5184 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5185 dl 1.119 }
5186    
5187     /**
5188     * Returns a task that when invoked, returns the result of
5189     * accumulating the given transformation of all keys using the given
5190     * reducer to combine values, and the given basis as an
5191     * identity value.
5192     *
5193     * @param map the map
5194     * @param transformer a function returning the transformation
5195     * for an element
5196     * @param basis the identity (initial default value) for the reduction
5197     * @param reducer a commutative associative combining function
5198     * @return the task
5199     */
5200     public static <K,V> ForkJoinTask<Integer> reduceKeysToInt
5201     (ConcurrentHashMap<K,V> map,
5202 dl 1.171 ToIntFunction<? super K> transformer,
5203 dl 1.119 int basis,
5204 dl 1.153 IntBinaryOperator reducer) {
5205 dl 1.119 if (transformer == null || reducer == null)
5206     throw new NullPointerException();
5207     return new MapReduceKeysToIntTask<K,V>
5208 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5209 dl 1.119 }
5210    
5211     /**
5212     * Returns a task that when invoked, performs the given action
5213 jsr166 1.123 * for each value.
5214 dl 1.119 *
5215     * @param map the map
5216     * @param action the action
5217 jsr166 1.173 * @return the task
5218 dl 1.119 */
5219 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachValue
5220 dl 1.119 (ConcurrentHashMap<K,V> map,
5221 dl 1.171 Consumer<? super V> action) {
5222 dl 1.119 if (action == null) throw new NullPointerException();
5223 dl 1.146 return new ForEachValueTask<K,V>(map, null, -1, action);
5224 dl 1.119 }
5225    
5226     /**
5227     * Returns a task that when invoked, performs the given action
5228 jsr166 1.123 * for each non-null transformation of each value.
5229 dl 1.119 *
5230     * @param map the map
5231     * @param transformer a function returning the transformation
5232 jsr166 1.135 * for an element, or null if there is no transformation (in
5233 jsr166 1.134 * which case the action is not applied)
5234 dl 1.119 * @param action the action
5235 jsr166 1.173 * @return the task
5236 dl 1.119 */
5237 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachValue
5238 dl 1.119 (ConcurrentHashMap<K,V> map,
5239 dl 1.153 Function<? super V, ? extends U> transformer,
5240 dl 1.171 Consumer<? super U> action) {
5241 dl 1.119 if (transformer == null || action == null)
5242     throw new NullPointerException();
5243     return new ForEachTransformedValueTask<K,V,U>
5244 dl 1.146 (map, null, -1, transformer, action);
5245 dl 1.119 }
5246    
5247     /**
5248     * Returns a task that when invoked, returns a non-null result
5249     * from applying the given search function on each value, or
5250 dl 1.126 * null if none. Upon success, further element processing is
5251     * suppressed and the results of any other parallel
5252     * invocations of the search function are ignored.
5253 dl 1.119 *
5254     * @param map the map
5255     * @param searchFunction a function returning a non-null
5256     * result on success, else null
5257     * @return the task
5258     */
5259     public static <K,V,U> ForkJoinTask<U> searchValues
5260     (ConcurrentHashMap<K,V> map,
5261 dl 1.153 Function<? super V, ? extends U> searchFunction) {
5262 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5263     return new SearchValuesTask<K,V,U>
5264 dl 1.146 (map, null, -1, searchFunction,
5265 dl 1.119 new AtomicReference<U>());
5266     }
5267    
5268     /**
5269     * Returns a task that when invoked, returns the result of
5270     * accumulating all values using the given reducer to combine
5271     * values, or null if none.
5272     *
5273     * @param map the map
5274     * @param reducer a commutative associative combining function
5275     * @return the task
5276     */
5277     public static <K,V> ForkJoinTask<V> reduceValues
5278     (ConcurrentHashMap<K,V> map,
5279 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5280 dl 1.119 if (reducer == null) throw new NullPointerException();
5281     return new ReduceValuesTask<K,V>
5282 dl 1.130 (map, null, -1, null, 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 values using the
5288     * given reducer to combine values, or null if none.
5289     *
5290     * @param map the map
5291     * @param transformer a function returning the transformation
5292 jsr166 1.135 * for an element, or null if there is no transformation (in
5293 jsr166 1.172 * which case it is not combined)
5294 dl 1.119 * @param reducer a commutative associative combining function
5295     * @return the task
5296     */
5297     public static <K,V,U> ForkJoinTask<U> reduceValues
5298     (ConcurrentHashMap<K,V> map,
5299 dl 1.153 Function<? super V, ? extends U> transformer,
5300     BiFunction<? super U, ? super U, ? extends U> reducer) {
5301 dl 1.119 if (transformer == null || reducer == null)
5302     throw new NullPointerException();
5303     return new MapReduceValuesTask<K,V,U>
5304 dl 1.130 (map, null, -1, null, transformer, reducer);
5305 dl 1.119 }
5306    
5307     /**
5308     * Returns a task that when invoked, returns the result of
5309     * accumulating the given transformation of all values using the
5310     * given reducer to combine values, and the given basis as an
5311     * identity value.
5312     *
5313     * @param map the map
5314     * @param transformer a function returning the transformation
5315     * for an element
5316     * @param basis the identity (initial default value) for the reduction
5317     * @param reducer a commutative associative combining function
5318     * @return the task
5319     */
5320     public static <K,V> ForkJoinTask<Double> reduceValuesToDouble
5321     (ConcurrentHashMap<K,V> map,
5322 dl 1.171 ToDoubleFunction<? super V> transformer,
5323 dl 1.119 double basis,
5324 dl 1.153 DoubleBinaryOperator reducer) {
5325 dl 1.119 if (transformer == null || reducer == null)
5326     throw new NullPointerException();
5327     return new MapReduceValuesToDoubleTask<K,V>
5328 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5329 dl 1.119 }
5330    
5331     /**
5332     * Returns a task that when invoked, returns the result of
5333     * accumulating the given transformation of all values using the
5334     * given reducer to combine values, and the given basis as an
5335     * identity value.
5336     *
5337     * @param map the map
5338     * @param transformer a function returning the transformation
5339     * for an element
5340     * @param basis the identity (initial default value) for the reduction
5341     * @param reducer a commutative associative combining function
5342     * @return the task
5343     */
5344     public static <K,V> ForkJoinTask<Long> reduceValuesToLong
5345     (ConcurrentHashMap<K,V> map,
5346 dl 1.171 ToLongFunction<? super V> transformer,
5347 dl 1.119 long basis,
5348 dl 1.153 LongBinaryOperator reducer) {
5349 dl 1.119 if (transformer == null || reducer == null)
5350     throw new NullPointerException();
5351     return new MapReduceValuesToLongTask<K,V>
5352 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5353 dl 1.119 }
5354    
5355     /**
5356     * Returns a task that when invoked, returns the result of
5357     * accumulating the given transformation of all values using the
5358     * given reducer to combine values, and the given basis as an
5359     * identity value.
5360     *
5361     * @param map the map
5362     * @param transformer a function returning the transformation
5363     * for an element
5364     * @param basis the identity (initial default value) for the reduction
5365     * @param reducer a commutative associative combining function
5366     * @return the task
5367     */
5368     public static <K,V> ForkJoinTask<Integer> reduceValuesToInt
5369     (ConcurrentHashMap<K,V> map,
5370 dl 1.171 ToIntFunction<? super V> transformer,
5371 dl 1.119 int basis,
5372 dl 1.153 IntBinaryOperator reducer) {
5373 dl 1.119 if (transformer == null || reducer == null)
5374     throw new NullPointerException();
5375     return new MapReduceValuesToIntTask<K,V>
5376 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5377 dl 1.119 }
5378    
5379     /**
5380     * Returns a task that when invoked, perform the given action
5381 jsr166 1.123 * for each entry.
5382 dl 1.119 *
5383     * @param map the map
5384     * @param action the action
5385 jsr166 1.173 * @return the task
5386 dl 1.119 */
5387 jsr166 1.120 public static <K,V> ForkJoinTask<Void> forEachEntry
5388 dl 1.119 (ConcurrentHashMap<K,V> map,
5389 dl 1.171 Consumer<? super Map.Entry<K,V>> action) {
5390 dl 1.119 if (action == null) throw new NullPointerException();
5391 dl 1.146 return new ForEachEntryTask<K,V>(map, null, -1, action);
5392 dl 1.119 }
5393    
5394     /**
5395     * Returns a task that when invoked, perform the given action
5396 jsr166 1.123 * for each non-null transformation of each entry.
5397 dl 1.119 *
5398     * @param map the map
5399     * @param transformer a function returning the transformation
5400 jsr166 1.135 * for an element, or null if there is no transformation (in
5401 jsr166 1.134 * which case the action is not applied)
5402 dl 1.119 * @param action the action
5403 jsr166 1.173 * @return the task
5404 dl 1.119 */
5405 jsr166 1.120 public static <K,V,U> ForkJoinTask<Void> forEachEntry
5406 dl 1.119 (ConcurrentHashMap<K,V> map,
5407 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5408 dl 1.171 Consumer<? super U> action) {
5409 dl 1.119 if (transformer == null || action == null)
5410     throw new NullPointerException();
5411     return new ForEachTransformedEntryTask<K,V,U>
5412 dl 1.146 (map, null, -1, transformer, action);
5413 dl 1.119 }
5414    
5415     /**
5416     * Returns a task that when invoked, returns a non-null result
5417     * from applying the given search function on each entry, or
5418 dl 1.126 * null if none. Upon success, further element processing is
5419     * suppressed and the results of any other parallel
5420     * invocations of the search function are ignored.
5421 dl 1.119 *
5422     * @param map the map
5423     * @param searchFunction a function returning a non-null
5424     * result on success, else null
5425     * @return the task
5426     */
5427     public static <K,V,U> ForkJoinTask<U> searchEntries
5428     (ConcurrentHashMap<K,V> map,
5429 dl 1.153 Function<Map.Entry<K,V>, ? extends U> searchFunction) {
5430 dl 1.119 if (searchFunction == null) throw new NullPointerException();
5431     return new SearchEntriesTask<K,V,U>
5432 dl 1.146 (map, null, -1, searchFunction,
5433 dl 1.119 new AtomicReference<U>());
5434     }
5435    
5436     /**
5437     * Returns a task that when invoked, returns the result of
5438     * accumulating all entries using the given reducer to combine
5439     * values, or null if none.
5440     *
5441     * @param map the map
5442     * @param reducer a commutative associative combining function
5443     * @return the task
5444     */
5445     public static <K,V> ForkJoinTask<Map.Entry<K,V>> reduceEntries
5446     (ConcurrentHashMap<K,V> map,
5447 dl 1.153 BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
5448 dl 1.119 if (reducer == null) throw new NullPointerException();
5449     return new ReduceEntriesTask<K,V>
5450 dl 1.130 (map, null, -1, null, 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 entries using the
5456     * given reducer to combine values, or null if none.
5457     *
5458     * @param map the map
5459     * @param transformer a function returning the transformation
5460 jsr166 1.135 * for an element, or null if there is no transformation (in
5461 jsr166 1.172 * which case it is not combined)
5462 dl 1.119 * @param reducer a commutative associative combining function
5463     * @return the task
5464     */
5465     public static <K,V,U> ForkJoinTask<U> reduceEntries
5466     (ConcurrentHashMap<K,V> map,
5467 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
5468     BiFunction<? super U, ? super U, ? extends U> reducer) {
5469 dl 1.119 if (transformer == null || reducer == null)
5470     throw new NullPointerException();
5471     return new MapReduceEntriesTask<K,V,U>
5472 dl 1.130 (map, null, -1, null, transformer, reducer);
5473 dl 1.119 }
5474    
5475     /**
5476     * Returns a task that when invoked, returns the result of
5477     * accumulating the given transformation of all entries using the
5478     * given reducer to combine values, and the given basis as an
5479     * identity value.
5480     *
5481     * @param map the map
5482     * @param transformer a function returning the transformation
5483     * for an element
5484     * @param basis the identity (initial default value) for the reduction
5485     * @param reducer a commutative associative combining function
5486     * @return the task
5487     */
5488     public static <K,V> ForkJoinTask<Double> reduceEntriesToDouble
5489     (ConcurrentHashMap<K,V> map,
5490 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
5491 dl 1.119 double basis,
5492 dl 1.153 DoubleBinaryOperator reducer) {
5493 dl 1.119 if (transformer == null || reducer == null)
5494     throw new NullPointerException();
5495     return new MapReduceEntriesToDoubleTask<K,V>
5496 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5497 dl 1.119 }
5498    
5499     /**
5500     * Returns a task that when invoked, returns the result of
5501     * accumulating the given transformation of all entries using the
5502     * given reducer to combine values, and the given basis as an
5503     * identity value.
5504     *
5505     * @param map the map
5506     * @param transformer a function returning the transformation
5507     * for an element
5508     * @param basis the identity (initial default value) for the reduction
5509     * @param reducer a commutative associative combining function
5510     * @return the task
5511     */
5512     public static <K,V> ForkJoinTask<Long> reduceEntriesToLong
5513     (ConcurrentHashMap<K,V> map,
5514 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
5515 dl 1.119 long basis,
5516 dl 1.153 LongBinaryOperator reducer) {
5517 dl 1.119 if (transformer == null || reducer == null)
5518     throw new NullPointerException();
5519     return new MapReduceEntriesToLongTask<K,V>
5520 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5521 dl 1.119 }
5522    
5523     /**
5524     * Returns a task that when invoked, returns the result of
5525     * accumulating the given transformation of all entries using the
5526     * given reducer to combine values, and the given basis as an
5527     * identity value.
5528     *
5529     * @param map the map
5530     * @param transformer a function returning the transformation
5531     * for an element
5532     * @param basis the identity (initial default value) for the reduction
5533     * @param reducer a commutative associative combining function
5534     * @return the task
5535     */
5536     public static <K,V> ForkJoinTask<Integer> reduceEntriesToInt
5537     (ConcurrentHashMap<K,V> map,
5538 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
5539 dl 1.119 int basis,
5540 dl 1.153 IntBinaryOperator reducer) {
5541 dl 1.119 if (transformer == null || reducer == null)
5542     throw new NullPointerException();
5543     return new MapReduceEntriesToIntTask<K,V>
5544 dl 1.130 (map, null, -1, null, transformer, basis, reducer);
5545 dl 1.119 }
5546     }
5547    
5548     // -------------------------------------------------------
5549    
5550     /*
5551     * Task classes. Coded in a regular but ugly format/style to
5552     * simplify checks that each variant differs in the right way from
5553 dl 1.149 * others. The null screenings exist because compilers cannot tell
5554     * that we've already null-checked task arguments, so we force
5555     * simplest hoisted bypass to help avoid convoluted traps.
5556 dl 1.119 */
5557    
5558 dl 1.128 @SuppressWarnings("serial") static final class ForEachKeyTask<K,V>
5559 dl 1.146 extends Traverser<K,V,Void> {
5560 dl 1.171 final Consumer<? super K> action;
5561 dl 1.119 ForEachKeyTask
5562 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5563 dl 1.171 Consumer<? super K> action) {
5564 dl 1.146 super(m, p, b);
5565 dl 1.119 this.action = action;
5566     }
5567 jsr166 1.168 public final void compute() {
5568 dl 1.171 final Consumer<? super K> action;
5569 dl 1.149 if ((action = this.action) != null) {
5570     for (int b; (b = preSplit()) > 0;)
5571     new ForEachKeyTask<K,V>(map, this, b, action).fork();
5572     while (advance() != null)
5573 jsr166 1.168 action.accept(nextKey);
5574 dl 1.149 propagateCompletion();
5575     }
5576 dl 1.119 }
5577     }
5578    
5579 dl 1.128 @SuppressWarnings("serial") static final class ForEachValueTask<K,V>
5580 dl 1.146 extends Traverser<K,V,Void> {
5581 dl 1.171 final Consumer<? super V> action;
5582 dl 1.119 ForEachValueTask
5583 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5584 dl 1.171 Consumer<? super V> action) {
5585 dl 1.146 super(m, p, b);
5586 dl 1.119 this.action = action;
5587     }
5588 jsr166 1.168 public final void compute() {
5589 dl 1.171 final Consumer<? super V> action;
5590 dl 1.149 if ((action = this.action) != null) {
5591     for (int b; (b = preSplit()) > 0;)
5592     new ForEachValueTask<K,V>(map, this, b, action).fork();
5593 dl 1.151 V v;
5594 dl 1.149 while ((v = advance()) != null)
5595 dl 1.153 action.accept(v);
5596 dl 1.149 propagateCompletion();
5597     }
5598 dl 1.119 }
5599     }
5600    
5601 dl 1.128 @SuppressWarnings("serial") static final class ForEachEntryTask<K,V>
5602 dl 1.146 extends Traverser<K,V,Void> {
5603 dl 1.171 final Consumer<? super Entry<K,V>> action;
5604 dl 1.119 ForEachEntryTask
5605 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5606 dl 1.171 Consumer<? super Entry<K,V>> action) {
5607 dl 1.146 super(m, p, b);
5608 dl 1.119 this.action = action;
5609     }
5610 jsr166 1.168 public final void compute() {
5611 dl 1.171 final Consumer<? super Entry<K,V>> action;
5612 dl 1.149 if ((action = this.action) != null) {
5613     for (int b; (b = preSplit()) > 0;)
5614     new ForEachEntryTask<K,V>(map, this, b, action).fork();
5615 dl 1.151 V v;
5616 dl 1.149 while ((v = advance()) != null)
5617 jsr166 1.168 action.accept(entryFor(nextKey, v));
5618 dl 1.149 propagateCompletion();
5619     }
5620 dl 1.119 }
5621     }
5622    
5623 dl 1.128 @SuppressWarnings("serial") static final class ForEachMappingTask<K,V>
5624 dl 1.146 extends Traverser<K,V,Void> {
5625 dl 1.171 final BiConsumer<? super K, ? super V> action;
5626 dl 1.119 ForEachMappingTask
5627 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5628 dl 1.171 BiConsumer<? super K,? super V> action) {
5629 dl 1.146 super(m, p, b);
5630 dl 1.119 this.action = action;
5631     }
5632 jsr166 1.168 public final void compute() {
5633 dl 1.171 final BiConsumer<? super K, ? super V> action;
5634 dl 1.149 if ((action = this.action) != null) {
5635     for (int b; (b = preSplit()) > 0;)
5636     new ForEachMappingTask<K,V>(map, this, b, action).fork();
5637 dl 1.151 V v;
5638 dl 1.149 while ((v = advance()) != null)
5639 jsr166 1.168 action.accept(nextKey, v);
5640 dl 1.149 propagateCompletion();
5641     }
5642 dl 1.119 }
5643     }
5644    
5645 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedKeyTask<K,V,U>
5646 dl 1.146 extends Traverser<K,V,Void> {
5647 dl 1.153 final Function<? super K, ? extends U> transformer;
5648 dl 1.171 final Consumer<? super U> action;
5649 dl 1.119 ForEachTransformedKeyTask
5650 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5651 dl 1.171 Function<? super K, ? extends U> transformer, Consumer<? super U> action) {
5652 dl 1.146 super(m, p, b);
5653     this.transformer = transformer; this.action = action;
5654     }
5655 jsr166 1.168 public final void compute() {
5656 dl 1.153 final Function<? super K, ? extends U> transformer;
5657 dl 1.171 final Consumer<? super U> action;
5658 dl 1.149 if ((transformer = this.transformer) != null &&
5659     (action = this.action) != null) {
5660     for (int b; (b = preSplit()) > 0;)
5661     new ForEachTransformedKeyTask<K,V,U>
5662     (map, this, b, transformer, action).fork();
5663     U u;
5664     while (advance() != null) {
5665 jsr166 1.168 if ((u = transformer.apply(nextKey)) != null)
5666 dl 1.153 action.accept(u);
5667 dl 1.149 }
5668     propagateCompletion();
5669 dl 1.119 }
5670     }
5671     }
5672    
5673 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U>
5674 dl 1.146 extends Traverser<K,V,Void> {
5675 dl 1.153 final Function<? super V, ? extends U> transformer;
5676 dl 1.171 final Consumer<? super U> action;
5677 dl 1.119 ForEachTransformedValueTask
5678 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5679 dl 1.171 Function<? super V, ? extends U> transformer, Consumer<? super U> action) {
5680 dl 1.146 super(m, p, b);
5681     this.transformer = transformer; this.action = action;
5682     }
5683 jsr166 1.168 public final void compute() {
5684 dl 1.153 final Function<? super V, ? extends U> transformer;
5685 dl 1.171 final Consumer<? super U> action;
5686 dl 1.149 if ((transformer = this.transformer) != null &&
5687     (action = this.action) != null) {
5688     for (int b; (b = preSplit()) > 0;)
5689     new ForEachTransformedValueTask<K,V,U>
5690     (map, this, b, transformer, action).fork();
5691 dl 1.151 V v; U u;
5692 dl 1.149 while ((v = advance()) != null) {
5693 dl 1.151 if ((u = transformer.apply(v)) != null)
5694 dl 1.153 action.accept(u);
5695 dl 1.149 }
5696     propagateCompletion();
5697 dl 1.119 }
5698     }
5699 tim 1.1 }
5700    
5701 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedEntryTask<K,V,U>
5702 dl 1.146 extends Traverser<K,V,Void> {
5703 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5704 dl 1.171 final Consumer<? super U> action;
5705 dl 1.119 ForEachTransformedEntryTask
5706 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5707 dl 1.171 Function<Map.Entry<K,V>, ? extends U> transformer, Consumer<? super U> action) {
5708 dl 1.146 super(m, p, b);
5709     this.transformer = transformer; this.action = action;
5710     }
5711 jsr166 1.168 public final void compute() {
5712 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
5713 dl 1.171 final Consumer<? super U> action;
5714 dl 1.149 if ((transformer = this.transformer) != null &&
5715     (action = this.action) != null) {
5716     for (int b; (b = preSplit()) > 0;)
5717     new ForEachTransformedEntryTask<K,V,U>
5718     (map, this, b, transformer, action).fork();
5719 dl 1.151 V v; U u;
5720 dl 1.149 while ((v = advance()) != null) {
5721 jsr166 1.168 if ((u = transformer.apply(entryFor(nextKey,
5722 dl 1.151 v))) != null)
5723 dl 1.153 action.accept(u);
5724 dl 1.149 }
5725     propagateCompletion();
5726 dl 1.119 }
5727     }
5728 tim 1.1 }
5729    
5730 dl 1.128 @SuppressWarnings("serial") static final class ForEachTransformedMappingTask<K,V,U>
5731 dl 1.146 extends Traverser<K,V,Void> {
5732 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5733 dl 1.171 final Consumer<? super U> action;
5734 dl 1.119 ForEachTransformedMappingTask
5735 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5736 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
5737 dl 1.171 Consumer<? super U> action) {
5738 dl 1.146 super(m, p, b);
5739     this.transformer = transformer; this.action = action;
5740 dl 1.119 }
5741 jsr166 1.168 public final void compute() {
5742 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
5743 dl 1.171 final Consumer<? super U> action;
5744 dl 1.149 if ((transformer = this.transformer) != null &&
5745     (action = this.action) != null) {
5746     for (int b; (b = preSplit()) > 0;)
5747     new ForEachTransformedMappingTask<K,V,U>
5748     (map, this, b, transformer, action).fork();
5749 dl 1.151 V v; U u;
5750 dl 1.149 while ((v = advance()) != null) {
5751 jsr166 1.168 if ((u = transformer.apply(nextKey, v)) != null)
5752 dl 1.153 action.accept(u);
5753 dl 1.149 }
5754     propagateCompletion();
5755 dl 1.119 }
5756     }
5757 tim 1.1 }
5758    
5759 dl 1.128 @SuppressWarnings("serial") static final class SearchKeysTask<K,V,U>
5760 dl 1.146 extends Traverser<K,V,U> {
5761 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5762 dl 1.119 final AtomicReference<U> result;
5763     SearchKeysTask
5764 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5765 dl 1.153 Function<? super K, ? extends U> searchFunction,
5766 dl 1.119 AtomicReference<U> result) {
5767 dl 1.146 super(m, p, b);
5768 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5769     }
5770 dl 1.146 public final U getRawResult() { return result.get(); }
5771 jsr166 1.168 public final void compute() {
5772 dl 1.153 final Function<? super K, ? extends U> searchFunction;
5773 dl 1.146 final AtomicReference<U> result;
5774 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5775     (result = this.result) != null) {
5776     for (int b;;) {
5777     if (result.get() != null)
5778     return;
5779     if ((b = preSplit()) <= 0)
5780     break;
5781     new SearchKeysTask<K,V,U>
5782     (map, this, b, searchFunction, result).fork();
5783 dl 1.128 }
5784 dl 1.149 while (result.get() == null) {
5785     U u;
5786     if (advance() == null) {
5787     propagateCompletion();
5788     break;
5789     }
5790 jsr166 1.168 if ((u = searchFunction.apply(nextKey)) != null) {
5791 dl 1.149 if (result.compareAndSet(null, u))
5792     quietlyCompleteRoot();
5793     break;
5794     }
5795 dl 1.119 }
5796     }
5797     }
5798 tim 1.1 }
5799    
5800 dl 1.128 @SuppressWarnings("serial") static final class SearchValuesTask<K,V,U>
5801 dl 1.146 extends Traverser<K,V,U> {
5802 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5803 dl 1.119 final AtomicReference<U> result;
5804     SearchValuesTask
5805 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5806 dl 1.153 Function<? super V, ? extends U> searchFunction,
5807 dl 1.119 AtomicReference<U> result) {
5808 dl 1.146 super(m, p, b);
5809 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5810     }
5811 dl 1.146 public final U getRawResult() { return result.get(); }
5812 jsr166 1.168 public final void compute() {
5813 dl 1.153 final Function<? super V, ? extends U> searchFunction;
5814 dl 1.146 final AtomicReference<U> result;
5815 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5816     (result = this.result) != null) {
5817     for (int b;;) {
5818     if (result.get() != null)
5819     return;
5820     if ((b = preSplit()) <= 0)
5821     break;
5822     new SearchValuesTask<K,V,U>
5823     (map, this, b, searchFunction, result).fork();
5824 dl 1.128 }
5825 dl 1.149 while (result.get() == null) {
5826 dl 1.151 V v; U u;
5827 dl 1.149 if ((v = advance()) == null) {
5828     propagateCompletion();
5829     break;
5830     }
5831 dl 1.151 if ((u = searchFunction.apply(v)) != null) {
5832 dl 1.149 if (result.compareAndSet(null, u))
5833     quietlyCompleteRoot();
5834     break;
5835     }
5836 dl 1.119 }
5837     }
5838     }
5839     }
5840 tim 1.11
5841 dl 1.128 @SuppressWarnings("serial") static final class SearchEntriesTask<K,V,U>
5842 dl 1.146 extends Traverser<K,V,U> {
5843 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5844 dl 1.119 final AtomicReference<U> result;
5845     SearchEntriesTask
5846 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5847 dl 1.153 Function<Entry<K,V>, ? extends U> searchFunction,
5848 dl 1.119 AtomicReference<U> result) {
5849 dl 1.146 super(m, p, b);
5850 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5851     }
5852 dl 1.146 public final U getRawResult() { return result.get(); }
5853 jsr166 1.168 public final void compute() {
5854 dl 1.153 final Function<Entry<K,V>, ? extends U> searchFunction;
5855 dl 1.146 final AtomicReference<U> result;
5856 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5857     (result = this.result) != null) {
5858     for (int b;;) {
5859     if (result.get() != null)
5860     return;
5861     if ((b = preSplit()) <= 0)
5862     break;
5863     new SearchEntriesTask<K,V,U>
5864     (map, this, b, searchFunction, result).fork();
5865 dl 1.128 }
5866 dl 1.149 while (result.get() == null) {
5867 dl 1.151 V v; U u;
5868 dl 1.149 if ((v = advance()) == null) {
5869     propagateCompletion();
5870     break;
5871     }
5872 jsr166 1.168 if ((u = searchFunction.apply(entryFor(nextKey,
5873 dl 1.151 v))) != null) {
5874 dl 1.149 if (result.compareAndSet(null, u))
5875     quietlyCompleteRoot();
5876     return;
5877     }
5878 dl 1.119 }
5879     }
5880     }
5881     }
5882 tim 1.1
5883 dl 1.128 @SuppressWarnings("serial") static final class SearchMappingsTask<K,V,U>
5884 dl 1.146 extends Traverser<K,V,U> {
5885 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5886 dl 1.119 final AtomicReference<U> result;
5887     SearchMappingsTask
5888 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5889 dl 1.153 BiFunction<? super K, ? super V, ? extends U> searchFunction,
5890 dl 1.119 AtomicReference<U> result) {
5891 dl 1.146 super(m, p, b);
5892 dl 1.119 this.searchFunction = searchFunction; this.result = result;
5893     }
5894 dl 1.146 public final U getRawResult() { return result.get(); }
5895 jsr166 1.168 public final void compute() {
5896 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> searchFunction;
5897 dl 1.146 final AtomicReference<U> result;
5898 dl 1.149 if ((searchFunction = this.searchFunction) != null &&
5899     (result = this.result) != null) {
5900     for (int b;;) {
5901     if (result.get() != null)
5902     return;
5903     if ((b = preSplit()) <= 0)
5904     break;
5905     new SearchMappingsTask<K,V,U>
5906     (map, this, b, searchFunction, result).fork();
5907 dl 1.128 }
5908 dl 1.149 while (result.get() == null) {
5909 dl 1.151 V v; U u;
5910 dl 1.149 if ((v = advance()) == null) {
5911     propagateCompletion();
5912     break;
5913     }
5914 jsr166 1.168 if ((u = searchFunction.apply(nextKey, v)) != null) {
5915 dl 1.149 if (result.compareAndSet(null, u))
5916     quietlyCompleteRoot();
5917     break;
5918     }
5919 dl 1.119 }
5920     }
5921 tim 1.1 }
5922 dl 1.119 }
5923 tim 1.1
5924 dl 1.128 @SuppressWarnings("serial") static final class ReduceKeysTask<K,V>
5925 dl 1.146 extends Traverser<K,V,K> {
5926 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5927 dl 1.119 K result;
5928 dl 1.128 ReduceKeysTask<K,V> rights, nextRight;
5929 dl 1.119 ReduceKeysTask
5930 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5931 dl 1.128 ReduceKeysTask<K,V> nextRight,
5932 dl 1.153 BiFunction<? super K, ? super K, ? extends K> reducer) {
5933 dl 1.130 super(m, p, b); this.nextRight = nextRight;
5934 dl 1.119 this.reducer = reducer;
5935     }
5936 dl 1.146 public final K getRawResult() { return result; }
5937     @SuppressWarnings("unchecked") public final void compute() {
5938 dl 1.153 final BiFunction<? super K, ? super K, ? extends K> reducer;
5939 dl 1.149 if ((reducer = this.reducer) != null) {
5940     for (int b; (b = preSplit()) > 0;)
5941     (rights = new ReduceKeysTask<K,V>
5942     (map, this, b, rights, reducer)).fork();
5943     K r = null;
5944     while (advance() != null) {
5945 jsr166 1.168 K u = nextKey;
5946 jsr166 1.154 r = (r == null) ? u : u == null ? r : reducer.apply(r, u);
5947 dl 1.149 }
5948     result = r;
5949     CountedCompleter<?> c;
5950     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5951     ReduceKeysTask<K,V>
5952     t = (ReduceKeysTask<K,V>)c,
5953     s = t.rights;
5954     while (s != null) {
5955     K tr, sr;
5956     if ((sr = s.result) != null)
5957     t.result = (((tr = t.result) == null) ? sr :
5958     reducer.apply(tr, sr));
5959     s = t.rights = s.nextRight;
5960     }
5961 dl 1.99 }
5962 dl 1.138 }
5963 tim 1.1 }
5964 dl 1.119 }
5965 tim 1.1
5966 dl 1.128 @SuppressWarnings("serial") static final class ReduceValuesTask<K,V>
5967 dl 1.146 extends Traverser<K,V,V> {
5968 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5969 dl 1.119 V result;
5970 dl 1.128 ReduceValuesTask<K,V> rights, nextRight;
5971 dl 1.119 ReduceValuesTask
5972 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
5973 dl 1.128 ReduceValuesTask<K,V> nextRight,
5974 dl 1.153 BiFunction<? super V, ? super V, ? extends V> reducer) {
5975 dl 1.130 super(m, p, b); this.nextRight = nextRight;
5976 dl 1.119 this.reducer = reducer;
5977     }
5978 dl 1.146 public final V getRawResult() { return result; }
5979     @SuppressWarnings("unchecked") public final void compute() {
5980 dl 1.153 final BiFunction<? super V, ? super V, ? extends V> reducer;
5981 dl 1.149 if ((reducer = this.reducer) != null) {
5982     for (int b; (b = preSplit()) > 0;)
5983     (rights = new ReduceValuesTask<K,V>
5984     (map, this, b, rights, reducer)).fork();
5985 dl 1.153 V r = null, v;
5986     while ((v = advance()) != null)
5987 dl 1.156 r = (r == null) ? v : reducer.apply(r, v);
5988 dl 1.149 result = r;
5989     CountedCompleter<?> c;
5990     for (c = firstComplete(); c != null; c = c.nextComplete()) {
5991     ReduceValuesTask<K,V>
5992     t = (ReduceValuesTask<K,V>)c,
5993     s = t.rights;
5994     while (s != null) {
5995     V tr, sr;
5996     if ((sr = s.result) != null)
5997     t.result = (((tr = t.result) == null) ? sr :
5998     reducer.apply(tr, sr));
5999     s = t.rights = s.nextRight;
6000     }
6001 dl 1.119 }
6002     }
6003 tim 1.1 }
6004 dl 1.119 }
6005 tim 1.1
6006 dl 1.128 @SuppressWarnings("serial") static final class ReduceEntriesTask<K,V>
6007 dl 1.146 extends Traverser<K,V,Map.Entry<K,V>> {
6008 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6009 dl 1.119 Map.Entry<K,V> result;
6010 dl 1.128 ReduceEntriesTask<K,V> rights, nextRight;
6011 dl 1.119 ReduceEntriesTask
6012 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6013 dl 1.130 ReduceEntriesTask<K,V> nextRight,
6014 dl 1.153 BiFunction<Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer) {
6015 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6016 dl 1.119 this.reducer = reducer;
6017     }
6018 dl 1.146 public final Map.Entry<K,V> getRawResult() { return result; }
6019     @SuppressWarnings("unchecked") public final void compute() {
6020 dl 1.153 final BiFunction<Map.Entry<K,V>, Map.Entry<K,V>, ? extends Map.Entry<K,V>> reducer;
6021 dl 1.149 if ((reducer = this.reducer) != null) {
6022     for (int b; (b = preSplit()) > 0;)
6023     (rights = new ReduceEntriesTask<K,V>
6024     (map, this, b, rights, reducer)).fork();
6025     Map.Entry<K,V> r = null;
6026 dl 1.151 V v;
6027 dl 1.149 while ((v = advance()) != null) {
6028 jsr166 1.168 Map.Entry<K,V> u = entryFor(nextKey, v);
6029 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6030     }
6031     result = r;
6032     CountedCompleter<?> c;
6033     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6034     ReduceEntriesTask<K,V>
6035     t = (ReduceEntriesTask<K,V>)c,
6036     s = t.rights;
6037     while (s != null) {
6038     Map.Entry<K,V> tr, sr;
6039     if ((sr = s.result) != null)
6040     t.result = (((tr = t.result) == null) ? sr :
6041     reducer.apply(tr, sr));
6042     s = t.rights = s.nextRight;
6043     }
6044 dl 1.119 }
6045 dl 1.138 }
6046 dl 1.119 }
6047     }
6048 dl 1.99
6049 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysTask<K,V,U>
6050 dl 1.146 extends Traverser<K,V,U> {
6051 dl 1.153 final Function<? super K, ? extends U> transformer;
6052     final BiFunction<? super U, ? super U, ? extends U> reducer;
6053 dl 1.119 U result;
6054 dl 1.128 MapReduceKeysTask<K,V,U> rights, nextRight;
6055 dl 1.119 MapReduceKeysTask
6056 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6057 dl 1.128 MapReduceKeysTask<K,V,U> nextRight,
6058 dl 1.153 Function<? super K, ? extends U> transformer,
6059     BiFunction<? super U, ? super U, ? extends U> reducer) {
6060 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6061 dl 1.119 this.transformer = transformer;
6062     this.reducer = reducer;
6063     }
6064 dl 1.146 public final U getRawResult() { return result; }
6065     @SuppressWarnings("unchecked") public final void compute() {
6066 dl 1.153 final Function<? super K, ? extends U> transformer;
6067     final BiFunction<? super U, ? super U, ? extends U> reducer;
6068 dl 1.149 if ((transformer = this.transformer) != null &&
6069     (reducer = this.reducer) != null) {
6070     for (int b; (b = preSplit()) > 0;)
6071     (rights = new MapReduceKeysTask<K,V,U>
6072     (map, this, b, rights, transformer, reducer)).fork();
6073     U r = null, u;
6074     while (advance() != null) {
6075 jsr166 1.168 if ((u = transformer.apply(nextKey)) != null)
6076 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6077     }
6078     result = r;
6079     CountedCompleter<?> c;
6080     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6081     MapReduceKeysTask<K,V,U>
6082     t = (MapReduceKeysTask<K,V,U>)c,
6083     s = t.rights;
6084     while (s != null) {
6085     U tr, sr;
6086     if ((sr = s.result) != null)
6087     t.result = (((tr = t.result) == null) ? sr :
6088     reducer.apply(tr, sr));
6089     s = t.rights = s.nextRight;
6090     }
6091 dl 1.119 }
6092 dl 1.138 }
6093 tim 1.1 }
6094 dl 1.4 }
6095    
6096 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesTask<K,V,U>
6097 dl 1.146 extends Traverser<K,V,U> {
6098 dl 1.153 final Function<? super V, ? extends U> transformer;
6099     final BiFunction<? super U, ? super U, ? extends U> reducer;
6100 dl 1.119 U result;
6101 dl 1.128 MapReduceValuesTask<K,V,U> rights, nextRight;
6102 dl 1.119 MapReduceValuesTask
6103 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6104 dl 1.128 MapReduceValuesTask<K,V,U> nextRight,
6105 dl 1.153 Function<? super V, ? extends U> transformer,
6106     BiFunction<? super U, ? super U, ? extends U> reducer) {
6107 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6108 dl 1.119 this.transformer = transformer;
6109     this.reducer = reducer;
6110     }
6111 dl 1.146 public final U getRawResult() { return result; }
6112     @SuppressWarnings("unchecked") public final void compute() {
6113 dl 1.153 final Function<? super V, ? extends U> transformer;
6114     final BiFunction<? super U, ? super U, ? extends U> reducer;
6115 dl 1.149 if ((transformer = this.transformer) != null &&
6116     (reducer = this.reducer) != null) {
6117     for (int b; (b = preSplit()) > 0;)
6118     (rights = new MapReduceValuesTask<K,V,U>
6119     (map, this, b, rights, transformer, reducer)).fork();
6120     U r = null, u;
6121 dl 1.151 V v;
6122 dl 1.149 while ((v = advance()) != null) {
6123 dl 1.151 if ((u = transformer.apply(v)) != null)
6124 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6125     }
6126     result = r;
6127     CountedCompleter<?> c;
6128     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6129     MapReduceValuesTask<K,V,U>
6130     t = (MapReduceValuesTask<K,V,U>)c,
6131     s = t.rights;
6132     while (s != null) {
6133     U tr, sr;
6134     if ((sr = s.result) != null)
6135     t.result = (((tr = t.result) == null) ? sr :
6136     reducer.apply(tr, sr));
6137     s = t.rights = s.nextRight;
6138     }
6139 dl 1.119 }
6140     }
6141     }
6142 dl 1.4 }
6143    
6144 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesTask<K,V,U>
6145 dl 1.146 extends Traverser<K,V,U> {
6146 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
6147     final BiFunction<? super U, ? super U, ? extends U> reducer;
6148 dl 1.119 U result;
6149 dl 1.128 MapReduceEntriesTask<K,V,U> rights, nextRight;
6150 dl 1.119 MapReduceEntriesTask
6151 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6152 dl 1.128 MapReduceEntriesTask<K,V,U> nextRight,
6153 dl 1.153 Function<Map.Entry<K,V>, ? extends U> transformer,
6154     BiFunction<? super U, ? super U, ? extends U> reducer) {
6155 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6156 dl 1.119 this.transformer = transformer;
6157     this.reducer = reducer;
6158     }
6159 dl 1.146 public final U getRawResult() { return result; }
6160     @SuppressWarnings("unchecked") public final void compute() {
6161 dl 1.153 final Function<Map.Entry<K,V>, ? extends U> transformer;
6162     final BiFunction<? super U, ? super U, ? extends U> reducer;
6163 dl 1.149 if ((transformer = this.transformer) != null &&
6164     (reducer = this.reducer) != null) {
6165     for (int b; (b = preSplit()) > 0;)
6166     (rights = new MapReduceEntriesTask<K,V,U>
6167     (map, this, b, rights, transformer, reducer)).fork();
6168     U r = null, u;
6169 dl 1.151 V v;
6170 dl 1.149 while ((v = advance()) != null) {
6171 jsr166 1.168 if ((u = transformer.apply(entryFor(nextKey,
6172 dl 1.151 v))) != null)
6173 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6174     }
6175     result = r;
6176     CountedCompleter<?> c;
6177     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6178     MapReduceEntriesTask<K,V,U>
6179     t = (MapReduceEntriesTask<K,V,U>)c,
6180     s = t.rights;
6181     while (s != null) {
6182     U tr, sr;
6183     if ((sr = s.result) != null)
6184     t.result = (((tr = t.result) == null) ? sr :
6185     reducer.apply(tr, sr));
6186     s = t.rights = s.nextRight;
6187     }
6188 dl 1.119 }
6189 dl 1.138 }
6190 dl 1.119 }
6191 dl 1.4 }
6192 tim 1.1
6193 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsTask<K,V,U>
6194 dl 1.146 extends Traverser<K,V,U> {
6195 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
6196     final BiFunction<? super U, ? super U, ? extends U> reducer;
6197 dl 1.119 U result;
6198 dl 1.128 MapReduceMappingsTask<K,V,U> rights, nextRight;
6199 dl 1.119 MapReduceMappingsTask
6200 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6201 dl 1.128 MapReduceMappingsTask<K,V,U> nextRight,
6202 dl 1.153 BiFunction<? super K, ? super V, ? extends U> transformer,
6203     BiFunction<? super U, ? super U, ? extends U> reducer) {
6204 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6205 dl 1.119 this.transformer = transformer;
6206     this.reducer = reducer;
6207     }
6208 dl 1.146 public final U getRawResult() { return result; }
6209     @SuppressWarnings("unchecked") public final void compute() {
6210 dl 1.153 final BiFunction<? super K, ? super V, ? extends U> transformer;
6211     final BiFunction<? super U, ? super U, ? extends U> reducer;
6212 dl 1.149 if ((transformer = this.transformer) != null &&
6213     (reducer = this.reducer) != null) {
6214     for (int b; (b = preSplit()) > 0;)
6215     (rights = new MapReduceMappingsTask<K,V,U>
6216     (map, this, b, rights, transformer, reducer)).fork();
6217     U r = null, u;
6218 dl 1.151 V v;
6219 dl 1.149 while ((v = advance()) != null) {
6220 jsr166 1.168 if ((u = transformer.apply(nextKey, v)) != null)
6221 dl 1.149 r = (r == null) ? u : reducer.apply(r, u);
6222     }
6223     result = r;
6224     CountedCompleter<?> c;
6225     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6226     MapReduceMappingsTask<K,V,U>
6227     t = (MapReduceMappingsTask<K,V,U>)c,
6228     s = t.rights;
6229     while (s != null) {
6230     U tr, sr;
6231     if ((sr = s.result) != null)
6232     t.result = (((tr = t.result) == null) ? sr :
6233     reducer.apply(tr, sr));
6234     s = t.rights = s.nextRight;
6235     }
6236 dl 1.119 }
6237     }
6238     }
6239     }
6240 jsr166 1.114
6241 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V>
6242 dl 1.146 extends Traverser<K,V,Double> {
6243 dl 1.171 final ToDoubleFunction<? super K> transformer;
6244 dl 1.153 final DoubleBinaryOperator reducer;
6245 dl 1.119 final double basis;
6246     double result;
6247 dl 1.128 MapReduceKeysToDoubleTask<K,V> rights, nextRight;
6248 dl 1.119 MapReduceKeysToDoubleTask
6249 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6250 dl 1.128 MapReduceKeysToDoubleTask<K,V> nextRight,
6251 dl 1.171 ToDoubleFunction<? super K> transformer,
6252 dl 1.119 double basis,
6253 dl 1.153 DoubleBinaryOperator reducer) {
6254 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6255 dl 1.119 this.transformer = transformer;
6256     this.basis = basis; this.reducer = reducer;
6257     }
6258 dl 1.146 public final Double getRawResult() { return result; }
6259     @SuppressWarnings("unchecked") public final void compute() {
6260 dl 1.171 final ToDoubleFunction<? super K> transformer;
6261 dl 1.153 final DoubleBinaryOperator reducer;
6262 dl 1.149 if ((transformer = this.transformer) != null &&
6263     (reducer = this.reducer) != null) {
6264     double r = this.basis;
6265     for (int b; (b = preSplit()) > 0;)
6266     (rights = new MapReduceKeysToDoubleTask<K,V>
6267     (map, this, b, rights, transformer, r, reducer)).fork();
6268     while (advance() != null)
6269 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey));
6270 dl 1.149 result = r;
6271     CountedCompleter<?> c;
6272     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6273     MapReduceKeysToDoubleTask<K,V>
6274     t = (MapReduceKeysToDoubleTask<K,V>)c,
6275     s = t.rights;
6276     while (s != null) {
6277 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6278 dl 1.149 s = t.rights = s.nextRight;
6279     }
6280 dl 1.119 }
6281 dl 1.138 }
6282 dl 1.79 }
6283 dl 1.119 }
6284 dl 1.79
6285 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask<K,V>
6286 dl 1.146 extends Traverser<K,V,Double> {
6287 dl 1.171 final ToDoubleFunction<? super V> transformer;
6288 dl 1.153 final DoubleBinaryOperator reducer;
6289 dl 1.119 final double basis;
6290     double result;
6291 dl 1.128 MapReduceValuesToDoubleTask<K,V> rights, nextRight;
6292 dl 1.119 MapReduceValuesToDoubleTask
6293 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6294 dl 1.128 MapReduceValuesToDoubleTask<K,V> nextRight,
6295 dl 1.171 ToDoubleFunction<? super V> transformer,
6296 dl 1.119 double basis,
6297 dl 1.153 DoubleBinaryOperator reducer) {
6298 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6299 dl 1.119 this.transformer = transformer;
6300     this.basis = basis; this.reducer = reducer;
6301     }
6302 dl 1.146 public final Double getRawResult() { return result; }
6303     @SuppressWarnings("unchecked") public final void compute() {
6304 dl 1.171 final ToDoubleFunction<? super V> transformer;
6305 dl 1.153 final DoubleBinaryOperator reducer;
6306 dl 1.149 if ((transformer = this.transformer) != null &&
6307     (reducer = this.reducer) != null) {
6308     double r = this.basis;
6309     for (int b; (b = preSplit()) > 0;)
6310     (rights = new MapReduceValuesToDoubleTask<K,V>
6311     (map, this, b, rights, transformer, r, reducer)).fork();
6312 dl 1.151 V v;
6313 dl 1.149 while ((v = advance()) != null)
6314 dl 1.153 r = reducer.applyAsDouble(r, transformer.applyAsDouble(v));
6315 dl 1.149 result = r;
6316     CountedCompleter<?> c;
6317     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6318     MapReduceValuesToDoubleTask<K,V>
6319     t = (MapReduceValuesToDoubleTask<K,V>)c,
6320     s = t.rights;
6321     while (s != null) {
6322 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6323 dl 1.149 s = t.rights = s.nextRight;
6324     }
6325 dl 1.119 }
6326     }
6327 dl 1.30 }
6328 dl 1.79 }
6329 dl 1.30
6330 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V>
6331 dl 1.146 extends Traverser<K,V,Double> {
6332 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6333 dl 1.153 final DoubleBinaryOperator reducer;
6334 dl 1.119 final double basis;
6335     double result;
6336 dl 1.128 MapReduceEntriesToDoubleTask<K,V> rights, nextRight;
6337 dl 1.119 MapReduceEntriesToDoubleTask
6338 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6339 dl 1.128 MapReduceEntriesToDoubleTask<K,V> nextRight,
6340 dl 1.171 ToDoubleFunction<Map.Entry<K,V>> transformer,
6341 dl 1.119 double basis,
6342 dl 1.153 DoubleBinaryOperator reducer) {
6343 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6344 dl 1.119 this.transformer = transformer;
6345     this.basis = basis; this.reducer = reducer;
6346     }
6347 dl 1.146 public final Double getRawResult() { return result; }
6348     @SuppressWarnings("unchecked") public final void compute() {
6349 dl 1.171 final ToDoubleFunction<Map.Entry<K,V>> transformer;
6350 dl 1.153 final DoubleBinaryOperator reducer;
6351 dl 1.149 if ((transformer = this.transformer) != null &&
6352     (reducer = this.reducer) != null) {
6353     double r = this.basis;
6354     for (int b; (b = preSplit()) > 0;)
6355     (rights = new MapReduceEntriesToDoubleTask<K,V>
6356     (map, this, b, rights, transformer, r, reducer)).fork();
6357 dl 1.151 V v;
6358 dl 1.149 while ((v = advance()) != null)
6359 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(entryFor(nextKey,
6360 dl 1.151 v)));
6361 dl 1.149 result = r;
6362     CountedCompleter<?> c;
6363     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6364     MapReduceEntriesToDoubleTask<K,V>
6365     t = (MapReduceEntriesToDoubleTask<K,V>)c,
6366     s = t.rights;
6367     while (s != null) {
6368 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6369 dl 1.149 s = t.rights = s.nextRight;
6370     }
6371 dl 1.119 }
6372 dl 1.138 }
6373 dl 1.30 }
6374 tim 1.1 }
6375    
6376 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask<K,V>
6377 dl 1.146 extends Traverser<K,V,Double> {
6378 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
6379 dl 1.153 final DoubleBinaryOperator reducer;
6380 dl 1.119 final double basis;
6381     double result;
6382 dl 1.128 MapReduceMappingsToDoubleTask<K,V> rights, nextRight;
6383 dl 1.119 MapReduceMappingsToDoubleTask
6384 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6385 dl 1.128 MapReduceMappingsToDoubleTask<K,V> nextRight,
6386 dl 1.171 ToDoubleBiFunction<? super K, ? super V> transformer,
6387 dl 1.119 double basis,
6388 dl 1.153 DoubleBinaryOperator reducer) {
6389 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6390 dl 1.119 this.transformer = transformer;
6391     this.basis = basis; this.reducer = reducer;
6392     }
6393 dl 1.146 public final Double getRawResult() { return result; }
6394     @SuppressWarnings("unchecked") public final void compute() {
6395 dl 1.171 final ToDoubleBiFunction<? super K, ? super V> transformer;
6396 dl 1.153 final DoubleBinaryOperator reducer;
6397 dl 1.149 if ((transformer = this.transformer) != null &&
6398     (reducer = this.reducer) != null) {
6399     double r = this.basis;
6400     for (int b; (b = preSplit()) > 0;)
6401     (rights = new MapReduceMappingsToDoubleTask<K,V>
6402     (map, this, b, rights, transformer, r, reducer)).fork();
6403 dl 1.151 V v;
6404 dl 1.149 while ((v = advance()) != null)
6405 jsr166 1.168 r = reducer.applyAsDouble(r, transformer.applyAsDouble(nextKey, v));
6406 dl 1.149 result = r;
6407     CountedCompleter<?> c;
6408     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6409     MapReduceMappingsToDoubleTask<K,V>
6410     t = (MapReduceMappingsToDoubleTask<K,V>)c,
6411     s = t.rights;
6412     while (s != null) {
6413 dl 1.153 t.result = reducer.applyAsDouble(t.result, s.result);
6414 dl 1.149 s = t.rights = s.nextRight;
6415     }
6416 dl 1.119 }
6417     }
6418 dl 1.4 }
6419 dl 1.119 }
6420    
6421 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToLongTask<K,V>
6422 dl 1.146 extends Traverser<K,V,Long> {
6423 dl 1.171 final ToLongFunction<? super K> transformer;
6424 dl 1.153 final LongBinaryOperator reducer;
6425 dl 1.119 final long basis;
6426     long result;
6427 dl 1.128 MapReduceKeysToLongTask<K,V> rights, nextRight;
6428 dl 1.119 MapReduceKeysToLongTask
6429 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6430 dl 1.128 MapReduceKeysToLongTask<K,V> nextRight,
6431 dl 1.171 ToLongFunction<? super K> transformer,
6432 dl 1.119 long basis,
6433 dl 1.153 LongBinaryOperator reducer) {
6434 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6435 dl 1.119 this.transformer = transformer;
6436     this.basis = basis; this.reducer = reducer;
6437     }
6438 dl 1.146 public final Long getRawResult() { return result; }
6439     @SuppressWarnings("unchecked") public final void compute() {
6440 dl 1.171 final ToLongFunction<? super K> transformer;
6441 dl 1.153 final LongBinaryOperator reducer;
6442 dl 1.149 if ((transformer = this.transformer) != null &&
6443     (reducer = this.reducer) != null) {
6444     long r = this.basis;
6445     for (int b; (b = preSplit()) > 0;)
6446     (rights = new MapReduceKeysToLongTask<K,V>
6447     (map, this, b, rights, transformer, r, reducer)).fork();
6448     while (advance() != null)
6449 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey));
6450 dl 1.149 result = r;
6451     CountedCompleter<?> c;
6452     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6453     MapReduceKeysToLongTask<K,V>
6454     t = (MapReduceKeysToLongTask<K,V>)c,
6455     s = t.rights;
6456     while (s != null) {
6457 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6458 dl 1.149 s = t.rights = s.nextRight;
6459     }
6460 dl 1.119 }
6461 dl 1.138 }
6462 dl 1.4 }
6463 dl 1.119 }
6464    
6465 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V>
6466 dl 1.146 extends Traverser<K,V,Long> {
6467 dl 1.171 final ToLongFunction<? super V> transformer;
6468 dl 1.153 final LongBinaryOperator reducer;
6469 dl 1.119 final long basis;
6470     long result;
6471 dl 1.128 MapReduceValuesToLongTask<K,V> rights, nextRight;
6472 dl 1.119 MapReduceValuesToLongTask
6473 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6474 dl 1.128 MapReduceValuesToLongTask<K,V> nextRight,
6475 dl 1.171 ToLongFunction<? super V> transformer,
6476 dl 1.119 long basis,
6477 dl 1.153 LongBinaryOperator reducer) {
6478 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6479 dl 1.119 this.transformer = transformer;
6480     this.basis = basis; this.reducer = reducer;
6481     }
6482 dl 1.146 public final Long getRawResult() { return result; }
6483     @SuppressWarnings("unchecked") public final void compute() {
6484 dl 1.171 final ToLongFunction<? super V> transformer;
6485 dl 1.153 final LongBinaryOperator reducer;
6486 dl 1.149 if ((transformer = this.transformer) != null &&
6487     (reducer = this.reducer) != null) {
6488     long r = this.basis;
6489     for (int b; (b = preSplit()) > 0;)
6490     (rights = new MapReduceValuesToLongTask<K,V>
6491     (map, this, b, rights, transformer, r, reducer)).fork();
6492 dl 1.151 V v;
6493 dl 1.149 while ((v = advance()) != null)
6494 dl 1.153 r = reducer.applyAsLong(r, transformer.applyAsLong(v));
6495 dl 1.149 result = r;
6496     CountedCompleter<?> c;
6497     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6498     MapReduceValuesToLongTask<K,V>
6499     t = (MapReduceValuesToLongTask<K,V>)c,
6500     s = t.rights;
6501     while (s != null) {
6502 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6503 dl 1.149 s = t.rights = s.nextRight;
6504     }
6505 dl 1.119 }
6506     }
6507 jsr166 1.95 }
6508 dl 1.119 }
6509    
6510 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V>
6511 dl 1.146 extends Traverser<K,V,Long> {
6512 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6513 dl 1.153 final LongBinaryOperator reducer;
6514 dl 1.119 final long basis;
6515     long result;
6516 dl 1.128 MapReduceEntriesToLongTask<K,V> rights, nextRight;
6517 dl 1.119 MapReduceEntriesToLongTask
6518 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6519 dl 1.128 MapReduceEntriesToLongTask<K,V> nextRight,
6520 dl 1.171 ToLongFunction<Map.Entry<K,V>> transformer,
6521 dl 1.119 long basis,
6522 dl 1.153 LongBinaryOperator reducer) {
6523 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6524 dl 1.119 this.transformer = transformer;
6525     this.basis = basis; this.reducer = reducer;
6526     }
6527 dl 1.146 public final Long getRawResult() { return result; }
6528     @SuppressWarnings("unchecked") public final void compute() {
6529 dl 1.171 final ToLongFunction<Map.Entry<K,V>> transformer;
6530 dl 1.153 final LongBinaryOperator reducer;
6531 dl 1.149 if ((transformer = this.transformer) != null &&
6532     (reducer = this.reducer) != null) {
6533     long r = this.basis;
6534     for (int b; (b = preSplit()) > 0;)
6535     (rights = new MapReduceEntriesToLongTask<K,V>
6536     (map, this, b, rights, transformer, r, reducer)).fork();
6537 dl 1.151 V v;
6538 dl 1.149 while ((v = advance()) != null)
6539 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(entryFor(nextKey, v)));
6540 dl 1.149 result = r;
6541     CountedCompleter<?> c;
6542     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6543     MapReduceEntriesToLongTask<K,V>
6544     t = (MapReduceEntriesToLongTask<K,V>)c,
6545     s = t.rights;
6546     while (s != null) {
6547 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6548 dl 1.149 s = t.rights = s.nextRight;
6549     }
6550 dl 1.119 }
6551 dl 1.138 }
6552 dl 1.4 }
6553 tim 1.1 }
6554    
6555 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V>
6556 dl 1.146 extends Traverser<K,V,Long> {
6557 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6558 dl 1.153 final LongBinaryOperator reducer;
6559 dl 1.119 final long basis;
6560     long result;
6561 dl 1.128 MapReduceMappingsToLongTask<K,V> rights, nextRight;
6562 dl 1.119 MapReduceMappingsToLongTask
6563 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6564 dl 1.128 MapReduceMappingsToLongTask<K,V> nextRight,
6565 dl 1.171 ToLongBiFunction<? super K, ? super V> transformer,
6566 dl 1.119 long basis,
6567 dl 1.153 LongBinaryOperator reducer) {
6568 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6569 dl 1.119 this.transformer = transformer;
6570     this.basis = basis; this.reducer = reducer;
6571     }
6572 dl 1.146 public final Long getRawResult() { return result; }
6573     @SuppressWarnings("unchecked") public final void compute() {
6574 dl 1.171 final ToLongBiFunction<? super K, ? super V> transformer;
6575 dl 1.153 final LongBinaryOperator reducer;
6576 dl 1.149 if ((transformer = this.transformer) != null &&
6577     (reducer = this.reducer) != null) {
6578     long r = this.basis;
6579     for (int b; (b = preSplit()) > 0;)
6580     (rights = new MapReduceMappingsToLongTask<K,V>
6581     (map, this, b, rights, transformer, r, reducer)).fork();
6582 dl 1.151 V v;
6583 dl 1.149 while ((v = advance()) != null)
6584 jsr166 1.168 r = reducer.applyAsLong(r, transformer.applyAsLong(nextKey, v));
6585 dl 1.149 result = r;
6586     CountedCompleter<?> c;
6587     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6588     MapReduceMappingsToLongTask<K,V>
6589     t = (MapReduceMappingsToLongTask<K,V>)c,
6590     s = t.rights;
6591     while (s != null) {
6592 dl 1.153 t.result = reducer.applyAsLong(t.result, s.result);
6593 dl 1.149 s = t.rights = s.nextRight;
6594     }
6595 dl 1.119 }
6596     }
6597 dl 1.4 }
6598 tim 1.1 }
6599    
6600 dl 1.128 @SuppressWarnings("serial") static final class MapReduceKeysToIntTask<K,V>
6601 dl 1.146 extends Traverser<K,V,Integer> {
6602 dl 1.171 final ToIntFunction<? super K> transformer;
6603 dl 1.153 final IntBinaryOperator reducer;
6604 dl 1.119 final int basis;
6605     int result;
6606 dl 1.128 MapReduceKeysToIntTask<K,V> rights, nextRight;
6607 dl 1.119 MapReduceKeysToIntTask
6608 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6609 dl 1.128 MapReduceKeysToIntTask<K,V> nextRight,
6610 dl 1.171 ToIntFunction<? super K> transformer,
6611 dl 1.119 int basis,
6612 dl 1.153 IntBinaryOperator reducer) {
6613 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6614 dl 1.119 this.transformer = transformer;
6615     this.basis = basis; this.reducer = reducer;
6616     }
6617 dl 1.146 public final Integer getRawResult() { return result; }
6618     @SuppressWarnings("unchecked") public final void compute() {
6619 dl 1.171 final ToIntFunction<? super K> transformer;
6620 dl 1.153 final IntBinaryOperator reducer;
6621 dl 1.149 if ((transformer = this.transformer) != null &&
6622     (reducer = this.reducer) != null) {
6623     int r = this.basis;
6624     for (int b; (b = preSplit()) > 0;)
6625     (rights = new MapReduceKeysToIntTask<K,V>
6626     (map, this, b, rights, transformer, r, reducer)).fork();
6627     while (advance() != null)
6628 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey));
6629 dl 1.149 result = r;
6630     CountedCompleter<?> c;
6631     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6632     MapReduceKeysToIntTask<K,V>
6633     t = (MapReduceKeysToIntTask<K,V>)c,
6634     s = t.rights;
6635     while (s != null) {
6636 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6637 dl 1.149 s = t.rights = s.nextRight;
6638     }
6639 dl 1.119 }
6640 dl 1.138 }
6641 dl 1.30 }
6642     }
6643    
6644 dl 1.128 @SuppressWarnings("serial") static final class MapReduceValuesToIntTask<K,V>
6645 dl 1.146 extends Traverser<K,V,Integer> {
6646 dl 1.171 final ToIntFunction<? super V> transformer;
6647 dl 1.153 final IntBinaryOperator reducer;
6648 dl 1.119 final int basis;
6649     int result;
6650 dl 1.128 MapReduceValuesToIntTask<K,V> rights, nextRight;
6651 dl 1.119 MapReduceValuesToIntTask
6652 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6653 dl 1.128 MapReduceValuesToIntTask<K,V> nextRight,
6654 dl 1.171 ToIntFunction<? super V> transformer,
6655 dl 1.119 int basis,
6656 dl 1.153 IntBinaryOperator reducer) {
6657 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6658 dl 1.119 this.transformer = transformer;
6659     this.basis = basis; this.reducer = reducer;
6660     }
6661 dl 1.146 public final Integer getRawResult() { return result; }
6662     @SuppressWarnings("unchecked") public final void compute() {
6663 dl 1.171 final ToIntFunction<? super V> transformer;
6664 dl 1.153 final IntBinaryOperator reducer;
6665 dl 1.149 if ((transformer = this.transformer) != null &&
6666     (reducer = this.reducer) != null) {
6667     int r = this.basis;
6668     for (int b; (b = preSplit()) > 0;)
6669     (rights = new MapReduceValuesToIntTask<K,V>
6670     (map, this, b, rights, transformer, r, reducer)).fork();
6671 dl 1.151 V v;
6672 dl 1.149 while ((v = advance()) != null)
6673 dl 1.153 r = reducer.applyAsInt(r, transformer.applyAsInt(v));
6674 dl 1.149 result = r;
6675     CountedCompleter<?> c;
6676     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6677     MapReduceValuesToIntTask<K,V>
6678     t = (MapReduceValuesToIntTask<K,V>)c,
6679     s = t.rights;
6680     while (s != null) {
6681 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6682 dl 1.149 s = t.rights = s.nextRight;
6683     }
6684 dl 1.119 }
6685 dl 1.2 }
6686 tim 1.1 }
6687     }
6688    
6689 dl 1.128 @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask<K,V>
6690 dl 1.146 extends Traverser<K,V,Integer> {
6691 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6692 dl 1.153 final IntBinaryOperator reducer;
6693 dl 1.119 final int basis;
6694     int result;
6695 dl 1.128 MapReduceEntriesToIntTask<K,V> rights, nextRight;
6696 dl 1.119 MapReduceEntriesToIntTask
6697 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6698 dl 1.128 MapReduceEntriesToIntTask<K,V> nextRight,
6699 dl 1.171 ToIntFunction<Map.Entry<K,V>> transformer,
6700 dl 1.119 int basis,
6701 dl 1.153 IntBinaryOperator reducer) {
6702 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6703 dl 1.119 this.transformer = transformer;
6704     this.basis = basis; this.reducer = reducer;
6705     }
6706 dl 1.146 public final Integer getRawResult() { return result; }
6707     @SuppressWarnings("unchecked") public final void compute() {
6708 dl 1.171 final ToIntFunction<Map.Entry<K,V>> transformer;
6709 dl 1.153 final IntBinaryOperator reducer;
6710 dl 1.149 if ((transformer = this.transformer) != null &&
6711     (reducer = this.reducer) != null) {
6712     int r = this.basis;
6713     for (int b; (b = preSplit()) > 0;)
6714     (rights = new MapReduceEntriesToIntTask<K,V>
6715     (map, this, b, rights, transformer, r, reducer)).fork();
6716 dl 1.151 V v;
6717 dl 1.149 while ((v = advance()) != null)
6718 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(entryFor(nextKey,
6719 dl 1.151 v)));
6720 dl 1.149 result = r;
6721     CountedCompleter<?> c;
6722     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6723     MapReduceEntriesToIntTask<K,V>
6724     t = (MapReduceEntriesToIntTask<K,V>)c,
6725     s = t.rights;
6726     while (s != null) {
6727 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6728 dl 1.149 s = t.rights = s.nextRight;
6729     }
6730 dl 1.119 }
6731 dl 1.138 }
6732 dl 1.4 }
6733 dl 1.119 }
6734 tim 1.1
6735 dl 1.128 @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask<K,V>
6736 dl 1.146 extends Traverser<K,V,Integer> {
6737 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6738 dl 1.153 final IntBinaryOperator reducer;
6739 dl 1.119 final int basis;
6740     int result;
6741 dl 1.128 MapReduceMappingsToIntTask<K,V> rights, nextRight;
6742 dl 1.119 MapReduceMappingsToIntTask
6743 dl 1.146 (ConcurrentHashMap<K,V> m, Traverser<K,V,?> p, int b,
6744     MapReduceMappingsToIntTask<K,V> nextRight,
6745 dl 1.171 ToIntBiFunction<? super K, ? super V> transformer,
6746 dl 1.119 int basis,
6747 dl 1.153 IntBinaryOperator reducer) {
6748 dl 1.130 super(m, p, b); this.nextRight = nextRight;
6749 dl 1.119 this.transformer = transformer;
6750     this.basis = basis; this.reducer = reducer;
6751     }
6752 dl 1.146 public final Integer getRawResult() { return result; }
6753     @SuppressWarnings("unchecked") public final void compute() {
6754 dl 1.171 final ToIntBiFunction<? super K, ? super V> transformer;
6755 dl 1.153 final IntBinaryOperator reducer;
6756 dl 1.149 if ((transformer = this.transformer) != null &&
6757     (reducer = this.reducer) != null) {
6758     int r = this.basis;
6759     for (int b; (b = preSplit()) > 0;)
6760     (rights = new MapReduceMappingsToIntTask<K,V>
6761     (map, this, b, rights, transformer, r, reducer)).fork();
6762 dl 1.151 V v;
6763 dl 1.149 while ((v = advance()) != null)
6764 jsr166 1.168 r = reducer.applyAsInt(r, transformer.applyAsInt(nextKey, v));
6765 dl 1.149 result = r;
6766     CountedCompleter<?> c;
6767     for (c = firstComplete(); c != null; c = c.nextComplete()) {
6768     MapReduceMappingsToIntTask<K,V>
6769     t = (MapReduceMappingsToIntTask<K,V>)c,
6770     s = t.rights;
6771     while (s != null) {
6772 dl 1.153 t.result = reducer.applyAsInt(t.result, s.result);
6773 dl 1.149 s = t.rights = s.nextRight;
6774     }
6775 dl 1.119 }
6776 dl 1.138 }
6777 tim 1.1 }
6778     }
6779 dl 1.99
6780     // Unsafe mechanics
6781 dl 1.149 private static final sun.misc.Unsafe U;
6782     private static final long SIZECTL;
6783     private static final long TRANSFERINDEX;
6784     private static final long TRANSFERORIGIN;
6785     private static final long BASECOUNT;
6786 dl 1.153 private static final long CELLSBUSY;
6787 dl 1.149 private static final long CELLVALUE;
6788 dl 1.119 private static final long ABASE;
6789     private static final int ASHIFT;
6790 dl 1.99
6791     static {
6792     try {
6793 dl 1.149 U = sun.misc.Unsafe.getUnsafe();
6794 dl 1.119 Class<?> k = ConcurrentHashMap.class;
6795 dl 1.149 SIZECTL = U.objectFieldOffset
6796 dl 1.119 (k.getDeclaredField("sizeCtl"));
6797 dl 1.149 TRANSFERINDEX = U.objectFieldOffset
6798     (k.getDeclaredField("transferIndex"));
6799     TRANSFERORIGIN = U.objectFieldOffset
6800     (k.getDeclaredField("transferOrigin"));
6801     BASECOUNT = U.objectFieldOffset
6802     (k.getDeclaredField("baseCount"));
6803 dl 1.153 CELLSBUSY = U.objectFieldOffset
6804     (k.getDeclaredField("cellsBusy"));
6805     Class<?> ck = Cell.class;
6806 dl 1.149 CELLVALUE = U.objectFieldOffset
6807     (ck.getDeclaredField("value"));
6808 dl 1.119 Class<?> sc = Node[].class;
6809 dl 1.149 ABASE = U.arrayBaseOffset(sc);
6810 jsr166 1.167 int scale = U.arrayIndexScale(sc);
6811     if ((scale & (scale - 1)) != 0)
6812     throw new Error("data type scale not a power of two");
6813     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
6814 dl 1.99 } catch (Exception e) {
6815     throw new Error(e);
6816     }
6817     }
6818 jsr166 1.152
6819     }