ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.38
Committed: Sun Dec 1 16:56:07 2013 UTC (10 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.37: +11 -11 lines
Log Message:
whitespace

File Contents

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