ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.50
Committed: Thu Jun 24 23:55:01 2004 UTC (19 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.49: +5 -6 lines
Log Message:
Documentation wording fixes

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/licenses/publicdomain
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
37 * {@link ConcurrentModificationException}. However, iterators are
38 * designed to be used by only one thread at a time.
39 *
40 * <p> The allowed concurrency among update operations is guided by
41 * the optional <tt>concurrencyLevel</tt> constructor argument
42 * (default 16), which is used as a hint for internal sizing. The
43 * table is internally partitioned to try to permit the indicated
44 * number of concurrent updates without contention. Because placement
45 * in hash tables is essentially random, the actual concurrency will
46 * vary. Ideally, you should choose a value to accommodate as many
47 * threads as will ever concurrently modify the table. Using a
48 * significantly higher value than you need can waste space and time,
49 * and a significantly lower value can lead to thread contention. But
50 * overestimates and underestimates within an order of magnitude do
51 * not usually have much noticeable impact. A value of one is
52 * appropriate when it is known that only one thread will modify and
53 * all others will only read. Also, resizing this or any other kind of
54 * hash table is a relatively slow operation, so, when possible, it is
55 * a good idea to provide estimates of expected table sizes in
56 * constructors.
57 *
58 * <p>This class and its views and iterators implement all of the
59 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
60 * interfaces.
61 *
62 * <p> Like {@link java.util.Hashtable} but unlike {@link
63 * java.util.HashMap}, this class does NOT allow <tt>null</tt> to be
64 * used as a key or value.
65 *
66 * <p>This class is a member of the
67 * <a href="{@docRoot}/../guide/collections/index.html">
68 * Java Collections Framework</a>.
69 *
70 * @since 1.5
71 * @author Doug Lea
72 * @param <K> the type of keys maintained by this map
73 * @param <V> the type of mapped values
74 */
75 public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
76 implements ConcurrentMap<K, V>, Serializable {
77 private static final long serialVersionUID = 7249069246763182397L;
78
79 /*
80 * The basic strategy is to subdivide the table among Segments,
81 * each of which itself is a concurrently readable hash table.
82 */
83
84 /* ---------------- Constants -------------- */
85
86 /**
87 * The default initial number of table slots for this table.
88 * Used when not otherwise specified in constructor.
89 */
90 static int DEFAULT_INITIAL_CAPACITY = 16;
91
92 /**
93 * The maximum capacity, used if a higher value is implicitly
94 * specified by either of the constructors with arguments. MUST
95 * be a power of two <= 1<<30 to ensure that entries are indexible
96 * using ints.
97 */
98 static final int MAXIMUM_CAPACITY = 1 << 30;
99
100 /**
101 * The default load factor for this table. Used when not
102 * otherwise specified in constructor.
103 */
104 static final float DEFAULT_LOAD_FACTOR = 0.75f;
105
106 /**
107 * The default number of concurrency control segments.
108 **/
109 static final int DEFAULT_SEGMENTS = 16;
110
111 /**
112 * The maximum number of segments to allow; used to bound
113 * constructor arguments.
114 */
115 static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
116
117 /**
118 * Number of unsynchronized retries in size and containsValue
119 * methods before resorting to locking. This is used to avoid
120 * unbounded retries if tables undergo continuous modification
121 * which would make it impossible to obtain an accurate result.
122 */
123 static final int RETRIES_BEFORE_LOCK = 2;
124
125 /* ---------------- Fields -------------- */
126
127 /**
128 * Mask value for indexing into segments. The upper bits of a
129 * key's hash code are used to choose the segment.
130 **/
131 final int segmentMask;
132
133 /**
134 * Shift value for indexing within segments.
135 **/
136 final int segmentShift;
137
138 /**
139 * The segments, each of which is a specialized hash table
140 */
141 final Segment[] segments;
142
143 transient Set<K> keySet;
144 transient Set<Map.Entry<K,V>> entrySet;
145 transient Collection<V> values;
146
147 /* ---------------- Small Utilities -------------- */
148
149 /**
150 * Returns a hash code for non-null Object x.
151 * Uses the same hash code spreader as most other java.util hash tables.
152 * @param x the object serving as a key
153 * @return the hash code
154 */
155 static int hash(Object x) {
156 int h = x.hashCode();
157 h += ~(h << 9);
158 h ^= (h >>> 14);
159 h += (h << 4);
160 h ^= (h >>> 10);
161 return h;
162 }
163
164 /**
165 * Returns the segment that should be used for key with given hash
166 * @param hash the hash code for the key
167 * @return the segment
168 */
169 final Segment<K,V> segmentFor(int hash) {
170 return (Segment<K,V>) segments[(hash >>> segmentShift) & segmentMask];
171 }
172
173 /* ---------------- Inner Classes -------------- */
174
175 /**
176 * ConcurrentHashMap list entry. Note that this is never exported
177 * out as a user-visible Map.Entry.
178 *
179 * Because the value field is volatile, not final, it is legal wrt
180 * the Java Memory Model for an unsynchronized reader to see null
181 * instead of initial value when read via a data race. Although a
182 * reordering leading to this is not likely to ever actually
183 * occur, the Segment.readValueUnderLock method is used as a
184 * backup in case a null (pre-initialized) value is ever seen in
185 * an unsynchronized access method.
186 */
187 static final class HashEntry<K,V> {
188 final K key;
189 final int hash;
190 volatile V value;
191 final HashEntry<K,V> next;
192
193 HashEntry(K key, int hash, HashEntry<K,V> next, V value) {
194 this.key = key;
195 this.hash = hash;
196 this.next = next;
197 this.value = value;
198 }
199 }
200
201 /**
202 * Segments are specialized versions of hash tables. This
203 * subclasses from ReentrantLock opportunistically, just to
204 * simplify some locking and avoid separate construction.
205 **/
206 static final class Segment<K,V> extends ReentrantLock implements Serializable {
207 /*
208 * Segments maintain a table of entry lists that are ALWAYS
209 * kept in a consistent state, so can be read without locking.
210 * Next fields of nodes are immutable (final). All list
211 * additions are performed at the front of each bin. This
212 * makes it easy to check changes, and also fast to traverse.
213 * When nodes would otherwise be changed, new nodes are
214 * created to replace them. This works well for hash tables
215 * since the bin lists tend to be short. (The average length
216 * is less than two for the default load factor threshold.)
217 *
218 * Read operations can thus proceed without locking, but rely
219 * on selected uses of volatiles to ensure that completed
220 * write operations performed by other threads are
221 * noticed. For most purposes, the "count" field, tracking the
222 * number of elements, serves as that volatile variable
223 * ensuring visibility. This is convenient because this field
224 * needs to be read in many read operations anyway:
225 *
226 * - All (unsynchronized) read operations must first read the
227 * "count" field, and should not look at table entries if
228 * it is 0.
229 *
230 * - All (synchronized) write operations should write to
231 * the "count" field after structurally changing any bin.
232 * The operations must not take any action that could even
233 * momentarily cause a concurrent read operation to see
234 * inconsistent data. This is made easier by the nature of
235 * the read operations in Map. For example, no operation
236 * can reveal that the table has grown but the threshold
237 * has not yet been updated, so there are no atomicity
238 * requirements for this with respect to reads.
239 *
240 * As a guide, all critical volatile reads and writes to the
241 * count field are marked in code comments.
242 */
243
244 private static final long serialVersionUID = 2249069246763182397L;
245
246 /**
247 * The number of elements in this segment's region.
248 **/
249 transient volatile int count;
250
251 /**
252 * Number of updates that alter the size of the table. This is
253 * used during bulk-read methods to make sure they see a
254 * consistent snapshot: If modCounts change during a traversal
255 * of segments computing size or checking containsValue, then
256 * we might have an inconsistent view of state so (usually)
257 * must retry.
258 */
259 transient int modCount;
260
261 /**
262 * The table is rehashed when its size exceeds this threshold.
263 * (The value of this field is always (int)(capacity *
264 * loadFactor).)
265 */
266 transient int threshold;
267
268 /**
269 * The per-segment table. Declared as a raw type, casted
270 * to HashEntry<K,V> on each use.
271 */
272 transient volatile HashEntry[] table;
273
274 /**
275 * The load factor for the hash table. Even though this value
276 * is same for all segments, it is replicated to avoid needing
277 * links to outer object.
278 * @serial
279 */
280 final float loadFactor;
281
282 Segment(int initialCapacity, float lf) {
283 loadFactor = lf;
284 setTable(new HashEntry[initialCapacity]);
285 }
286
287 /**
288 * Set table to new HashEntry array.
289 * Call only while holding lock or in constructor.
290 **/
291 void setTable(HashEntry[] newTable) {
292 threshold = (int)(newTable.length * loadFactor);
293 table = newTable;
294 }
295
296 /**
297 * Return properly casted first entry of bin for given hash
298 */
299 HashEntry<K,V> getFirst(int hash) {
300 HashEntry[] tab = table;
301 return (HashEntry<K,V>) tab[hash & (tab.length - 1)];
302 }
303
304 /**
305 * Read value field of an entry under lock. Called if value
306 * field ever appears to be null. This is possible only if a
307 * compiler happens to reorder a HashEntry initialization with
308 * its table assignment, which is legal under memory model
309 * but is not known to ever occur.
310 */
311 V readValueUnderLock(HashEntry<K,V> e) {
312 lock();
313 try {
314 return e.value;
315 } finally {
316 unlock();
317 }
318 }
319
320 /* Specialized implementations of map methods */
321
322 V get(Object key, int hash) {
323 if (count != 0) { // read-volatile
324 HashEntry<K,V> e = getFirst(hash);
325 while (e != null) {
326 if (e.hash == hash && key.equals(e.key)) {
327 V v = e.value;
328 if (v != null)
329 return v;
330 return readValueUnderLock(e); // recheck
331 }
332 e = e.next;
333 }
334 }
335 return null;
336 }
337
338 boolean containsKey(Object key, int hash) {
339 if (count != 0) { // read-volatile
340 HashEntry<K,V> e = getFirst(hash);
341 while (e != null) {
342 if (e.hash == hash && key.equals(e.key))
343 return true;
344 e = e.next;
345 }
346 }
347 return false;
348 }
349
350 boolean containsValue(Object value) {
351 if (count != 0) { // read-volatile
352 HashEntry[] tab = table;
353 int len = tab.length;
354 for (int i = 0 ; i < len; i++) {
355 for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i];
356 e != null ;
357 e = e.next) {
358 V v = e.value;
359 if (v == null) // recheck
360 v = readValueUnderLock(e);
361 if (value.equals(v))
362 return true;
363 }
364 }
365 }
366 return false;
367 }
368
369 boolean replace(K key, int hash, V oldValue, V newValue) {
370 lock();
371 try {
372 HashEntry<K,V> e = getFirst(hash);
373 while (e != null && (e.hash != hash || !key.equals(e.key)))
374 e = e.next;
375
376 boolean replaced = false;
377 if (e != null && oldValue.equals(e.value)) {
378 replaced = true;
379 e.value = newValue;
380 }
381 return replaced;
382 } finally {
383 unlock();
384 }
385 }
386
387 V replace(K key, int hash, V newValue) {
388 lock();
389 try {
390 HashEntry<K,V> e = getFirst(hash);
391 while (e != null && (e.hash != hash || !key.equals(e.key)))
392 e = e.next;
393
394 V oldValue = null;
395 if (e != null) {
396 oldValue = e.value;
397 e.value = newValue;
398 }
399 return oldValue;
400 } finally {
401 unlock();
402 }
403 }
404
405
406 V put(K key, int hash, V value, boolean onlyIfAbsent) {
407 lock();
408 try {
409 int c = count;
410 if (c++ > threshold) // ensure capacity
411 rehash();
412 HashEntry[] tab = table;
413 int index = hash & (tab.length - 1);
414 HashEntry<K,V> first = (HashEntry<K,V>) tab[index];
415 HashEntry<K,V> e = first;
416 while (e != null && (e.hash != hash || !key.equals(e.key)))
417 e = e.next;
418
419 V oldValue;
420 if (e != null) {
421 oldValue = e.value;
422 if (!onlyIfAbsent)
423 e.value = value;
424 }
425 else {
426 oldValue = null;
427 ++modCount;
428 tab[index] = new HashEntry<K,V>(key, hash, first, value);
429 count = c; // write-volatile
430 }
431 return oldValue;
432 } finally {
433 unlock();
434 }
435 }
436
437 void rehash() {
438 HashEntry[] oldTable = table;
439 int oldCapacity = oldTable.length;
440 if (oldCapacity >= MAXIMUM_CAPACITY)
441 return;
442
443 /*
444 * Reclassify nodes in each list to new Map. Because we are
445 * using power-of-two expansion, the elements from each bin
446 * must either stay at same index, or move with a power of two
447 * offset. We eliminate unnecessary node creation by catching
448 * cases where old nodes can be reused because their next
449 * fields won't change. Statistically, at the default
450 * threshold, only about one-sixth of them need cloning when
451 * a table doubles. The nodes they replace will be garbage
452 * collectable as soon as they are no longer referenced by any
453 * reader thread that may be in the midst of traversing table
454 * right now.
455 */
456
457 HashEntry[] newTable = new HashEntry[oldCapacity << 1];
458 threshold = (int)(newTable.length * loadFactor);
459 int sizeMask = newTable.length - 1;
460 for (int i = 0; i < oldCapacity ; i++) {
461 // We need to guarantee that any existing reads of old Map can
462 // proceed. So we cannot yet null out each bin.
463 HashEntry<K,V> e = (HashEntry<K,V>)oldTable[i];
464
465 if (e != null) {
466 HashEntry<K,V> next = e.next;
467 int idx = e.hash & sizeMask;
468
469 // Single node on list
470 if (next == null)
471 newTable[idx] = e;
472
473 else {
474 // Reuse trailing consecutive sequence at same slot
475 HashEntry<K,V> lastRun = e;
476 int lastIdx = idx;
477 for (HashEntry<K,V> last = next;
478 last != null;
479 last = last.next) {
480 int k = last.hash & sizeMask;
481 if (k != lastIdx) {
482 lastIdx = k;
483 lastRun = last;
484 }
485 }
486 newTable[lastIdx] = lastRun;
487
488 // Clone all remaining nodes
489 for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
490 int k = p.hash & sizeMask;
491 HashEntry<K,V> n = (HashEntry<K,V>)newTable[k];
492 newTable[k] = new HashEntry<K,V>(p.key, p.hash,
493 n, p.value);
494 }
495 }
496 }
497 }
498 table = newTable;
499 }
500
501 /**
502 * Remove; match on key only if value null, else match both.
503 */
504 V remove(Object key, int hash, Object value) {
505 lock();
506 try {
507 int c = count - 1;
508 HashEntry[] tab = table;
509 int index = hash & (tab.length - 1);
510 HashEntry<K,V> first = (HashEntry<K,V>)tab[index];
511 HashEntry<K,V> e = first;
512 while (e != null && (e.hash != hash || !key.equals(e.key)))
513 e = e.next;
514
515 V oldValue = null;
516 if (e != null) {
517 V v = e.value;
518 if (value == null || value.equals(v)) {
519 oldValue = v;
520 // All entries following removed node can stay
521 // in list, but all preceding ones need to be
522 // cloned.
523 ++modCount;
524 HashEntry<K,V> newFirst = e.next;
525 for (HashEntry<K,V> p = first; p != e; p = p.next)
526 newFirst = new HashEntry<K,V>(p.key, p.hash,
527 newFirst, p.value);
528 tab[index] = newFirst;
529 count = c; // write-volatile
530 }
531 }
532 return oldValue;
533 } finally {
534 unlock();
535 }
536 }
537
538 void clear() {
539 if (count != 0) {
540 lock();
541 try {
542 HashEntry[] tab = table;
543 for (int i = 0; i < tab.length ; i++)
544 tab[i] = null;
545 ++modCount;
546 count = 0; // write-volatile
547 } finally {
548 unlock();
549 }
550 }
551 }
552 }
553
554
555
556 /* ---------------- Public operations -------------- */
557
558 /**
559 * Creates a new, empty map with the specified initial
560 * capacity and the specified load factor.
561 *
562 * @param initialCapacity the initial capacity. The implementation
563 * performs internal sizing to accommodate this many elements.
564 * @param loadFactor the load factor threshold, used to control resizing.
565 * @param concurrencyLevel the estimated number of concurrently
566 * updating threads. The implementation performs internal sizing
567 * to try to accommodate this many threads.
568 * @throws IllegalArgumentException if the initial capacity is
569 * negative or the load factor or concurrencyLevel are
570 * nonpositive.
571 */
572 public ConcurrentHashMap(int initialCapacity,
573 float loadFactor, int concurrencyLevel) {
574 if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
575 throw new IllegalArgumentException();
576
577 if (concurrencyLevel > MAX_SEGMENTS)
578 concurrencyLevel = MAX_SEGMENTS;
579
580 // Find power-of-two sizes best matching arguments
581 int sshift = 0;
582 int ssize = 1;
583 while (ssize < concurrencyLevel) {
584 ++sshift;
585 ssize <<= 1;
586 }
587 segmentShift = 32 - sshift;
588 segmentMask = ssize - 1;
589 this.segments = new Segment[ssize];
590
591 if (initialCapacity > MAXIMUM_CAPACITY)
592 initialCapacity = MAXIMUM_CAPACITY;
593 int c = initialCapacity / ssize;
594 if (c * ssize < initialCapacity)
595 ++c;
596 int cap = 1;
597 while (cap < c)
598 cap <<= 1;
599
600 for (int i = 0; i < this.segments.length; ++i)
601 this.segments[i] = new Segment<K,V>(cap, loadFactor);
602 }
603
604 /**
605 * Creates a new, empty map with the specified initial
606 * capacity, and with default load factor and concurrencyLevel.
607 *
608 * @param initialCapacity The implementation performs internal
609 * sizing to accommodate this many elements.
610 * @throws IllegalArgumentException if the initial capacity of
611 * elements is negative.
612 */
613 public ConcurrentHashMap(int initialCapacity) {
614 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
615 }
616
617 /**
618 * Creates a new, empty map with a default initial capacity,
619 * load factor, and concurrencyLevel.
620 */
621 public ConcurrentHashMap() {
622 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
623 }
624
625 /**
626 * Creates a new map with the same mappings as the given map. The
627 * map is created with a capacity of twice the number of mappings in
628 * the given map or 11 (whichever is greater), and a default load factor
629 * and concurrencyLevel.
630 * @param t the map
631 */
632 public ConcurrentHashMap(Map<? extends K, ? extends V> t) {
633 this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
634 11),
635 DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
636 putAll(t);
637 }
638
639 // inherit Map javadoc
640 public boolean isEmpty() {
641 final Segment[] segments = this.segments;
642 /*
643 * We keep track of per-segment modCounts to avoid ABA
644 * problems in which an element in one segment was added and
645 * in another removed during traversal, in which case the
646 * table was never actually empty at any point. Note the
647 * similar use of modCounts in the size() and containsValue()
648 * methods, which are the only other methods also susceptible
649 * to ABA problems.
650 */
651 int[] mc = new int[segments.length];
652 int mcsum = 0;
653 for (int i = 0; i < segments.length; ++i) {
654 if (segments[i].count != 0)
655 return false;
656 else
657 mcsum += mc[i] = segments[i].modCount;
658 }
659 // If mcsum happens to be zero, then we know we got a snapshot
660 // before any modifications at all were made. This is
661 // probably common enough to bother tracking.
662 if (mcsum != 0) {
663 for (int i = 0; i < segments.length; ++i) {
664 if (segments[i].count != 0 ||
665 mc[i] != segments[i].modCount)
666 return false;
667 }
668 }
669 return true;
670 }
671
672 // inherit Map javadoc
673 public int size() {
674 final Segment[] segments = this.segments;
675 long sum = 0;
676 long check = 0;
677 int[] mc = new int[segments.length];
678 // Try a few times to get accurate count. On failure due to
679 // continuous async changes in table, resort to locking.
680 for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
681 check = 0;
682 sum = 0;
683 int mcsum = 0;
684 for (int i = 0; i < segments.length; ++i) {
685 sum += segments[i].count;
686 mcsum += mc[i] = segments[i].modCount;
687 }
688 if (mcsum != 0) {
689 for (int i = 0; i < segments.length; ++i) {
690 check += segments[i].count;
691 if (mc[i] != segments[i].modCount) {
692 check = -1; // force retry
693 break;
694 }
695 }
696 }
697 if (check == sum)
698 break;
699 }
700 if (check != sum) { // Resort to locking all segments
701 sum = 0;
702 for (int i = 0; i < segments.length; ++i)
703 segments[i].lock();
704 for (int i = 0; i < segments.length; ++i)
705 sum += segments[i].count;
706 for (int i = 0; i < segments.length; ++i)
707 segments[i].unlock();
708 }
709 if (sum > Integer.MAX_VALUE)
710 return Integer.MAX_VALUE;
711 else
712 return (int)sum;
713 }
714
715
716 /**
717 * Returns the value to which the specified key is mapped in this table.
718 *
719 * @param key a key in the table.
720 * @return the value to which the key is mapped in this table;
721 * <tt>null</tt> if the key is not mapped to any value in
722 * this table.
723 * @throws NullPointerException if the key is
724 * <tt>null</tt>.
725 */
726 public V get(Object key) {
727 int hash = hash(key); // throws NullPointerException if key null
728 return segmentFor(hash).get(key, hash);
729 }
730
731 /**
732 * Tests if the specified object is a key in this table.
733 *
734 * @param key possible key.
735 * @return <tt>true</tt> if and only if the specified object
736 * is a key in this table, as determined by the
737 * <tt>equals</tt> method; <tt>false</tt> otherwise.
738 * @throws NullPointerException if the key is
739 * <tt>null</tt>.
740 */
741 public boolean containsKey(Object key) {
742 int hash = hash(key); // throws NullPointerException if key null
743 return segmentFor(hash).containsKey(key, hash);
744 }
745
746 /**
747 * Returns <tt>true</tt> if this map maps one or more keys to the
748 * specified value. Note: This method requires a full internal
749 * traversal of the hash table, and so is much slower than
750 * method <tt>containsKey</tt>.
751 *
752 * @param value value whose presence in this map is to be tested.
753 * @return <tt>true</tt> if this map maps one or more keys to the
754 * specified value.
755 * @throws NullPointerException if the value is <tt>null</tt>.
756 */
757 public boolean containsValue(Object value) {
758 if (value == null)
759 throw new NullPointerException();
760
761 // See explanation of modCount use above
762
763 final Segment[] segments = this.segments;
764 int[] mc = new int[segments.length];
765
766 // Try a few times without locking
767 for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
768 int sum = 0;
769 int mcsum = 0;
770 for (int i = 0; i < segments.length; ++i) {
771 int c = segments[i].count;
772 mcsum += mc[i] = segments[i].modCount;
773 if (segments[i].containsValue(value))
774 return true;
775 }
776 boolean cleanSweep = true;
777 if (mcsum != 0) {
778 for (int i = 0; i < segments.length; ++i) {
779 int c = segments[i].count;
780 if (mc[i] != segments[i].modCount) {
781 cleanSweep = false;
782 break;
783 }
784 }
785 }
786 if (cleanSweep)
787 return false;
788 }
789 // Resort to locking all segments
790 for (int i = 0; i < segments.length; ++i)
791 segments[i].lock();
792 boolean found = false;
793 try {
794 for (int i = 0; i < segments.length; ++i) {
795 if (segments[i].containsValue(value)) {
796 found = true;
797 break;
798 }
799 }
800 } finally {
801 for (int i = 0; i < segments.length; ++i)
802 segments[i].unlock();
803 }
804 return found;
805 }
806
807 /**
808 * Legacy method testing if some key maps into the specified value
809 * in this table. This method is identical in functionality to
810 * {@link #containsValue}, and exists solely to ensure
811 * full compatibility with class {@link java.util.Hashtable},
812 * which supported this method prior to introduction of the
813 * Java Collections framework.
814
815 * @param value a value to search for.
816 * @return <tt>true</tt> if and only if some key maps to the
817 * <tt>value</tt> argument in this table as
818 * determined by the <tt>equals</tt> method;
819 * <tt>false</tt> otherwise.
820 * @throws NullPointerException if the value is <tt>null</tt>.
821 */
822 public boolean contains(Object value) {
823 return containsValue(value);
824 }
825
826 /**
827 * Maps the specified <tt>key</tt> to the specified
828 * <tt>value</tt> in this table. Neither the key nor the
829 * value can be <tt>null</tt>.
830 *
831 * <p> The value can be retrieved by calling the <tt>get</tt> method
832 * with a key that is equal to the original key.
833 *
834 * @param key the table key.
835 * @param value the value.
836 * @return the previous value of the specified key in this table,
837 * or <tt>null</tt> if it did not have one.
838 * @throws NullPointerException if the key or value is
839 * <tt>null</tt>.
840 */
841 public V put(K key, V value) {
842 if (value == null)
843 throw new NullPointerException();
844 int hash = hash(key);
845 return segmentFor(hash).put(key, hash, value, false);
846 }
847
848 /**
849 * If the specified key is not already associated
850 * with a value, associate it with the given value.
851 * This is equivalent to
852 * <pre>
853 * if (!map.containsKey(key))
854 * return map.put(key, value);
855 * else
856 * return map.get(key);
857 * </pre>
858 * Except that the action is performed atomically.
859 * @param key key with which the specified value is to be associated.
860 * @param value value to be associated with the specified key.
861 * @return previous value associated with specified key, or <tt>null</tt>
862 * if there was no mapping for key. A <tt>null</tt> return can
863 * also indicate that the map previously associated <tt>null</tt>
864 * with the specified key, if the implementation supports
865 * <tt>null</tt> values.
866 *
867 * @throws ClassCastException if the class of the specified key or value
868 * prevents it from being stored in this map.
869 * @throws NullPointerException if the specified key or value is
870 * <tt>null</tt>.
871 *
872 **/
873 public V putIfAbsent(K key, V value) {
874 if (value == null)
875 throw new NullPointerException();
876 int hash = hash(key);
877 return segmentFor(hash).put(key, hash, value, true);
878 }
879
880
881 /**
882 * Copies all of the mappings from the specified map to this one.
883 *
884 * These mappings replace any mappings that this map had for any of the
885 * keys currently in the specified Map.
886 *
887 * @param t Mappings to be stored in this map.
888 */
889 public void putAll(Map<? extends K, ? extends V> t) {
890 for (Iterator<? extends Map.Entry<? extends K, ? extends V>> it = (Iterator<? extends Map.Entry<? extends K, ? extends V>>) t.entrySet().iterator(); it.hasNext(); ) {
891 Entry<? extends K, ? extends V> e = it.next();
892 put(e.getKey(), e.getValue());
893 }
894 }
895
896 /**
897 * Removes the key (and its corresponding value) from this
898 * table. This method does nothing if the key is not in the table.
899 *
900 * @param key the key that needs to be removed.
901 * @return the value to which the key had been mapped in this table,
902 * or <tt>null</tt> if the key did not have a mapping.
903 * @throws NullPointerException if the key is
904 * <tt>null</tt>.
905 */
906 public V remove(Object key) {
907 int hash = hash(key);
908 return segmentFor(hash).remove(key, hash, null);
909 }
910
911 /**
912 * Remove entry for key only if currently mapped to given value.
913 * Acts as
914 * <pre>
915 * if (map.get(key).equals(value)) {
916 * map.remove(key);
917 * return true;
918 * } else return false;
919 * </pre>
920 * except that the action is performed atomically.
921 * @param key key with which the specified value is associated.
922 * @param value value associated with the specified key.
923 * @return true if the value was removed
924 * @throws NullPointerException if the specified key is
925 * <tt>null</tt>.
926 */
927 public boolean remove(Object key, Object value) {
928 int hash = hash(key);
929 return segmentFor(hash).remove(key, hash, value) != null;
930 }
931
932
933 /**
934 * Replace entry for key only if currently mapped to given value.
935 * Acts as
936 * <pre>
937 * if (map.get(key).equals(oldValue)) {
938 * map.put(key, newValue);
939 * return true;
940 * } else return false;
941 * </pre>
942 * except that the action is performed atomically.
943 * @param key key with which the specified value is associated.
944 * @param oldValue value expected to be associated with the specified key.
945 * @param newValue value to be associated with the specified key.
946 * @return true if the value was replaced
947 * @throws NullPointerException if the specified key or values are
948 * <tt>null</tt>.
949 */
950 public boolean replace(K key, V oldValue, V newValue) {
951 if (oldValue == null || newValue == null)
952 throw new NullPointerException();
953 int hash = hash(key);
954 return segmentFor(hash).replace(key, hash, oldValue, newValue);
955 }
956
957 /**
958 * Replace entry for key only if currently mapped to some value.
959 * Acts as
960 * <pre>
961 * if ((map.containsKey(key)) {
962 * return map.put(key, value);
963 * } else return null;
964 * </pre>
965 * except that the action is performed atomically.
966 * @param key key with which the specified value is associated.
967 * @param value value to be associated with the specified key.
968 * @return previous value associated with specified key, or <tt>null</tt>
969 * if there was no mapping for key.
970 * @throws NullPointerException if the specified key or value is
971 * <tt>null</tt>.
972 */
973 public V replace(K key, V value) {
974 if (value == null)
975 throw new NullPointerException();
976 int hash = hash(key);
977 return segmentFor(hash).replace(key, hash, value);
978 }
979
980
981 /**
982 * Removes all mappings from this map.
983 */
984 public void clear() {
985 for (int i = 0; i < segments.length; ++i)
986 segments[i].clear();
987 }
988
989 /**
990 * Returns a set view of the keys contained in this map. The set is
991 * backed by the map, so changes to the map are reflected in the set, and
992 * vice-versa. The set supports element removal, which removes the
993 * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
994 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
995 * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
996 * <tt>addAll</tt> operations.
997 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
998 * will never throw {@link java.util.ConcurrentModificationException},
999 * and guarantees to traverse elements as they existed upon
1000 * construction of the iterator, and may (but is not guaranteed to)
1001 * reflect any modifications subsequent to construction.
1002 *
1003 * @return a set view of the keys contained in this map.
1004 */
1005 public Set<K> keySet() {
1006 Set<K> ks = keySet;
1007 return (ks != null) ? ks : (keySet = new KeySet());
1008 }
1009
1010
1011 /**
1012 * Returns a collection view of the values contained in this map. The
1013 * collection is backed by the map, so changes to the map are reflected in
1014 * the collection, and vice-versa. The collection supports element
1015 * removal, which removes the corresponding mapping from this map, via the
1016 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
1017 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
1018 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
1019 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
1020 * will never throw {@link java.util.ConcurrentModificationException},
1021 * and guarantees to traverse elements as they existed upon
1022 * construction of the iterator, and may (but is not guaranteed to)
1023 * reflect any modifications subsequent to construction.
1024 *
1025 * @return a collection view of the values contained in this map.
1026 */
1027 public Collection<V> values() {
1028 Collection<V> vs = values;
1029 return (vs != null) ? vs : (values = new Values());
1030 }
1031
1032
1033 /**
1034 * Returns a collection view of the mappings contained in this map. Each
1035 * element in the returned collection is a <tt>Map.Entry</tt>. The
1036 * collection is backed by the map, so changes to the map are reflected in
1037 * the collection, and vice-versa. The collection supports element
1038 * removal, which removes the corresponding mapping from the map, via the
1039 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
1040 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
1041 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
1042 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
1043 * will never throw {@link java.util.ConcurrentModificationException},
1044 * and guarantees to traverse elements as they existed upon
1045 * construction of the iterator, and may (but is not guaranteed to)
1046 * reflect any modifications subsequent to construction.
1047 *
1048 * @return a collection view of the mappings contained in this map.
1049 */
1050 public Set<Map.Entry<K,V>> entrySet() {
1051 Set<Map.Entry<K,V>> es = entrySet;
1052 return (es != null) ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet());
1053 }
1054
1055
1056 /**
1057 * Returns an enumeration of the keys in this table.
1058 *
1059 * @return an enumeration of the keys in this table.
1060 * @see #keySet
1061 */
1062 public Enumeration<K> keys() {
1063 return new KeyIterator();
1064 }
1065
1066 /**
1067 * Returns an enumeration of the values in this table.
1068 *
1069 * @return an enumeration of the values in this table.
1070 * @see #values
1071 */
1072 public Enumeration<V> elements() {
1073 return new ValueIterator();
1074 }
1075
1076 /* ---------------- Iterator Support -------------- */
1077
1078 abstract class HashIterator {
1079 int nextSegmentIndex;
1080 int nextTableIndex;
1081 HashEntry[] currentTable;
1082 HashEntry<K, V> nextEntry;
1083 HashEntry<K, V> lastReturned;
1084
1085 HashIterator() {
1086 nextSegmentIndex = segments.length - 1;
1087 nextTableIndex = -1;
1088 advance();
1089 }
1090
1091 public boolean hasMoreElements() { return hasNext(); }
1092
1093 final void advance() {
1094 if (nextEntry != null && (nextEntry = nextEntry.next) != null)
1095 return;
1096
1097 while (nextTableIndex >= 0) {
1098 if ( (nextEntry = (HashEntry<K,V>)currentTable[nextTableIndex--]) != null)
1099 return;
1100 }
1101
1102 while (nextSegmentIndex >= 0) {
1103 Segment<K,V> seg = (Segment<K,V>)segments[nextSegmentIndex--];
1104 if (seg.count != 0) {
1105 currentTable = seg.table;
1106 for (int j = currentTable.length - 1; j >= 0; --j) {
1107 if ( (nextEntry = (HashEntry<K,V>)currentTable[j]) != null) {
1108 nextTableIndex = j - 1;
1109 return;
1110 }
1111 }
1112 }
1113 }
1114 }
1115
1116 public boolean hasNext() { return nextEntry != null; }
1117
1118 HashEntry<K,V> nextEntry() {
1119 if (nextEntry == null)
1120 throw new NoSuchElementException();
1121 lastReturned = nextEntry;
1122 advance();
1123 return lastReturned;
1124 }
1125
1126 public void remove() {
1127 if (lastReturned == null)
1128 throw new IllegalStateException();
1129 ConcurrentHashMap.this.remove(lastReturned.key);
1130 lastReturned = null;
1131 }
1132 }
1133
1134 final class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> {
1135 public K next() { return super.nextEntry().key; }
1136 public K nextElement() { return super.nextEntry().key; }
1137 }
1138
1139 final class ValueIterator extends HashIterator implements Iterator<V>, Enumeration<V> {
1140 public V next() { return super.nextEntry().value; }
1141 public V nextElement() { return super.nextEntry().value; }
1142 }
1143
1144
1145
1146 /**
1147 * Entry iterator. Exported Entry objects must write-through
1148 * changes in setValue, even if the nodes have been cloned. So we
1149 * cannot return internal HashEntry objects. Instead, the iterator
1150 * itself acts as a forwarding pseudo-entry.
1151 */
1152 final class EntryIterator extends HashIterator implements Map.Entry<K,V>, Iterator<Entry<K,V>> {
1153 public Map.Entry<K,V> next() {
1154 nextEntry();
1155 return this;
1156 }
1157
1158 public K getKey() {
1159 if (lastReturned == null)
1160 throw new IllegalStateException("Entry was removed");
1161 return lastReturned.key;
1162 }
1163
1164 public V getValue() {
1165 if (lastReturned == null)
1166 throw new IllegalStateException("Entry was removed");
1167 return ConcurrentHashMap.this.get(lastReturned.key);
1168 }
1169
1170 public V setValue(V value) {
1171 if (lastReturned == null)
1172 throw new IllegalStateException("Entry was removed");
1173 return ConcurrentHashMap.this.put(lastReturned.key, value);
1174 }
1175
1176 public boolean equals(Object o) {
1177 // If not acting as entry, just use default.
1178 if (lastReturned == null)
1179 return super.equals(o);
1180 if (!(o instanceof Map.Entry))
1181 return false;
1182 Map.Entry e = (Map.Entry)o;
1183 return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue());
1184 }
1185
1186 public int hashCode() {
1187 // If not acting as entry, just use default.
1188 if (lastReturned == null)
1189 return super.hashCode();
1190
1191 Object k = getKey();
1192 Object v = getValue();
1193 return ((k == null) ? 0 : k.hashCode()) ^
1194 ((v == null) ? 0 : v.hashCode());
1195 }
1196
1197 public String toString() {
1198 // If not acting as entry, just use default.
1199 if (lastReturned == null)
1200 return super.toString();
1201 else
1202 return getKey() + "=" + getValue();
1203 }
1204
1205 boolean eq(Object o1, Object o2) {
1206 return (o1 == null ? o2 == null : o1.equals(o2));
1207 }
1208
1209 }
1210
1211 final class KeySet extends AbstractSet<K> {
1212 public Iterator<K> iterator() {
1213 return new KeyIterator();
1214 }
1215 public int size() {
1216 return ConcurrentHashMap.this.size();
1217 }
1218 public boolean contains(Object o) {
1219 return ConcurrentHashMap.this.containsKey(o);
1220 }
1221 public boolean remove(Object o) {
1222 return ConcurrentHashMap.this.remove(o) != null;
1223 }
1224 public void clear() {
1225 ConcurrentHashMap.this.clear();
1226 }
1227 public Object[] toArray() {
1228 Collection<K> c = new ArrayList<K>();
1229 for (Iterator<K> i = iterator(); i.hasNext(); )
1230 c.add(i.next());
1231 return c.toArray();
1232 }
1233 public <T> T[] toArray(T[] a) {
1234 Collection<K> c = new ArrayList<K>();
1235 for (Iterator<K> i = iterator(); i.hasNext(); )
1236 c.add(i.next());
1237 return c.toArray(a);
1238 }
1239 }
1240
1241 final class Values extends AbstractCollection<V> {
1242 public Iterator<V> iterator() {
1243 return new ValueIterator();
1244 }
1245 public int size() {
1246 return ConcurrentHashMap.this.size();
1247 }
1248 public boolean contains(Object o) {
1249 return ConcurrentHashMap.this.containsValue(o);
1250 }
1251 public void clear() {
1252 ConcurrentHashMap.this.clear();
1253 }
1254 public Object[] toArray() {
1255 Collection<V> c = new ArrayList<V>();
1256 for (Iterator<V> i = iterator(); i.hasNext(); )
1257 c.add(i.next());
1258 return c.toArray();
1259 }
1260 public <T> T[] toArray(T[] a) {
1261 Collection<V> c = new ArrayList<V>();
1262 for (Iterator<V> i = iterator(); i.hasNext(); )
1263 c.add(i.next());
1264 return c.toArray(a);
1265 }
1266 }
1267
1268 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1269 public Iterator<Map.Entry<K,V>> iterator() {
1270 return new EntryIterator();
1271 }
1272 public boolean contains(Object o) {
1273 if (!(o instanceof Map.Entry))
1274 return false;
1275 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
1276 V v = ConcurrentHashMap.this.get(e.getKey());
1277 return v != null && v.equals(e.getValue());
1278 }
1279 public boolean remove(Object o) {
1280 if (!(o instanceof Map.Entry))
1281 return false;
1282 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
1283 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1284 }
1285 public int size() {
1286 return ConcurrentHashMap.this.size();
1287 }
1288 public void clear() {
1289 ConcurrentHashMap.this.clear();
1290 }
1291 public Object[] toArray() {
1292 // Since we don't ordinarily have distinct Entry objects, we
1293 // must pack elements using exportable SimpleEntry
1294 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
1295 for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
1296 c.add(new SimpleEntry<K,V>(i.next()));
1297 return c.toArray();
1298 }
1299 public <T> T[] toArray(T[] a) {
1300 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
1301 for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
1302 c.add(new SimpleEntry<K,V>(i.next()));
1303 return c.toArray(a);
1304 }
1305
1306 }
1307
1308 /**
1309 * This duplicates java.util.AbstractMap.SimpleEntry until this class
1310 * is made accessible.
1311 */
1312 static final class SimpleEntry<K,V> implements Entry<K,V> {
1313 K key;
1314 V value;
1315
1316 public SimpleEntry(K key, V value) {
1317 this.key = key;
1318 this.value = value;
1319 }
1320
1321 public SimpleEntry(Entry<K,V> e) {
1322 this.key = e.getKey();
1323 this.value = e.getValue();
1324 }
1325
1326 public K getKey() {
1327 return key;
1328 }
1329
1330 public V getValue() {
1331 return value;
1332 }
1333
1334 public V setValue(V value) {
1335 V oldValue = this.value;
1336 this.value = value;
1337 return oldValue;
1338 }
1339
1340 public boolean equals(Object o) {
1341 if (!(o instanceof Map.Entry))
1342 return false;
1343 Map.Entry e = (Map.Entry)o;
1344 return eq(key, e.getKey()) && eq(value, e.getValue());
1345 }
1346
1347 public int hashCode() {
1348 return ((key == null) ? 0 : key.hashCode()) ^
1349 ((value == null) ? 0 : value.hashCode());
1350 }
1351
1352 public String toString() {
1353 return key + "=" + value;
1354 }
1355
1356 static boolean eq(Object o1, Object o2) {
1357 return (o1 == null ? o2 == null : o1.equals(o2));
1358 }
1359 }
1360
1361 /* ---------------- Serialization Support -------------- */
1362
1363 /**
1364 * Save the state of the <tt>ConcurrentHashMap</tt>
1365 * instance to a stream (i.e.,
1366 * serialize it).
1367 * @param s the stream
1368 * @serialData
1369 * the key (Object) and value (Object)
1370 * for each key-value mapping, followed by a null pair.
1371 * The key-value mappings are emitted in no particular order.
1372 */
1373 private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1374 s.defaultWriteObject();
1375
1376 for (int k = 0; k < segments.length; ++k) {
1377 Segment<K,V> seg = (Segment<K,V>)segments[k];
1378 seg.lock();
1379 try {
1380 HashEntry[] tab = seg.table;
1381 for (int i = 0; i < tab.length; ++i) {
1382 for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i]; e != null; e = e.next) {
1383 s.writeObject(e.key);
1384 s.writeObject(e.value);
1385 }
1386 }
1387 } finally {
1388 seg.unlock();
1389 }
1390 }
1391 s.writeObject(null);
1392 s.writeObject(null);
1393 }
1394
1395 /**
1396 * Reconstitute the <tt>ConcurrentHashMap</tt>
1397 * instance from a stream (i.e.,
1398 * deserialize it).
1399 * @param s the stream
1400 */
1401 private void readObject(java.io.ObjectInputStream s)
1402 throws IOException, ClassNotFoundException {
1403 s.defaultReadObject();
1404
1405 // Initialize each segment to be minimally sized, and let grow.
1406 for (int i = 0; i < segments.length; ++i) {
1407 segments[i].setTable(new HashEntry[1]);
1408 }
1409
1410 // Read the keys and values, and put the mappings in the table
1411 for (;;) {
1412 K key = (K) s.readObject();
1413 V value = (V) s.readObject();
1414 if (key == null)
1415 break;
1416 put(key, value);
1417 }
1418 }
1419 }
1420