ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.106
Committed: Fri Apr 22 01:22:02 2011 UTC (13 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.105: +1 -1 lines
Log Message:
typo

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.locks.*;
9 import java.util.*;
10 import java.io.Serializable;
11 import java.io.IOException;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14
15 /**
16 * A hash table supporting full concurrency of retrievals and
17 * adjustable expected concurrency for updates. This class obeys the
18 * same functional specification as {@link java.util.Hashtable}, and
19 * includes versions of methods corresponding to each method of
20 * <tt>Hashtable</tt>. However, even though all operations are
21 * thread-safe, retrieval operations do <em>not</em> entail locking,
22 * and there is <em>not</em> any support for locking the entire table
23 * in a way that prevents all access. This class is fully
24 * interoperable with <tt>Hashtable</tt> in programs that rely on its
25 * thread safety but not on its synchronization details.
26 *
27 * <p> Retrieval operations (including <tt>get</tt>) generally do not
28 * block, so may overlap with update operations (including
29 * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
30 * of the most recently <em>completed</em> update operations holding
31 * upon their onset. For aggregate operations such as <tt>putAll</tt>
32 * and <tt>clear</tt>, concurrent retrievals may reflect insertion or
33 * removal of only some entries. Similarly, Iterators and
34 * Enumerations return elements reflecting the state of the hash table
35 * at some point at or since the creation of the iterator/enumeration.
36 * They do <em>not</em> throw {@link ConcurrentModificationException}.
37 * However, iterators are designed to be used by only one thread at a time.
38 *
39 * <p> The allowed concurrency among update operations is guided by
40 * the optional <tt>concurrencyLevel</tt> constructor argument
41 * (default <tt>16</tt>), which is used as a hint for internal sizing. The
42 * table is internally partitioned to try to permit the indicated
43 * number of concurrent updates without contention. Because placement
44 * in hash tables is essentially random, the actual concurrency will
45 * vary. Ideally, you should choose a value to accommodate as many
46 * threads as will ever concurrently modify the table. Using a
47 * significantly higher value than you need can waste space and time,
48 * and a significantly lower value can lead to thread contention. But
49 * overestimates and underestimates within an order of magnitude do
50 * not usually have much noticeable impact. A value of one is
51 * appropriate when it is known that only one thread will modify and
52 * all others will only read. Also, resizing this or any other kind of
53 * hash table is a relatively slow operation, so, when possible, it is
54 * a good idea to provide estimates of expected table sizes in
55 * constructors.
56 *
57 * <p>This class and its views and iterators implement all of the
58 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
59 * interfaces.
60 *
61 * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
62 * does <em>not</em> allow <tt>null</tt> to be used as a key or value.
63 *
64 * <p>This class is a member of the
65 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
66 * Java Collections Framework</a>.
67 *
68 * @since 1.5
69 * @author Doug Lea
70 * @param <K> the type of keys maintained by this map
71 * @param <V> the type of mapped values
72 */
73 public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
74 implements ConcurrentMap<K, V>, Serializable {
75 private static final long serialVersionUID = 7249069246763182397L;
76
77 /*
78 * The basic strategy is to subdivide the table among Segments,
79 * each of which itself is a concurrently readable hash table. To
80 * reduce footprint, all but one segments are constructed only
81 * when first needed (see ensureSegment). To maintain visibility
82 * in the presence of lazy construction, accesses to segments as
83 * well as elements of segment's table must use volatile access,
84 * which is done via Unsafe within methods segmentAt etc
85 * below. These provide the functionality of AtomicReferenceArrays
86 * but reduce the levels of indirection. Additionally,
87 * volatile-writes of table elements and entry "next" fields
88 * within locked operations use the cheaper "lazySet" forms of
89 * writes (via putOrderedObject) because these writes are always
90 * followed by lock releases that maintain sequential consistency
91 * of table updates.
92 *
93 * Historical note: The previous version of this class relied
94 * heavily on "final" fields, which avoided some volatile reads at
95 * the expense of a large initial footprint. Some remnants of
96 * that design (including forced construction of segment 0) exist
97 * to ensure serialization compatibility.
98 */
99
100 /* ---------------- Constants -------------- */
101
102 /**
103 * The default initial capacity for this table,
104 * used when not otherwise specified in a constructor.
105 */
106 static final int DEFAULT_INITIAL_CAPACITY = 16;
107
108 /**
109 * The default load factor for this table, used when not
110 * otherwise specified in a constructor.
111 */
112 static final float DEFAULT_LOAD_FACTOR = 0.75f;
113
114 /**
115 * The default concurrency level for this table, used when not
116 * otherwise specified in a constructor.
117 */
118 static final int DEFAULT_CONCURRENCY_LEVEL = 16;
119
120 /**
121 * The maximum capacity, used if a higher value is implicitly
122 * specified by either of the constructors with arguments. MUST
123 * be a power of two <= 1<<30 to ensure that entries are indexable
124 * using ints.
125 */
126 static final int MAXIMUM_CAPACITY = 1 << 30;
127
128 /**
129 * The minimum capacity for per-segment tables. Must be a power
130 * of two, at least two to avoid immediate resizing on next use
131 * after lazy construction.
132 */
133 static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
134
135 /**
136 * The maximum number of segments to allow; used to bound
137 * constructor arguments. Must be power of two less than 1 << 24.
138 */
139 static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
140
141 /**
142 * Number of unsynchronized retries in size and containsValue
143 * methods before resorting to locking. This is used to avoid
144 * unbounded retries if tables undergo continuous modification
145 * which would make it impossible to obtain an accurate result.
146 */
147 static final int RETRIES_BEFORE_LOCK = 2;
148
149 /* ---------------- Fields -------------- */
150
151 /**
152 * Mask value for indexing into segments. The upper bits of a
153 * key's hash code are used to choose the segment.
154 */
155 final int segmentMask;
156
157 /**
158 * Shift value for indexing within segments.
159 */
160 final int segmentShift;
161
162 /**
163 * The segments, each of which is a specialized hash table.
164 */
165 final Segment<K,V>[] segments;
166
167 transient Set<K> keySet;
168 transient Set<Map.Entry<K,V>> entrySet;
169 transient Collection<V> values;
170
171 /**
172 * ConcurrentHashMap list entry. Note that this is never exported
173 * out as a user-visible Map.Entry.
174 */
175 static final class HashEntry<K,V> {
176 final int hash;
177 final K key;
178 volatile V value;
179 volatile HashEntry<K,V> next;
180
181 HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
182 this.hash = hash;
183 this.key = key;
184 this.value = value;
185 this.next = next;
186 }
187
188 /**
189 * Sets next field with volatile write semantics. (See above
190 * about use of putOrderedObject.)
191 */
192 final void setNext(HashEntry<K,V> n) {
193 UNSAFE.putOrderedObject(this, nextOffset, n);
194 }
195
196 // Unsafe mechanics
197 static final sun.misc.Unsafe UNSAFE;
198 static final long nextOffset;
199 static {
200 try {
201 UNSAFE = sun.misc.Unsafe.getUnsafe();
202 Class k = HashEntry.class;
203 nextOffset = UNSAFE.objectFieldOffset
204 (k.getDeclaredField("next"));
205 } catch (Exception e) {
206 throw new Error(e);
207 }
208 }
209 }
210
211 /**
212 * Gets the ith element of given table (if nonnull) with volatile
213 * read semantics. Note: This is manually integrated into a few
214 * performance-sensitive methods to reduce call overhead.
215 */
216 @SuppressWarnings("unchecked")
217 static final <K,V> HashEntry<K,V> entryAt(HashEntry<K,V>[] tab, int i) {
218 return (tab == null) ? null :
219 (HashEntry<K,V>) UNSAFE.getObjectVolatile
220 (tab, ((long)i << TSHIFT) + TBASE);
221 }
222
223 /**
224 * Sets the ith element of given table, with volatile write
225 * semantics. (See above about use of putOrderedObject.)
226 */
227 static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
228 HashEntry<K,V> e) {
229 UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
230 }
231
232 /**
233 * Applies a supplemental hash function to a given hashCode, which
234 * defends against poor quality hash functions. This is critical
235 * because ConcurrentHashMap uses power-of-two length hash tables,
236 * that otherwise encounter collisions for hashCodes that do not
237 * differ in lower or upper bits.
238 */
239 private static int hash(int h) {
240 // Spread bits to regularize both segment and index locations,
241 // using variant of single-word Wang/Jenkins hash.
242 h += (h << 15) ^ 0xffffcd7d;
243 h ^= (h >>> 10);
244 h += (h << 3);
245 h ^= (h >>> 6);
246 h += (h << 2) + (h << 14);
247 return h ^ (h >>> 16);
248 }
249
250 /**
251 * Segments are specialized versions of hash tables. This
252 * subclasses from ReentrantLock opportunistically, just to
253 * simplify some locking and avoid separate construction.
254 */
255 static final class Segment<K,V> extends ReentrantLock implements Serializable {
256 /*
257 * Segments maintain a table of entry lists that are always
258 * kept in a consistent state, so can be read (via volatile
259 * reads of segments and tables) without locking. This
260 * requires replicating nodes when necessary during table
261 * resizing, so the old lists can be traversed by readers
262 * still using old version of table.
263 *
264 * This class defines only mutative methods requiring locking.
265 * Except as noted, the methods of this class perform the
266 * per-segment versions of ConcurrentHashMap methods. (Other
267 * methods are integrated directly into ConcurrentHashMap
268 * methods.) These mutative methods use a form of controlled
269 * spinning on contention via methods scanAndLock and
270 * scanAndLockForPut. These intersperse tryLocks with
271 * traversals to locate nodes. The main benefit is to absorb
272 * cache misses (which are very common for hash tables) while
273 * obtaining locks so that traversal is faster once
274 * acquired. We do not actually use the found nodes since they
275 * must be re-acquired under lock anyway to ensure sequential
276 * consistency of updates (and in any case may be undetectably
277 * stale), but they will normally be much faster to re-locate.
278 * Also, scanAndLockForPut speculatively creates a fresh node
279 * to use in put if no node is found.
280 */
281
282 private static final long serialVersionUID = 2249069246763182397L;
283
284 /**
285 * The maximum number of times to tryLock in a prescan before
286 * possibly blocking on acquire in preparation for a locked
287 * segment operation. On multiprocessors, using a bounded
288 * number of retries maintains cache acquired while locating
289 * nodes.
290 */
291 static final int MAX_SCAN_RETRIES =
292 Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
293
294 /**
295 * The per-segment table. Elements are accessed via
296 * entryAt/setEntryAt providing volatile semantics.
297 */
298 transient volatile HashEntry<K,V>[] table;
299
300 /**
301 * The number of elements. Accessed only either within locks
302 * or among other volatile reads that maintain visibility.
303 */
304 transient int count;
305
306 /**
307 * The total number of mutative operations in this segment.
308 * Even though this may overflows 32 bits, it provides
309 * sufficient accuracy for stability checks in CHM isEmpty()
310 * and size() methods. Accessed only either within locks or
311 * among other volatile reads that maintain visibility.
312 */
313 transient int modCount;
314
315 /**
316 * The table is rehashed when its size exceeds this threshold.
317 * (The value of this field is always <tt>(int)(capacity *
318 * loadFactor)</tt>.)
319 */
320 transient int threshold;
321
322 /**
323 * The load factor for the hash table. Even though this value
324 * is same for all segments, it is replicated to avoid needing
325 * links to outer object.
326 * @serial
327 */
328 final float loadFactor;
329
330 Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
331 this.loadFactor = lf;
332 this.threshold = threshold;
333 this.table = tab;
334 }
335
336 final V put(K key, int hash, V value, boolean onlyIfAbsent) {
337 HashEntry<K,V> node = tryLock() ? null :
338 scanAndLockForPut(key, hash, value);
339 V oldValue;
340 try {
341 HashEntry<K,V>[] tab = table;
342 int index = (tab.length - 1) & hash;
343 HashEntry<K,V> first = entryAt(tab, index);
344 for (HashEntry<K,V> e = first;;) {
345 if (e != null) {
346 K k;
347 if ((k = e.key) == key ||
348 (e.hash == hash && key.equals(k))) {
349 oldValue = e.value;
350 if (!onlyIfAbsent) {
351 e.value = value;
352 ++modCount;
353 }
354 break;
355 }
356 e = e.next;
357 }
358 else {
359 if (node != null)
360 node.setNext(first);
361 else
362 node = new HashEntry<K,V>(hash, key, value, first);
363 int c = count + 1;
364 if (c > threshold && tab.length < MAXIMUM_CAPACITY)
365 rehash(node);
366 else
367 setEntryAt(tab, index, node);
368 ++modCount;
369 count = c;
370 oldValue = null;
371 break;
372 }
373 }
374 } finally {
375 unlock();
376 }
377 return oldValue;
378 }
379
380 /**
381 * Doubles size of table and repacks entries, also adding the
382 * given node to new table
383 */
384 @SuppressWarnings("unchecked")
385 private void rehash(HashEntry<K,V> node) {
386 /*
387 * Reclassify nodes in each list to new table. Because we
388 * are using power-of-two expansion, the elements from
389 * each bin must either stay at same index, or move with a
390 * power of two offset. We eliminate unnecessary node
391 * creation by catching cases where old nodes can be
392 * reused because their next fields won't change.
393 * Statistically, at the default threshold, only about
394 * one-sixth of them need cloning when a table
395 * doubles. The nodes they replace will be garbage
396 * collectable as soon as they are no longer referenced by
397 * any reader thread that may be in the midst of
398 * concurrently traversing table. Entry accesses use plain
399 * array indexing because they are followed by volatile
400 * table write.
401 */
402 HashEntry<K,V>[] oldTable = table;
403 int oldCapacity = oldTable.length;
404 int newCapacity = oldCapacity << 1;
405 threshold = (int)(newCapacity * loadFactor);
406 HashEntry<K,V>[] newTable =
407 (HashEntry<K,V>[]) new HashEntry[newCapacity];
408 int sizeMask = newCapacity - 1;
409 for (int i = 0; i < oldCapacity ; i++) {
410 HashEntry<K,V> e = oldTable[i];
411 if (e != null) {
412 HashEntry<K,V> next = e.next;
413 int idx = e.hash & sizeMask;
414 if (next == null) // Single node on list
415 newTable[idx] = e;
416 else { // Reuse consecutive sequence at same slot
417 HashEntry<K,V> lastRun = e;
418 int lastIdx = idx;
419 for (HashEntry<K,V> last = next;
420 last != null;
421 last = last.next) {
422 int k = last.hash & sizeMask;
423 if (k != lastIdx) {
424 lastIdx = k;
425 lastRun = last;
426 }
427 }
428 newTable[lastIdx] = lastRun;
429 // Clone remaining nodes
430 for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
431 V v = p.value;
432 int h = p.hash;
433 int k = h & sizeMask;
434 HashEntry<K,V> n = newTable[k];
435 newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
436 }
437 }
438 }
439 }
440 int nodeIndex = node.hash & sizeMask; // add the new node
441 node.setNext(newTable[nodeIndex]);
442 newTable[nodeIndex] = node;
443 table = newTable;
444 }
445
446 /**
447 * Scans for a node containing given key while trying to
448 * acquire lock, creating and returning one if not found. Upon
449 * return, guarantees that lock is held. Unlike in most
450 * methods, calls to method equals are not screened: Since
451 * traversal speed doesn't matter, we might as well help warm
452 * up the associated code and accesses as well.
453 *
454 * @return a new node if key not found, else null
455 */
456 private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
457 HashEntry<K,V> first = entryForHash(this, hash);
458 HashEntry<K,V> e = first;
459 HashEntry<K,V> node = null;
460 int retries = -1; // negative while locating node
461 while (!tryLock()) {
462 HashEntry<K,V> f; // to recheck first below
463 if (retries < 0) {
464 if (e == null) {
465 if (node == null) // speculatively create node
466 node = new HashEntry<K,V>(hash, key, value, null);
467 retries = 0;
468 }
469 else if (key.equals(e.key))
470 retries = 0;
471 else
472 e = e.next;
473 }
474 else if (++retries > MAX_SCAN_RETRIES) {
475 lock();
476 break;
477 }
478 else if ((retries & 1) == 0 &&
479 (f = entryForHash(this, hash)) != first) {
480 e = first = f; // re-traverse if entry changed
481 retries = -1;
482 }
483 }
484 return node;
485 }
486
487 /**
488 * Scans for a node containing the given key while trying to
489 * acquire lock for a remove or replace operation. Upon
490 * return, guarantees that lock is held. Note that we must
491 * lock even if the key is not found, to ensure sequential
492 * consistency of updates.
493 */
494 private void scanAndLock(Object key, int hash) {
495 // similar to but simpler than scanAndLockForPut
496 HashEntry<K,V> first = entryForHash(this, hash);
497 HashEntry<K,V> e = first;
498 int retries = -1;
499 while (!tryLock()) {
500 HashEntry<K,V> f;
501 if (retries < 0) {
502 if (e == null || key.equals(e.key))
503 retries = 0;
504 else
505 e = e.next;
506 }
507 else if (++retries > MAX_SCAN_RETRIES) {
508 lock();
509 break;
510 }
511 else if ((retries & 1) == 0 &&
512 (f = entryForHash(this, hash)) != first) {
513 e = first = f;
514 retries = -1;
515 }
516 }
517 }
518
519 /**
520 * Remove; match on key only if value null, else match both.
521 */
522 final V remove(Object key, int hash, Object value) {
523 if (!tryLock())
524 scanAndLock(key, hash);
525 V oldValue = null;
526 try {
527 HashEntry<K,V>[] tab = table;
528 int index = (tab.length - 1) & hash;
529 HashEntry<K,V> e = entryAt(tab, index);
530 HashEntry<K,V> pred = null;
531 while (e != null) {
532 K k;
533 HashEntry<K,V> next = e.next;
534 if ((k = e.key) == key ||
535 (e.hash == hash && key.equals(k))) {
536 V v = e.value;
537 if (value == null || value == v || value.equals(v)) {
538 if (pred == null)
539 setEntryAt(tab, index, next);
540 else
541 pred.setNext(next);
542 ++modCount;
543 --count;
544 oldValue = v;
545 }
546 break;
547 }
548 pred = e;
549 e = next;
550 }
551 } finally {
552 unlock();
553 }
554 return oldValue;
555 }
556
557 final boolean replace(K key, int hash, V oldValue, V newValue) {
558 if (!tryLock())
559 scanAndLock(key, hash);
560 boolean replaced = false;
561 try {
562 HashEntry<K,V> e;
563 for (e = entryForHash(this, hash); e != null; e = e.next) {
564 K k;
565 if ((k = e.key) == key ||
566 (e.hash == hash && key.equals(k))) {
567 if (oldValue.equals(e.value)) {
568 e.value = newValue;
569 ++modCount;
570 replaced = true;
571 }
572 break;
573 }
574 }
575 } finally {
576 unlock();
577 }
578 return replaced;
579 }
580
581 final V replace(K key, int hash, V value) {
582 if (!tryLock())
583 scanAndLock(key, hash);
584 V oldValue = null;
585 try {
586 HashEntry<K,V> e;
587 for (e = entryForHash(this, hash); e != null; e = e.next) {
588 K k;
589 if ((k = e.key) == key ||
590 (e.hash == hash && key.equals(k))) {
591 oldValue = e.value;
592 e.value = value;
593 ++modCount;
594 break;
595 }
596 }
597 } finally {
598 unlock();
599 }
600 return oldValue;
601 }
602
603 final void clear() {
604 lock();
605 try {
606 HashEntry<K,V>[] tab = table;
607 for (int i = 0; i < tab.length ; i++)
608 setEntryAt(tab, i, null);
609 ++modCount;
610 count = 0;
611 } finally {
612 unlock();
613 }
614 }
615 }
616
617 // Accessing segments
618
619 /**
620 * Gets the jth element of given segment array (if nonnull) with
621 * volatile element access semantics via Unsafe. (The null check
622 * can trigger harmlessly only during deserialization.) Note:
623 * because each element of segments array is set only once (using
624 * fully ordered writes), some performance-sensitive methods rely
625 * on this method only as a recheck upon null reads.
626 */
627 @SuppressWarnings("unchecked")
628 static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
629 long u = (j << SSHIFT) + SBASE;
630 return ss == null ? null :
631 (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
632 }
633
634 /**
635 * Returns the segment for the given index, creating it and
636 * recording in segment table (via CAS) if not already present.
637 *
638 * @param k the index
639 * @return the segment
640 */
641 @SuppressWarnings("unchecked")
642 private Segment<K,V> ensureSegment(int k) {
643 final Segment<K,V>[] ss = this.segments;
644 long u = (k << SSHIFT) + SBASE; // raw offset
645 Segment<K,V> seg;
646 if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
647 Segment<K,V> proto = ss[0]; // use segment 0 as prototype
648 int cap = proto.table.length;
649 float lf = proto.loadFactor;
650 int threshold = (int)(cap * lf);
651 HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
652 if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
653 == null) { // recheck
654 Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
655 while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
656 == null) {
657 if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
658 break;
659 }
660 }
661 }
662 return seg;
663 }
664
665 // Hash-based segment and entry accesses
666
667 /**
668 * Get the segment for the given hash
669 */
670 @SuppressWarnings("unchecked")
671 private Segment<K,V> segmentForHash(int h) {
672 long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
673 return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
674 }
675
676 /**
677 * Gets the table entry for the given segment and hash
678 */
679 @SuppressWarnings("unchecked")
680 static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
681 HashEntry<K,V>[] tab;
682 return (seg == null || (tab = seg.table) == null) ? null :
683 (HashEntry<K,V>) UNSAFE.getObjectVolatile
684 (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
685 }
686
687 /* ---------------- Public operations -------------- */
688
689 /**
690 * Creates a new, empty map with the specified initial
691 * capacity, load factor and concurrency level.
692 *
693 * @param initialCapacity the initial capacity. The implementation
694 * performs internal sizing to accommodate this many elements.
695 * @param loadFactor the load factor threshold, used to control resizing.
696 * Resizing may be performed when the average number of elements per
697 * bin exceeds this threshold.
698 * @param concurrencyLevel the estimated number of concurrently
699 * updating threads. The implementation performs internal sizing
700 * to try to accommodate this many threads.
701 * @throws IllegalArgumentException if the initial capacity is
702 * negative or the load factor or concurrencyLevel are
703 * nonpositive.
704 */
705 @SuppressWarnings("unchecked")
706 public ConcurrentHashMap(int initialCapacity,
707 float loadFactor, int concurrencyLevel) {
708 if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
709 throw new IllegalArgumentException();
710 if (concurrencyLevel > MAX_SEGMENTS)
711 concurrencyLevel = MAX_SEGMENTS;
712 // Find power-of-two sizes best matching arguments
713 int sshift = 0;
714 int ssize = 1;
715 while (ssize < concurrencyLevel) {
716 ++sshift;
717 ssize <<= 1;
718 }
719 this.segmentShift = 32 - sshift;
720 this.segmentMask = ssize - 1;
721 if (initialCapacity > MAXIMUM_CAPACITY)
722 initialCapacity = MAXIMUM_CAPACITY;
723 int c = initialCapacity / ssize;
724 if (c * ssize < initialCapacity)
725 ++c;
726 int cap = MIN_SEGMENT_TABLE_CAPACITY;
727 while (cap < c)
728 cap <<= 1;
729 // create segments and segments[0]
730 Segment<K,V> s0 =
731 new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
732 (HashEntry<K,V>[])new HashEntry[cap]);
733 Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
734 UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
735 this.segments = ss;
736 }
737
738 /**
739 * Creates a new, empty map with the specified initial capacity
740 * and load factor and with the default concurrencyLevel (16).
741 *
742 * @param initialCapacity The implementation performs internal
743 * sizing to accommodate this many elements.
744 * @param loadFactor the load factor threshold, used to control resizing.
745 * Resizing may be performed when the average number of elements per
746 * bin exceeds this threshold.
747 * @throws IllegalArgumentException if the initial capacity of
748 * elements is negative or the load factor is nonpositive
749 *
750 * @since 1.6
751 */
752 public ConcurrentHashMap(int initialCapacity, float loadFactor) {
753 this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
754 }
755
756 /**
757 * Creates a new, empty map with the specified initial capacity,
758 * and with default load factor (0.75) and concurrencyLevel (16).
759 *
760 * @param initialCapacity the initial capacity. The implementation
761 * performs internal sizing to accommodate this many elements.
762 * @throws IllegalArgumentException if the initial capacity of
763 * elements is negative.
764 */
765 public ConcurrentHashMap(int initialCapacity) {
766 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
767 }
768
769 /**
770 * Creates a new, empty map with a default initial capacity (16),
771 * load factor (0.75) and concurrencyLevel (16).
772 */
773 public ConcurrentHashMap() {
774 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
775 }
776
777 /**
778 * Creates a new map with the same mappings as the given map.
779 * The map is created with a capacity of 1.5 times the number
780 * of mappings in the given map or 16 (whichever is greater),
781 * and a default load factor (0.75) and concurrencyLevel (16).
782 *
783 * @param m the map
784 */
785 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
786 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
787 DEFAULT_INITIAL_CAPACITY),
788 DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
789 putAll(m);
790 }
791
792 /**
793 * Returns <tt>true</tt> if this map contains no key-value mappings.
794 *
795 * @return <tt>true</tt> if this map contains no key-value mappings
796 */
797 public boolean isEmpty() {
798 /*
799 * Sum per-segment modCounts to avoid mis-reporting when
800 * elements are concurrently added and removed in one segment
801 * while checking another, in which case the table was never
802 * actually empty at any point. (The sum ensures accuracy up
803 * through at least 1<<31 per-segment modifications before
804 * recheck.) Methods size() and containsValue() use similar
805 * constructions for stability checks.
806 */
807 long sum = 0L;
808 final Segment<K,V>[] segments = this.segments;
809 for (int j = 0; j < segments.length; ++j) {
810 Segment<K,V> seg = segmentAt(segments, j);
811 if (seg != null) {
812 if (seg.count != 0)
813 return false;
814 sum += seg.modCount;
815 }
816 }
817 if (sum != 0L) { // recheck unless no modifications
818 for (int j = 0; j < segments.length; ++j) {
819 Segment<K,V> seg = segmentAt(segments, j);
820 if (seg != null) {
821 if (seg.count != 0)
822 return false;
823 sum -= seg.modCount;
824 }
825 }
826 if (sum != 0L)
827 return false;
828 }
829 return true;
830 }
831
832 /**
833 * Returns the number of key-value mappings in this map. If the
834 * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
835 * <tt>Integer.MAX_VALUE</tt>.
836 *
837 * @return the number of key-value mappings in this map
838 */
839 public int size() {
840 // Try a few times to get accurate count. On failure due to
841 // continuous async changes in table, resort to locking.
842 final Segment<K,V>[] segments = this.segments;
843 int size;
844 boolean overflow; // true if size overflows 32 bits
845 long sum; // sum of modCounts
846 long last = 0L; // previous sum
847 int retries = -1; // first iteration isn't retry
848 try {
849 for (;;) {
850 if (retries++ == RETRIES_BEFORE_LOCK) {
851 for (int j = 0; j < segments.length; ++j)
852 ensureSegment(j).lock(); // force creation
853 }
854 sum = 0L;
855 size = 0;
856 overflow = false;
857 for (int j = 0; j < segments.length; ++j) {
858 Segment<K,V> seg = segmentAt(segments, j);
859 if (seg != null) {
860 sum += seg.modCount;
861 int c = seg.count;
862 if (c < 0 || (size += c) < 0)
863 overflow = true;
864 }
865 }
866 if (sum == last)
867 break;
868 last = sum;
869 }
870 } finally {
871 if (retries > RETRIES_BEFORE_LOCK) {
872 for (int j = 0; j < segments.length; ++j)
873 segmentAt(segments, j).unlock();
874 }
875 }
876 return overflow ? Integer.MAX_VALUE : size;
877 }
878
879 /**
880 * Returns the value to which the specified key is mapped,
881 * or {@code null} if this map contains no mapping for the key.
882 *
883 * <p>More formally, if this map contains a mapping from a key
884 * {@code k} to a value {@code v} such that {@code key.equals(k)},
885 * then this method returns {@code v}; otherwise it returns
886 * {@code null}. (There can be at most one such mapping.)
887 *
888 * @throws NullPointerException if the specified key is null
889 */
890 public V get(Object key) {
891 Segment<K,V> s; // manually integrate access methods to reduce overhead
892 HashEntry<K,V>[] tab;
893 int h = hash(key.hashCode());
894 long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
895 if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
896 (tab = s.table) != null) {
897 for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
898 (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
899 e != null; e = e.next) {
900 K k;
901 if ((k = e.key) == key || (e.hash == h && key.equals(k)))
902 return e.value;
903 }
904 }
905 return null;
906 }
907
908 /**
909 * Tests if the specified object is a key in this table.
910 *
911 * @param key possible key
912 * @return <tt>true</tt> if and only if the specified object
913 * is a key in this table, as determined by the
914 * <tt>equals</tt> method; <tt>false</tt> otherwise.
915 * @throws NullPointerException if the specified key is null
916 */
917 @SuppressWarnings("unchecked")
918 public boolean containsKey(Object key) {
919 Segment<K,V> s; // same as get() except no need for volatile value read
920 HashEntry<K,V>[] tab;
921 int h = hash(key.hashCode());
922 long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
923 if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
924 (tab = s.table) != null) {
925 for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
926 (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
927 e != null; e = e.next) {
928 K k;
929 if ((k = e.key) == key || (e.hash == h && key.equals(k)))
930 return true;
931 }
932 }
933 return false;
934 }
935
936 /**
937 * Returns <tt>true</tt> if this map maps one or more keys to the
938 * specified value. Note: This method requires a full internal
939 * traversal of the hash table, and so is much slower than
940 * method <tt>containsKey</tt>.
941 *
942 * @param value value whose presence in this map is to be tested
943 * @return <tt>true</tt> if this map maps one or more keys to the
944 * specified value
945 * @throws NullPointerException if the specified value is null
946 */
947 public boolean containsValue(Object value) {
948 // Same idea as size()
949 if (value == null)
950 throw new NullPointerException();
951 final Segment<K,V>[] segments = this.segments;
952 boolean found = false;
953 long last = 0;
954 int retries = -1;
955 try {
956 outer: for (;;) {
957 if (retries++ == RETRIES_BEFORE_LOCK) {
958 for (int j = 0; j < segments.length; ++j)
959 ensureSegment(j).lock(); // force creation
960 }
961 long hashSum = 0L;
962 int sum = 0;
963 for (int j = 0; j < segments.length; ++j) {
964 HashEntry<K,V>[] tab;
965 Segment<K,V> seg = segmentAt(segments, j);
966 if (seg != null && (tab = seg.table) != null) {
967 for (int i = 0 ; i < tab.length; i++) {
968 HashEntry<K,V> e;
969 for (e = entryAt(tab, i); e != null; e = e.next) {
970 V v = e.value;
971 if (v != null && value.equals(v)) {
972 found = true;
973 break outer;
974 }
975 }
976 }
977 sum += seg.modCount;
978 }
979 }
980 if (retries > 0 && sum == last)
981 break;
982 last = sum;
983 }
984 } finally {
985 if (retries > RETRIES_BEFORE_LOCK) {
986 for (int j = 0; j < segments.length; ++j)
987 segmentAt(segments, j).unlock();
988 }
989 }
990 return found;
991 }
992
993 /**
994 * Legacy method testing if some key maps into the specified value
995 * in this table. This method is identical in functionality to
996 * {@link #containsValue}, and exists solely to ensure
997 * full compatibility with class {@link java.util.Hashtable},
998 * which supported this method prior to introduction of the
999 * Java Collections framework.
1000
1001 * @param value a value to search for
1002 * @return <tt>true</tt> if and only if some key maps to the
1003 * <tt>value</tt> argument in this table as
1004 * determined by the <tt>equals</tt> method;
1005 * <tt>false</tt> otherwise
1006 * @throws NullPointerException if the specified value is null
1007 */
1008 public boolean contains(Object value) {
1009 return containsValue(value);
1010 }
1011
1012 /**
1013 * Maps the specified key to the specified value in this table.
1014 * Neither the key nor the value can be null.
1015 *
1016 * <p> The value can be retrieved by calling the <tt>get</tt> method
1017 * with a key that is equal to the original key.
1018 *
1019 * @param key key with which the specified value is to be associated
1020 * @param value value to be associated with the specified key
1021 * @return the previous value associated with <tt>key</tt>, or
1022 * <tt>null</tt> if there was no mapping for <tt>key</tt>
1023 * @throws NullPointerException if the specified key or value is null
1024 */
1025 @SuppressWarnings("unchecked")
1026 public V put(K key, V value) {
1027 Segment<K,V> s;
1028 if (value == null)
1029 throw new NullPointerException();
1030 int hash = hash(key.hashCode());
1031 int j = (hash >>> segmentShift) & segmentMask;
1032 if ((s = (Segment<K,V>)UNSAFE.getObject // nonvolatile; recheck
1033 (segments, (j << SSHIFT) + SBASE)) == null) // in ensureSegment
1034 s = ensureSegment(j);
1035 return s.put(key, hash, value, false);
1036 }
1037
1038 /**
1039 * {@inheritDoc}
1040 *
1041 * @return the previous value associated with the specified key,
1042 * or <tt>null</tt> if there was no mapping for the key
1043 * @throws NullPointerException if the specified key or value is null
1044 */
1045 @SuppressWarnings("unchecked")
1046 public V putIfAbsent(K key, V value) {
1047 Segment<K,V> s;
1048 if (value == null)
1049 throw new NullPointerException();
1050 int hash = hash(key.hashCode());
1051 int j = (hash >>> segmentShift) & segmentMask;
1052 if ((s = (Segment<K,V>)UNSAFE.getObject
1053 (segments, (j << SSHIFT) + SBASE)) == null)
1054 s = ensureSegment(j);
1055 return s.put(key, hash, value, true);
1056 }
1057
1058 /**
1059 * Copies all of the mappings from the specified map to this one.
1060 * These mappings replace any mappings that this map had for any of the
1061 * keys currently in the specified map.
1062 *
1063 * @param m mappings to be stored in this map
1064 */
1065 public void putAll(Map<? extends K, ? extends V> m) {
1066 for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1067 put(e.getKey(), e.getValue());
1068 }
1069
1070 /**
1071 * Removes the key (and its corresponding value) from this map.
1072 * This method does nothing if the key is not in the map.
1073 *
1074 * @param key the key that needs to be removed
1075 * @return the previous value associated with <tt>key</tt>, or
1076 * <tt>null</tt> if there was no mapping for <tt>key</tt>
1077 * @throws NullPointerException if the specified key is null
1078 */
1079 public V remove(Object key) {
1080 int hash = hash(key.hashCode());
1081 Segment<K,V> s = segmentForHash(hash);
1082 return s == null ? null : s.remove(key, hash, null);
1083 }
1084
1085 /**
1086 * {@inheritDoc}
1087 *
1088 * @throws NullPointerException if the specified key is null
1089 */
1090 public boolean remove(Object key, Object value) {
1091 int hash = hash(key.hashCode());
1092 Segment<K,V> s;
1093 return value != null && (s = segmentForHash(hash)) != null &&
1094 s.remove(key, hash, value) != null;
1095 }
1096
1097 /**
1098 * {@inheritDoc}
1099 *
1100 * @throws NullPointerException if any of the arguments are null
1101 */
1102 public boolean replace(K key, V oldValue, V newValue) {
1103 int hash = hash(key.hashCode());
1104 if (oldValue == null || newValue == null)
1105 throw new NullPointerException();
1106 Segment<K,V> s = segmentForHash(hash);
1107 return s != null && s.replace(key, hash, oldValue, newValue);
1108 }
1109
1110 /**
1111 * {@inheritDoc}
1112 *
1113 * @return the previous value associated with the specified key,
1114 * or <tt>null</tt> if there was no mapping for the key
1115 * @throws NullPointerException if the specified key or value is null
1116 */
1117 public V replace(K key, V value) {
1118 int hash = hash(key.hashCode());
1119 if (value == null)
1120 throw new NullPointerException();
1121 Segment<K,V> s = segmentForHash(hash);
1122 return s == null ? null : s.replace(key, hash, value);
1123 }
1124
1125 /**
1126 * Removes all of the mappings from this map.
1127 */
1128 public void clear() {
1129 final Segment<K,V>[] segments = this.segments;
1130 for (int j = 0; j < segments.length; ++j) {
1131 Segment<K,V> s = segmentAt(segments, j);
1132 if (s != null)
1133 s.clear();
1134 }
1135 }
1136
1137 /**
1138 * Returns a {@link Set} view of the keys contained in this map.
1139 * The set is backed by the map, so changes to the map are
1140 * reflected in the set, and vice-versa. The set supports element
1141 * removal, which removes the corresponding mapping from this map,
1142 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1143 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1144 * operations. It does not support the <tt>add</tt> or
1145 * <tt>addAll</tt> operations.
1146 *
1147 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1148 * that will never throw {@link ConcurrentModificationException},
1149 * and guarantees to traverse elements as they existed upon
1150 * construction of the iterator, and may (but is not guaranteed to)
1151 * reflect any modifications subsequent to construction.
1152 */
1153 public Set<K> keySet() {
1154 Set<K> ks = keySet;
1155 return (ks != null) ? ks : (keySet = new KeySet());
1156 }
1157
1158 /**
1159 * Returns a {@link Collection} view of the values contained in this map.
1160 * The collection is backed by the map, so changes to the map are
1161 * reflected in the collection, and vice-versa. The collection
1162 * supports element removal, which removes the corresponding
1163 * mapping from this map, via the <tt>Iterator.remove</tt>,
1164 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1165 * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
1166 * support the <tt>add</tt> or <tt>addAll</tt> operations.
1167 *
1168 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1169 * that will never throw {@link ConcurrentModificationException},
1170 * and guarantees to traverse elements as they existed upon
1171 * construction of the iterator, and may (but is not guaranteed to)
1172 * reflect any modifications subsequent to construction.
1173 */
1174 public Collection<V> values() {
1175 Collection<V> vs = values;
1176 return (vs != null) ? vs : (values = new Values());
1177 }
1178
1179 /**
1180 * Returns a {@link Set} view of the mappings contained in this map.
1181 * The set is backed by the map, so changes to the map are
1182 * reflected in the set, and vice-versa. The set supports element
1183 * removal, which removes the corresponding mapping from the map,
1184 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1185 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1186 * operations. It does not support the <tt>add</tt> or
1187 * <tt>addAll</tt> operations.
1188 *
1189 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1190 * that will never throw {@link ConcurrentModificationException},
1191 * and guarantees to traverse elements as they existed upon
1192 * construction of the iterator, and may (but is not guaranteed to)
1193 * reflect any modifications subsequent to construction.
1194 */
1195 public Set<Map.Entry<K,V>> entrySet() {
1196 Set<Map.Entry<K,V>> es = entrySet;
1197 return (es != null) ? es : (entrySet = new EntrySet());
1198 }
1199
1200 /**
1201 * Returns an enumeration of the keys in this table.
1202 *
1203 * @return an enumeration of the keys in this table
1204 * @see #keySet()
1205 */
1206 public Enumeration<K> keys() {
1207 return new KeyIterator();
1208 }
1209
1210 /**
1211 * Returns an enumeration of the values in this table.
1212 *
1213 * @return an enumeration of the values in this table
1214 * @see #values()
1215 */
1216 public Enumeration<V> elements() {
1217 return new ValueIterator();
1218 }
1219
1220 /* ---------------- Iterator Support -------------- */
1221
1222 abstract class HashIterator {
1223 int nextSegmentIndex;
1224 int nextTableIndex;
1225 HashEntry<K,V>[] currentTable;
1226 HashEntry<K, V> nextEntry;
1227 HashEntry<K, V> lastReturned;
1228
1229 HashIterator() {
1230 nextSegmentIndex = segments.length - 1;
1231 nextTableIndex = -1;
1232 advance();
1233 }
1234
1235 /**
1236 * Set nextEntry to first node of next non-empty table
1237 * (in backwards order, to simplify checks).
1238 */
1239 final void advance() {
1240 for (;;) {
1241 if (nextTableIndex >= 0) {
1242 if ((nextEntry = entryAt(currentTable,
1243 nextTableIndex--)) != null)
1244 break;
1245 }
1246 else if (nextSegmentIndex >= 0) {
1247 Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
1248 if (seg != null && (currentTable = seg.table) != null)
1249 nextTableIndex = currentTable.length - 1;
1250 }
1251 else
1252 break;
1253 }
1254 }
1255
1256 final HashEntry<K,V> nextEntry() {
1257 HashEntry<K,V> e = nextEntry;
1258 if (e == null)
1259 throw new NoSuchElementException();
1260 lastReturned = e; // cannot assign until after null check
1261 if ((nextEntry = e.next) == null)
1262 advance();
1263 return e;
1264 }
1265
1266 public final boolean hasNext() { return nextEntry != null; }
1267 public final boolean hasMoreElements() { return nextEntry != null; }
1268
1269 public final void remove() {
1270 if (lastReturned == null)
1271 throw new IllegalStateException();
1272 ConcurrentHashMap.this.remove(lastReturned.key);
1273 lastReturned = null;
1274 }
1275 }
1276
1277 final class KeyIterator
1278 extends HashIterator
1279 implements Iterator<K>, Enumeration<K>
1280 {
1281 public final K next() { return super.nextEntry().key; }
1282 public final K nextElement() { return super.nextEntry().key; }
1283 }
1284
1285 final class ValueIterator
1286 extends HashIterator
1287 implements Iterator<V>, Enumeration<V>
1288 {
1289 public final V next() { return super.nextEntry().value; }
1290 public final V nextElement() { return super.nextEntry().value; }
1291 }
1292
1293 /**
1294 * Custom Entry class used by EntryIterator.next(), that relays
1295 * setValue changes to the underlying map.
1296 */
1297 final class WriteThroughEntry
1298 extends AbstractMap.SimpleEntry<K,V>
1299 {
1300 WriteThroughEntry(K k, V v) {
1301 super(k,v);
1302 }
1303
1304 /**
1305 * Set our entry's value and write through to the map. The
1306 * value to return is somewhat arbitrary here. Since a
1307 * WriteThroughEntry does not necessarily track asynchronous
1308 * changes, the most recent "previous" value could be
1309 * different from what we return (or could even have been
1310 * removed in which case the put will re-establish). We do not
1311 * and cannot guarantee more.
1312 */
1313 public V setValue(V value) {
1314 if (value == null) throw new NullPointerException();
1315 V v = super.setValue(value);
1316 ConcurrentHashMap.this.put(getKey(), value);
1317 return v;
1318 }
1319 }
1320
1321 final class EntryIterator
1322 extends HashIterator
1323 implements Iterator<Entry<K,V>>
1324 {
1325 public Map.Entry<K,V> next() {
1326 HashEntry<K,V> e = super.nextEntry();
1327 return new WriteThroughEntry(e.key, e.value);
1328 }
1329 }
1330
1331 final class KeySet extends AbstractSet<K> {
1332 public Iterator<K> iterator() {
1333 return new KeyIterator();
1334 }
1335 public int size() {
1336 return ConcurrentHashMap.this.size();
1337 }
1338 public boolean isEmpty() {
1339 return ConcurrentHashMap.this.isEmpty();
1340 }
1341 public boolean contains(Object o) {
1342 return ConcurrentHashMap.this.containsKey(o);
1343 }
1344 public boolean remove(Object o) {
1345 return ConcurrentHashMap.this.remove(o) != null;
1346 }
1347 public void clear() {
1348 ConcurrentHashMap.this.clear();
1349 }
1350 }
1351
1352 final class Values extends AbstractCollection<V> {
1353 public Iterator<V> iterator() {
1354 return new ValueIterator();
1355 }
1356 public int size() {
1357 return ConcurrentHashMap.this.size();
1358 }
1359 public boolean isEmpty() {
1360 return ConcurrentHashMap.this.isEmpty();
1361 }
1362 public boolean contains(Object o) {
1363 return ConcurrentHashMap.this.containsValue(o);
1364 }
1365 public void clear() {
1366 ConcurrentHashMap.this.clear();
1367 }
1368 }
1369
1370 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1371 public Iterator<Map.Entry<K,V>> iterator() {
1372 return new EntryIterator();
1373 }
1374 public boolean contains(Object o) {
1375 if (!(o instanceof Map.Entry))
1376 return false;
1377 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1378 V v = ConcurrentHashMap.this.get(e.getKey());
1379 return v != null && v.equals(e.getValue());
1380 }
1381 public boolean remove(Object o) {
1382 if (!(o instanceof Map.Entry))
1383 return false;
1384 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1385 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1386 }
1387 public int size() {
1388 return ConcurrentHashMap.this.size();
1389 }
1390 public boolean isEmpty() {
1391 return ConcurrentHashMap.this.isEmpty();
1392 }
1393 public void clear() {
1394 ConcurrentHashMap.this.clear();
1395 }
1396 }
1397
1398 /* ---------------- Serialization Support -------------- */
1399
1400 /**
1401 * Save the state of the <tt>ConcurrentHashMap</tt> instance to a
1402 * stream (i.e., serialize it).
1403 * @param s the stream
1404 * @serialData
1405 * the key (Object) and value (Object)
1406 * for each key-value mapping, followed by a null pair.
1407 * The key-value mappings are emitted in no particular order.
1408 */
1409 private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1410 // force all segments for serialization compatibility
1411 for (int k = 0; k < segments.length; ++k)
1412 ensureSegment(k);
1413 s.defaultWriteObject();
1414
1415 final Segment<K,V>[] segments = this.segments;
1416 for (int k = 0; k < segments.length; ++k) {
1417 Segment<K,V> seg = segmentAt(segments, k);
1418 seg.lock();
1419 try {
1420 HashEntry<K,V>[] tab = seg.table;
1421 for (int i = 0; i < tab.length; ++i) {
1422 HashEntry<K,V> e;
1423 for (e = entryAt(tab, i); e != null; e = e.next) {
1424 s.writeObject(e.key);
1425 s.writeObject(e.value);
1426 }
1427 }
1428 } finally {
1429 seg.unlock();
1430 }
1431 }
1432 s.writeObject(null);
1433 s.writeObject(null);
1434 }
1435
1436 /**
1437 * Reconstitute the <tt>ConcurrentHashMap</tt> instance from a
1438 * stream (i.e., deserialize it).
1439 * @param s the stream
1440 */
1441 @SuppressWarnings("unchecked")
1442 private void readObject(java.io.ObjectInputStream s)
1443 throws IOException, ClassNotFoundException {
1444 s.defaultReadObject();
1445
1446 // Re-initialize segments to be minimally sized, and let grow.
1447 int cap = MIN_SEGMENT_TABLE_CAPACITY;
1448 final Segment<K,V>[] segments = this.segments;
1449 for (int k = 0; k < segments.length; ++k) {
1450 Segment<K,V> seg = segments[k];
1451 if (seg != null) {
1452 seg.threshold = (int)(cap * seg.loadFactor);
1453 seg.table = (HashEntry<K,V>[]) new HashEntry[cap];
1454 }
1455 }
1456
1457 // Read the keys and values, and put the mappings in the table
1458 for (;;) {
1459 K key = (K) s.readObject();
1460 V value = (V) s.readObject();
1461 if (key == null)
1462 break;
1463 put(key, value);
1464 }
1465 }
1466
1467 // Unsafe mechanics
1468 private static final sun.misc.Unsafe UNSAFE;
1469 private static final long SBASE;
1470 private static final int SSHIFT;
1471 private static final long TBASE;
1472 private static final int TSHIFT;
1473
1474 static {
1475 int ss, ts;
1476 try {
1477 UNSAFE = sun.misc.Unsafe.getUnsafe();
1478 Class tc = HashEntry[].class;
1479 Class sc = Segment[].class;
1480 TBASE = UNSAFE.arrayBaseOffset(tc);
1481 SBASE = UNSAFE.arrayBaseOffset(sc);
1482 ts = UNSAFE.arrayIndexScale(tc);
1483 ss = UNSAFE.arrayIndexScale(sc);
1484 } catch (Exception e) {
1485 throw new Error(e);
1486 }
1487 if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
1488 throw new Error("data type scale not a power of two");
1489 SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1490 TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
1491 }
1492
1493 }