ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.41
Committed: Thu Feb 26 06:53:34 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.40: +0 -2 lines
Log Message:
delete unused imports

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 refering to
321 * concurrencyLevel. We accept a loadFactor constructor argument,
322 * but apply it only to initial table capacity (which is the only
323 * time that we can guarantee to honor it.) We also declare an
324 * unused "Segment" class that is instantiated in minimal form
325 * only when serializing.
326 *
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 s.putFields().put("segments", segments);
1239 s.putFields().put("segmentShift", segmentShift);
1240 s.putFields().put("segmentMask", segmentMask);
1241 s.writeFields();
1242
1243 Node<K,V>[] t;
1244 if ((t = table) != null) {
1245 Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
1246 for (Node<K,V> p; (p = it.advance()) != null; ) {
1247 s.writeObject(p.key);
1248 s.writeObject(p.val);
1249 }
1250 }
1251 s.writeObject(null);
1252 s.writeObject(null);
1253 segments = null; // throw away
1254 }
1255
1256 /**
1257 * Reconstitutes the instance from a stream (that is, deserializes it).
1258 * @param s the stream
1259 */
1260 private void readObject(java.io.ObjectInputStream s)
1261 throws java.io.IOException, ClassNotFoundException {
1262 /*
1263 * To improve performance in typical cases, we create nodes
1264 * while reading, then place in table once size is known.
1265 * However, we must also validate uniqueness and deal with
1266 * overpopulated bins while doing so, which requires
1267 * specialized versions of putVal mechanics.
1268 */
1269 sizeCtl = -1; // force exclusion for table construction
1270 s.defaultReadObject();
1271 long size = 0L;
1272 Node<K,V> p = null;
1273 for (;;) {
1274 @SuppressWarnings("unchecked") K k = (K) s.readObject();
1275 @SuppressWarnings("unchecked") V v = (V) s.readObject();
1276 if (k != null && v != null) {
1277 p = new Node<K,V>(spread(k.hashCode()), k, v, p);
1278 ++size;
1279 }
1280 else
1281 break;
1282 }
1283 if (size == 0L)
1284 sizeCtl = 0;
1285 else {
1286 int n;
1287 if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1288 n = MAXIMUM_CAPACITY;
1289 else {
1290 int sz = (int)size;
1291 n = tableSizeFor(sz + (sz >>> 1) + 1);
1292 }
1293 @SuppressWarnings("unchecked")
1294 Node<K,V>[] tab = (Node<K,V>[])new Node<?,?>[n];
1295 int mask = n - 1;
1296 long added = 0L;
1297 while (p != null) {
1298 boolean insertAtFront;
1299 Node<K,V> next = p.next, first;
1300 int h = p.hash, j = h & mask;
1301 if ((first = tabAt(tab, j)) == null)
1302 insertAtFront = true;
1303 else {
1304 K k = p.key;
1305 if (first.hash < 0) {
1306 TreeBin<K,V> t = (TreeBin<K,V>)first;
1307 if (t.putTreeVal(h, k, p.val) == null)
1308 ++added;
1309 insertAtFront = false;
1310 }
1311 else {
1312 int binCount = 0;
1313 insertAtFront = true;
1314 Node<K,V> q; K qk;
1315 for (q = first; q != null; q = q.next) {
1316 if (q.hash == h &&
1317 ((qk = q.key) == k ||
1318 (qk != null && k.equals(qk)))) {
1319 insertAtFront = false;
1320 break;
1321 }
1322 ++binCount;
1323 }
1324 if (insertAtFront && binCount >= TREEIFY_THRESHOLD) {
1325 insertAtFront = false;
1326 ++added;
1327 p.next = first;
1328 TreeNode<K,V> hd = null, tl = null;
1329 for (q = p; q != null; q = q.next) {
1330 TreeNode<K,V> t = new TreeNode<K,V>
1331 (q.hash, q.key, q.val, null, null);
1332 if ((t.prev = tl) == null)
1333 hd = t;
1334 else
1335 tl.next = t;
1336 tl = t;
1337 }
1338 setTabAt(tab, j, new TreeBin<K,V>(hd));
1339 }
1340 }
1341 }
1342 if (insertAtFront) {
1343 ++added;
1344 p.next = first;
1345 setTabAt(tab, j, p);
1346 }
1347 p = next;
1348 }
1349 table = tab;
1350 sizeCtl = n - (n >>> 2);
1351 baseCount = added;
1352 }
1353 }
1354
1355 // ConcurrentMap methods
1356
1357 /**
1358 * {@inheritDoc}
1359 *
1360 * @return the previous value associated with the specified key,
1361 * or {@code null} if there was no mapping for the key
1362 * @throws NullPointerException if the specified key or value is null
1363 */
1364 public V putIfAbsent(K key, V value) {
1365 return putVal(key, value, true);
1366 }
1367
1368 /**
1369 * {@inheritDoc}
1370 *
1371 * @throws NullPointerException if the specified key is null
1372 */
1373 public boolean remove(Object key, Object value) {
1374 if (key == null)
1375 throw new NullPointerException();
1376 return value != null && replaceNode(key, null, value) != null;
1377 }
1378
1379 /**
1380 * {@inheritDoc}
1381 *
1382 * @throws NullPointerException if any of the arguments are null
1383 */
1384 public boolean replace(K key, V oldValue, V newValue) {
1385 if (key == null || oldValue == null || newValue == null)
1386 throw new NullPointerException();
1387 return replaceNode(key, newValue, oldValue) != null;
1388 }
1389
1390 /**
1391 * {@inheritDoc}
1392 *
1393 * @return the previous value associated with the specified key,
1394 * or {@code null} if there was no mapping for the key
1395 * @throws NullPointerException if the specified key or value is null
1396 */
1397 public V replace(K key, V value) {
1398 if (key == null || value == null)
1399 throw new NullPointerException();
1400 return replaceNode(key, value, null);
1401 }
1402 // Hashtable legacy methods
1403
1404 /**
1405 * Legacy method testing if some key maps into the specified value
1406 * in this table.
1407 *
1408 * @deprecated This method is identical in functionality to
1409 * {@link #containsValue(Object)}, and exists solely to ensure
1410 * full compatibility with class {@link java.util.Hashtable},
1411 * which supported this method prior to introduction of the
1412 * Java Collections framework.
1413 *
1414 * @param value a value to search for
1415 * @return {@code true} if and only if some key maps to the
1416 * {@code value} argument in this table as
1417 * determined by the {@code equals} method;
1418 * {@code false} otherwise
1419 * @throws NullPointerException if the specified value is null
1420 */
1421 @Deprecated public boolean contains(Object value) {
1422 return containsValue(value);
1423 }
1424
1425 /**
1426 * Returns an enumeration of the keys in this table.
1427 *
1428 * @return an enumeration of the keys in this table
1429 * @see #keySet()
1430 */
1431 public Enumeration<K> keys() {
1432 Node<K,V>[] t;
1433 int f = (t = table) == null ? 0 : t.length;
1434 return new KeyIterator<K,V>(t, f, 0, f, this);
1435 }
1436
1437 /**
1438 * Returns an enumeration of the values in this table.
1439 *
1440 * @return an enumeration of the values in this table
1441 * @see #values()
1442 */
1443 public Enumeration<V> elements() {
1444 Node<K,V>[] t;
1445 int f = (t = table) == null ? 0 : t.length;
1446 return new ValueIterator<K,V>(t, f, 0, f, this);
1447 }
1448
1449 // ConcurrentHashMap-only methods
1450
1451 /**
1452 * Returns the number of mappings. This method should be used
1453 * instead of {@link #size} because a ConcurrentHashMap may
1454 * contain more mappings than can be represented as an int. The
1455 * value returned is an estimate; the actual count may differ if
1456 * there are concurrent insertions or removals.
1457 *
1458 * @return the number of mappings
1459 * @since 1.8
1460 */
1461 public long mappingCount() {
1462 long n = sumCount();
1463 return (n < 0L) ? 0L : n; // ignore transient negative values
1464 }
1465
1466 /**
1467 * Creates a new {@link Set} backed by a ConcurrentHashMap
1468 * from the given type to {@code Boolean.TRUE}.
1469 *
1470 * @param <K> the element type of the returned set
1471 * @return the new set
1472 * @since 1.8
1473 */
1474 public static <K> KeySetView<K,Boolean> newKeySet() {
1475 return new KeySetView<K,Boolean>
1476 (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
1477 }
1478
1479 /**
1480 * Creates a new {@link Set} backed by a ConcurrentHashMap
1481 * from the given type to {@code Boolean.TRUE}.
1482 *
1483 * @param initialCapacity The implementation performs internal
1484 * sizing to accommodate this many elements.
1485 * @param <K> the element type of the returned set
1486 * @return the new set
1487 * @throws IllegalArgumentException if the initial capacity of
1488 * elements is negative
1489 * @since 1.8
1490 */
1491 public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
1492 return new KeySetView<K,Boolean>
1493 (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
1494 }
1495
1496 /**
1497 * Returns a {@link Set} view of the keys in this map, using the
1498 * given common mapped value for any additions (i.e., {@link
1499 * Collection#add} and {@link Collection#addAll(Collection)}).
1500 * This is of course only appropriate if it is acceptable to use
1501 * the same value for all additions from this view.
1502 *
1503 * @param mappedValue the mapped value to use for any additions
1504 * @return the set view
1505 * @throws NullPointerException if the mappedValue is null
1506 */
1507 public KeySetView<K,V> keySet(V mappedValue) {
1508 if (mappedValue == null)
1509 throw new NullPointerException();
1510 return new KeySetView<K,V>(this, mappedValue);
1511 }
1512
1513 /* ---------------- Special Nodes -------------- */
1514
1515 /**
1516 * A node inserted at head of bins during transfer operations.
1517 */
1518 static final class ForwardingNode<K,V> extends Node<K,V> {
1519 final Node<K,V>[] nextTable;
1520 ForwardingNode(Node<K,V>[] tab) {
1521 super(MOVED, null, null, null);
1522 this.nextTable = tab;
1523 }
1524
1525 Node<K,V> find(int h, Object k) {
1526 Node<K,V> e; int n;
1527 Node<K,V>[] tab = nextTable;
1528 if (k != null && tab != null && (n = tab.length) > 0 &&
1529 (e = tabAt(tab, (n - 1) & h)) != null) {
1530 do {
1531 int eh; K ek;
1532 if ((eh = e.hash) == h &&
1533 ((ek = e.key) == k || (ek != null && k.equals(ek))))
1534 return e;
1535 if (eh < 0)
1536 return e.find(h, k);
1537 } while ((e = e.next) != null);
1538 }
1539 return null;
1540 }
1541 }
1542
1543 /**
1544 * A place-holder node used in computeIfAbsent and compute
1545 */
1546 static final class ReservationNode<K,V> extends Node<K,V> {
1547 ReservationNode() {
1548 super(RESERVED, null, null, null);
1549 }
1550
1551 Node<K,V> find(int h, Object k) {
1552 return null;
1553 }
1554 }
1555
1556 /* ---------------- Table Initialization and Resizing -------------- */
1557
1558 /**
1559 * Returns the stamp bits for resizing a table of size n.
1560 * Must be negative when shifted left by RESIZE_STAMP_SHIFT.
1561 */
1562 static final int resizeStamp(int n) {
1563 return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
1564 }
1565
1566 /**
1567 * Initializes table, using the size recorded in sizeCtl.
1568 */
1569 private final Node<K,V>[] initTable() {
1570 Node<K,V>[] tab; int sc;
1571 while ((tab = table) == null || tab.length == 0) {
1572 if ((sc = sizeCtl) < 0)
1573 Thread.yield(); // lost initialization race; just spin
1574 else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1575 try {
1576 if ((tab = table) == null || tab.length == 0) {
1577 int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1578 @SuppressWarnings("unchecked")
1579 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
1580 table = tab = nt;
1581 sc = n - (n >>> 2);
1582 }
1583 } finally {
1584 sizeCtl = sc;
1585 }
1586 break;
1587 }
1588 }
1589 return tab;
1590 }
1591
1592 /**
1593 * Adds to count, and if table is too small and not already
1594 * resizing, initiates transfer. If already resizing, helps
1595 * perform transfer if work is available. Rechecks occupancy
1596 * after a transfer to see if another resize is already needed
1597 * because resizings are lagging additions.
1598 *
1599 * @param x the count to add
1600 * @param check if <0, don't check resize, if <= 1 only check if uncontended
1601 */
1602 private final void addCount(long x, int check) {
1603 CounterCell[] as; long b, s;
1604 if ((as = counterCells) != null ||
1605 !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
1606 CounterHashCode hc; CounterCell a; long v; int m;
1607 boolean uncontended = true;
1608 if ((hc = threadCounterHashCode.get()) == null ||
1609 as == null || (m = as.length - 1) < 0 ||
1610 (a = as[m & hc.code]) == null ||
1611 !(uncontended =
1612 U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
1613 fullAddCount(x, hc, uncontended);
1614 return;
1615 }
1616 if (check <= 1)
1617 return;
1618 s = sumCount();
1619 }
1620 if (check >= 0) {
1621 Node<K,V>[] tab, nt; int n, sc;
1622 while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
1623 (n = tab.length) < MAXIMUM_CAPACITY) {
1624 int rs = resizeStamp(n);
1625 if (sc < 0) {
1626 if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
1627 sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
1628 transferIndex <= 0)
1629 break;
1630 if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
1631 transfer(tab, nt);
1632 }
1633 else if (U.compareAndSwapInt(this, SIZECTL, sc,
1634 (rs << RESIZE_STAMP_SHIFT) + 2))
1635 transfer(tab, null);
1636 s = sumCount();
1637 }
1638 }
1639 }
1640
1641 /**
1642 * Helps transfer if a resize is in progress.
1643 */
1644 final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
1645 Node<K,V>[] nextTab; int sc;
1646 if (tab != null && (f instanceof ForwardingNode) &&
1647 (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
1648 int rs = resizeStamp(tab.length);
1649 while (nextTab == nextTable && table == tab &&
1650 (sc = sizeCtl) < 0) {
1651 if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
1652 sc == rs + MAX_RESIZERS || transferIndex <= 0)
1653 break;
1654 if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
1655 transfer(tab, nextTab);
1656 break;
1657 }
1658 }
1659 return nextTab;
1660 }
1661 return table;
1662 }
1663
1664 /**
1665 * Tries to presize table to accommodate the given number of elements.
1666 *
1667 * @param size number of elements (doesn't need to be perfectly accurate)
1668 */
1669 private final void tryPresize(int size) {
1670 int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1671 tableSizeFor(size + (size >>> 1) + 1);
1672 int sc;
1673 while ((sc = sizeCtl) >= 0) {
1674 Node<K,V>[] tab = table; int n;
1675 if (tab == null || (n = tab.length) == 0) {
1676 n = (sc > c) ? sc : c;
1677 if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
1678 try {
1679 if (table == tab) {
1680 @SuppressWarnings("unchecked")
1681 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
1682 table = nt;
1683 sc = n - (n >>> 2);
1684 }
1685 } finally {
1686 sizeCtl = sc;
1687 }
1688 }
1689 }
1690 else if (c <= sc || n >= MAXIMUM_CAPACITY)
1691 break;
1692 else if (tab == table) {
1693 int rs = resizeStamp(n);
1694 if (sc < 0) {
1695 Node<K,V>[] nt;
1696 if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
1697 sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
1698 transferIndex <= 0)
1699 break;
1700 if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
1701 transfer(tab, nt);
1702 }
1703 else if (U.compareAndSwapInt(this, SIZECTL, sc,
1704 (rs << RESIZE_STAMP_SHIFT) + 2))
1705 transfer(tab, null);
1706 }
1707 }
1708 }
1709
1710 /**
1711 * Moves and/or copies the nodes in each bin to new table. See
1712 * above for explanation.
1713 */
1714 private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
1715 int n = tab.length, stride;
1716 if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
1717 stride = MIN_TRANSFER_STRIDE; // subdivide range
1718 if (nextTab == null) { // initiating
1719 try {
1720 @SuppressWarnings("unchecked")
1721 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
1722 nextTab = nt;
1723 } catch (Throwable ex) { // try to cope with OOME
1724 sizeCtl = Integer.MAX_VALUE;
1725 return;
1726 }
1727 nextTable = nextTab;
1728 transferIndex = n;
1729 }
1730 int nextn = nextTab.length;
1731 ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
1732 boolean advance = true;
1733 boolean finishing = false; // to ensure sweep before committing nextTab
1734 for (int i = 0, bound = 0;;) {
1735 Node<K,V> f; int fh;
1736 while (advance) {
1737 int nextIndex, nextBound;
1738 if (--i >= bound || finishing)
1739 advance = false;
1740 else if ((nextIndex = transferIndex) <= 0) {
1741 i = -1;
1742 advance = false;
1743 }
1744 else if (U.compareAndSwapInt
1745 (this, TRANSFERINDEX, nextIndex,
1746 nextBound = (nextIndex > stride ?
1747 nextIndex - stride : 0))) {
1748 bound = nextBound;
1749 i = nextIndex - 1;
1750 advance = false;
1751 }
1752 }
1753 if (i < 0 || i >= n || i + n >= nextn) {
1754 int sc;
1755 if (finishing) {
1756 nextTable = null;
1757 table = nextTab;
1758 sizeCtl = (n << 1) - (n >>> 1);
1759 return;
1760 }
1761 if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
1762 if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
1763 return;
1764 finishing = advance = true;
1765 i = n; // recheck before commit
1766 }
1767 }
1768 else if ((f = tabAt(tab, i)) == null)
1769 advance = casTabAt(tab, i, null, fwd);
1770 else if ((fh = f.hash) == MOVED)
1771 advance = true; // already processed
1772 else {
1773 synchronized (f) {
1774 if (tabAt(tab, i) == f) {
1775 Node<K,V> ln, hn;
1776 if (fh >= 0) {
1777 int runBit = fh & n;
1778 Node<K,V> lastRun = f;
1779 for (Node<K,V> p = f.next; p != null; p = p.next) {
1780 int b = p.hash & n;
1781 if (b != runBit) {
1782 runBit = b;
1783 lastRun = p;
1784 }
1785 }
1786 if (runBit == 0) {
1787 ln = lastRun;
1788 hn = null;
1789 }
1790 else {
1791 hn = lastRun;
1792 ln = null;
1793 }
1794 for (Node<K,V> p = f; p != lastRun; p = p.next) {
1795 int ph = p.hash; K pk = p.key; V pv = p.val;
1796 if ((ph & n) == 0)
1797 ln = new Node<K,V>(ph, pk, pv, ln);
1798 else
1799 hn = new Node<K,V>(ph, pk, pv, hn);
1800 }
1801 setTabAt(nextTab, i, ln);
1802 setTabAt(nextTab, i + n, hn);
1803 setTabAt(tab, i, fwd);
1804 advance = true;
1805 }
1806 else if (f instanceof TreeBin) {
1807 TreeBin<K,V> t = (TreeBin<K,V>)f;
1808 TreeNode<K,V> lo = null, loTail = null;
1809 TreeNode<K,V> hi = null, hiTail = null;
1810 int lc = 0, hc = 0;
1811 for (Node<K,V> e = t.first; e != null; e = e.next) {
1812 int h = e.hash;
1813 TreeNode<K,V> p = new TreeNode<K,V>
1814 (h, e.key, e.val, null, null);
1815 if ((h & n) == 0) {
1816 if ((p.prev = loTail) == null)
1817 lo = p;
1818 else
1819 loTail.next = p;
1820 loTail = p;
1821 ++lc;
1822 }
1823 else {
1824 if ((p.prev = hiTail) == null)
1825 hi = p;
1826 else
1827 hiTail.next = p;
1828 hiTail = p;
1829 ++hc;
1830 }
1831 }
1832 ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
1833 (hc != 0) ? new TreeBin<K,V>(lo) : t;
1834 hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
1835 (lc != 0) ? new TreeBin<K,V>(hi) : t;
1836 setTabAt(nextTab, i, ln);
1837 setTabAt(nextTab, i + n, hn);
1838 setTabAt(tab, i, fwd);
1839 advance = true;
1840 }
1841 }
1842 }
1843 }
1844 }
1845 }
1846
1847 /* ---------------- Conversion from/to TreeBins -------------- */
1848
1849 /**
1850 * Replaces all linked nodes in bin at given index unless table is
1851 * too small, in which case resizes instead.
1852 */
1853 private final void treeifyBin(Node<K,V>[] tab, int index) {
1854 Node<K,V> b; int n, sc;
1855 if (tab != null) {
1856 if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
1857 tryPresize(n << 1);
1858 else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
1859 synchronized (b) {
1860 if (tabAt(tab, index) == b) {
1861 TreeNode<K,V> hd = null, tl = null;
1862 for (Node<K,V> e = b; e != null; e = e.next) {
1863 TreeNode<K,V> p =
1864 new TreeNode<K,V>(e.hash, e.key, e.val,
1865 null, null);
1866 if ((p.prev = tl) == null)
1867 hd = p;
1868 else
1869 tl.next = p;
1870 tl = p;
1871 }
1872 setTabAt(tab, index, new TreeBin<K,V>(hd));
1873 }
1874 }
1875 }
1876 }
1877 }
1878
1879 /**
1880 * Returns a list on non-TreeNodes replacing those in given list.
1881 */
1882 static <K,V> Node<K,V> untreeify(Node<K,V> b) {
1883 Node<K,V> hd = null, tl = null;
1884 for (Node<K,V> q = b; q != null; q = q.next) {
1885 Node<K,V> p = new Node<K,V>(q.hash, q.key, q.val, null);
1886 if (tl == null)
1887 hd = p;
1888 else
1889 tl.next = p;
1890 tl = p;
1891 }
1892 return hd;
1893 }
1894
1895 /* ---------------- TreeNodes -------------- */
1896
1897 /**
1898 * Nodes for use in TreeBins
1899 */
1900 static final class TreeNode<K,V> extends Node<K,V> {
1901 TreeNode<K,V> parent; // red-black tree links
1902 TreeNode<K,V> left;
1903 TreeNode<K,V> right;
1904 TreeNode<K,V> prev; // needed to unlink next upon deletion
1905 boolean red;
1906
1907 TreeNode(int hash, K key, V val, Node<K,V> next,
1908 TreeNode<K,V> parent) {
1909 super(hash, key, val, next);
1910 this.parent = parent;
1911 }
1912
1913 Node<K,V> find(int h, Object k) {
1914 return findTreeNode(h, k, null);
1915 }
1916
1917 /**
1918 * Returns the TreeNode (or null if not found) for the given key
1919 * starting at given root.
1920 */
1921 final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
1922 if (k != null) {
1923 TreeNode<K,V> p = this;
1924 do {
1925 int ph, dir; K pk; TreeNode<K,V> q;
1926 TreeNode<K,V> pl = p.left, pr = p.right;
1927 if ((ph = p.hash) > h)
1928 p = pl;
1929 else if (ph < h)
1930 p = pr;
1931 else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
1932 return p;
1933 else if (pl == null)
1934 p = pr;
1935 else if (pr == null)
1936 p = pl;
1937 else if ((kc != null ||
1938 (kc = comparableClassFor(k)) != null) &&
1939 (dir = compareComparables(kc, k, pk)) != 0)
1940 p = (dir < 0) ? pl : pr;
1941 else if ((q = pr.findTreeNode(h, k, kc)) != null)
1942 return q;
1943 else
1944 p = pl;
1945 } while (p != null);
1946 }
1947 return null;
1948 }
1949 }
1950
1951
1952 /* ---------------- TreeBins -------------- */
1953
1954 /**
1955 * TreeNodes used at the heads of bins. TreeBins do not hold user
1956 * keys or values, but instead point to list of TreeNodes and
1957 * their root. They also maintain a parasitic read-write lock
1958 * forcing writers (who hold bin lock) to wait for readers (who do
1959 * not) to complete before tree restructuring operations.
1960 */
1961 static final class TreeBin<K,V> extends Node<K,V> {
1962 TreeNode<K,V> root;
1963 volatile TreeNode<K,V> first;
1964 volatile Thread waiter;
1965 volatile int lockState;
1966 // values for lockState
1967 static final int WRITER = 1; // set while holding write lock
1968 static final int WAITER = 2; // set when waiting for write lock
1969 static final int READER = 4; // increment value for setting read lock
1970
1971 /**
1972 * Tie-breaking utility for ordering insertions when equal
1973 * hashCodes and non-comparable. We don't require a total
1974 * order, just a consistent insertion rule to maintain
1975 * equivalence across rebalancings. Tie-breaking further than
1976 * necessary simplifies testing a bit.
1977 */
1978 static int tieBreakOrder(Object a, Object b) {
1979 int d;
1980 if (a == null || b == null ||
1981 (d = a.getClass().getName().
1982 compareTo(b.getClass().getName())) == 0)
1983 d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
1984 -1 : 1);
1985 return d;
1986 }
1987
1988 /**
1989 * Creates bin with initial set of nodes headed by b.
1990 */
1991 TreeBin(TreeNode<K,V> b) {
1992 super(TREEBIN, null, null, null);
1993 this.first = b;
1994 TreeNode<K,V> r = null;
1995 for (TreeNode<K,V> x = b, next; x != null; x = next) {
1996 next = (TreeNode<K,V>)x.next;
1997 x.left = x.right = null;
1998 if (r == null) {
1999 x.parent = null;
2000 x.red = false;
2001 r = x;
2002 }
2003 else {
2004 K k = x.key;
2005 int h = x.hash;
2006 Class<?> kc = null;
2007 for (TreeNode<K,V> p = r;;) {
2008 int dir, ph;
2009 K pk = p.key;
2010 if ((ph = p.hash) > h)
2011 dir = -1;
2012 else if (ph < h)
2013 dir = 1;
2014 else if ((kc == null &&
2015 (kc = comparableClassFor(k)) == null) ||
2016 (dir = compareComparables(kc, k, pk)) == 0)
2017 dir = tieBreakOrder(k, pk);
2018 TreeNode<K,V> xp = p;
2019 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2020 x.parent = xp;
2021 if (dir <= 0)
2022 xp.left = x;
2023 else
2024 xp.right = x;
2025 r = balanceInsertion(r, x);
2026 break;
2027 }
2028 }
2029 }
2030 }
2031 this.root = r;
2032 assert checkInvariants(root);
2033 }
2034
2035 /**
2036 * Acquires write lock for tree restructuring.
2037 */
2038 private final void lockRoot() {
2039 if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
2040 contendedLock(); // offload to separate method
2041 }
2042
2043 /**
2044 * Releases write lock for tree restructuring.
2045 */
2046 private final void unlockRoot() {
2047 lockState = 0;
2048 }
2049
2050 /**
2051 * Possibly blocks awaiting root lock.
2052 */
2053 private final void contendedLock() {
2054 boolean waiting = false;
2055 for (int s;;) {
2056 if (((s = lockState) & ~WAITER) == 0) {
2057 if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
2058 if (waiting)
2059 waiter = null;
2060 return;
2061 }
2062 }
2063 else if ((s & WAITER) == 0) {
2064 if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
2065 waiting = true;
2066 waiter = Thread.currentThread();
2067 }
2068 }
2069 else if (waiting)
2070 LockSupport.park(this);
2071 }
2072 }
2073
2074 /**
2075 * Returns matching node or null if none. Tries to search
2076 * using tree comparisons from root, but continues linear
2077 * search when lock not available.
2078 */
2079 final Node<K,V> find(int h, Object k) {
2080 if (k != null) {
2081 for (Node<K,V> e = first; e != null; ) {
2082 int s; K ek;
2083 if (((s = lockState) & (WAITER|WRITER)) != 0) {
2084 if (e.hash == h &&
2085 ((ek = e.key) == k || (ek != null && k.equals(ek))))
2086 return e;
2087 e = e.next;
2088 }
2089 else if (U.compareAndSwapInt(this, LOCKSTATE, s,
2090 s + READER)) {
2091 TreeNode<K,V> r, p;
2092 try {
2093 p = ((r = root) == null ? null :
2094 r.findTreeNode(h, k, null));
2095 } finally {
2096
2097 Thread w;
2098 int ls;
2099 do {} while (!U.compareAndSwapInt
2100 (this, LOCKSTATE,
2101 ls = lockState, ls - READER));
2102 if (ls == (READER|WAITER) && (w = waiter) != null)
2103 LockSupport.unpark(w);
2104 }
2105 return p;
2106 }
2107 }
2108 }
2109 return null;
2110 }
2111
2112 /**
2113 * Finds or adds a node.
2114 * @return null if added
2115 */
2116 /**
2117 * Finds or adds a node.
2118 * @return null if added
2119 */
2120 final TreeNode<K,V> putTreeVal(int h, K k, V v) {
2121 Class<?> kc = null;
2122 boolean searched = false;
2123 for (TreeNode<K,V> p = root;;) {
2124 int dir, ph; K pk;
2125 if (p == null) {
2126 first = root = new TreeNode<K,V>(h, k, v, null, null);
2127 break;
2128 }
2129 else if ((ph = p.hash) > h)
2130 dir = -1;
2131 else if (ph < h)
2132 dir = 1;
2133 else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
2134 return p;
2135 else if ((kc == null &&
2136 (kc = comparableClassFor(k)) == null) ||
2137 (dir = compareComparables(kc, k, pk)) == 0) {
2138 if (!searched) {
2139 TreeNode<K,V> q, ch;
2140 searched = true;
2141 if (((ch = p.left) != null &&
2142 (q = ch.findTreeNode(h, k, kc)) != null) ||
2143 ((ch = p.right) != null &&
2144 (q = ch.findTreeNode(h, k, kc)) != null))
2145 return q;
2146 }
2147 dir = tieBreakOrder(k, pk);
2148 }
2149
2150 TreeNode<K,V> xp = p;
2151 if ((p = (dir <= 0) ? p.left : p.right) == null) {
2152 TreeNode<K,V> x, f = first;
2153 first = x = new TreeNode<K,V>(h, k, v, f, xp);
2154 if (f != null)
2155 f.prev = x;
2156 if (dir <= 0)
2157 xp.left = x;
2158 else
2159 xp.right = x;
2160 if (!xp.red)
2161 x.red = true;
2162 else {
2163 lockRoot();
2164 try {
2165 root = balanceInsertion(root, x);
2166 } finally {
2167 unlockRoot();
2168 }
2169 }
2170 break;
2171 }
2172 }
2173 assert checkInvariants(root);
2174 return null;
2175 }
2176
2177 /**
2178 * Removes the given node, that must be present before this
2179 * call. This is messier than typical red-black deletion code
2180 * because we cannot swap the contents of an interior node
2181 * with a leaf successor that is pinned by "next" pointers
2182 * that are accessible independently of lock. So instead we
2183 * swap the tree linkages.
2184 *
2185 * @return true if now too small, so should be untreeified
2186 */
2187 final boolean removeTreeNode(TreeNode<K,V> p) {
2188 TreeNode<K,V> next = (TreeNode<K,V>)p.next;
2189 TreeNode<K,V> pred = p.prev; // unlink traversal pointers
2190 TreeNode<K,V> r, rl;
2191 if (pred == null)
2192 first = next;
2193 else
2194 pred.next = next;
2195 if (next != null)
2196 next.prev = pred;
2197 if (first == null) {
2198 root = null;
2199 return true;
2200 }
2201 if ((r = root) == null || r.right == null || // too small
2202 (rl = r.left) == null || rl.left == null)
2203 return true;
2204 lockRoot();
2205 try {
2206 TreeNode<K,V> replacement;
2207 TreeNode<K,V> pl = p.left;
2208 TreeNode<K,V> pr = p.right;
2209 if (pl != null && pr != null) {
2210 TreeNode<K,V> s = pr, sl;
2211 while ((sl = s.left) != null) // find successor
2212 s = sl;
2213 boolean c = s.red; s.red = p.red; p.red = c; // swap colors
2214 TreeNode<K,V> sr = s.right;
2215 TreeNode<K,V> pp = p.parent;
2216 if (s == pr) { // p was s's direct parent
2217 p.parent = s;
2218 s.right = p;
2219 }
2220 else {
2221 TreeNode<K,V> sp = s.parent;
2222 if ((p.parent = sp) != null) {
2223 if (s == sp.left)
2224 sp.left = p;
2225 else
2226 sp.right = p;
2227 }
2228 if ((s.right = pr) != null)
2229 pr.parent = s;
2230 }
2231 p.left = null;
2232 if ((p.right = sr) != null)
2233 sr.parent = p;
2234 if ((s.left = pl) != null)
2235 pl.parent = s;
2236 if ((s.parent = pp) == null)
2237 r = s;
2238 else if (p == pp.left)
2239 pp.left = s;
2240 else
2241 pp.right = s;
2242 if (sr != null)
2243 replacement = sr;
2244 else
2245 replacement = p;
2246 }
2247 else if (pl != null)
2248 replacement = pl;
2249 else if (pr != null)
2250 replacement = pr;
2251 else
2252 replacement = p;
2253 if (replacement != p) {
2254 TreeNode<K,V> pp = replacement.parent = p.parent;
2255 if (pp == null)
2256 r = replacement;
2257 else if (p == pp.left)
2258 pp.left = replacement;
2259 else
2260 pp.right = replacement;
2261 p.left = p.right = p.parent = null;
2262 }
2263
2264 root = (p.red) ? r : balanceDeletion(r, replacement);
2265
2266 if (p == replacement) { // detach pointers
2267 TreeNode<K,V> pp;
2268 if ((pp = p.parent) != null) {
2269 if (p == pp.left)
2270 pp.left = null;
2271 else if (p == pp.right)
2272 pp.right = null;
2273 p.parent = null;
2274 }
2275 }
2276 } finally {
2277 unlockRoot();
2278 }
2279 assert checkInvariants(root);
2280 return false;
2281 }
2282
2283 /* ------------------------------------------------------------ */
2284 // Red-black tree methods, all adapted from CLR
2285
2286 static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
2287 TreeNode<K,V> p) {
2288 TreeNode<K,V> r, pp, rl;
2289 if (p != null && (r = p.right) != null) {
2290 if ((rl = p.right = r.left) != null)
2291 rl.parent = p;
2292 if ((pp = r.parent = p.parent) == null)
2293 (root = r).red = false;
2294 else if (pp.left == p)
2295 pp.left = r;
2296 else
2297 pp.right = r;
2298 r.left = p;
2299 p.parent = r;
2300 }
2301 return root;
2302 }
2303
2304 static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
2305 TreeNode<K,V> p) {
2306 TreeNode<K,V> l, pp, lr;
2307 if (p != null && (l = p.left) != null) {
2308 if ((lr = p.left = l.right) != null)
2309 lr.parent = p;
2310 if ((pp = l.parent = p.parent) == null)
2311 (root = l).red = false;
2312 else if (pp.right == p)
2313 pp.right = l;
2314 else
2315 pp.left = l;
2316 l.right = p;
2317 p.parent = l;
2318 }
2319 return root;
2320 }
2321
2322 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
2323 TreeNode<K,V> x) {
2324 x.red = true;
2325 for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
2326 if ((xp = x.parent) == null) {
2327 x.red = false;
2328 return x;
2329 }
2330 else if (!xp.red || (xpp = xp.parent) == null)
2331 return root;
2332 if (xp == (xppl = xpp.left)) {
2333 if ((xppr = xpp.right) != null && xppr.red) {
2334 xppr.red = false;
2335 xp.red = false;
2336 xpp.red = true;
2337 x = xpp;
2338 }
2339 else {
2340 if (x == xp.right) {
2341 root = rotateLeft(root, x = xp);
2342 xpp = (xp = x.parent) == null ? null : xp.parent;
2343 }
2344 if (xp != null) {
2345 xp.red = false;
2346 if (xpp != null) {
2347 xpp.red = true;
2348 root = rotateRight(root, xpp);
2349 }
2350 }
2351 }
2352 }
2353 else {
2354 if (xppl != null && xppl.red) {
2355 xppl.red = false;
2356 xp.red = false;
2357 xpp.red = true;
2358 x = xpp;
2359 }
2360 else {
2361 if (x == xp.left) {
2362 root = rotateRight(root, x = xp);
2363 xpp = (xp = x.parent) == null ? null : xp.parent;
2364 }
2365 if (xp != null) {
2366 xp.red = false;
2367 if (xpp != null) {
2368 xpp.red = true;
2369 root = rotateLeft(root, xpp);
2370 }
2371 }
2372 }
2373 }
2374 }
2375 }
2376
2377 static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
2378 TreeNode<K,V> x) {
2379 for (TreeNode<K,V> xp, xpl, xpr;;) {
2380 if (x == null || x == root)
2381 return root;
2382 else if ((xp = x.parent) == null) {
2383 x.red = false;
2384 return x;
2385 }
2386 else if (x.red) {
2387 x.red = false;
2388 return root;
2389 }
2390 else if ((xpl = xp.left) == x) {
2391 if ((xpr = xp.right) != null && xpr.red) {
2392 xpr.red = false;
2393 xp.red = true;
2394 root = rotateLeft(root, xp);
2395 xpr = (xp = x.parent) == null ? null : xp.right;
2396 }
2397 if (xpr == null)
2398 x = xp;
2399 else {
2400 TreeNode<K,V> sl = xpr.left, sr = xpr.right;
2401 if ((sr == null || !sr.red) &&
2402 (sl == null || !sl.red)) {
2403 xpr.red = true;
2404 x = xp;
2405 }
2406 else {
2407 if (sr == null || !sr.red) {
2408 if (sl != null)
2409 sl.red = false;
2410 xpr.red = true;
2411 root = rotateRight(root, xpr);
2412 xpr = (xp = x.parent) == null ?
2413 null : xp.right;
2414 }
2415 if (xpr != null) {
2416 xpr.red = (xp == null) ? false : xp.red;
2417 if ((sr = xpr.right) != null)
2418 sr.red = false;
2419 }
2420 if (xp != null) {
2421 xp.red = false;
2422 root = rotateLeft(root, xp);
2423 }
2424 x = root;
2425 }
2426 }
2427 }
2428 else { // symmetric
2429 if (xpl != null && xpl.red) {
2430 xpl.red = false;
2431 xp.red = true;
2432 root = rotateRight(root, xp);
2433 xpl = (xp = x.parent) == null ? null : xp.left;
2434 }
2435 if (xpl == null)
2436 x = xp;
2437 else {
2438 TreeNode<K,V> sl = xpl.left, sr = xpl.right;
2439 if ((sl == null || !sl.red) &&
2440 (sr == null || !sr.red)) {
2441 xpl.red = true;
2442 x = xp;
2443 }
2444 else {
2445 if (sl == null || !sl.red) {
2446 if (sr != null)
2447 sr.red = false;
2448 xpl.red = true;
2449 root = rotateLeft(root, xpl);
2450 xpl = (xp = x.parent) == null ?
2451 null : xp.left;
2452 }
2453 if (xpl != null) {
2454 xpl.red = (xp == null) ? false : xp.red;
2455 if ((sl = xpl.left) != null)
2456 sl.red = false;
2457 }
2458 if (xp != null) {
2459 xp.red = false;
2460 root = rotateRight(root, xp);
2461 }
2462 x = root;
2463 }
2464 }
2465 }
2466 }
2467 }
2468
2469 /**
2470 * Recursive invariant check
2471 */
2472 static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
2473 TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
2474 tb = t.prev, tn = (TreeNode<K,V>)t.next;
2475 if (tb != null && tb.next != t)
2476 return false;
2477 if (tn != null && tn.prev != t)
2478 return false;
2479 if (tp != null && t != tp.left && t != tp.right)
2480 return false;
2481 if (tl != null && (tl.parent != t || tl.hash > t.hash))
2482 return false;
2483 if (tr != null && (tr.parent != t || tr.hash < t.hash))
2484 return false;
2485 if (t.red && tl != null && tl.red && tr != null && tr.red)
2486 return false;
2487 if (tl != null && !checkInvariants(tl))
2488 return false;
2489 if (tr != null && !checkInvariants(tr))
2490 return false;
2491 return true;
2492 }
2493
2494 private static final sun.misc.Unsafe U;
2495 private static final long LOCKSTATE;
2496 static {
2497 try {
2498 U = sun.misc.Unsafe.getUnsafe();
2499 Class<?> k = TreeBin.class;
2500 LOCKSTATE = U.objectFieldOffset
2501 (k.getDeclaredField("lockState"));
2502 } catch (Exception e) {
2503 throw new Error(e);
2504 }
2505 }
2506 }
2507
2508 /* ----------------Table Traversal -------------- */
2509
2510 /**
2511 * Records the table, its length, and current traversal index for a
2512 * traverser that must process a region of a forwarded table before
2513 * proceeding with current table.
2514 */
2515 static final class TableStack<K,V> {
2516 int length;
2517 int index;
2518 Node<K,V>[] tab;
2519 TableStack<K,V> next;
2520 }
2521
2522 /**
2523 * Encapsulates traversal for methods such as containsValue; also
2524 * serves as a base class for other iterators and spliterators.
2525 *
2526 * Method advance visits once each still-valid node that was
2527 * reachable upon iterator construction. It might miss some that
2528 * were added to a bin after the bin was visited, which is OK wrt
2529 * consistency guarantees. Maintaining this property in the face
2530 * of possible ongoing resizes requires a fair amount of
2531 * bookkeeping state that is difficult to optimize away amidst
2532 * volatile accesses. Even so, traversal maintains reasonable
2533 * throughput.
2534 *
2535 * Normally, iteration proceeds bin-by-bin traversing lists.
2536 * However, if the table has been resized, then all future steps
2537 * must traverse both the bin at the current index as well as at
2538 * (index + baseSize); and so on for further resizings. To
2539 * paranoically cope with potential sharing by users of iterators
2540 * across threads, iteration terminates if a bounds checks fails
2541 * for a table read.
2542 */
2543 static class Traverser<K,V> {
2544 Node<K,V>[] tab; // current table; updated if resized
2545 Node<K,V> next; // the next entry to use
2546 TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
2547 int index; // index of bin to use next
2548 int baseIndex; // current index of initial table
2549 int baseLimit; // index bound for initial table
2550 final int baseSize; // initial table size
2551
2552 Traverser(Node<K,V>[] tab, int size, int index, int limit) {
2553 this.tab = tab;
2554 this.baseSize = size;
2555 this.baseIndex = this.index = index;
2556 this.baseLimit = limit;
2557 this.next = null;
2558 }
2559
2560 /**
2561 * Advances if possible, returning next valid node, or null if none.
2562 */
2563 final Node<K,V> advance() {
2564 Node<K,V> e;
2565 if ((e = next) != null)
2566 e = e.next;
2567 for (;;) {
2568 Node<K,V>[] t; int i, n; // must use locals in checks
2569 if (e != null)
2570 return next = e;
2571 if (baseIndex >= baseLimit || (t = tab) == null ||
2572 (n = t.length) <= (i = index) || i < 0)
2573 return next = null;
2574 if ((e = tabAt(t, i)) != null && e.hash < 0) {
2575 if (e instanceof ForwardingNode) {
2576 tab = ((ForwardingNode<K,V>)e).nextTable;
2577 e = null;
2578 pushState(t, i, n);
2579 continue;
2580 }
2581 else if (e instanceof TreeBin)
2582 e = ((TreeBin<K,V>)e).first;
2583 else
2584 e = null;
2585 }
2586 if (stack != null)
2587 recoverState(n);
2588 else if ((index = i + baseSize) >= n)
2589 index = ++baseIndex; // visit upper slots if present
2590 }
2591 }
2592
2593 /**
2594 * Saves traversal state upon encountering a forwarding node.
2595 */
2596 private void pushState(Node<K,V>[] t, int i, int n) {
2597 TableStack<K,V> s = spare; // reuse if possible
2598 if (s != null)
2599 spare = s.next;
2600 else
2601 s = new TableStack<K,V>();
2602 s.tab = t;
2603 s.length = n;
2604 s.index = i;
2605 s.next = stack;
2606 stack = s;
2607 }
2608
2609 /**
2610 * Possibly pops traversal state.
2611 *
2612 * @param n length of current table
2613 */
2614 private void recoverState(int n) {
2615 TableStack<K,V> s; int len;
2616 while ((s = stack) != null && (index += (len = s.length)) >= n) {
2617 n = len;
2618 index = s.index;
2619 tab = s.tab;
2620 s.tab = null;
2621 TableStack<K,V> next = s.next;
2622 s.next = spare; // save for reuse
2623 stack = next;
2624 spare = s;
2625 }
2626 if (s == null && (index += baseSize) >= n)
2627 index = ++baseIndex;
2628 }
2629 }
2630
2631 /**
2632 * Base of key, value, and entry Iterators. Adds fields to
2633 * Traverser to support iterator.remove.
2634 */
2635 static class BaseIterator<K,V> extends Traverser<K,V> {
2636 final ConcurrentHashMap<K,V> map;
2637 Node<K,V> lastReturned;
2638 BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
2639 ConcurrentHashMap<K,V> map) {
2640 super(tab, size, index, limit);
2641 this.map = map;
2642 advance();
2643 }
2644
2645 public final boolean hasNext() { return next != null; }
2646 public final boolean hasMoreElements() { return next != null; }
2647
2648 public final void remove() {
2649 Node<K,V> p;
2650 if ((p = lastReturned) == null)
2651 throw new IllegalStateException();
2652 lastReturned = null;
2653 map.replaceNode(p.key, null, null);
2654 }
2655 }
2656
2657 static final class KeyIterator<K,V> extends BaseIterator<K,V>
2658 implements Iterator<K>, Enumeration<K> {
2659 KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
2660 ConcurrentHashMap<K,V> map) {
2661 super(tab, index, size, limit, map);
2662 }
2663
2664 public final K next() {
2665 Node<K,V> p;
2666 if ((p = next) == null)
2667 throw new NoSuchElementException();
2668 K k = p.key;
2669 lastReturned = p;
2670 advance();
2671 return k;
2672 }
2673
2674 public final K nextElement() { return next(); }
2675 }
2676
2677 static final class ValueIterator<K,V> extends BaseIterator<K,V>
2678 implements Iterator<V>, Enumeration<V> {
2679 ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
2680 ConcurrentHashMap<K,V> map) {
2681 super(tab, index, size, limit, map);
2682 }
2683
2684 public final V next() {
2685 Node<K,V> p;
2686 if ((p = next) == null)
2687 throw new NoSuchElementException();
2688 V v = p.val;
2689 lastReturned = p;
2690 advance();
2691 return v;
2692 }
2693
2694 public final V nextElement() { return next(); }
2695 }
2696
2697 static final class EntryIterator<K,V> extends BaseIterator<K,V>
2698 implements Iterator<Map.Entry<K,V>> {
2699 EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
2700 ConcurrentHashMap<K,V> map) {
2701 super(tab, index, size, limit, map);
2702 }
2703
2704 public final Map.Entry<K,V> next() {
2705 Node<K,V> p;
2706 if ((p = next) == null)
2707 throw new NoSuchElementException();
2708 K k = p.key;
2709 V v = p.val;
2710 lastReturned = p;
2711 advance();
2712 return new MapEntry<K,V>(k, v, map);
2713 }
2714 }
2715
2716 /**
2717 * Exported Entry for EntryIterator
2718 */
2719 static final class MapEntry<K,V> implements Map.Entry<K,V> {
2720 final K key; // non-null
2721 V val; // non-null
2722 final ConcurrentHashMap<K,V> map;
2723 MapEntry(K key, V val, ConcurrentHashMap<K,V> map) {
2724 this.key = key;
2725 this.val = val;
2726 this.map = map;
2727 }
2728 public K getKey() { return key; }
2729 public V getValue() { return val; }
2730 public int hashCode() { return key.hashCode() ^ val.hashCode(); }
2731 public String toString() { return key + "=" + val; }
2732
2733 public boolean equals(Object o) {
2734 Object k, v; Map.Entry<?,?> e;
2735 return ((o instanceof Map.Entry) &&
2736 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2737 (v = e.getValue()) != null &&
2738 (k == key || k.equals(key)) &&
2739 (v == val || v.equals(val)));
2740 }
2741
2742 /**
2743 * Sets our entry's value and writes through to the map. The
2744 * value to return is somewhat arbitrary here. Since we do not
2745 * necessarily track asynchronous changes, the most recent
2746 * "previous" value could be different from what we return (or
2747 * could even have been removed, in which case the put will
2748 * re-establish). We do not and cannot guarantee more.
2749 */
2750 public V setValue(V value) {
2751 if (value == null) throw new NullPointerException();
2752 V v = val;
2753 val = value;
2754 map.put(key, value);
2755 return v;
2756 }
2757 }
2758
2759 /* ----------------Views -------------- */
2760
2761 /**
2762 * Base class for views.
2763 */
2764 abstract static class CollectionView<K,V,E>
2765 implements Collection<E>, java.io.Serializable {
2766 private static final long serialVersionUID = 7249069246763182397L;
2767 final ConcurrentHashMap<K,V> map;
2768 CollectionView(ConcurrentHashMap<K,V> map) { this.map = map; }
2769
2770 /**
2771 * Returns the map backing this view.
2772 *
2773 * @return the map backing this view
2774 */
2775 public ConcurrentHashMap<K,V> getMap() { return map; }
2776
2777 /**
2778 * Removes all of the elements from this view, by removing all
2779 * the mappings from the map backing this view.
2780 */
2781 public final void clear() { map.clear(); }
2782 public final int size() { return map.size(); }
2783 public final boolean isEmpty() { return map.isEmpty(); }
2784
2785 // implementations below rely on concrete classes supplying these
2786 // abstract methods
2787 /**
2788 * Returns a "weakly consistent" iterator that will never
2789 * throw {@link ConcurrentModificationException}, and
2790 * guarantees to traverse elements as they existed upon
2791 * construction of the iterator, and may (but is not
2792 * guaranteed to) reflect any modifications subsequent to
2793 * construction.
2794 */
2795 public abstract Iterator<E> iterator();
2796 public abstract boolean contains(Object o);
2797 public abstract boolean remove(Object o);
2798
2799 private static final String oomeMsg = "Required array size too large";
2800
2801 public final Object[] toArray() {
2802 long sz = map.mappingCount();
2803 if (sz > MAX_ARRAY_SIZE)
2804 throw new OutOfMemoryError(oomeMsg);
2805 int n = (int)sz;
2806 Object[] r = new Object[n];
2807 int i = 0;
2808 for (E e : this) {
2809 if (i == n) {
2810 if (n >= MAX_ARRAY_SIZE)
2811 throw new OutOfMemoryError(oomeMsg);
2812 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2813 n = MAX_ARRAY_SIZE;
2814 else
2815 n += (n >>> 1) + 1;
2816 r = Arrays.copyOf(r, n);
2817 }
2818 r[i++] = e;
2819 }
2820 return (i == n) ? r : Arrays.copyOf(r, i);
2821 }
2822
2823 @SuppressWarnings("unchecked")
2824 public final <T> T[] toArray(T[] a) {
2825 long sz = map.mappingCount();
2826 if (sz > MAX_ARRAY_SIZE)
2827 throw new OutOfMemoryError(oomeMsg);
2828 int m = (int)sz;
2829 T[] r = (a.length >= m) ? a :
2830 (T[])java.lang.reflect.Array
2831 .newInstance(a.getClass().getComponentType(), m);
2832 int n = r.length;
2833 int i = 0;
2834 for (E e : this) {
2835 if (i == n) {
2836 if (n >= MAX_ARRAY_SIZE)
2837 throw new OutOfMemoryError(oomeMsg);
2838 if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2839 n = MAX_ARRAY_SIZE;
2840 else
2841 n += (n >>> 1) + 1;
2842 r = Arrays.copyOf(r, n);
2843 }
2844 r[i++] = (T)e;
2845 }
2846 if (a == r && i < n) {
2847 r[i] = null; // null-terminate
2848 return r;
2849 }
2850 return (i == n) ? r : Arrays.copyOf(r, i);
2851 }
2852
2853 /**
2854 * Returns a string representation of this collection.
2855 * The string representation consists of the string representations
2856 * of the collection's elements in the order they are returned by
2857 * its iterator, enclosed in square brackets ({@code "[]"}).
2858 * Adjacent elements are separated by the characters {@code ", "}
2859 * (comma and space). Elements are converted to strings as by
2860 * {@link String#valueOf(Object)}.
2861 *
2862 * @return a string representation of this collection
2863 */
2864 public final String toString() {
2865 StringBuilder sb = new StringBuilder();
2866 sb.append('[');
2867 Iterator<E> it = iterator();
2868 if (it.hasNext()) {
2869 for (;;) {
2870 Object e = it.next();
2871 sb.append(e == this ? "(this Collection)" : e);
2872 if (!it.hasNext())
2873 break;
2874 sb.append(',').append(' ');
2875 }
2876 }
2877 return sb.append(']').toString();
2878 }
2879
2880 public final boolean containsAll(Collection<?> c) {
2881 if (c != this) {
2882 for (Object e : c) {
2883 if (e == null || !contains(e))
2884 return false;
2885 }
2886 }
2887 return true;
2888 }
2889
2890 public final boolean removeAll(Collection<?> c) {
2891 boolean modified = false;
2892 for (Iterator<E> it = iterator(); it.hasNext();) {
2893 if (c.contains(it.next())) {
2894 it.remove();
2895 modified = true;
2896 }
2897 }
2898 return modified;
2899 }
2900
2901 public final boolean retainAll(Collection<?> c) {
2902 boolean modified = false;
2903 for (Iterator<E> it = iterator(); it.hasNext();) {
2904 if (!c.contains(it.next())) {
2905 it.remove();
2906 modified = true;
2907 }
2908 }
2909 return modified;
2910 }
2911
2912 }
2913
2914 /**
2915 * A view of a ConcurrentHashMap as a {@link Set} of keys, in
2916 * which additions may optionally be enabled by mapping to a
2917 * common value. This class cannot be directly instantiated.
2918 * See {@link #keySet() keySet()},
2919 * {@link #keySet(Object) keySet(V)},
2920 * {@link #newKeySet() newKeySet()},
2921 * {@link #newKeySet(int) newKeySet(int)}.
2922 *
2923 * @since 1.8
2924 */
2925 public static class KeySetView<K,V> extends CollectionView<K,V,K>
2926 implements Set<K>, java.io.Serializable {
2927 private static final long serialVersionUID = 7249069246763182397L;
2928 private final V value;
2929 KeySetView(ConcurrentHashMap<K,V> map, V value) { // non-public
2930 super(map);
2931 this.value = value;
2932 }
2933
2934 /**
2935 * Returns the default mapped value for additions,
2936 * or {@code null} if additions are not supported.
2937 *
2938 * @return the default mapped value for additions, or {@code null}
2939 * if not supported
2940 */
2941 public V getMappedValue() { return value; }
2942
2943 /**
2944 * {@inheritDoc}
2945 * @throws NullPointerException if the specified key is null
2946 */
2947 public boolean contains(Object o) { return map.containsKey(o); }
2948
2949 /**
2950 * Removes the key from this map view, by removing the key (and its
2951 * corresponding value) from the backing map. This method does
2952 * nothing if the key is not in the map.
2953 *
2954 * @param o the key to be removed from the backing map
2955 * @return {@code true} if the backing map contained the specified key
2956 * @throws NullPointerException if the specified key is null
2957 */
2958 public boolean remove(Object o) { return map.remove(o) != null; }
2959
2960 /**
2961 * @return an iterator over the keys of the backing map
2962 */
2963 public Iterator<K> iterator() {
2964 Node<K,V>[] t;
2965 ConcurrentHashMap<K,V> m = map;
2966 int f = (t = m.table) == null ? 0 : t.length;
2967 return new KeyIterator<K,V>(t, f, 0, f, m);
2968 }
2969
2970 /**
2971 * Adds the specified key to this set view by mapping the key to
2972 * the default mapped value in the backing map, if defined.
2973 *
2974 * @param e key to be added
2975 * @return {@code true} if this set changed as a result of the call
2976 * @throws NullPointerException if the specified key is null
2977 * @throws UnsupportedOperationException if no default mapped value
2978 * for additions was provided
2979 */
2980 public boolean add(K e) {
2981 V v;
2982 if ((v = value) == null)
2983 throw new UnsupportedOperationException();
2984 return map.putVal(e, v, true) == null;
2985 }
2986
2987 /**
2988 * Adds all of the elements in the specified collection to this set,
2989 * as if by calling {@link #add} on each one.
2990 *
2991 * @param c the elements to be inserted into this set
2992 * @return {@code true} if this set changed as a result of the call
2993 * @throws NullPointerException if the collection or any of its
2994 * elements are {@code null}
2995 * @throws UnsupportedOperationException if no default mapped value
2996 * for additions was provided
2997 */
2998 public boolean addAll(Collection<? extends K> c) {
2999 boolean added = false;
3000 V v;
3001 if ((v = value) == null)
3002 throw new UnsupportedOperationException();
3003 for (K e : c) {
3004 if (map.putVal(e, v, true) == null)
3005 added = true;
3006 }
3007 return added;
3008 }
3009
3010 public int hashCode() {
3011 int h = 0;
3012 for (K e : this)
3013 h += e.hashCode();
3014 return h;
3015 }
3016
3017 public boolean equals(Object o) {
3018 Set<?> c;
3019 return ((o instanceof Set) &&
3020 ((c = (Set<?>)o) == this ||
3021 (containsAll(c) && c.containsAll(this))));
3022 }
3023
3024 }
3025
3026 /**
3027 * A view of a ConcurrentHashMap as a {@link Collection} of
3028 * values, in which additions are disabled. This class cannot be
3029 * directly instantiated. See {@link #values()}.
3030 */
3031 static final class ValuesView<K,V> extends CollectionView<K,V,V>
3032 implements Collection<V>, java.io.Serializable {
3033 private static final long serialVersionUID = 2249069246763182397L;
3034 ValuesView(ConcurrentHashMap<K,V> map) { super(map); }
3035 public final boolean contains(Object o) {
3036 return map.containsValue(o);
3037 }
3038
3039 public final boolean remove(Object o) {
3040 if (o != null) {
3041 for (Iterator<V> it = iterator(); it.hasNext();) {
3042 if (o.equals(it.next())) {
3043 it.remove();
3044 return true;
3045 }
3046 }
3047 }
3048 return false;
3049 }
3050
3051 public final Iterator<V> iterator() {
3052 ConcurrentHashMap<K,V> m = map;
3053 Node<K,V>[] t;
3054 int f = (t = m.table) == null ? 0 : t.length;
3055 return new ValueIterator<K,V>(t, f, 0, f, m);
3056 }
3057
3058 public final boolean add(V e) {
3059 throw new UnsupportedOperationException();
3060 }
3061 public final boolean addAll(Collection<? extends V> c) {
3062 throw new UnsupportedOperationException();
3063 }
3064
3065 }
3066
3067 /**
3068 * A view of a ConcurrentHashMap as a {@link Set} of (key, value)
3069 * entries. This class cannot be directly instantiated. See
3070 * {@link #entrySet()}.
3071 */
3072 static final class EntrySetView<K,V> extends CollectionView<K,V,Map.Entry<K,V>>
3073 implements Set<Map.Entry<K,V>>, java.io.Serializable {
3074 private static final long serialVersionUID = 2249069246763182397L;
3075 EntrySetView(ConcurrentHashMap<K,V> map) { super(map); }
3076
3077 public boolean contains(Object o) {
3078 Object k, v, r; Map.Entry<?,?> e;
3079 return ((o instanceof Map.Entry) &&
3080 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3081 (r = map.get(k)) != null &&
3082 (v = e.getValue()) != null &&
3083 (v == r || v.equals(r)));
3084 }
3085
3086 public boolean remove(Object o) {
3087 Object k, v; Map.Entry<?,?> e;
3088 return ((o instanceof Map.Entry) &&
3089 (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
3090 (v = e.getValue()) != null &&
3091 map.remove(k, v));
3092 }
3093
3094 /**
3095 * @return an iterator over the entries of the backing map
3096 */
3097 public Iterator<Map.Entry<K,V>> iterator() {
3098 ConcurrentHashMap<K,V> m = map;
3099 Node<K,V>[] t;
3100 int f = (t = m.table) == null ? 0 : t.length;
3101 return new EntryIterator<K,V>(t, f, 0, f, m);
3102 }
3103
3104 public boolean add(Entry<K,V> e) {
3105 return map.putVal(e.getKey(), e.getValue(), false) == null;
3106 }
3107
3108 public boolean addAll(Collection<? extends Entry<K,V>> c) {
3109 boolean added = false;
3110 for (Entry<K,V> e : c) {
3111 if (add(e))
3112 added = true;
3113 }
3114 return added;
3115 }
3116
3117 public final int hashCode() {
3118 int h = 0;
3119 Node<K,V>[] t;
3120 if ((t = map.table) != null) {
3121 Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
3122 for (Node<K,V> p; (p = it.advance()) != null; ) {
3123 h += p.hashCode();
3124 }
3125 }
3126 return h;
3127 }
3128
3129 public final boolean equals(Object o) {
3130 Set<?> c;
3131 return ((o instanceof Set) &&
3132 ((c = (Set<?>)o) == this ||
3133 (containsAll(c) && c.containsAll(this))));
3134 }
3135
3136 }
3137
3138
3139 /* ---------------- Counters -------------- */
3140
3141 // Adapted from LongAdder and Striped64.
3142 // See their internal docs for explanation.
3143
3144 // A padded cell for distributing counts
3145 static final class CounterCell {
3146 volatile long p0, p1, p2, p3, p4, p5, p6;
3147 volatile long value;
3148 volatile long q0, q1, q2, q3, q4, q5, q6;
3149 CounterCell(long x) { value = x; }
3150 }
3151
3152 /**
3153 * Holder for the thread-local hash code determining which
3154 * CounterCell to use. The code is initialized via the
3155 * counterHashCodeGenerator, but may be moved upon collisions.
3156 */
3157 static final class CounterHashCode {
3158 int code;
3159 }
3160
3161 /**
3162 * Generates initial value for per-thread CounterHashCodes.
3163 */
3164 static final AtomicInteger counterHashCodeGenerator = new AtomicInteger();
3165
3166 /**
3167 * Increment for counterHashCodeGenerator. See class ThreadLocal
3168 * for explanation.
3169 */
3170 static final int SEED_INCREMENT = 0x61c88647;
3171
3172 /**
3173 * Per-thread counter hash codes. Shared across all instances.
3174 */
3175 static final ThreadLocal<CounterHashCode> threadCounterHashCode =
3176 new ThreadLocal<CounterHashCode>();
3177
3178 final long sumCount() {
3179 CounterCell[] as = counterCells; CounterCell a;
3180 long sum = baseCount;
3181 if (as != null) {
3182 for (int i = 0; i < as.length; ++i) {
3183 if ((a = as[i]) != null)
3184 sum += a.value;
3185 }
3186 }
3187 return sum;
3188 }
3189
3190 // See LongAdder version for explanation
3191 private final void fullAddCount(long x, CounterHashCode hc,
3192 boolean wasUncontended) {
3193 int h;
3194 if (hc == null) {
3195 hc = new CounterHashCode();
3196 int s = counterHashCodeGenerator.addAndGet(SEED_INCREMENT);
3197 h = hc.code = (s == 0) ? 1 : s; // Avoid zero
3198 threadCounterHashCode.set(hc);
3199 }
3200 else
3201 h = hc.code;
3202 boolean collide = false; // True if last slot nonempty
3203 for (;;) {
3204 CounterCell[] as; CounterCell a; int n; long v;
3205 if ((as = counterCells) != null && (n = as.length) > 0) {
3206 if ((a = as[(n - 1) & h]) == null) {
3207 if (cellsBusy == 0) { // Try to attach new Cell
3208 CounterCell r = new CounterCell(x); // Optimistic create
3209 if (cellsBusy == 0 &&
3210 U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3211 boolean created = false;
3212 try { // Recheck under lock
3213 CounterCell[] rs; int m, j;
3214 if ((rs = counterCells) != null &&
3215 (m = rs.length) > 0 &&
3216 rs[j = (m - 1) & h] == null) {
3217 rs[j] = r;
3218 created = true;
3219 }
3220 } finally {
3221 cellsBusy = 0;
3222 }
3223 if (created)
3224 break;
3225 continue; // Slot is now non-empty
3226 }
3227 }
3228 collide = false;
3229 }
3230 else if (!wasUncontended) // CAS already known to fail
3231 wasUncontended = true; // Continue after rehash
3232 else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
3233 break;
3234 else if (counterCells != as || n >= NCPU)
3235 collide = false; // At max size or stale
3236 else if (!collide)
3237 collide = true;
3238 else if (cellsBusy == 0 &&
3239 U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3240 try {
3241 if (counterCells == as) {// Expand table unless stale
3242 CounterCell[] rs = new CounterCell[n << 1];
3243 for (int i = 0; i < n; ++i)
3244 rs[i] = as[i];
3245 counterCells = rs;
3246 }
3247 } finally {
3248 cellsBusy = 0;
3249 }
3250 collide = false;
3251 continue; // Retry with expanded table
3252 }
3253 h ^= h << 13; // Rehash
3254 h ^= h >>> 17;
3255 h ^= h << 5;
3256 }
3257 else if (cellsBusy == 0 && counterCells == as &&
3258 U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
3259 boolean init = false;
3260 try { // Initialize table
3261 if (counterCells == as) {
3262 CounterCell[] rs = new CounterCell[2];
3263 rs[h & 1] = new CounterCell(x);
3264 counterCells = rs;
3265 init = true;
3266 }
3267 } finally {
3268 cellsBusy = 0;
3269 }
3270 if (init)
3271 break;
3272 }
3273 else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
3274 break; // Fall back on using base
3275 }
3276 hc.code = h; // Record index for next time
3277 }
3278
3279 // Unsafe mechanics
3280 private static final sun.misc.Unsafe U;
3281 private static final long SIZECTL;
3282 private static final long TRANSFERINDEX;
3283 private static final long BASECOUNT;
3284 private static final long CELLSBUSY;
3285 private static final long CELLVALUE;
3286 private static final long ABASE;
3287 private static final int ASHIFT;
3288
3289 static {
3290 try {
3291 U = sun.misc.Unsafe.getUnsafe();
3292 Class<?> k = ConcurrentHashMap.class;
3293 SIZECTL = U.objectFieldOffset
3294 (k.getDeclaredField("sizeCtl"));
3295 TRANSFERINDEX = U.objectFieldOffset
3296 (k.getDeclaredField("transferIndex"));
3297 BASECOUNT = U.objectFieldOffset
3298 (k.getDeclaredField("baseCount"));
3299 CELLSBUSY = U.objectFieldOffset
3300 (k.getDeclaredField("cellsBusy"));
3301 Class<?> ck = CounterCell.class;
3302 CELLVALUE = U.objectFieldOffset
3303 (ck.getDeclaredField("value"));
3304 Class<?> ak = Node[].class;
3305 ABASE = U.arrayBaseOffset(ak);
3306 int scale = U.arrayIndexScale(ak);
3307 if ((scale & (scale - 1)) != 0)
3308 throw new Error("data type scale not a power of two");
3309 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3310 } catch (Exception e) {
3311 throw new Error(e);
3312 }
3313 }
3314
3315 }