ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.43
Committed: Sat Feb 7 13:03:59 2004 UTC (20 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.42: +8 -1 lines
Log Message:
Match iterator-as-entry behavior to changes in java.util versions

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