ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.40
Committed: Tue Jan 20 04:35:02 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.39: +1 -0 lines
Log Message:
javadoc lint; Thread.interrupt shouldn't throw exception if thread dead

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