ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
Revision: 1.113
Committed: Mon Jul 22 16:54:43 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.112: +4 -0 lines
Log Message:
sync javadoc fixes from src/main

File Contents

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