ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.45
Committed: Mon Mar 7 23:55:31 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.44: +1 -1 lines
Log Message:
typo

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