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