ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.35
Committed: Wed Sep 11 14:53:48 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.34: +130 -80 lines
Log Message:
Apply jdk8 traversal improvements

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/publicdomain/zero/1.0/
5     */
6    
7     package java.util.concurrent;
8    
9 dl 1.20 import java.io.ObjectStreamField;
10     import java.io.Serializable;
11     import java.lang.reflect.ParameterizedType;
12     import java.lang.reflect.Type;
13 dl 1.1 import java.util.Arrays;
14     import java.util.Collection;
15 dl 1.20 import java.util.Comparator;
16     import java.util.ConcurrentModificationException;
17     import java.util.Enumeration;
18     import java.util.HashMap;
19 dl 1.1 import java.util.Hashtable;
20     import java.util.Iterator;
21 dl 1.20 import java.util.Map;
22 dl 1.1 import java.util.NoSuchElementException;
23 dl 1.20 import java.util.Set;
24 dl 1.1 import java.util.concurrent.ConcurrentMap;
25 dl 1.20 import java.util.concurrent.ForkJoinPool;
26 dl 1.1 import java.util.concurrent.atomic.AtomicInteger;
27 dl 1.20 import java.util.concurrent.locks.LockSupport;
28     import java.util.concurrent.locks.ReentrantLock;
29 dl 1.1
30     /**
31     * A hash table supporting full concurrency of retrievals and
32     * high expected concurrency for updates. This class obeys the
33     * same functional specification as {@link java.util.Hashtable}, and
34     * includes versions of methods corresponding to each method of
35     * {@code Hashtable}. However, even though all operations are
36     * thread-safe, retrieval operations do <em>not</em> entail locking,
37     * and there is <em>not</em> any support for locking the entire table
38     * in a way that prevents all access. This class is fully
39     * interoperable with {@code Hashtable} in programs that rely on its
40     * thread safety but not on its synchronization details.
41     *
42     * <p>Retrieval operations (including {@code get}) generally do not
43     * block, so may overlap with update operations (including {@code put}
44     * and {@code remove}). Retrievals reflect the results of the most
45     * recently <em>completed</em> update operations holding upon their
46     * onset. (More formally, an update operation for a given key bears a
47     * <em>happens-before</em> relation with any (non-null) retrieval for
48     * that key reporting the updated value.) For aggregate operations
49     * such as {@code putAll} and {@code clear}, concurrent retrievals may
50     * reflect insertion or removal of only some entries. Similarly,
51     * Iterators and Enumerations return elements reflecting the state of
52     * the hash table at some point at or since the creation of the
53     * iterator/enumeration. They do <em>not</em> throw {@link
54     * ConcurrentModificationException}. However, iterators are designed
55     * to be used by only one thread at a time. Bear in mind that the
56     * results of aggregate status methods including {@code size}, {@code
57     * isEmpty}, and {@code containsValue} are typically useful only when
58     * a map is not undergoing concurrent updates in other threads.
59     * Otherwise the results of these methods reflect transient states
60     * that may be adequate for monitoring or estimation purposes, but not
61     * for program control.
62     *
63     * <p>The table is dynamically expanded when there are too many
64     * collisions (i.e., keys that have distinct hash codes but fall into
65     * the same slot modulo the table size), with the expected average
66     * effect of maintaining roughly two bins per mapping (corresponding
67     * to a 0.75 load factor threshold for resizing). There may be much
68     * variance around this average as mappings are added and removed, but
69     * overall, this maintains a commonly accepted time/space tradeoff for
70     * hash tables. However, resizing this or any other kind of hash
71     * table may be a relatively slow operation. When possible, it is a
72     * good idea to provide a size estimate as an optional {@code
73     * initialCapacity} constructor argument. An additional optional
74     * {@code loadFactor} constructor argument provides a further means of
75     * customizing initial table capacity by specifying the table density
76     * to be used in calculating the amount of space to allocate for the
77     * given number of elements. Also, for compatibility with previous
78     * versions of this class, constructors may optionally specify an
79     * expected {@code concurrencyLevel} as an additional hint for
80     * internal sizing. Note that using many keys with exactly the same
81     * {@code hashCode()} is a sure way to slow down performance of any
82 dl 1.20 * hash table. To ameliorate impact, when keys are {@link Comparable},
83     * this class may use comparison order among keys to help break ties.
84 dl 1.1 *
85     * <p>A {@link Set} projection of a ConcurrentHashMap may be created
86     * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
87     * (using {@link #keySet(Object)} when only keys are of interest, and the
88     * mapped values are (perhaps transiently) not used or all take the
89     * same mapping value.
90     *
91     * <p>This class and its views and iterators implement all of the
92     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
93     * interfaces.
94     *
95     * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
96     * does <em>not</em> allow {@code null} to be used as a key or value.
97     *
98     * <p>This class is a member of the
99     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
100     * Java Collections Framework</a>.
101     *
102     * @since 1.5
103     * @author Doug Lea
104     * @param <K> the type of keys maintained by this map
105     * @param <V> the type of mapped values
106     */
107 dl 1.20 public class ConcurrentHashMap<K,V> implements ConcurrentMap<K,V>, Serializable {
108 dl 1.1 private static final long serialVersionUID = 7249069246763182397L;
109    
110     /*
111     * Overview:
112     *
113     * The primary design goal of this hash table is to maintain
114     * concurrent readability (typically method get(), but also
115     * iterators and related methods) while minimizing update
116     * contention. Secondary goals are to keep space consumption about
117     * the same or better than java.util.HashMap, and to support high
118     * initial insertion rates on an empty table by many threads.
119     *
120 dl 1.20 * This map usually acts as a binned (bucketed) hash table. Each
121     * key-value mapping is held in a Node. Most nodes are instances
122     * of the basic Node class with hash, key, value, and next
123     * fields. However, various subclasses exist: TreeNodes are
124     * arranged in balanced trees, not lists. TreeBins hold the roots
125     * of sets of TreeNodes. ForwardingNodes are placed at the heads
126     * of bins during resizing. ReservationNodes are used as
127     * placeholders while establishing values in computeIfAbsent and
128     * related methods. The types TreeBin, ForwardingNode, and
129     * ReservationNode do not hold normal user keys, values, or
130     * hashes, and are readily distinguishable during search etc
131     * because they have negative hash fields and null key and value
132     * fields. (These special nodes are either uncommon or transient,
133     * so the impact of carrying around some unused fields is
134 jsr166 1.28 * insignificant.)
135 dl 1.1 *
136     * The table is lazily initialized to a power-of-two size upon the
137     * first insertion. Each bin in the table normally contains a
138     * list of Nodes (most often, the list has only zero or one Node).
139     * Table accesses require volatile/atomic reads, writes, and
140     * CASes. Because there is no other way to arrange this without
141     * adding further indirections, we use intrinsics
142 dl 1.20 * (sun.misc.Unsafe) operations.
143 dl 1.1 *
144     * We use the top (sign) bit of Node hash fields for control
145     * purposes -- it is available anyway because of addressing
146 dl 1.20 * constraints. Nodes with negative hash fields are specially
147     * handled or ignored in map methods.
148 dl 1.1 *
149     * Insertion (via put or its variants) of the first node in an
150     * empty bin is performed by just CASing it to the bin. This is
151     * by far the most common case for put operations under most
152     * key/hash distributions. Other update operations (insert,
153     * delete, and replace) require locks. We do not want to waste
154     * the space required to associate a distinct lock object with
155     * each bin, so instead use the first node of a bin list itself as
156     * a lock. Locking support for these locks relies on builtin
157     * "synchronized" monitors.
158     *
159     * Using the first node of a list as a lock does not by itself
160     * suffice though: When a node is locked, any update must first
161     * validate that it is still the first node after locking it, and
162     * retry if not. Because new nodes are always appended to lists,
163     * once a node is first in a bin, it remains first until deleted
164 dl 1.20 * or the bin becomes invalidated (upon resizing).
165 dl 1.1 *
166     * The main disadvantage of per-bin locks is that other update
167     * operations on other nodes in a bin list protected by the same
168     * lock can stall, for example when user equals() or mapping
169     * functions take a long time. However, statistically, under
170     * random hash codes, this is not a common problem. Ideally, the
171     * frequency of nodes in bins follows a Poisson distribution
172     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
173     * parameter of about 0.5 on average, given the resizing threshold
174     * of 0.75, although with a large variance because of resizing
175     * granularity. Ignoring variance, the expected occurrences of
176     * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
177     * first values are:
178     *
179     * 0: 0.60653066
180     * 1: 0.30326533
181     * 2: 0.07581633
182     * 3: 0.01263606
183     * 4: 0.00157952
184     * 5: 0.00015795
185     * 6: 0.00001316
186     * 7: 0.00000094
187     * 8: 0.00000006
188     * more: less than 1 in ten million
189     *
190     * Lock contention probability for two threads accessing distinct
191     * elements is roughly 1 / (8 * #elements) under random hashes.
192     *
193     * Actual hash code distributions encountered in practice
194     * sometimes deviate significantly from uniform randomness. This
195     * includes the case when N > (1<<30), so some keys MUST collide.
196     * Similarly for dumb or hostile usages in which multiple keys are
197 dl 1.20 * designed to have identical hash codes or ones that differs only
198     * in masked-out high bits. So we use a secondary strategy that
199     * applies when the number of nodes in a bin exceeds a
200     * threshold. These TreeBins use a balanced tree to hold nodes (a
201     * specialized form of red-black trees), bounding search time to
202     * O(log N). Each search step in a TreeBin is at least twice as
203 dl 1.1 * slow as in a regular list, but given that N cannot exceed
204     * (1<<64) (before running out of addresses) this bounds search
205     * steps, lock hold times, etc, to reasonable constants (roughly
206     * 100 nodes inspected per operation worst case) so long as keys
207     * are Comparable (which is very common -- String, Long, etc).
208     * TreeBin nodes (TreeNodes) also maintain the same "next"
209     * traversal pointers as regular nodes, so can be traversed in
210     * iterators in the same way.
211     *
212     * The table is resized when occupancy exceeds a percentage
213     * threshold (nominally, 0.75, but see below). Any thread
214     * noticing an overfull bin may assist in resizing after the
215 dl 1.35 * initiating thread allocates and sets up the replacement array.
216     * However, rather than stalling, these other threads may proceed
217     * with insertions etc. The use of TreeBins shields us from the
218     * worst case effects of overfilling while resizes are in
219 dl 1.1 * progress. Resizing proceeds by transferring bins, one by one,
220 dl 1.35 * from the table to the next table. However, threads claim small
221     * blocks of indices to transfer (via field transferIndex) before
222     * doing so, reducing contention. Because we are using
223     * power-of-two expansion, the elements from each bin must either
224     * stay at same index, or move with a power of two offset. We
225     * eliminate unnecessary node creation by catching cases where old
226     * nodes can be reused because their next fields won't change. On
227     * average, only about one-sixth of them need cloning when a table
228     * doubles. The nodes they replace will be garbage collectable as
229     * soon as they are no longer referenced by any reader thread that
230     * may be in the midst of concurrently traversing table. Upon
231     * transfer, the old table bin contains only a special forwarding
232     * node (with hash field "MOVED") that contains the next table as
233     * its key. On encountering a forwarding node, access and update
234     * operations restart, using the new table.
235 dl 1.1 *
236     * Each bin transfer requires its bin lock, which can stall
237     * waiting for locks while resizing. However, because other
238     * threads can join in and help resize rather than contend for
239     * locks, average aggregate waits become shorter as resizing
240     * progresses. The transfer operation must also ensure that all
241     * accessible bins in both the old and new table are usable by any
242 dl 1.35 * traversal. This is arranged in part by proceeding from the
243     * last bin (table.length - 1) up towards the first. Upon seeing
244     * a forwarding node, traversals (see class Traverser) arrange to
245     * move to the new table without revisiting nodes. To ensure that
246     * no intervening nodes are skipped even when moved out of order,
247     * a stack (see class TableStack) is created on first encounter of
248     * a forwarding node during a traversal, to maintain its place if
249     * later processing the current table. The need for these
250     * save/restore mechanics is relatively rare, but when one
251     * forwarding node is encountered, typically many more will be.
252     * So Traversers use a simple caching scheme to avoid creating so
253     * many new TableStack nodes. (Thanks to Peter Levart for
254     * suggesting use of a stack here.)
255 dl 1.1 *
256     * The traversal scheme also applies to partial traversals of
257     * ranges of bins (via an alternate Traverser constructor)
258     * to support partitioned aggregate operations. Also, read-only
259     * operations give up if ever forwarded to a null table, which
260     * provides support for shutdown-style clearing, which is also not
261     * currently implemented.
262     *
263     * Lazy table initialization minimizes footprint until first use,
264     * and also avoids resizings when the first operation is from a
265     * putAll, constructor with map argument, or deserialization.
266     * These cases attempt to override the initial capacity settings,
267     * but harmlessly fail to take effect in cases of races.
268     *
269     * The element count is maintained using a specialization of
270     * LongAdder. We need to incorporate a specialization rather than
271     * just use a LongAdder in order to access implicit
272     * contention-sensing that leads to creation of multiple
273     * CounterCells. The counter mechanics avoid contention on
274     * updates but can encounter cache thrashing if read too
275     * frequently during concurrent access. To avoid reading so often,
276     * resizing under contention is attempted only upon adding to a
277     * bin already holding two or more nodes. Under uniform hash
278     * distributions, the probability of this occurring at threshold
279     * is around 13%, meaning that only about 1 in 8 puts check
280 dl 1.20 * threshold (and after resizing, many fewer do so).
281     *
282     * TreeBins use a special form of comparison for search and
283     * related operations (which is the main reason we cannot use
284     * existing collections such as TreeMaps). TreeBins contain
285     * Comparable elements, but may contain others, as well as
286 dl 1.30 * elements that are Comparable but not necessarily Comparable for
287     * the same T, so we cannot invoke compareTo among them. To handle
288     * this, the tree is ordered primarily by hash value, then by
289     * Comparable.compareTo order if applicable. On lookup at a node,
290     * if elements are not comparable or compare as 0 then both left
291     * and right children may need to be searched in the case of tied
292     * hash values. (This corresponds to the full list search that
293     * would be necessary if all elements were non-Comparable and had
294     * tied hashes.) On insertion, to keep a total ordering (or as
295     * close as is required here) across rebalancings, we compare
296     * classes and identityHashCodes as tie-breakers. The red-black
297     * balancing code is updated from pre-jdk-collections
298 dl 1.20 * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
299     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
300     * Algorithms" (CLR).
301     *
302     * TreeBins also require an additional locking mechanism. While
303     * list traversal is always possible by readers even during
304 jsr166 1.28 * updates, tree traversal is not, mainly because of tree-rotations
305 dl 1.20 * that may change the root node and/or its linkages. TreeBins
306     * include a simple read-write lock mechanism parasitic on the
307     * main bin-synchronization strategy: Structural adjustments
308     * associated with an insertion or removal are already bin-locked
309     * (and so cannot conflict with other writers) but must wait for
310     * ongoing readers to finish. Since there can be only one such
311     * waiter, we use a simple scheme using a single "waiter" field to
312     * block writers. However, readers need never block. If the root
313     * lock is held, they proceed along the slow traversal path (via
314     * next-pointers) until the lock becomes available or the list is
315     * exhausted, whichever comes first. These cases are not fast, but
316     * maximize aggregate expected throughput.
317 dl 1.1 *
318     * Maintaining API and serialization compatibility with previous
319     * versions of this class introduces several oddities. Mainly: We
320     * leave untouched but unused constructor arguments refering to
321     * concurrencyLevel. We accept a loadFactor constructor argument,
322     * but apply it only to initial table capacity (which is the only
323     * time that we can guarantee to honor it.) We also declare an
324     * unused "Segment" class that is instantiated in minimal form
325     * only when serializing.
326 dl 1.20 *
327 dl 1.35 * Also, solely for compatibility with previous versions of this
328     * class, it extends AbstractMap, even though all of its methods
329     * are overridden, so it is just useless baggage.
330     *
331 dl 1.20 * This file is organized to make things a little easier to follow
332     * while reading than they might otherwise: First the main static
333     * declarations and utilities, then fields, then main public
334     * methods (with a few factorings of multiple public methods into
335     * internal ones), then sizing methods, trees, traversers, and
336     * bulk operations.
337 dl 1.1 */
338    
339 dl 1.35
340 dl 1.1 /* ---------------- Constants -------------- */
341    
342     /**
343     * The largest possible table capacity. This value must be
344     * exactly 1<<30 to stay within Java array allocation and indexing
345     * bounds for power of two table sizes, and is further required
346     * because the top two bits of 32bit hash fields are used for
347     * control purposes.
348     */
349     private static final int MAXIMUM_CAPACITY = 1 << 30;
350    
351     /**
352     * The default initial table capacity. Must be a power of 2
353     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
354     */
355     private static final int DEFAULT_CAPACITY = 16;
356    
357     /**
358     * The largest possible (non-power of two) array size.
359     * Needed by toArray and related methods.
360     */
361     static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
362    
363     /**
364     * The default concurrency level for this table. Unused but
365     * defined for compatibility with previous versions of this class.
366     */
367     private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
368    
369     /**
370     * The load factor for this table. Overrides of this value in
371     * constructors affect only the initial table capacity. The
372     * actual floating point value isn't normally used -- it is
373     * simpler to use expressions such as {@code n - (n >>> 2)} for
374     * the associated resizing threshold.
375     */
376     private static final float LOAD_FACTOR = 0.75f;
377    
378     /**
379     * The bin count threshold for using a tree rather than list for a
380 dl 1.20 * bin. Bins are converted to trees when adding an element to a
381     * bin with at least this many nodes. The value must be greater
382     * than 2, and should be at least 8 to mesh with assumptions in
383     * tree removal about conversion back to plain bins upon
384     * shrinkage.
385     */
386     static final int TREEIFY_THRESHOLD = 8;
387    
388     /**
389     * The bin count threshold for untreeifying a (split) bin during a
390     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
391     * most 6 to mesh with shrinkage detection under removal.
392 dl 1.1 */
393 dl 1.20 static final int UNTREEIFY_THRESHOLD = 6;
394    
395     /**
396     * The smallest table capacity for which bins may be treeified.
397     * (Otherwise the table is resized if too many nodes in a bin.)
398     * The value should be at least 4 * TREEIFY_THRESHOLD to avoid
399     * conflicts between resizing and treeification thresholds.
400     */
401     static final int MIN_TREEIFY_CAPACITY = 64;
402 dl 1.1
403     /**
404     * Minimum number of rebinnings per transfer step. Ranges are
405     * subdivided to allow multiple resizer threads. This value
406     * serves as a lower bound to avoid resizers encountering
407     * excessive memory contention. The value should be at least
408     * DEFAULT_CAPACITY.
409     */
410     private static final int MIN_TRANSFER_STRIDE = 16;
411    
412     /*
413     * Encodings for Node hash fields. See above for explanation.
414     */
415 dl 1.20 static final int MOVED = 0x8fffffff; // (-1) hash for forwarding nodes
416 jsr166 1.28 static final int TREEBIN = 0x80000000; // hash for roots of trees
417 dl 1.20 static final int RESERVED = 0x80000001; // hash for transient reservations
418 dl 1.1 static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
419    
420     /** Number of CPUS, to place bounds on some sizings */
421     static final int NCPU = Runtime.getRuntime().availableProcessors();
422    
423 dl 1.20 /** For serialization compatibility. */
424     private static final ObjectStreamField[] serialPersistentFields = {
425     new ObjectStreamField("segments", Segment[].class),
426     new ObjectStreamField("segmentMask", Integer.TYPE),
427     new ObjectStreamField("segmentShift", Integer.TYPE)
428     };
429    
430     /* ---------------- Nodes -------------- */
431    
432     /**
433     * Key-value entry. This class is never exported out as a
434     * user-mutable Map.Entry (i.e., one supporting setValue; see
435     * MapEntry below), but can be used for read-only traversals used
436 jsr166 1.28 * in bulk tasks. Subclasses of Node with a negative hash field
437 dl 1.20 * are special, and contain null keys and values (but are never
438     * exported). Otherwise, keys and vals are never null.
439     */
440     static class Node<K,V> implements Map.Entry<K,V> {
441     final int hash;
442     final K key;
443     volatile V val;
444     Node<K,V> next;
445    
446     Node(int hash, K key, V val, Node<K,V> next) {
447     this.hash = hash;
448     this.key = key;
449     this.val = val;
450     this.next = next;
451     }
452    
453     public final K getKey() { return key; }
454     public final V getValue() { return val; }
455     public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
456     public final String toString(){ return key + "=" + val; }
457     public final V setValue(V value) {
458     throw new UnsupportedOperationException();
459     }
460 dl 1.1
461 dl 1.20 public final boolean equals(Object o) {
462     Object k, v, u; Map.Entry<?,?> e;
463     return ((o instanceof Map.Entry) &&
464     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
465     (v = e.getValue()) != null &&
466     (k == key || k.equals(key)) &&
467     (v == (u = val) || v.equals(u)));
468     }
469 dl 1.1
470 dl 1.20 /**
471     * Virtualized support for map.get(); overridden in subclasses.
472     */
473     Node<K,V> find(int h, Object k) {
474     Node<K,V> e = this;
475     if (k != null) {
476     do {
477     K ek;
478     if (e.hash == h &&
479     ((ek = e.key) == k || (ek != null && k.equals(ek))))
480     return e;
481     } while ((e = e.next) != null);
482     }
483     return null;
484     }
485 dl 1.1 }
486    
487 dl 1.20 /* ---------------- Static utilities -------------- */
488    
489 dl 1.1 /**
490 dl 1.20 * Spreads (XORs) higher bits of hash to lower and also forces top
491     * bit to 0. Because the table uses power-of-two masking, sets of
492     * hashes that vary only in bits above the current mask will
493     * always collide. (Among known examples are sets of Float keys
494     * holding consecutive whole numbers in small tables.) So we
495     * apply a transform that spreads the impact of higher bits
496     * downward. There is a tradeoff between speed, utility, and
497     * quality of bit-spreading. Because many common sets of hashes
498     * are already reasonably distributed (so don't benefit from
499     * spreading), and because we use trees to handle large sets of
500     * collisions in bins, we just XOR some shifted bits in the
501     * cheapest possible way to reduce systematic lossage, as well as
502     * to incorporate impact of the highest bits that would otherwise
503     * never be used in index calculations because of table bounds.
504 dl 1.1 */
505 dl 1.20 static final int spread(int h) {
506     return (h ^ (h >>> 16)) & HASH_BITS;
507 dl 1.1 }
508    
509     /**
510 dl 1.20 * Returns a power of two table size for the given desired capacity.
511     * See Hackers Delight, sec 3.2
512 dl 1.1 */
513 dl 1.20 private static final int tableSizeFor(int c) {
514     int n = c - 1;
515     n |= n >>> 1;
516     n |= n >>> 2;
517     n |= n >>> 4;
518     n |= n >>> 8;
519     n |= n >>> 16;
520     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
521     }
522 dl 1.1
523     /**
524 dl 1.20 * Returns x's Class if it is of the form "class C implements
525     * Comparable<C>", else null.
526 dl 1.1 */
527 dl 1.20 static Class<?> comparableClassFor(Object x) {
528     if (x instanceof Comparable) {
529     Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
530     if ((c = x.getClass()) == String.class) // bypass checks
531     return c;
532     if ((ts = c.getGenericInterfaces()) != null) {
533     for (int i = 0; i < ts.length; ++i) {
534     if (((t = ts[i]) instanceof ParameterizedType) &&
535     ((p = (ParameterizedType)t).getRawType() ==
536     Comparable.class) &&
537     (as = p.getActualTypeArguments()) != null &&
538     as.length == 1 && as[0] == c) // type arg is c
539     return c;
540     }
541     }
542     }
543     return null;
544     }
545 dl 1.1
546     /**
547 dl 1.20 * Returns k.compareTo(x) if x matches kc (k's screened comparable
548     * class), else 0.
549 dl 1.1 */
550 dl 1.20 @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
551     static int compareComparables(Class<?> kc, Object k, Object x) {
552     return (x == null || x.getClass() != kc ? 0 :
553     ((Comparable)k).compareTo(x));
554     }
555    
556     /* ---------------- Table element access -------------- */
557    
558     /*
559     * Volatile access methods are used for table elements as well as
560     * elements of in-progress next table while resizing. All uses of
561     * the tab arguments must be null checked by callers. All callers
562     * also paranoically precheck that tab's length is not zero (or an
563     * equivalent check), thus ensuring that any index argument taking
564     * the form of a hash value anded with (length - 1) is a valid
565     * index. Note that, to be correct wrt arbitrary concurrency
566     * errors by users, these checks must operate on local variables,
567     * which accounts for some odd-looking inline assignments below.
568     * Note that calls to setTabAt always occur within locked regions,
569     * and so do not need full volatile semantics, but still require
570     * ordering to maintain concurrent readability.
571     */
572    
573     @SuppressWarnings("unchecked")
574     static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
575     return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
576     }
577    
578     static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
579     Node<K,V> c, Node<K,V> v) {
580     return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
581     }
582    
583     static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
584     U.putOrderedObject(tab, ((long)i << ASHIFT) + ABASE, v);
585     }
586 dl 1.1
587     /* ---------------- Fields -------------- */
588    
589     /**
590     * The array of bins. Lazily initialized upon first insertion.
591     * Size is always a power of two. Accessed directly by iterators.
592     */
593 dl 1.20 transient volatile Node<K,V>[] table;
594 dl 1.1
595     /**
596     * The next table to use; non-null only while resizing.
597     */
598 dl 1.20 private transient volatile Node<K,V>[] nextTable;
599 dl 1.1
600     /**
601     * Base counter value, used mainly when there is no contention,
602     * but also as a fallback during table initialization
603     * races. Updated via CAS.
604     */
605     private transient volatile long baseCount;
606    
607     /**
608     * Table initialization and resizing control. When negative, the
609     * table is being initialized or resized: -1 for initialization,
610     * else -(1 + the number of active resizing threads). Otherwise,
611     * when table is null, holds the initial table size to use upon
612     * creation, or 0 for default. After initialization, holds the
613     * next element count value upon which to resize the table.
614     */
615     private transient volatile int sizeCtl;
616    
617     /**
618     * The next table index (plus one) to split while resizing.
619     */
620     private transient volatile int transferIndex;
621    
622     /**
623 dl 1.20 * Spinlock (locked via CAS) used when resizing and/or creating CounterCells.
624 dl 1.1 */
625 dl 1.20 private transient volatile int cellsBusy;
626 dl 1.1
627     /**
628     * Table of counter cells. When non-null, size is a power of 2.
629     */
630     private transient volatile CounterCell[] counterCells;
631    
632     // views
633     private transient KeySetView<K,V> keySet;
634     private transient ValuesView<K,V> values;
635     private transient EntrySetView<K,V> entrySet;
636    
637    
638 dl 1.20 /* ---------------- Public operations -------------- */
639 dl 1.1
640 dl 1.20 /**
641     * Creates a new, empty map with the default initial table size (16).
642     */
643     public ConcurrentHashMap() {
644 dl 1.1 }
645    
646 dl 1.20 /**
647     * Creates a new, empty map with an initial table size
648     * accommodating the specified number of elements without the need
649     * to dynamically resize.
650     *
651     * @param initialCapacity The implementation performs internal
652     * sizing to accommodate this many elements.
653     * @throws IllegalArgumentException if the initial capacity of
654     * elements is negative
655     */
656     public ConcurrentHashMap(int initialCapacity) {
657     if (initialCapacity < 0)
658     throw new IllegalArgumentException();
659     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
660     MAXIMUM_CAPACITY :
661     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
662     this.sizeCtl = cap;
663 dl 1.1 }
664    
665 dl 1.20 /**
666     * Creates a new map with the same mappings as the given map.
667     *
668     * @param m the map
669     */
670     public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
671     this.sizeCtl = DEFAULT_CAPACITY;
672     putAll(m);
673 dl 1.1 }
674    
675 dl 1.20 /**
676     * Creates a new, empty map with an initial table size based on
677     * the given number of elements ({@code initialCapacity}) and
678     * initial table density ({@code loadFactor}).
679     *
680     * @param initialCapacity the initial capacity. The implementation
681     * performs internal sizing to accommodate this many elements,
682     * given the specified load factor.
683     * @param loadFactor the load factor (table density) for
684     * establishing the initial table size
685     * @throws IllegalArgumentException if the initial capacity of
686     * elements is negative or the load factor is nonpositive
687     *
688     * @since 1.6
689     */
690     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
691     this(initialCapacity, loadFactor, 1);
692     }
693 dl 1.1
694     /**
695 dl 1.20 * Creates a new, empty map with an initial table size based on
696     * the given number of elements ({@code initialCapacity}), table
697     * density ({@code loadFactor}), and number of concurrently
698     * updating threads ({@code concurrencyLevel}).
699     *
700     * @param initialCapacity the initial capacity. The implementation
701     * performs internal sizing to accommodate this many elements,
702     * given the specified load factor.
703     * @param loadFactor the load factor (table density) for
704     * establishing the initial table size
705     * @param concurrencyLevel the estimated number of concurrently
706     * updating threads. The implementation may use this value as
707     * a sizing hint.
708     * @throws IllegalArgumentException if the initial capacity is
709     * negative or the load factor or concurrencyLevel are
710     * nonpositive
711 dl 1.1 */
712 dl 1.20 public ConcurrentHashMap(int initialCapacity,
713     float loadFactor, int concurrencyLevel) {
714     if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
715     throw new IllegalArgumentException();
716     if (initialCapacity < concurrencyLevel) // Use at least as many bins
717     initialCapacity = concurrencyLevel; // as estimated threads
718     long size = (long)(1.0 + (long)initialCapacity / loadFactor);
719     int cap = (size >= (long)MAXIMUM_CAPACITY) ?
720     MAXIMUM_CAPACITY : tableSizeFor((int)size);
721     this.sizeCtl = cap;
722 dl 1.1 }
723    
724 dl 1.20 // Original (since JDK1.2) Map methods
725 dl 1.1
726     /**
727 dl 1.20 * {@inheritDoc}
728 dl 1.1 */
729 dl 1.20 public int size() {
730     long n = sumCount();
731     return ((n < 0L) ? 0 :
732     (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
733     (int)n);
734     }
735 dl 1.1
736 dl 1.20 /**
737     * {@inheritDoc}
738     */
739     public boolean isEmpty() {
740     return sumCount() <= 0L; // ignore transient negative values
741 dl 1.1 }
742    
743     /**
744 dl 1.20 * Returns the value to which the specified key is mapped,
745     * or {@code null} if this map contains no mapping for the key.
746     *
747     * <p>More formally, if this map contains a mapping from a key
748     * {@code k} to a value {@code v} such that {@code key.equals(k)},
749     * then this method returns {@code v}; otherwise it returns
750     * {@code null}. (There can be at most one such mapping.)
751 dl 1.1 *
752 dl 1.20 * @throws NullPointerException if the specified key is null
753     */
754     public V get(Object key) {
755     Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
756     int h = spread(key.hashCode());
757     if ((tab = table) != null && (n = tab.length) > 0 &&
758     (e = tabAt(tab, (n - 1) & h)) != null) {
759     if ((eh = e.hash) == h) {
760     if ((ek = e.key) == key || (ek != null && key.equals(ek)))
761     return e.val;
762     }
763     else if (eh < 0)
764     return (p = e.find(h, key)) != null ? p.val : null;
765     while ((e = e.next) != null) {
766     if (e.hash == h &&
767     ((ek = e.key) == key || (ek != null && key.equals(ek))))
768     return e.val;
769 dl 1.1 }
770     }
771 dl 1.20 return null;
772     }
773 dl 1.1
774 dl 1.20 /**
775     * Tests if the specified object is a key in this table.
776     *
777     * @param key possible key
778     * @return {@code true} if and only if the specified object
779     * is a key in this table, as determined by the
780     * {@code equals} method; {@code false} otherwise
781     * @throws NullPointerException if the specified key is null
782     */
783     public boolean containsKey(Object key) {
784     return get(key) != null;
785     }
786 dl 1.1
787 dl 1.20 /**
788     * Returns {@code true} if this map maps one or more keys to the
789     * specified value. Note: This method may require a full traversal
790     * of the map, and is much slower than method {@code containsKey}.
791     *
792     * @param value value whose presence in this map is to be tested
793     * @return {@code true} if this map maps one or more keys to the
794     * specified value
795     * @throws NullPointerException if the specified value is null
796     */
797     public boolean containsValue(Object value) {
798     if (value == null)
799     throw new NullPointerException();
800     Node<K,V>[] t;
801     if ((t = table) != null) {
802     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
803     for (Node<K,V> p; (p = it.advance()) != null; ) {
804     V v;
805     if ((v = p.val) == value || (v != null && value.equals(v)))
806     return true;
807 dl 1.1 }
808     }
809 dl 1.20 return false;
810     }
811 dl 1.1
812 dl 1.20 /**
813     * Maps the specified key to the specified value in this table.
814     * Neither the key nor the value can be null.
815     *
816     * <p>The value can be retrieved by calling the {@code get} method
817     * with a key that is equal to the original key.
818     *
819     * @param key key with which the specified value is to be associated
820     * @param value value to be associated with the specified key
821     * @return the previous value associated with {@code key}, or
822     * {@code null} if there was no mapping for {@code key}
823     * @throws NullPointerException if the specified key or value is null
824     */
825     public V put(K key, V value) {
826     return putVal(key, value, false);
827     }
828 dl 1.1
829 dl 1.20 /** Implementation for put and putIfAbsent */
830     final V putVal(K key, V value, boolean onlyIfAbsent) {
831     if (key == null || value == null) throw new NullPointerException();
832     int hash = spread(key.hashCode());
833     int binCount = 0;
834     for (Node<K,V>[] tab = table;;) {
835     Node<K,V> f; int n, i, fh;
836     if (tab == null || (n = tab.length) == 0)
837     tab = initTable();
838     else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
839     if (casTabAt(tab, i, null,
840     new Node<K,V>(hash, key, value, null)))
841     break; // no lock when adding to empty bin
842 dl 1.1 }
843 dl 1.20 else if ((fh = f.hash) == MOVED)
844     tab = helpTransfer(tab, f);
845 dl 1.1 else {
846 dl 1.20 V oldVal = null;
847     synchronized (f) {
848     if (tabAt(tab, i) == f) {
849     if (fh >= 0) {
850     binCount = 1;
851     for (Node<K,V> e = f;; ++binCount) {
852     K ek;
853     if (e.hash == hash &&
854     ((ek = e.key) == key ||
855     (ek != null && key.equals(ek)))) {
856     oldVal = e.val;
857     if (!onlyIfAbsent)
858     e.val = value;
859     break;
860 dl 1.1 }
861 dl 1.20 Node<K,V> pred = e;
862     if ((e = e.next) == null) {
863     pred.next = new Node<K,V>(hash, key,
864     value, null);
865     break;
866 dl 1.1 }
867     }
868     }
869 dl 1.20 else if (f instanceof TreeBin) {
870     Node<K,V> p;
871     binCount = 2;
872     if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
873     value)) != null) {
874     oldVal = p.val;
875     if (!onlyIfAbsent)
876     p.val = value;
877 dl 1.1 }
878     }
879     }
880     }
881 dl 1.20 if (binCount != 0) {
882     if (binCount >= TREEIFY_THRESHOLD)
883     treeifyBin(tab, i);
884     if (oldVal != null)
885     return oldVal;
886     break;
887     }
888 dl 1.1 }
889     }
890 dl 1.20 addCount(1L, binCount);
891     return null;
892 dl 1.1 }
893    
894     /**
895 dl 1.20 * Copies all of the mappings from the specified map to this one.
896     * These mappings replace any mappings that this map had for any of the
897     * keys currently in the specified map.
898     *
899     * @param m mappings to be stored in this map
900     */
901     public void putAll(Map<? extends K, ? extends V> m) {
902     tryPresize(m.size());
903     for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
904     putVal(e.getKey(), e.getValue(), false);
905 dl 1.1 }
906    
907     /**
908 dl 1.20 * Removes the key (and its corresponding value) from this map.
909     * This method does nothing if the key is not in the map.
910     *
911     * @param key the key that needs to be removed
912     * @return the previous value associated with {@code key}, or
913     * {@code null} if there was no mapping for {@code key}
914     * @throws NullPointerException if the specified key is null
915     */
916     public V remove(Object key) {
917     return replaceNode(key, null, null);
918 dl 1.1 }
919    
920     /**
921     * Implementation for the four public remove/replace methods:
922     * Replaces node value with v, conditional upon match of cv if
923     * non-null. If resulting value is null, delete.
924     */
925 dl 1.20 final V replaceNode(Object key, V value, Object cv) {
926     int hash = spread(key.hashCode());
927     for (Node<K,V>[] tab = table;;) {
928     Node<K,V> f; int n, i, fh;
929     if (tab == null || (n = tab.length) == 0 ||
930     (f = tabAt(tab, i = (n - 1) & hash)) == null)
931 dl 1.1 break;
932 dl 1.20 else if ((fh = f.hash) == MOVED)
933     tab = helpTransfer(tab, f);
934 dl 1.1 else {
935 dl 1.20 V oldVal = null;
936 dl 1.1 boolean validated = false;
937     synchronized (f) {
938     if (tabAt(tab, i) == f) {
939 dl 1.20 if (fh >= 0) {
940     validated = true;
941     for (Node<K,V> e = f, pred = null;;) {
942     K ek;
943     if (e.hash == hash &&
944     ((ek = e.key) == key ||
945     (ek != null && key.equals(ek)))) {
946     V ev = e.val;
947     if (cv == null || cv == ev ||
948     (ev != null && cv.equals(ev))) {
949     oldVal = ev;
950     if (value != null)
951     e.val = value;
952     else if (pred != null)
953     pred.next = e.next;
954 dl 1.1 else
955 dl 1.20 setTabAt(tab, i, e.next);
956 dl 1.1 }
957 dl 1.20 break;
958     }
959     pred = e;
960     if ((e = e.next) == null)
961     break;
962     }
963     }
964     else if (f instanceof TreeBin) {
965     validated = true;
966     TreeBin<K,V> t = (TreeBin<K,V>)f;
967     TreeNode<K,V> r, p;
968     if ((r = t.root) != null &&
969     (p = r.findTreeNode(hash, key, null)) != null) {
970     V pv = p.val;
971     if (cv == null || cv == pv ||
972     (pv != null && cv.equals(pv))) {
973     oldVal = pv;
974     if (value != null)
975     p.val = value;
976     else if (t.removeTreeNode(p))
977     setTabAt(tab, i, untreeify(t.first));
978 dl 1.1 }
979     }
980     }
981     }
982     }
983     if (validated) {
984 dl 1.20 if (oldVal != null) {
985     if (value == null)
986     addCount(-1L, -1);
987     return oldVal;
988 dl 1.1 }
989     break;
990     }
991     }
992     }
993     return null;
994     }
995    
996     /**
997 dl 1.20 * Removes all of the mappings from this map.
998 dl 1.1 */
999 dl 1.20 public void clear() {
1000 dl 1.1 long delta = 0L; // negative number of deletions
1001     int i = 0;
1002 dl 1.20 Node<K,V>[] tab = table;
1003 dl 1.1 while (tab != null && i < tab.length) {
1004 dl 1.20 int fh;
1005     Node<K,V> f = tabAt(tab, i);
1006 dl 1.1 if (f == null)
1007     ++i;
1008 dl 1.20 else if ((fh = f.hash) == MOVED) {
1009     tab = helpTransfer(tab, f);
1010     i = 0; // restart
1011 dl 1.1 }
1012     else {
1013     synchronized (f) {
1014     if (tabAt(tab, i) == f) {
1015 dl 1.20 Node<K,V> p = (fh >= 0 ? f :
1016     (f instanceof TreeBin) ?
1017     ((TreeBin<K,V>)f).first : null);
1018     while (p != null) {
1019     --delta;
1020     p = p.next;
1021 dl 1.1 }
1022 dl 1.20 setTabAt(tab, i++, null);
1023 dl 1.1 }
1024     }
1025     }
1026     }
1027     if (delta != 0L)
1028     addCount(delta, -1);
1029     }
1030    
1031     /**
1032 dl 1.20 * Returns a {@link Set} view of the keys contained in this map.
1033     * The set is backed by the map, so changes to the map are
1034     * reflected in the set, and vice-versa. The set supports element
1035     * removal, which removes the corresponding mapping from this map,
1036     * via the {@code Iterator.remove}, {@code Set.remove},
1037     * {@code removeAll}, {@code retainAll}, and {@code clear}
1038     * operations. It does not support the {@code add} or
1039     * {@code addAll} operations.
1040     *
1041     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1042     * that will never throw {@link ConcurrentModificationException},
1043     * and guarantees to traverse elements as they existed upon
1044     * construction of the iterator, and may (but is not guaranteed to)
1045     * reflect any modifications subsequent to construction.
1046     *
1047     * @return the set view
1048 dl 1.1 */
1049 dl 1.20 public KeySetView<K,V> keySet() {
1050     KeySetView<K,V> ks;
1051     return (ks = keySet) != null ? ks : (keySet = new KeySetView<K,V>(this, null));
1052 dl 1.1 }
1053    
1054     /**
1055 dl 1.20 * Returns a {@link Collection} view of the values contained in this map.
1056     * The collection is backed by the map, so changes to the map are
1057     * reflected in the collection, and vice-versa. The collection
1058     * supports element removal, which removes the corresponding
1059     * mapping from this map, via the {@code Iterator.remove},
1060     * {@code Collection.remove}, {@code removeAll},
1061     * {@code retainAll}, and {@code clear} operations. It does not
1062     * support the {@code add} or {@code addAll} operations.
1063 dl 1.1 *
1064 dl 1.20 * <p>The view's {@code iterator} is a "weakly consistent" iterator
1065     * that will never throw {@link ConcurrentModificationException},
1066     * and guarantees to traverse elements as they existed upon
1067     * construction of the iterator, and may (but is not guaranteed to)
1068     * reflect any modifications subsequent to construction.
1069 dl 1.1 *
1070 dl 1.20 * @return the collection view
1071 dl 1.1 */
1072 dl 1.20 public Collection<V> values() {
1073     ValuesView<K,V> vs;
1074     return (vs = values) != null ? vs : (values = new ValuesView<K,V>(this));
1075 dl 1.1 }
1076    
1077     /**
1078 dl 1.20 * Returns a {@link Set} view of the mappings contained in this map.
1079     * The set is backed by the map, so changes to the map are
1080     * reflected in the set, and vice-versa. The set supports element
1081     * removal, which removes the corresponding mapping from the map,
1082     * via the {@code Iterator.remove}, {@code Set.remove},
1083     * {@code removeAll}, {@code retainAll}, and {@code clear}
1084     * operations.
1085     *
1086     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1087     * that will never throw {@link ConcurrentModificationException},
1088     * and guarantees to traverse elements as they existed upon
1089     * construction of the iterator, and may (but is not guaranteed to)
1090     * reflect any modifications subsequent to construction.
1091 dl 1.1 *
1092 dl 1.20 * @return the set view
1093 dl 1.1 */
1094 dl 1.20 public Set<Map.Entry<K,V>> entrySet() {
1095     EntrySetView<K,V> es;
1096     return (es = entrySet) != null ? es : (entrySet = new EntrySetView<K,V>(this));
1097 dl 1.1 }
1098    
1099     /**
1100     * Returns the hash code value for this {@link Map}, i.e.,
1101     * the sum of, for each key-value pair in the map,
1102     * {@code key.hashCode() ^ value.hashCode()}.
1103     *
1104     * @return the hash code value for this map
1105     */
1106     public int hashCode() {
1107     int h = 0;
1108 dl 1.20 Node<K,V>[] t;
1109     if ((t = table) != null) {
1110     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1111     for (Node<K,V> p; (p = it.advance()) != null; )
1112     h += p.key.hashCode() ^ p.val.hashCode();
1113 dl 1.1 }
1114     return h;
1115     }
1116    
1117     /**
1118     * Returns a string representation of this map. The string
1119     * representation consists of a list of key-value mappings (in no
1120     * particular order) enclosed in braces ("{@code {}}"). Adjacent
1121     * mappings are separated by the characters {@code ", "} (comma
1122     * and space). Each key-value mapping is rendered as the key
1123     * followed by an equals sign ("{@code =}") followed by the
1124     * associated value.
1125     *
1126     * @return a string representation of this map
1127     */
1128     public String toString() {
1129 dl 1.20 Node<K,V>[] t;
1130     int f = (t = table) == null ? 0 : t.length;
1131     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1132 dl 1.1 StringBuilder sb = new StringBuilder();
1133     sb.append('{');
1134 dl 1.20 Node<K,V> p;
1135     if ((p = it.advance()) != null) {
1136 dl 1.1 for (;;) {
1137 dl 1.20 K k = p.key;
1138     V v = p.val;
1139 dl 1.1 sb.append(k == this ? "(this Map)" : k);
1140     sb.append('=');
1141     sb.append(v == this ? "(this Map)" : v);
1142 dl 1.20 if ((p = it.advance()) == null)
1143 dl 1.1 break;
1144     sb.append(',').append(' ');
1145     }
1146     }
1147     return sb.append('}').toString();
1148     }
1149    
1150     /**
1151     * Compares the specified object with this map for equality.
1152     * Returns {@code true} if the given object is a map with the same
1153     * mappings as this map. This operation may return misleading
1154     * results if either map is concurrently modified during execution
1155     * of this method.
1156     *
1157     * @param o object to be compared for equality with this map
1158     * @return {@code true} if the specified object is equal to this map
1159     */
1160     public boolean equals(Object o) {
1161     if (o != this) {
1162     if (!(o instanceof Map))
1163     return false;
1164     Map<?,?> m = (Map<?,?>) o;
1165 dl 1.20 Node<K,V>[] t;
1166     int f = (t = table) == null ? 0 : t.length;
1167     Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
1168     for (Node<K,V> p; (p = it.advance()) != null; ) {
1169     V val = p.val;
1170     Object v = m.get(p.key);
1171 dl 1.1 if (v == null || (v != val && !v.equals(val)))
1172     return false;
1173     }
1174     for (Map.Entry<?,?> e : m.entrySet()) {
1175     Object mk, mv, v;
1176     if ((mk = e.getKey()) == null ||
1177     (mv = e.getValue()) == null ||
1178 dl 1.20 (v = get(mk)) == null ||
1179 dl 1.1 (mv != v && !mv.equals(v)))
1180     return false;
1181     }
1182     }
1183     return true;
1184     }
1185    
1186     /**
1187     * Stripped-down version of helper class used in previous version,
1188     * declared for the sake of serialization compatibility
1189     */
1190 dl 1.20 static class Segment<K,V> extends ReentrantLock implements Serializable {
1191 dl 1.1 private static final long serialVersionUID = 2249069246763182397L;
1192     final float loadFactor;
1193     Segment(float lf) { this.loadFactor = lf; }
1194     }
1195    
1196     /**
1197     * Saves the state of the {@code ConcurrentHashMap} instance to a
1198     * stream (i.e., serializes it).
1199     * @param s the stream
1200     * @serialData
1201     * the key (Object) and value (Object)
1202     * for each key-value mapping, followed by a null pair.
1203     * The key-value mappings are emitted in no particular order.
1204     */
1205 dl 1.20 private void writeObject(java.io.ObjectOutputStream s)
1206 dl 1.1 throws java.io.IOException {
1207 dl 1.20 // For serialization compatibility
1208     // Emulate segment calculation from previous version of this class
1209     int sshift = 0;
1210     int ssize = 1;
1211     while (ssize < DEFAULT_CONCURRENCY_LEVEL) {
1212     ++sshift;
1213     ssize <<= 1;
1214     }
1215     int segmentShift = 32 - sshift;
1216     int segmentMask = ssize - 1;
1217     @SuppressWarnings("unchecked") Segment<K,V>[] segments = (Segment<K,V>[])
1218     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
1219     for (int i = 0; i < segments.length; ++i)
1220     segments[i] = new Segment<K,V>(LOAD_FACTOR);
1221     s.putFields().put("segments", segments);
1222     s.putFields().put("segmentShift", segmentShift);
1223     s.putFields().put("segmentMask", segmentMask);
1224     s.writeFields();
1225    
1226     Node<K,V>[] t;
1227     if ((t = table) != null) {
1228     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1229     for (Node<K,V> p; (p = it.advance()) != null; ) {
1230     s.writeObject(p.key);
1231     s.writeObject(p.val);
1232     }
1233 dl 1.1 }
1234     s.writeObject(null);
1235     s.writeObject(null);
1236     segments = null; // throw away
1237     }
1238    
1239     /**
1240     * Reconstitutes the instance from a stream (that is, deserializes it).
1241     * @param s the stream
1242     */
1243 dl 1.20 private void readObject(java.io.ObjectInputStream s)
1244 dl 1.1 throws java.io.IOException, ClassNotFoundException {
1245 dl 1.20 /*
1246     * To improve performance in typical cases, we create nodes
1247     * while reading, then place in table once size is known.
1248     * However, we must also validate uniqueness and deal with
1249     * overpopulated bins while doing so, which requires
1250     * specialized versions of putVal mechanics.
1251     */
1252     sizeCtl = -1; // force exclusion for table construction
1253 dl 1.1 s.defaultReadObject();
1254     long size = 0L;
1255 dl 1.20 Node<K,V> p = null;
1256 dl 1.1 for (;;) {
1257 dl 1.20 @SuppressWarnings("unchecked") K k = (K) s.readObject();
1258     @SuppressWarnings("unchecked") V v = (V) s.readObject();
1259 dl 1.1 if (k != null && v != null) {
1260 dl 1.20 p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1261 dl 1.1 ++size;
1262     }
1263     else
1264     break;
1265     }
1266 dl 1.20 if (size == 0L)
1267     sizeCtl = 0;
1268     else {
1269 dl 1.1 int n;
1270     if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1271     n = MAXIMUM_CAPACITY;
1272     else {
1273     int sz = (int)size;
1274     n = tableSizeFor(sz + (sz >>> 1) + 1);
1275     }
1276 jsr166 1.33 @SuppressWarnings("unchecked")
1277     Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1278 dl 1.20 int mask = n - 1;
1279     long added = 0L;
1280     while (p != null) {
1281     boolean insertAtFront;
1282     Node<K,V> next = p.next, first;
1283     int h = p.hash, j = h & mask;
1284     if ((first = tabAt(tab, j)) == null)
1285     insertAtFront = true;
1286     else {
1287     K k = p.key;
1288     if (first.hash < 0) {
1289     TreeBin<K,V> t = (TreeBin<K,V>)first;
1290     if (t.putTreeVal(h, k, p.val) == null)
1291     ++added;
1292     insertAtFront = false;
1293 dl 1.1 }
1294 dl 1.20 else {
1295     int binCount = 0;
1296     insertAtFront = true;
1297     Node<K,V> q; K qk;
1298     for (q = first; q != null; q = q.next) {
1299     if (q.hash == h &&
1300     ((qk = q.key) == k ||
1301     (qk != null && k.equals(qk)))) {
1302     insertAtFront = false;
1303 dl 1.1 break;
1304     }
1305 dl 1.20 ++binCount;
1306     }
1307     if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1308     insertAtFront = false;
1309     ++added;
1310     p.next = first;
1311     TreeNode<K,V> hd = null, tl = null;
1312     for (q = p; q != null; q = q.next) {
1313     TreeNode<K,V> t = new TreeNode<K,V>
1314     (q.hash, q.key, q.val, null, null);
1315     if ((t.prev = tl) == null)
1316     hd = t;
1317     else
1318     tl.next = t;
1319     tl = t;
1320     }
1321     setTabAt(tab, j, new TreeBin<K,V>(hd));
1322 dl 1.1 }
1323     }
1324     }
1325 dl 1.20 if (insertAtFront) {
1326     ++added;
1327     p.next = first;
1328     setTabAt(tab, j, p);
1329 dl 1.1 }
1330 dl 1.20 p = next;
1331 dl 1.1 }
1332 dl 1.20 table = tab;
1333     sizeCtl = n - (n >>> 2);
1334     baseCount = added;
1335 dl 1.1 }
1336     }
1337    
1338 dl 1.20 // ConcurrentMap methods
1339 dl 1.1
1340     /**
1341 dl 1.20 * {@inheritDoc}
1342 dl 1.1 *
1343 dl 1.20 * @return the previous value associated with the specified key,
1344     * or {@code null} if there was no mapping for the key
1345     * @throws NullPointerException if the specified key or value is null
1346 dl 1.1 */
1347 dl 1.20 public V putIfAbsent(K key, V value) {
1348     return putVal(key, value, true);
1349 dl 1.1 }
1350    
1351     /**
1352 dl 1.20 * {@inheritDoc}
1353 dl 1.1 *
1354 dl 1.20 * @throws NullPointerException if the specified key is null
1355 dl 1.1 */
1356 dl 1.20 public boolean remove(Object key, Object value) {
1357     if (key == null)
1358     throw new NullPointerException();
1359     return value != null && replaceNode(key, null, value) != null;
1360 dl 1.1 }
1361    
1362     /**
1363 dl 1.20 * {@inheritDoc}
1364 dl 1.1 *
1365 dl 1.20 * @throws NullPointerException if any of the arguments are null
1366 dl 1.1 */
1367 dl 1.20 public boolean replace(K key, V oldValue, V newValue) {
1368     if (key == null || oldValue == null || newValue == null)
1369     throw new NullPointerException();
1370     return replaceNode(key, newValue, oldValue) != null;
1371 dl 1.1 }
1372    
1373     /**
1374 dl 1.20 * {@inheritDoc}
1375 dl 1.1 *
1376 dl 1.20 * @return the previous value associated with the specified key,
1377     * or {@code null} if there was no mapping for the key
1378     * @throws NullPointerException if the specified key or value is null
1379 dl 1.1 */
1380 dl 1.20 public V replace(K key, V value) {
1381     if (key == null || value == null)
1382     throw new NullPointerException();
1383     return replaceNode(key, value, null);
1384 dl 1.1 }
1385 dl 1.20 // Hashtable legacy methods
1386 dl 1.1
1387     /**
1388 dl 1.20 * Legacy method testing if some key maps into the specified value
1389 jsr166 1.34 * in this table.
1390     *
1391     * @deprecated This method is identical in functionality to
1392 dl 1.20 * {@link #containsValue(Object)}, and exists solely to ensure
1393     * full compatibility with class {@link java.util.Hashtable},
1394     * which supported this method prior to introduction of the
1395     * Java Collections framework.
1396 dl 1.1 *
1397 dl 1.20 * @param value a value to search for
1398     * @return {@code true} if and only if some key maps to the
1399     * {@code value} argument in this table as
1400     * determined by the {@code equals} method;
1401     * {@code false} otherwise
1402     * @throws NullPointerException if the specified value is null
1403 dl 1.1 */
1404 dl 1.20 @Deprecated public boolean contains(Object value) {
1405     return containsValue(value);
1406 dl 1.1 }
1407    
1408     /**
1409 dl 1.20 * Returns an enumeration of the keys in this table.
1410 dl 1.1 *
1411 dl 1.20 * @return an enumeration of the keys in this table
1412     * @see #keySet()
1413 dl 1.1 */
1414 dl 1.20 public Enumeration<K> keys() {
1415     Node<K,V>[] t;
1416     int f = (t = table) == null ? 0 : t.length;
1417     return new KeyIterator<K,V>(t, f, 0, f, this);
1418 dl 1.1 }
1419    
1420     /**
1421 dl 1.20 * Returns an enumeration of the values in this table.
1422 dl 1.1 *
1423 dl 1.20 * @return an enumeration of the values in this table
1424     * @see #values()
1425 dl 1.1 */
1426 dl 1.20 public Enumeration<V> elements() {
1427     Node<K,V>[] t;
1428     int f = (t = table) == null ? 0 : t.length;
1429     return new ValueIterator<K,V>(t, f, 0, f, this);
1430 dl 1.1 }
1431    
1432 dl 1.20 // ConcurrentHashMap-only methods
1433    
1434 dl 1.1 /**
1435 dl 1.20 * Returns the number of mappings. This method should be used
1436     * instead of {@link #size} because a ConcurrentHashMap may
1437     * contain more mappings than can be represented as an int. The
1438     * value returned is an estimate; the actual count may differ if
1439     * there are concurrent insertions or removals.
1440 dl 1.1 *
1441 dl 1.20 * @return the number of mappings
1442     * @since 1.8
1443 dl 1.1 */
1444 dl 1.20 public long mappingCount() {
1445     long n = sumCount();
1446     return (n < 0L) ? 0L : n; // ignore transient negative values
1447 dl 1.1 }
1448    
1449     /**
1450 dl 1.20 * Creates a new {@link Set} backed by a ConcurrentHashMap
1451     * from the given type to {@code Boolean.TRUE}.
1452 dl 1.1 *
1453 jsr166 1.31 * @param <K> the element type of the returned set
1454 dl 1.20 * @return the new set
1455     * @since 1.8
1456 dl 1.1 */
1457 dl 1.20 public static <K> KeySetView<K,Boolean> newKeySet() {
1458     return new KeySetView<K,Boolean>
1459     (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
1460 dl 1.1 }
1461    
1462     /**
1463 dl 1.20 * Creates a new {@link Set} backed by a ConcurrentHashMap
1464     * from the given type to {@code Boolean.TRUE}.
1465 dl 1.1 *
1466 dl 1.20 * @param initialCapacity The implementation performs internal
1467     * sizing to accommodate this many elements.
1468 jsr166 1.31 * @param <K> the element type of the returned set
1469 jsr166 1.29 * @return the new set
1470 dl 1.20 * @throws IllegalArgumentException if the initial capacity of
1471     * elements is negative
1472     * @since 1.8
1473 dl 1.1 */
1474 dl 1.20 public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
1475     return new KeySetView<K,Boolean>
1476     (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
1477 dl 1.1 }
1478    
1479     /**
1480 dl 1.20 * Returns a {@link Set} view of the keys in this map, using the
1481     * given common mapped value for any additions (i.e., {@link
1482     * Collection#add} and {@link Collection#addAll(Collection)}).
1483     * This is of course only appropriate if it is acceptable to use
1484     * the same value for all additions from this view.
1485 dl 1.1 *
1486 dl 1.20 * @param mappedValue the mapped value to use for any additions
1487     * @return the set view
1488     * @throws NullPointerException if the mappedValue is null
1489 dl 1.1 */
1490 dl 1.20 public KeySetView<K,V> keySet(V mappedValue) {
1491     if (mappedValue == null)
1492     throw new NullPointerException();
1493     return new KeySetView<K,V>(this, mappedValue);
1494 dl 1.1 }
1495    
1496 dl 1.20 /* ---------------- Special Nodes -------------- */
1497    
1498 dl 1.1 /**
1499 dl 1.20 * A node inserted at head of bins during transfer operations.
1500 dl 1.1 */
1501 dl 1.20 static final class ForwardingNode<K,V> extends Node<K,V> {
1502     final Node<K,V>[] nextTable;
1503     ForwardingNode(Node<K,V>[] tab) {
1504     super(MOVED, null, null, null);
1505     this.nextTable = tab;
1506     }
1507    
1508     Node<K,V> find(int h, Object k) {
1509     Node<K,V> e; int n;
1510     Node<K,V>[] tab = nextTable;
1511     if (k != null && tab != null && (n = tab.length) > 0 &&
1512     (e = tabAt(tab, (n - 1) & h)) != null) {
1513     do {
1514     int eh; K ek;
1515     if ((eh = e.hash) == h &&
1516     ((ek = e.key) == k || (ek != null && k.equals(ek))))
1517     return e;
1518     if (eh < 0)
1519     return e.find(h, k);
1520     } while ((e = e.next) != null);
1521     }
1522     return null;
1523     }
1524 dl 1.1 }
1525    
1526     /**
1527 dl 1.20 * A place-holder node used in computeIfAbsent and compute
1528 dl 1.1 */
1529 dl 1.20 static final class ReservationNode<K,V> extends Node<K,V> {
1530     ReservationNode() {
1531     super(RESERVED, null, null, null);
1532     }
1533    
1534     Node<K,V> find(int h, Object k) {
1535     return null;
1536     }
1537 dl 1.1 }
1538    
1539 dl 1.20 /* ---------------- Table Initialization and Resizing -------------- */
1540    
1541 dl 1.1 /**
1542 dl 1.20 * Initializes table, using the size recorded in sizeCtl.
1543 dl 1.1 */
1544 dl 1.20 private final Node<K,V>[] initTable() {
1545     Node<K,V>[] tab; int sc;
1546     while ((tab = table) == null || tab.length == 0) {
1547     if ((sc = sizeCtl) < 0)
1548     Thread.yield(); // lost initialization race; just spin
1549     else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1550     try {
1551     if ((tab = table) == null || tab.length == 0) {
1552     int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1553 jsr166 1.33 @SuppressWarnings("unchecked")
1554     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
1555 dl 1.20 table = tab = nt;
1556     sc = n - (n >>> 2);
1557     }
1558     } finally {
1559     sizeCtl = sc;
1560     }
1561     break;
1562     }
1563     }
1564     return tab;
1565 dl 1.1 }
1566    
1567     /**
1568 dl 1.20 * Adds to count, and if table is too small and not already
1569     * resizing, initiates transfer. If already resizing, helps
1570     * perform transfer if work is available. Rechecks occupancy
1571     * after a transfer to see if another resize is already needed
1572     * because resizings are lagging additions.
1573 dl 1.1 *
1574 dl 1.20 * @param x the count to add
1575     * @param check if <0, don't check resize, if <= 1 only check if uncontended
1576 dl 1.1 */
1577 dl 1.20 private final void addCount(long x, int check) {
1578     CounterCell[] as; long b, s;
1579     if ((as = counterCells) != null ||
1580     !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1581     CounterHashCode hc; CounterCell a; long v; int m;
1582     boolean uncontended = true;
1583     if ((hc = threadCounterHashCode.get()) == null ||
1584     as == null || (m = as.length - 1) < 0 ||
1585     (a = as[m & hc.code]) == null ||
1586     !(uncontended =
1587     U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1588     fullAddCount(x, hc, uncontended);
1589     return;
1590     }
1591     if (check <= 1)
1592     return;
1593     s = sumCount();
1594     }
1595     if (check >= 0) {
1596     Node<K,V>[] tab, nt; int sc;
1597     while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1598     tab.length < MAXIMUM_CAPACITY) {
1599     if (sc < 0) {
1600 dl 1.35 if (sc == -1 || transferIndex <= 0 ||
1601 dl 1.20 (nt = nextTable) == null)
1602     break;
1603     if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
1604     transfer(tab, nt);
1605     }
1606     else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
1607     transfer(tab, null);
1608     s = sumCount();
1609     }
1610     }
1611 dl 1.1 }
1612    
1613     /**
1614 dl 1.20 * Helps transfer if a resize is in progress.
1615 dl 1.1 */
1616 dl 1.20 final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
1617     Node<K,V>[] nextTab; int sc;
1618     if ((f instanceof ForwardingNode) &&
1619     (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
1620 dl 1.35 while (transferIndex > 0 && nextTab == nextTable &&
1621     (sc = sizeCtl) < -1) {
1622     if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1)) {
1623     transfer(tab, nextTab);
1624     break;
1625     }
1626     }
1627 dl 1.20 return nextTab;
1628     }
1629     return table;
1630 dl 1.1 }
1631    
1632     /**
1633 dl 1.20 * Tries to presize table to accommodate the given number of elements.
1634 dl 1.1 *
1635 dl 1.20 * @param size number of elements (doesn't need to be perfectly accurate)
1636 dl 1.1 */
1637 dl 1.20 private final void tryPresize(int size) {
1638     int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1639     tableSizeFor(size + (size >>> 1) + 1);
1640     int sc;
1641     while ((sc = sizeCtl) >= 0) {
1642     Node<K,V>[] tab = table; int n;
1643     if (tab == null || (n = tab.length) == 0) {
1644     n = (sc > c) ? sc : c;
1645     if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1646     try {
1647     if (table == tab) {
1648 jsr166 1.33 @SuppressWarnings("unchecked")
1649     Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
1650 dl 1.20 table = nt;
1651     sc = n - (n >>> 2);
1652     }
1653     } finally {
1654     sizeCtl = sc;
1655     }
1656     }
1657     }
1658     else if (c <= sc || n >= MAXIMUM_CAPACITY)
1659     break;
1660     else if (tab == table &&
1661     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1662     transfer(tab, null);
1663     }
1664 dl 1.1 }
1665    
1666     /**
1667 dl 1.20 * Moves and/or copies the nodes in each bin to new table. See
1668     * above for explanation.
1669 dl 1.1 */
1670 dl 1.20 private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
1671     int n = tab.length, stride;
1672     if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1673     stride = MIN_TRANSFER_STRIDE; // subdivide range
1674     if (nextTab == null) { // initiating
1675     try {
1676 jsr166 1.33 @SuppressWarnings("unchecked")
1677 dl 1.35 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
1678 dl 1.20 nextTab = nt;
1679     } catch (Throwable ex) { // try to cope with OOME
1680     sizeCtl = Integer.MAX_VALUE;
1681     return;
1682     }
1683     nextTable = nextTab;
1684     transferIndex = n;
1685     }
1686     int nextn = nextTab.length;
1687     ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
1688     boolean advance = true;
1689 dl 1.35 boolean finishing = false; // to ensure sweep before committing nextTab
1690 dl 1.20 for (int i = 0, bound = 0;;) {
1691 dl 1.35 Node<K,V> f; int fh;
1692 dl 1.20 while (advance) {
1693 dl 1.35 int nextIndex, nextBound;
1694     if (--i >= bound || finishing)
1695 dl 1.20 advance = false;
1696 dl 1.35 else if ((nextIndex = transferIndex) <= 0) {
1697 dl 1.20 i = -1;
1698     advance = false;
1699     }
1700     else if (U.compareAndSwapInt
1701     (this, TRANSFERINDEX, nextIndex,
1702     nextBound = (nextIndex > stride ?
1703     nextIndex - stride : 0))) {
1704     bound = nextBound;
1705     i = nextIndex - 1;
1706     advance = false;
1707     }
1708     }
1709     if (i < 0 || i >= n || i + n >= nextn) {
1710 dl 1.35 int sc;
1711     if (finishing) {
1712     nextTable = null;
1713     table = nextTab;
1714     sizeCtl = (n << 1) - (n >>> 1);
1715     return;
1716     }
1717     if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
1718     if (sc != -1)
1719 dl 1.20 return;
1720 dl 1.35 finishing = advance = true;
1721     i = n; // recheck before commit
1722 dl 1.20 }
1723     }
1724 dl 1.35 else if ((f = tabAt(tab, i)) == null)
1725     advance = casTabAt(tab, i, null, fwd);
1726 dl 1.20 else if ((fh = f.hash) == MOVED)
1727     advance = true; // already processed
1728     else {
1729     synchronized (f) {
1730     if (tabAt(tab, i) == f) {
1731     Node<K,V> ln, hn;
1732     if (fh >= 0) {
1733     int runBit = fh & n;
1734     Node<K,V> lastRun = f;
1735     for (Node<K,V> p = f.next; p != null; p = p.next) {
1736     int b = p.hash & n;
1737     if (b != runBit) {
1738     runBit = b;
1739     lastRun = p;
1740     }
1741     }
1742     if (runBit == 0) {
1743     ln = lastRun;
1744     hn = null;
1745     }
1746     else {
1747     hn = lastRun;
1748     ln = null;
1749     }
1750     for (Node<K,V> p = f; p != lastRun; p = p.next) {
1751     int ph = p.hash; K pk = p.key; V pv = p.val;
1752     if ((ph & n) == 0)
1753     ln = new Node<K,V>(ph, pk, pv, ln);
1754     else
1755     hn = new Node<K,V>(ph, pk, pv, hn);
1756     }
1757 dl 1.35 setTabAt(nextTab, i, ln);
1758     setTabAt(nextTab, i + n, hn);
1759     setTabAt(tab, i, fwd);
1760     advance = true;
1761 dl 1.20 }
1762     else if (f instanceof TreeBin) {
1763     TreeBin<K,V> t = (TreeBin<K,V>)f;
1764     TreeNode<K,V> lo = null, loTail = null;
1765     TreeNode<K,V> hi = null, hiTail = null;
1766     int lc = 0, hc = 0;
1767     for (Node<K,V> e = t.first; e != null; e = e.next) {
1768     int h = e.hash;
1769     TreeNode<K,V> p = new TreeNode<K,V>
1770     (h, e.key, e.val, null, null);
1771     if ((h & n) == 0) {
1772     if ((p.prev = loTail) == null)
1773     lo = p;
1774     else
1775     loTail.next = p;
1776     loTail = p;
1777     ++lc;
1778     }
1779     else {
1780     if ((p.prev = hiTail) == null)
1781     hi = p;
1782     else
1783     hiTail.next = p;
1784     hiTail = p;
1785     ++hc;
1786     }
1787     }
1788 jsr166 1.24 ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
1789     (hc != 0) ? new TreeBin<K,V>(lo) : t;
1790     hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
1791     (lc != 0) ? new TreeBin<K,V>(hi) : t;
1792 dl 1.35 setTabAt(nextTab, i, ln);
1793     setTabAt(nextTab, i + n, hn);
1794     setTabAt(tab, i, fwd);
1795     advance = true;
1796 dl 1.20 }
1797     }
1798     }
1799     }
1800     }
1801 dl 1.1 }
1802    
1803 dl 1.20 /* ---------------- Conversion from/to TreeBins -------------- */
1804 dl 1.1
1805     /**
1806 dl 1.20 * Replaces all linked nodes in bin at given index unless table is
1807     * too small, in which case resizes instead.
1808 dl 1.1 */
1809 dl 1.20 private final void treeifyBin(Node<K,V>[] tab, int index) {
1810     Node<K,V> b; int n, sc;
1811     if (tab != null) {
1812     if ((n = tab.length) < MIN_TREEIFY_CAPACITY) {
1813     if (tab == table && (sc = sizeCtl) >= 0 &&
1814     U.compareAndSwapInt(this, SIZECTL, sc, -2))
1815     transfer(tab, null);
1816     }
1817     else if ((b = tabAt(tab, index)) != null) {
1818     synchronized (b) {
1819     if (tabAt(tab, index) == b) {
1820     TreeNode<K,V> hd = null, tl = null;
1821     for (Node<K,V> e = b; e != null; e = e.next) {
1822     TreeNode<K,V> p =
1823     new TreeNode<K,V>(e.hash, e.key, e.val,
1824     null, null);
1825     if ((p.prev = tl) == null)
1826     hd = p;
1827     else
1828     tl.next = p;
1829     tl = p;
1830     }
1831     setTabAt(tab, index, new TreeBin<K,V>(hd));
1832     }
1833     }
1834     }
1835     }
1836 dl 1.1 }
1837    
1838     /**
1839 jsr166 1.25 * Returns a list on non-TreeNodes replacing those in given list.
1840 dl 1.1 */
1841 dl 1.20 static <K,V> Node<K,V> untreeify(Node<K,V> b) {
1842     Node<K,V> hd = null, tl = null;
1843     for (Node<K,V> q = b; q != null; q = q.next) {
1844     Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
1845     if (tl == null)
1846     hd = p;
1847     else
1848     tl.next = p;
1849     tl = p;
1850     }
1851     return hd;
1852 dl 1.1 }
1853    
1854 dl 1.20 /* ---------------- TreeNodes -------------- */
1855 dl 1.1
1856     /**
1857 dl 1.20 * Nodes for use in TreeBins
1858 dl 1.1 */
1859 dl 1.20 static final class TreeNode<K,V> extends Node<K,V> {
1860     TreeNode<K,V> parent; // red-black tree links
1861     TreeNode<K,V> left;
1862     TreeNode<K,V> right;
1863     TreeNode<K,V> prev; // needed to unlink next upon deletion
1864     boolean red;
1865 dl 1.1
1866 dl 1.20 TreeNode(int hash, K key, V val, Node<K,V> next,
1867     TreeNode<K,V> parent) {
1868     super(hash, key, val, next);
1869     this.parent = parent;
1870     }
1871 dl 1.1
1872 dl 1.20 Node<K,V> find(int h, Object k) {
1873     return findTreeNode(h, k, null);
1874     }
1875 dl 1.1
1876 dl 1.20 /**
1877     * Returns the TreeNode (or null if not found) for the given key
1878     * starting at given root.
1879     */
1880     final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
1881     if (k != null) {
1882     TreeNode<K,V> p = this;
1883     do {
1884     int ph, dir; K pk; TreeNode<K,V> q;
1885     TreeNode<K,V> pl = p.left, pr = p.right;
1886     if ((ph = p.hash) > h)
1887     p = pl;
1888     else if (ph < h)
1889     p = pr;
1890     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
1891     return p;
1892 dl 1.30 else if (pl == null)
1893     p = pr;
1894     else if (pr == null)
1895     p = pl;
1896 jsr166 1.21 else if ((kc != null ||
1897 dl 1.20 (kc = comparableClassFor(k)) != null) &&
1898     (dir = compareComparables(kc, k, pk)) != 0)
1899     p = (dir < 0) ? pl : pr;
1900 dl 1.30 else if ((q = pr.findTreeNode(h, k, kc)) != null)
1901     return q;
1902     else
1903 dl 1.20 p = pl;
1904     } while (p != null);
1905     }
1906     return null;
1907     }
1908 dl 1.1 }
1909    
1910 dl 1.30
1911 dl 1.20 /* ---------------- TreeBins -------------- */
1912 dl 1.1
1913     /**
1914 dl 1.20 * TreeNodes used at the heads of bins. TreeBins do not hold user
1915     * keys or values, but instead point to list of TreeNodes and
1916     * their root. They also maintain a parasitic read-write lock
1917     * forcing writers (who hold bin lock) to wait for readers (who do
1918     * not) to complete before tree restructuring operations.
1919     */
1920     static final class TreeBin<K,V> extends Node<K,V> {
1921     TreeNode<K,V> root;
1922     volatile TreeNode<K,V> first;
1923     volatile Thread waiter;
1924     volatile int lockState;
1925     // values for lockState
1926     static final int WRITER = 1; // set while holding write lock
1927     static final int WAITER = 2; // set when waiting for write lock
1928     static final int READER = 4; // increment value for setting read lock
1929    
1930     /**
1931 dl 1.30 * Tie-breaking utility for ordering insertions when equal
1932     * hashCodes and non-comparable. We don't require a total
1933     * order, just a consistent insertion rule to maintain
1934     * equivalence across rebalancings. Tie-breaking further than
1935     * necessary simplifies testing a bit.
1936     */
1937     static int tieBreakOrder(Object a, Object b) {
1938     int d;
1939     if (a == null || b == null ||
1940     (d = a.getClass().getName().
1941     compareTo(b.getClass().getName())) == 0)
1942     d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
1943     -1 : 1);
1944     return d;
1945     }
1946    
1947     /**
1948 dl 1.20 * Creates bin with initial set of nodes headed by b.
1949     */
1950     TreeBin(TreeNode<K,V> b) {
1951     super(TREEBIN, null, null, null);
1952     this.first = b;
1953     TreeNode<K,V> r = null;
1954     for (TreeNode<K,V> x = b, next; x != null; x = next) {
1955     next = (TreeNode<K,V>)x.next;
1956     x.left = x.right = null;
1957     if (r == null) {
1958     x.parent = null;
1959     x.red = false;
1960     r = x;
1961     }
1962     else {
1963 dl 1.30 K k = x.key;
1964     int h = x.hash;
1965 dl 1.20 Class<?> kc = null;
1966     for (TreeNode<K,V> p = r;;) {
1967     int dir, ph;
1968 dl 1.30 K pk = p.key;
1969     if ((ph = p.hash) > h)
1970 dl 1.20 dir = -1;
1971 dl 1.30 else if (ph < h)
1972 dl 1.20 dir = 1;
1973 dl 1.30 else if ((kc == null &&
1974     (kc = comparableClassFor(k)) == null) ||
1975     (dir = compareComparables(kc, k, pk)) == 0)
1976     dir = tieBreakOrder(k, pk);
1977     TreeNode<K,V> xp = p;
1978 dl 1.20 if ((p = (dir <= 0) ? p.left : p.right) == null) {
1979     x.parent = xp;
1980     if (dir <= 0)
1981     xp.left = x;
1982     else
1983     xp.right = x;
1984     r = balanceInsertion(r, x);
1985     break;
1986     }
1987     }
1988     }
1989     }
1990     this.root = r;
1991 dl 1.30 assert checkInvariants(root);
1992 dl 1.20 }
1993 dl 1.1
1994 dl 1.20 /**
1995 jsr166 1.25 * Acquires write lock for tree restructuring.
1996 dl 1.20 */
1997     private final void lockRoot() {
1998     if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
1999     contendedLock(); // offload to separate method
2000     }
2001 dl 1.1
2002 dl 1.20 /**
2003 jsr166 1.25 * Releases write lock for tree restructuring.
2004 dl 1.20 */
2005     private final void unlockRoot() {
2006     lockState = 0;
2007     }
2008 dl 1.1
2009 dl 1.20 /**
2010 jsr166 1.25 * Possibly blocks awaiting root lock.
2011 dl 1.20 */
2012     private final void contendedLock() {
2013     boolean waiting = false;
2014     for (int s;;) {
2015     if (((s = lockState) & WRITER) == 0) {
2016     if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2017     if (waiting)
2018     waiter = null;
2019     return;
2020     }
2021     }
2022 dl 1.32 else if ((s & WAITER) == 0) {
2023 dl 1.20 if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2024     waiting = true;
2025     waiter = Thread.currentThread();
2026     }
2027     }
2028     else if (waiting)
2029     LockSupport.park(this);
2030     }
2031     }
2032 dl 1.1
2033 dl 1.20 /**
2034     * Returns matching node or null if none. Tries to search
2035 jsr166 1.28 * using tree comparisons from root, but continues linear
2036 dl 1.20 * search when lock not available.
2037     */
2038     final Node<K,V> find(int h, Object k) {
2039     if (k != null) {
2040     for (Node<K,V> e = first; e != null; e = e.next) {
2041     int s; K ek;
2042     if (((s = lockState) & (WAITER|WRITER)) != 0) {
2043     if (e.hash == h &&
2044     ((ek = e.key) == k || (ek != null && k.equals(ek))))
2045     return e;
2046     }
2047     else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2048     s + READER)) {
2049     TreeNode<K,V> r, p;
2050     try {
2051     p = ((r = root) == null ? null :
2052     r.findTreeNode(h, k, null));
2053     } finally {
2054 jsr166 1.21
2055 dl 1.20 Thread w;
2056     int ls;
2057     do {} while (!U.compareAndSwapInt
2058     (this, LOCKSTATE,
2059     ls = lockState, ls - READER));
2060     if (ls == (READER|WAITER) && (w = waiter) != null)
2061     LockSupport.unpark(w);
2062     }
2063     return p;
2064     }
2065     }
2066     }
2067     return null;
2068     }
2069 dl 1.1
2070     /**
2071 dl 1.20 * Finds or adds a node.
2072     * @return null if added
2073 dl 1.1 */
2074 dl 1.30 /**
2075     * Finds or adds a node.
2076     * @return null if added
2077     */
2078 dl 1.20 final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2079     Class<?> kc = null;
2080 dl 1.30 boolean searched = false;
2081 dl 1.20 for (TreeNode<K,V> p = root;;) {
2082 dl 1.30 int dir, ph; K pk;
2083 dl 1.20 if (p == null) {
2084     first = root = new TreeNode<K,V>(h, k, v, null, null);
2085     break;
2086     }
2087     else if ((ph = p.hash) > h)
2088     dir = -1;
2089     else if (ph < h)
2090     dir = 1;
2091     else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2092     return p;
2093     else if ((kc == null &&
2094     (kc = comparableClassFor(k)) == null) ||
2095     (dir = compareComparables(kc, k, pk)) == 0) {
2096 dl 1.30 if (!searched) {
2097     TreeNode<K,V> q, ch;
2098     searched = true;
2099     if (((ch = p.left) != null &&
2100     (q = ch.findTreeNode(h, k, kc)) != null) ||
2101     ((ch = p.right) != null &&
2102     (q = ch.findTreeNode(h, k, kc)) != null))
2103     return q;
2104     }
2105     dir = tieBreakOrder(k, pk);
2106 dl 1.20 }
2107 dl 1.30
2108 dl 1.20 TreeNode<K,V> xp = p;
2109 dl 1.30 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2110 dl 1.20 TreeNode<K,V> x, f = first;
2111     first = x = new TreeNode<K,V>(h, k, v, f, xp);
2112     if (f != null)
2113     f.prev = x;
2114 dl 1.30 if (dir <= 0)
2115 dl 1.20 xp.left = x;
2116 dl 1.1 else
2117 dl 1.20 xp.right = x;
2118     if (!xp.red)
2119     x.red = true;
2120     else {
2121     lockRoot();
2122     try {
2123     root = balanceInsertion(root, x);
2124     } finally {
2125     unlockRoot();
2126     }
2127     }
2128     break;
2129 dl 1.1 }
2130     }
2131 dl 1.20 assert checkInvariants(root);
2132     return null;
2133 dl 1.1 }
2134    
2135 dl 1.20 /**
2136     * Removes the given node, that must be present before this
2137     * call. This is messier than typical red-black deletion code
2138     * because we cannot swap the contents of an interior node
2139     * with a leaf successor that is pinned by "next" pointers
2140     * that are accessible independently of lock. So instead we
2141     * swap the tree linkages.
2142     *
2143 jsr166 1.27 * @return true if now too small, so should be untreeified
2144 dl 1.20 */
2145     final boolean removeTreeNode(TreeNode<K,V> p) {
2146     TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2147     TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2148     TreeNode<K,V> r, rl;
2149     if (pred == null)
2150     first = next;
2151     else
2152     pred.next = next;
2153     if (next != null)
2154     next.prev = pred;
2155     if (first == null) {
2156     root = null;
2157     return true;
2158     }
2159     if ((r = root) == null || r.right == null || // too small
2160     (rl = r.left) == null || rl.left == null)
2161     return true;
2162     lockRoot();
2163     try {
2164     TreeNode<K,V> replacement;
2165     TreeNode<K,V> pl = p.left;
2166     TreeNode<K,V> pr = p.right;
2167     if (pl != null && pr != null) {
2168     TreeNode<K,V> s = pr, sl;
2169     while ((sl = s.left) != null) // find successor
2170     s = sl;
2171     boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2172     TreeNode<K,V> sr = s.right;
2173     TreeNode<K,V> pp = p.parent;
2174     if (s == pr) { // p was s's direct parent
2175     p.parent = s;
2176     s.right = p;
2177     }
2178     else {
2179     TreeNode<K,V> sp = s.parent;
2180     if ((p.parent = sp) != null) {
2181     if (s == sp.left)
2182     sp.left = p;
2183     else
2184     sp.right = p;
2185     }
2186     if ((s.right = pr) != null)
2187     pr.parent = s;
2188     }
2189     p.left = null;
2190     if ((p.right = sr) != null)
2191     sr.parent = p;
2192     if ((s.left = pl) != null)
2193     pl.parent = s;
2194     if ((s.parent = pp) == null)
2195     r = s;
2196     else if (p == pp.left)
2197     pp.left = s;
2198     else
2199     pp.right = s;
2200     if (sr != null)
2201     replacement = sr;
2202     else
2203     replacement = p;
2204     }
2205     else if (pl != null)
2206     replacement = pl;
2207     else if (pr != null)
2208     replacement = pr;
2209     else
2210     replacement = p;
2211     if (replacement != p) {
2212     TreeNode<K,V> pp = replacement.parent = p.parent;
2213     if (pp == null)
2214     r = replacement;
2215     else if (p == pp.left)
2216     pp.left = replacement;
2217 dl 1.1 else
2218 dl 1.20 pp.right = replacement;
2219     p.left = p.right = p.parent = null;
2220     }
2221    
2222     root = (p.red) ? r : balanceDeletion(r, replacement);
2223    
2224     if (p == replacement) { // detach pointers
2225     TreeNode<K,V> pp;
2226     if ((pp = p.parent) != null) {
2227     if (p == pp.left)
2228     pp.left = null;
2229     else if (p == pp.right)
2230     pp.right = null;
2231     p.parent = null;
2232     }
2233 dl 1.1 }
2234 dl 1.20 } finally {
2235     unlockRoot();
2236 dl 1.1 }
2237 dl 1.20 assert checkInvariants(root);
2238     return false;
2239 dl 1.1 }
2240    
2241 dl 1.20 /* ------------------------------------------------------------ */
2242     // Red-black tree methods, all adapted from CLR
2243    
2244     static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2245     TreeNode<K,V> p) {
2246     TreeNode<K,V> r, pp, rl;
2247     if (p != null && (r = p.right) != null) {
2248     if ((rl = p.right = r.left) != null)
2249     rl.parent = p;
2250     if ((pp = r.parent = p.parent) == null)
2251     (root = r).red = false;
2252     else if (pp.left == p)
2253     pp.left = r;
2254     else
2255     pp.right = r;
2256     r.left = p;
2257     p.parent = r;
2258     }
2259     return root;
2260 dl 1.1 }
2261    
2262 dl 1.20 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2263     TreeNode<K,V> p) {
2264     TreeNode<K,V> l, pp, lr;
2265     if (p != null && (l = p.left) != null) {
2266     if ((lr = p.left = l.right) != null)
2267     lr.parent = p;
2268     if ((pp = l.parent = p.parent) == null)
2269     (root = l).red = false;
2270     else if (pp.right == p)
2271     pp.right = l;
2272     else
2273     pp.left = l;
2274     l.right = p;
2275     p.parent = l;
2276 dl 1.1 }
2277 dl 1.20 return root;
2278 dl 1.1 }
2279    
2280 dl 1.20 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2281     TreeNode<K,V> x) {
2282     x.red = true;
2283     for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2284     if ((xp = x.parent) == null) {
2285     x.red = false;
2286     return x;
2287     }
2288     else if (!xp.red || (xpp = xp.parent) == null)
2289     return root;
2290     if (xp == (xppl = xpp.left)) {
2291     if ((xppr = xpp.right) != null && xppr.red) {
2292     xppr.red = false;
2293     xp.red = false;
2294     xpp.red = true;
2295     x = xpp;
2296     }
2297     else {
2298     if (x == xp.right) {
2299     root = rotateLeft(root, x = xp);
2300     xpp = (xp = x.parent) == null ? null : xp.parent;
2301     }
2302     if (xp != null) {
2303     xp.red = false;
2304     if (xpp != null) {
2305     xpp.red = true;
2306     root = rotateRight(root, xpp);
2307     }
2308     }
2309     }
2310 dl 1.1 }
2311 dl 1.20 else {
2312     if (xppl != null && xppl.red) {
2313     xppl.red = false;
2314     xp.red = false;
2315     xpp.red = true;
2316     x = xpp;
2317     }
2318     else {
2319     if (x == xp.left) {
2320     root = rotateRight(root, x = xp);
2321     xpp = (xp = x.parent) == null ? null : xp.parent;
2322     }
2323     if (xp != null) {
2324     xp.red = false;
2325     if (xpp != null) {
2326     xpp.red = true;
2327     root = rotateLeft(root, xpp);
2328     }
2329     }
2330     }
2331 dl 1.1 }
2332     }
2333     }
2334    
2335 dl 1.20 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2336     TreeNode<K,V> x) {
2337     for (TreeNode<K,V> xp, xpl, xpr;;) {
2338     if (x == null || x == root)
2339     return root;
2340     else if ((xp = x.parent) == null) {
2341     x.red = false;
2342     return x;
2343     }
2344     else if (x.red) {
2345     x.red = false;
2346     return root;
2347     }
2348     else if ((xpl = xp.left) == x) {
2349     if ((xpr = xp.right) != null && xpr.red) {
2350     xpr.red = false;
2351     xp.red = true;
2352     root = rotateLeft(root, xp);
2353     xpr = (xp = x.parent) == null ? null : xp.right;
2354     }
2355     if (xpr == null)
2356     x = xp;
2357     else {
2358     TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2359     if ((sr == null || !sr.red) &&
2360     (sl == null || !sl.red)) {
2361     xpr.red = true;
2362     x = xp;
2363     }
2364     else {
2365     if (sr == null || !sr.red) {
2366     if (sl != null)
2367     sl.red = false;
2368     xpr.red = true;
2369     root = rotateRight(root, xpr);
2370     xpr = (xp = x.parent) == null ?
2371     null : xp.right;
2372     }
2373     if (xpr != null) {
2374     xpr.red = (xp == null) ? false : xp.red;
2375     if ((sr = xpr.right) != null)
2376     sr.red = false;
2377     }
2378     if (xp != null) {
2379     xp.red = false;
2380     root = rotateLeft(root, xp);
2381     }
2382     x = root;
2383     }
2384     }
2385     }
2386     else { // symmetric
2387     if (xpl != null && xpl.red) {
2388     xpl.red = false;
2389     xp.red = true;
2390     root = rotateRight(root, xp);
2391     xpl = (xp = x.parent) == null ? null : xp.left;
2392     }
2393     if (xpl == null)
2394     x = xp;
2395     else {
2396     TreeNode<K,V> sl = xpl.left, sr = xpl.right;
2397     if ((sl == null || !sl.red) &&
2398     (sr == null || !sr.red)) {
2399     xpl.red = true;
2400     x = xp;
2401     }
2402     else {
2403     if (sl == null || !sl.red) {
2404     if (sr != null)
2405     sr.red = false;
2406     xpl.red = true;
2407     root = rotateLeft(root, xpl);
2408     xpl = (xp = x.parent) == null ?
2409     null : xp.left;
2410     }
2411     if (xpl != null) {
2412     xpl.red = (xp == null) ? false : xp.red;
2413     if ((sl = xpl.left) != null)
2414     sl.red = false;
2415     }
2416     if (xp != null) {
2417     xp.red = false;
2418     root = rotateRight(root, xp);
2419     }
2420     x = root;
2421     }
2422     }
2423 dl 1.1 }
2424     }
2425     }
2426 jsr166 1.21
2427 dl 1.1 /**
2428 dl 1.20 * Recursive invariant check
2429 dl 1.1 */
2430 dl 1.20 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
2431     TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
2432     tb = t.prev, tn = (TreeNode<K,V>)t.next;
2433     if (tb != null && tb.next != t)
2434     return false;
2435     if (tn != null && tn.prev != t)
2436     return false;
2437     if (tp != null && t != tp.left && t != tp.right)
2438     return false;
2439     if (tl != null && (tl.parent != t || tl.hash > t.hash))
2440     return false;
2441     if (tr != null && (tr.parent != t || tr.hash < t.hash))
2442     return false;
2443     if (t.red && tl != null && tl.red && tr != null && tr.red)
2444     return false;
2445     if (tl != null && !checkInvariants(tl))
2446     return false;
2447     if (tr != null && !checkInvariants(tr))
2448     return false;
2449     return true;
2450     }
2451 dl 1.1
2452 dl 1.20 private static final sun.misc.Unsafe U;
2453     private static final long LOCKSTATE;
2454     static {
2455     try {
2456     U = sun.misc.Unsafe.getUnsafe();
2457     Class<?> k = TreeBin.class;
2458     LOCKSTATE = U.objectFieldOffset
2459     (k.getDeclaredField("lockState"));
2460     } catch (Exception e) {
2461     throw new Error(e);
2462 dl 1.1 }
2463     }
2464     }
2465    
2466 dl 1.20 /* ----------------Table Traversal -------------- */
2467    
2468 dl 1.1 /**
2469 dl 1.35 * Records the table, its length, and current traversal index for a
2470     * traverser that must process a region of a forwarded table before
2471     * proceeding with current table.
2472     */
2473     static final class TableStack<K,V> {
2474     int length;
2475     int index;
2476     Node<K,V>[] tab;
2477     TableStack<K,V> next;
2478     }
2479    
2480     /**
2481 dl 1.20 * Encapsulates traversal for methods such as containsValue; also
2482 dl 1.35 * serves as a base class for other iterators and spliterators.
2483 dl 1.20 *
2484     * Method advance visits once each still-valid node that was
2485     * reachable upon iterator construction. It might miss some that
2486     * were added to a bin after the bin was visited, which is OK wrt
2487     * consistency guarantees. Maintaining this property in the face
2488     * of possible ongoing resizes requires a fair amount of
2489     * bookkeeping state that is difficult to optimize away amidst
2490     * volatile accesses. Even so, traversal maintains reasonable
2491     * throughput.
2492 dl 1.1 *
2493 dl 1.20 * Normally, iteration proceeds bin-by-bin traversing lists.
2494     * However, if the table has been resized, then all future steps
2495     * must traverse both the bin at the current index as well as at
2496     * (index + baseSize); and so on for further resizings. To
2497     * paranoically cope with potential sharing by users of iterators
2498     * across threads, iteration terminates if a bounds checks fails
2499     * for a table read.
2500 dl 1.1 */
2501 dl 1.20 static class Traverser<K,V> {
2502     Node<K,V>[] tab; // current table; updated if resized
2503     Node<K,V> next; // the next entry to use
2504 dl 1.35 TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
2505 dl 1.20 int index; // index of bin to use next
2506     int baseIndex; // current index of initial table
2507     int baseLimit; // index bound for initial table
2508     final int baseSize; // initial table size
2509    
2510     Traverser(Node<K,V>[] tab, int size, int index, int limit) {
2511     this.tab = tab;
2512     this.baseSize = size;
2513     this.baseIndex = this.index = index;
2514     this.baseLimit = limit;
2515     this.next = null;
2516     }
2517    
2518     /**
2519     * Advances if possible, returning next valid node, or null if none.
2520     */
2521     final Node<K,V> advance() {
2522     Node<K,V> e;
2523     if ((e = next) != null)
2524     e = e.next;
2525     for (;;) {
2526 dl 1.35 Node<K,V>[] t; int i, n; // must use locals in checks
2527 dl 1.20 if (e != null)
2528     return next = e;
2529     if (baseIndex >= baseLimit || (t = tab) == null ||
2530     (n = t.length) <= (i = index) || i < 0)
2531     return next = null;
2532 dl 1.35 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2533 dl 1.20 if (e instanceof ForwardingNode) {
2534     tab = ((ForwardingNode<K,V>)e).nextTable;
2535     e = null;
2536 dl 1.35 pushState(t, i, n);
2537 dl 1.20 continue;
2538 dl 1.1 }
2539 dl 1.20 else if (e instanceof TreeBin)
2540     e = ((TreeBin<K,V>)e).first;
2541     else
2542     e = null;
2543 dl 1.1 }
2544 dl 1.35 if (stack != null)
2545     recoverState(n);
2546     else if ((index = i + baseSize) >= n)
2547     index = ++baseIndex; // visit upper slots if present
2548     }
2549     }
2550    
2551     /**
2552     * Saves traversal state upon encountering a forwarding node.
2553     */
2554     private void pushState(Node<K,V>[] t, int i, int n) {
2555     TableStack<K,V> s = spare; // reuse if possible
2556     if (s != null)
2557     spare = s.next;
2558     else
2559     s = new TableStack<K,V>();
2560     s.tab = t;
2561     s.length = n;
2562     s.index = i;
2563     s.next = stack;
2564     stack = s;
2565     }
2566    
2567     /**
2568     * Possibly pops traversal state.
2569     *
2570     * @param n length of current table
2571     */
2572     private void recoverState(int n) {
2573     TableStack<K,V> s; int len;
2574     while ((s = stack) != null && (index += (len = s.length)) >= n) {
2575     n = len;
2576     index = s.index;
2577     tab = s.tab;
2578     s.tab = null;
2579     TableStack<K,V> next = s.next;
2580     s.next = spare; // save for reuse
2581     stack = next;
2582     spare = s;
2583 dl 1.1 }
2584 dl 1.35 if (s == null && (index += baseSize) >= n)
2585     index = ++baseIndex;
2586 dl 1.1 }
2587     }
2588    
2589     /**
2590 dl 1.20 * Base of key, value, and entry Iterators. Adds fields to
2591 jsr166 1.25 * Traverser to support iterator.remove.
2592 dl 1.1 */
2593 dl 1.20 static class BaseIterator<K,V> extends Traverser<K,V> {
2594     final ConcurrentHashMap<K,V> map;
2595     Node<K,V> lastReturned;
2596     BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
2597     ConcurrentHashMap<K,V> map) {
2598     super(tab, size, index, limit);
2599     this.map = map;
2600     advance();
2601 dl 1.1 }
2602    
2603 dl 1.20 public final boolean hasNext() { return next != null; }
2604     public final boolean hasMoreElements() { return next != null; }
2605 dl 1.1
2606 dl 1.20 public final void remove() {
2607     Node<K,V> p;
2608     if ((p = lastReturned) == null)
2609     throw new IllegalStateException();
2610     lastReturned = null;
2611     map.replaceNode(p.key, null, null);
2612 dl 1.1 }
2613     }
2614    
2615 dl 1.20 static final class KeyIterator<K,V> extends BaseIterator<K,V>
2616     implements Iterator<K>, Enumeration<K> {
2617     KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
2618     ConcurrentHashMap<K,V> map) {
2619     super(tab, index, size, limit, map);
2620     }
2621 dl 1.1
2622 dl 1.20 public final K next() {
2623     Node<K,V> p;
2624     if ((p = next) == null)
2625     throw new NoSuchElementException();
2626     K k = p.key;
2627     lastReturned = p;
2628     advance();
2629     return k;
2630 dl 1.1 }
2631    
2632 dl 1.20 public final K nextElement() { return next(); }
2633     }
2634 dl 1.1
2635 dl 1.20 static final class ValueIterator<K,V> extends BaseIterator<K,V>
2636     implements Iterator<V>, Enumeration<V> {
2637     ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
2638     ConcurrentHashMap<K,V> map) {
2639     super(tab, index, size, limit, map);
2640 dl 1.1 }
2641    
2642 dl 1.20 public final V next() {
2643     Node<K,V> p;
2644     if ((p = next) == null)
2645     throw new NoSuchElementException();
2646     V v = p.val;
2647     lastReturned = p;
2648     advance();
2649     return v;
2650 dl 1.1 }
2651    
2652 dl 1.20 public final V nextElement() { return next(); }
2653     }
2654 dl 1.1
2655 dl 1.20 static final class EntryIterator<K,V> extends BaseIterator<K,V>
2656     implements Iterator<Map.Entry<K,V>> {
2657     EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
2658     ConcurrentHashMap<K,V> map) {
2659     super(tab, index, size, limit, map);
2660 dl 1.1 }
2661    
2662 dl 1.20 public final Map.Entry<K,V> next() {
2663     Node<K,V> p;
2664     if ((p = next) == null)
2665     throw new NoSuchElementException();
2666     K k = p.key;
2667     V v = p.val;
2668     lastReturned = p;
2669     advance();
2670     return new MapEntry<K,V>(k, v, map);
2671 dl 1.1 }
2672 dl 1.20 }
2673 dl 1.1
2674 dl 1.20 /**
2675     * Exported Entry for EntryIterator
2676     */
2677     static final class MapEntry<K,V> implements Map.Entry<K,V> {
2678     final K key; // non-null
2679     V val; // non-null
2680     final ConcurrentHashMap<K,V> map;
2681     MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
2682     this.key = key;
2683     this.val = val;
2684     this.map = map;
2685 dl 1.1 }
2686 dl 1.20 public K getKey() { return key; }
2687     public V getValue() { return val; }
2688     public int hashCode() { return key.hashCode() ^ val.hashCode(); }
2689     public String toString() { return key + "=" + val; }
2690 dl 1.1
2691 dl 1.20 public boolean equals(Object o) {
2692     Object k, v; Map.Entry<?,?> e;
2693     return ((o instanceof Map.Entry) &&
2694     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2695     (v = e.getValue()) != null &&
2696     (k == key || k.equals(key)) &&
2697     (v == val || v.equals(val)));
2698 dl 1.1 }
2699    
2700     /**
2701 dl 1.20 * Sets our entry's value and writes through to the map. The
2702     * value to return is somewhat arbitrary here. Since we do not
2703     * necessarily track asynchronous changes, the most recent
2704     * "previous" value could be different from what we return (or
2705     * could even have been removed, in which case the put will
2706     * re-establish). We do not and cannot guarantee more.
2707 dl 1.1 */
2708 dl 1.20 public V setValue(V value) {
2709     if (value == null) throw new NullPointerException();
2710     V v = val;
2711     val = value;
2712     map.put(key, value);
2713     return v;
2714 dl 1.1 }
2715 dl 1.20 }
2716 dl 1.1
2717 dl 1.20 /* ----------------Views -------------- */
2718 dl 1.1
2719 dl 1.20 /**
2720     * Base class for views.
2721     */
2722     abstract static class CollectionView<K,V,E>
2723     implements Collection<E>, java.io.Serializable {
2724     private static final long serialVersionUID = 7249069246763182397L;
2725     final ConcurrentHashMap<K,V> map;
2726     CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
2727 dl 1.1
2728     /**
2729 dl 1.20 * Returns the map backing this view.
2730 dl 1.1 *
2731 dl 1.20 * @return the map backing this view
2732 dl 1.1 */
2733 dl 1.20 public ConcurrentHashMap<K,V> getMap() { return map; }
2734 dl 1.1
2735     /**
2736 dl 1.20 * Removes all of the elements from this view, by removing all
2737     * the mappings from the map backing this view.
2738 dl 1.1 */
2739 dl 1.20 public final void clear() { map.clear(); }
2740     public final int size() { return map.size(); }
2741     public final boolean isEmpty() { return map.isEmpty(); }
2742 dl 1.1
2743 dl 1.20 // implementations below rely on concrete classes supplying these
2744     // abstract methods
2745 dl 1.1 /**
2746 dl 1.20 * Returns a "weakly consistent" iterator that will never
2747     * throw {@link ConcurrentModificationException}, and
2748     * guarantees to traverse elements as they existed upon
2749     * construction of the iterator, and may (but is not
2750     * guaranteed to) reflect any modifications subsequent to
2751     * construction.
2752 dl 1.1 */
2753 dl 1.20 public abstract Iterator<E> iterator();
2754     public abstract boolean contains(Object o);
2755     public abstract boolean remove(Object o);
2756 dl 1.1
2757 dl 1.20 private static final String oomeMsg = "Required array size too large";
2758 dl 1.1
2759 dl 1.20 public final Object[] toArray() {
2760     long sz = map.mappingCount();
2761     if (sz > MAX_ARRAY_SIZE)
2762     throw new OutOfMemoryError(oomeMsg);
2763     int n = (int)sz;
2764     Object[] r = new Object[n];
2765     int i = 0;
2766     for (E e : this) {
2767     if (i == n) {
2768     if (n >= MAX_ARRAY_SIZE)
2769     throw new OutOfMemoryError(oomeMsg);
2770     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2771     n = MAX_ARRAY_SIZE;
2772     else
2773     n += (n >>> 1) + 1;
2774     r = Arrays.copyOf(r, n);
2775     }
2776     r[i++] = e;
2777     }
2778     return (i == n) ? r : Arrays.copyOf(r, i);
2779 dl 1.1 }
2780    
2781 dl 1.20 @SuppressWarnings("unchecked")
2782     public final <T> T[] toArray(T[] a) {
2783     long sz = map.mappingCount();
2784     if (sz > MAX_ARRAY_SIZE)
2785     throw new OutOfMemoryError(oomeMsg);
2786     int m = (int)sz;
2787     T[] r = (a.length >= m) ? a :
2788     (T[])java.lang.reflect.Array
2789     .newInstance(a.getClass().getComponentType(), m);
2790     int n = r.length;
2791     int i = 0;
2792     for (E e : this) {
2793     if (i == n) {
2794     if (n >= MAX_ARRAY_SIZE)
2795     throw new OutOfMemoryError(oomeMsg);
2796     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2797     n = MAX_ARRAY_SIZE;
2798     else
2799     n += (n >>> 1) + 1;
2800     r = Arrays.copyOf(r, n);
2801     }
2802     r[i++] = (T)e;
2803     }
2804     if (a == r && i < n) {
2805     r[i] = null; // null-terminate
2806     return r;
2807     }
2808     return (i == n) ? r : Arrays.copyOf(r, i);
2809 dl 1.1 }
2810    
2811     /**
2812 dl 1.20 * Returns a string representation of this collection.
2813     * The string representation consists of the string representations
2814     * of the collection's elements in the order they are returned by
2815     * its iterator, enclosed in square brackets ({@code "[]"}).
2816     * Adjacent elements are separated by the characters {@code ", "}
2817     * (comma and space). Elements are converted to strings as by
2818     * {@link String#valueOf(Object)}.
2819 dl 1.1 *
2820 dl 1.20 * @return a string representation of this collection
2821 dl 1.1 */
2822 dl 1.20 public final String toString() {
2823     StringBuilder sb = new StringBuilder();
2824     sb.append('[');
2825     Iterator<E> it = iterator();
2826     if (it.hasNext()) {
2827     for (;;) {
2828     Object e = it.next();
2829     sb.append(e == this ? "(this Collection)" : e);
2830     if (!it.hasNext())
2831     break;
2832     sb.append(',').append(' ');
2833     }
2834     }
2835     return sb.append(']').toString();
2836 dl 1.1 }
2837    
2838 dl 1.20 public final boolean containsAll(Collection<?> c) {
2839     if (c != this) {
2840     for (Object e : c) {
2841     if (e == null || !contains(e))
2842     return false;
2843     }
2844     }
2845     return true;
2846 dl 1.1 }
2847    
2848 dl 1.20 public final boolean removeAll(Collection<?> c) {
2849     boolean modified = false;
2850     for (Iterator<E> it = iterator(); it.hasNext();) {
2851     if (c.contains(it.next())) {
2852     it.remove();
2853     modified = true;
2854     }
2855     }
2856     return modified;
2857 dl 1.1 }
2858    
2859 dl 1.20 public final boolean retainAll(Collection<?> c) {
2860     boolean modified = false;
2861     for (Iterator<E> it = iterator(); it.hasNext();) {
2862     if (!c.contains(it.next())) {
2863     it.remove();
2864     modified = true;
2865     }
2866     }
2867     return modified;
2868 dl 1.1 }
2869    
2870 dl 1.20 }
2871 dl 1.1
2872 dl 1.20 /**
2873     * A view of a ConcurrentHashMap as a {@link Set} of keys, in
2874     * which additions may optionally be enabled by mapping to a
2875     * common value. This class cannot be directly instantiated.
2876     * See {@link #keySet() keySet()},
2877     * {@link #keySet(Object) keySet(V)},
2878     * {@link #newKeySet() newKeySet()},
2879     * {@link #newKeySet(int) newKeySet(int)}.
2880     *
2881     * @since 1.8
2882     */
2883     public static class KeySetView<K,V> extends CollectionView<K,V,K>
2884     implements Set<K>, java.io.Serializable {
2885     private static final long serialVersionUID = 7249069246763182397L;
2886     private final V value;
2887     KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
2888     super(map);
2889     this.value = value;
2890 dl 1.1 }
2891    
2892     /**
2893 dl 1.20 * Returns the default mapped value for additions,
2894     * or {@code null} if additions are not supported.
2895 dl 1.1 *
2896 dl 1.20 * @return the default mapped value for additions, or {@code null}
2897     * if not supported
2898 dl 1.1 */
2899 dl 1.20 public V getMappedValue() { return value; }
2900 dl 1.1
2901     /**
2902 dl 1.20 * {@inheritDoc}
2903     * @throws NullPointerException if the specified key is null
2904 dl 1.1 */
2905 dl 1.20 public boolean contains(Object o) { return map.containsKey(o); }
2906 dl 1.1
2907     /**
2908 dl 1.20 * Removes the key from this map view, by removing the key (and its
2909     * corresponding value) from the backing map. This method does
2910     * nothing if the key is not in the map.
2911 dl 1.1 *
2912 dl 1.20 * @param o the key to be removed from the backing map
2913     * @return {@code true} if the backing map contained the specified key
2914     * @throws NullPointerException if the specified key is null
2915 dl 1.1 */
2916 dl 1.20 public boolean remove(Object o) { return map.remove(o) != null; }
2917 dl 1.1
2918     /**
2919 dl 1.20 * @return an iterator over the keys of the backing map
2920 dl 1.1 */
2921 dl 1.20 public Iterator<K> iterator() {
2922     Node<K,V>[] t;
2923     ConcurrentHashMap<K,V> m = map;
2924     int f = (t = m.table) == null ? 0 : t.length;
2925     return new KeyIterator<K,V>(t, f, 0, f, m);
2926 dl 1.1 }
2927    
2928     /**
2929 dl 1.20 * Adds the specified key to this set view by mapping the key to
2930     * the default mapped value in the backing map, if defined.
2931 dl 1.1 *
2932 dl 1.20 * @param e key to be added
2933     * @return {@code true} if this set changed as a result of the call
2934     * @throws NullPointerException if the specified key is null
2935     * @throws UnsupportedOperationException if no default mapped value
2936     * for additions was provided
2937 dl 1.1 */
2938 dl 1.20 public boolean add(K e) {
2939     V v;
2940     if ((v = value) == null)
2941     throw new UnsupportedOperationException();
2942     return map.putVal(e, v, true) == null;
2943 dl 1.1 }
2944    
2945     /**
2946 dl 1.20 * Adds all of the elements in the specified collection to this set,
2947     * as if by calling {@link #add} on each one.
2948 dl 1.1 *
2949 dl 1.20 * @param c the elements to be inserted into this set
2950     * @return {@code true} if this set changed as a result of the call
2951     * @throws NullPointerException if the collection or any of its
2952     * elements are {@code null}
2953     * @throws UnsupportedOperationException if no default mapped value
2954     * for additions was provided
2955 dl 1.1 */
2956 dl 1.20 public boolean addAll(Collection<? extends K> c) {
2957     boolean added = false;
2958     V v;
2959     if ((v = value) == null)
2960     throw new UnsupportedOperationException();
2961     for (K e : c) {
2962     if (map.putVal(e, v, true) == null)
2963     added = true;
2964 dl 1.1 }
2965 dl 1.20 return added;
2966 dl 1.1 }
2967    
2968 dl 1.20 public int hashCode() {
2969     int h = 0;
2970     for (K e : this)
2971     h += e.hashCode();
2972     return h;
2973 dl 1.1 }
2974    
2975 dl 1.20 public boolean equals(Object o) {
2976     Set<?> c;
2977     return ((o instanceof Set) &&
2978     ((c = (Set<?>)o) == this ||
2979     (containsAll(c) && c.containsAll(this))));
2980 dl 1.1 }
2981 dl 1.20
2982 dl 1.1 }
2983    
2984 dl 1.20 /**
2985     * A view of a ConcurrentHashMap as a {@link Collection} of
2986     * values, in which additions are disabled. This class cannot be
2987     * directly instantiated. See {@link #values()}.
2988     */
2989     static final class ValuesView<K,V> extends CollectionView<K,V,V>
2990     implements Collection<V>, java.io.Serializable {
2991     private static final long serialVersionUID = 2249069246763182397L;
2992     ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
2993     public final boolean contains(Object o) {
2994     return map.containsValue(o);
2995 dl 1.1 }
2996    
2997 dl 1.20 public final boolean remove(Object o) {
2998     if (o != null) {
2999     for (Iterator<V> it = iterator(); it.hasNext();) {
3000     if (o.equals(it.next())) {
3001     it.remove();
3002     return true;
3003 dl 1.1 }
3004     }
3005     }
3006 dl 1.20 return false;
3007 dl 1.1 }
3008    
3009 dl 1.20 public final Iterator<V> iterator() {
3010     ConcurrentHashMap<K,V> m = map;
3011     Node<K,V>[] t;
3012     int f = (t = m.table) == null ? 0 : t.length;
3013     return new ValueIterator<K,V>(t, f, 0, f, m);
3014 dl 1.1 }
3015    
3016 dl 1.20 public final boolean add(V e) {
3017     throw new UnsupportedOperationException();
3018     }
3019     public final boolean addAll(Collection<? extends V> c) {
3020     throw new UnsupportedOperationException();
3021 dl 1.1 }
3022 dl 1.20
3023 dl 1.1 }
3024    
3025 dl 1.20 /**
3026     * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
3027     * entries. This class cannot be directly instantiated. See
3028     * {@link #entrySet()}.
3029     */
3030     static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
3031     implements Set<Map.Entry<K,V>>, java.io.Serializable {
3032     private static final long serialVersionUID = 2249069246763182397L;
3033     EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
3034    
3035     public boolean contains(Object o) {
3036     Object k, v, r; Map.Entry<?,?> e;
3037     return ((o instanceof Map.Entry) &&
3038     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3039     (r = map.get(k)) != null &&
3040     (v = e.getValue()) != null &&
3041     (v == r || v.equals(r)));
3042 dl 1.1 }
3043    
3044 dl 1.20 public boolean remove(Object o) {
3045     Object k, v; Map.Entry<?,?> e;
3046     return ((o instanceof Map.Entry) &&
3047     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3048     (v = e.getValue()) != null &&
3049     map.remove(k, v));
3050 dl 1.1 }
3051    
3052 dl 1.20 /**
3053     * @return an iterator over the entries of the backing map
3054     */
3055     public Iterator<Map.Entry<K,V>> iterator() {
3056     ConcurrentHashMap<K,V> m = map;
3057     Node<K,V>[] t;
3058     int f = (t = m.table) == null ? 0 : t.length;
3059     return new EntryIterator<K,V>(t, f, 0, f, m);
3060 dl 1.1 }
3061    
3062 dl 1.20 public boolean add(Entry<K,V> e) {
3063     return map.putVal(e.getKey(), e.getValue(), false) == null;
3064 dl 1.1 }
3065    
3066 dl 1.20 public boolean addAll(Collection<? extends Entry<K,V>> c) {
3067     boolean added = false;
3068     for (Entry<K,V> e : c) {
3069     if (add(e))
3070     added = true;
3071 dl 1.1 }
3072 dl 1.20 return added;
3073 dl 1.1 }
3074    
3075 dl 1.20 public final int hashCode() {
3076     int h = 0;
3077     Node<K,V>[] t;
3078     if ((t = map.table) != null) {
3079     Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3080     for (Node<K,V> p; (p = it.advance()) != null; ) {
3081     h += p.hashCode();
3082 dl 1.1 }
3083     }
3084 dl 1.20 return h;
3085 dl 1.1 }
3086    
3087 dl 1.20 public final boolean equals(Object o) {
3088     Set<?> c;
3089     return ((o instanceof Set) &&
3090     ((c = (Set<?>)o) == this ||
3091     (containsAll(c) && c.containsAll(this))));
3092 dl 1.1 }
3093 dl 1.20
3094 dl 1.1 }
3095    
3096 dl 1.20
3097     /* ---------------- Counters -------------- */
3098    
3099     // Adapted from LongAdder and Striped64.
3100     // See their internal docs for explanation.
3101    
3102     // A padded cell for distributing counts
3103     static final class CounterCell {
3104     volatile long p0, p1, p2, p3, p4, p5, p6;
3105     volatile long value;
3106     volatile long q0, q1, q2, q3, q4, q5, q6;
3107     CounterCell(long x) { value = x; }
3108 dl 1.1 }
3109    
3110 dl 1.20 /**
3111     * Holder for the thread-local hash code determining which
3112     * CounterCell to use. The code is initialized via the
3113     * counterHashCodeGenerator, but may be moved upon collisions.
3114     */
3115     static final class CounterHashCode {
3116     int code;
3117 dl 1.1 }
3118    
3119 dl 1.20 /**
3120 jsr166 1.25 * Generates initial value for per-thread CounterHashCodes.
3121 dl 1.20 */
3122     static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
3123    
3124     /**
3125     * Increment for counterHashCodeGenerator. See class ThreadLocal
3126     * for explanation.
3127     */
3128     static final int SEED_INCREMENT = 0x61c88647;
3129    
3130     /**
3131     * Per-thread counter hash codes. Shared across all instances.
3132     */
3133     static final ThreadLocal<CounterHashCode> threadCounterHashCode =
3134     new ThreadLocal<CounterHashCode>();
3135    
3136     final long sumCount() {
3137     CounterCell[] as = counterCells; CounterCell a;
3138     long sum = baseCount;
3139     if (as != null) {
3140     for (int i = 0; i < as.length; ++i) {
3141     if ((a = as[i]) != null)
3142     sum += a.value;
3143 dl 1.1 }
3144     }
3145 dl 1.20 return sum;
3146 dl 1.1 }
3147    
3148 dl 1.20 // See LongAdder version for explanation
3149     private final void fullAddCount(long x, CounterHashCode hc,
3150     boolean wasUncontended) {
3151     int h;
3152     if (hc == null) {
3153     hc = new CounterHashCode();
3154     int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
3155     h = hc.code = (s == 0) ? 1 : s; // Avoid zero
3156     threadCounterHashCode.set(hc);
3157     }
3158     else
3159     h = hc.code;
3160     boolean collide = false; // True if last slot nonempty
3161     for (;;) {
3162     CounterCell[] as; CounterCell a; int n; long v;
3163     if ((as = counterCells) != null && (n = as.length) > 0) {
3164     if ((a = as[(n - 1) & h]) == null) {
3165     if (cellsBusy == 0) { // Try to attach new Cell
3166     CounterCell r = new CounterCell(x); // Optimistic create
3167     if (cellsBusy == 0 &&
3168     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3169     boolean created = false;
3170     try { // Recheck under lock
3171     CounterCell[] rs; int m, j;
3172     if ((rs = counterCells) != null &&
3173     (m = rs.length) > 0 &&
3174     rs[j = (m - 1) & h] == null) {
3175     rs[j] = r;
3176     created = true;
3177     }
3178     } finally {
3179     cellsBusy = 0;
3180     }
3181     if (created)
3182     break;
3183     continue; // Slot is now non-empty
3184     }
3185 dl 1.1 }
3186 dl 1.20 collide = false;
3187 dl 1.1 }
3188 dl 1.20 else if (!wasUncontended) // CAS already known to fail
3189     wasUncontended = true; // Continue after rehash
3190     else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
3191     break;
3192     else if (counterCells != as || n >= NCPU)
3193     collide = false; // At max size or stale
3194     else if (!collide)
3195     collide = true;
3196     else if (cellsBusy == 0 &&
3197     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3198     try {
3199     if (counterCells == as) {// Expand table unless stale
3200     CounterCell[] rs = new CounterCell[n << 1];
3201     for (int i = 0; i < n; ++i)
3202     rs[i] = as[i];
3203     counterCells = rs;
3204     }
3205     } finally {
3206     cellsBusy = 0;
3207 dl 1.1 }
3208 dl 1.20 collide = false;
3209     continue; // Retry with expanded table
3210 dl 1.1 }
3211 dl 1.20 h ^= h << 13; // Rehash
3212     h ^= h >>> 17;
3213     h ^= h << 5;
3214 dl 1.1 }
3215 dl 1.20 else if (cellsBusy == 0 && counterCells == as &&
3216     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3217     boolean init = false;
3218     try { // Initialize table
3219     if (counterCells == as) {
3220     CounterCell[] rs = new CounterCell[2];
3221     rs[h & 1] = new CounterCell(x);
3222     counterCells = rs;
3223     init = true;
3224 dl 1.1 }
3225 dl 1.20 } finally {
3226     cellsBusy = 0;
3227 dl 1.1 }
3228 dl 1.20 if (init)
3229     break;
3230 dl 1.1 }
3231 dl 1.20 else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
3232     break; // Fall back on using base
3233 dl 1.1 }
3234 dl 1.20 hc.code = h; // Record index for next time
3235 dl 1.1 }
3236    
3237     // Unsafe mechanics
3238     private static final sun.misc.Unsafe U;
3239     private static final long SIZECTL;
3240     private static final long TRANSFERINDEX;
3241     private static final long BASECOUNT;
3242 dl 1.20 private static final long CELLSBUSY;
3243 dl 1.1 private static final long CELLVALUE;
3244     private static final long ABASE;
3245     private static final int ASHIFT;
3246    
3247     static {
3248     try {
3249     U = sun.misc.Unsafe.getUnsafe();
3250     Class<?> k = ConcurrentHashMap.class;
3251     SIZECTL = U.objectFieldOffset
3252     (k.getDeclaredField("sizeCtl"));
3253     TRANSFERINDEX = U.objectFieldOffset
3254     (k.getDeclaredField("transferIndex"));
3255     BASECOUNT = U.objectFieldOffset
3256     (k.getDeclaredField("baseCount"));
3257 dl 1.20 CELLSBUSY = U.objectFieldOffset
3258     (k.getDeclaredField("cellsBusy"));
3259 dl 1.1 Class<?> ck = CounterCell.class;
3260     CELLVALUE = U.objectFieldOffset
3261     (ck.getDeclaredField("value"));
3262 jsr166 1.22 Class<?> ak = Node[].class;
3263     ABASE = U.arrayBaseOffset(ak);
3264     int scale = U.arrayIndexScale(ak);
3265 jsr166 1.9 if ((scale & (scale - 1)) != 0)
3266     throw new Error("data type scale not a power of two");
3267     ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3268 dl 1.1 } catch (Exception e) {
3269     throw new Error(e);
3270     }
3271     }
3272    
3273     }