ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.44
Committed: Mon Feb 9 13:28:47 2004 UTC (20 years, 3 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_PFD
Changes since 1.43: +10 -8 lines
Log Message:
Wording fixes and improvements

File Contents

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