ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.30
Committed: Sat Jul 20 16:50:08 2013 UTC (10 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.29: +67 -38 lines
Log Message:
Ensure consistent insertion

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