ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.32
Committed: Wed Dec 3 21:07:44 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.31: +30 -3 lines
Log Message:
Add ConcurrentMap.replace; fix other typos

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