ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.23
Committed: Sat Sep 13 18:51:10 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.22: +18 -28 lines
Log Message:
Proofreading pass -- many minor adjustments

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