ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.74
Committed: Wed Jun 8 01:44:14 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.73: +1 -1 lines
Log Message:
whitespace

File Contents

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