ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.22
Committed: Sun Aug 31 13:33:13 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.21: +5 -4 lines
Log Message:
Removed non-standard tags and misc javadoc cleanup

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