ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.31
Committed: Fri Nov 28 12:37:00 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.30: +54 -0 lines
Log Message:
Added replace method

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 V v = e.value;
309 if (v == null || !oldValue.equals(v))
310 return false;
311
312 e.value = newValue;
313 count = c; // write-volatile
314 return true;
315
316 } finally {
317 unlock();
318 }
319 }
320
321 V put(K key, int hash, V value, boolean onlyIfAbsent) {
322 lock();
323 try {
324 int c = count;
325 HashEntry[] tab = table;
326 int index = hash & (tab.length - 1);
327 HashEntry<K,V> first = (HashEntry<K,V>) tab[index];
328
329 for (HashEntry<K,V> e = first; e != null; e = (HashEntry<K,V>) e.next) {
330 if (e.hash == hash && key.equals(e.key)) {
331 V oldValue = e.value;
332 if (!onlyIfAbsent)
333 e.value = value;
334 ++modCount;
335 count = c; // write-volatile
336 return oldValue;
337 }
338 }
339
340 tab[index] = new HashEntry<K,V>(hash, key, value, first);
341 ++modCount;
342 ++c;
343 count = c; // write-volatile
344 if (c > threshold)
345 setTable(rehash(tab));
346 return null;
347 } finally {
348 unlock();
349 }
350 }
351
352 private HashEntry[] rehash(HashEntry[] oldTable) {
353 int oldCapacity = oldTable.length;
354 if (oldCapacity >= MAXIMUM_CAPACITY)
355 return oldTable;
356
357 /*
358 * Reclassify nodes in each list to new Map. Because we are
359 * using power-of-two expansion, the elements from each bin
360 * must either stay at same index, or move with a power of two
361 * offset. We eliminate unnecessary node creation by catching
362 * cases where old nodes can be reused because their next
363 * fields won't change. Statistically, at the default
364 * threshold, only about one-sixth of them need cloning when
365 * a table doubles. The nodes they replace will be garbage
366 * collectable as soon as they are no longer referenced by any
367 * reader thread that may be in the midst of traversing table
368 * right now.
369 */
370
371 HashEntry[] newTable = new HashEntry[oldCapacity << 1];
372 int sizeMask = newTable.length - 1;
373 for (int i = 0; i < oldCapacity ; i++) {
374 // We need to guarantee that any existing reads of old Map can
375 // proceed. So we cannot yet null out each bin.
376 HashEntry<K,V> e = (HashEntry<K,V>)oldTable[i];
377
378 if (e != null) {
379 HashEntry<K,V> next = e.next;
380 int idx = e.hash & sizeMask;
381
382 // Single node on list
383 if (next == null)
384 newTable[idx] = e;
385
386 else {
387 // Reuse trailing consecutive sequence at same slot
388 HashEntry<K,V> lastRun = e;
389 int lastIdx = idx;
390 for (HashEntry<K,V> last = next;
391 last != null;
392 last = last.next) {
393 int k = last.hash & sizeMask;
394 if (k != lastIdx) {
395 lastIdx = k;
396 lastRun = last;
397 }
398 }
399 newTable[lastIdx] = lastRun;
400
401 // Clone all remaining nodes
402 for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
403 int k = p.hash & sizeMask;
404 newTable[k] = new HashEntry<K,V>(p.hash,
405 p.key,
406 p.value,
407 (HashEntry<K,V>) newTable[k]);
408 }
409 }
410 }
411 }
412 return newTable;
413 }
414
415 /**
416 * Remove; match on key only if value null, else match both.
417 */
418 V remove(Object key, int hash, Object value) {
419 lock();
420 try {
421 int c = count;
422 HashEntry[] tab = table;
423 int index = hash & (tab.length - 1);
424 HashEntry<K,V> first = (HashEntry<K,V>)tab[index];
425
426 HashEntry<K,V> e = first;
427 for (;;) {
428 if (e == null)
429 return null;
430 if (e.hash == hash && key.equals(e.key))
431 break;
432 e = e.next;
433 }
434
435 V oldValue = e.value;
436 if (value != null && !value.equals(oldValue))
437 return null;
438
439 // All entries following removed node can stay in list, but
440 // all preceding ones need to be cloned.
441 HashEntry<K,V> newFirst = e.next;
442 for (HashEntry<K,V> p = first; p != e; p = p.next)
443 newFirst = new HashEntry<K,V>(p.hash, p.key,
444 p.value, newFirst);
445 tab[index] = newFirst;
446 ++modCount;
447 count = c-1; // write-volatile
448 return oldValue;
449 } finally {
450 unlock();
451 }
452 }
453
454 void clear() {
455 lock();
456 try {
457 HashEntry[] tab = table;
458 for (int i = 0; i < tab.length ; i++)
459 tab[i] = null;
460 ++modCount;
461 count = 0; // write-volatile
462 } finally {
463 unlock();
464 }
465 }
466 }
467
468 /**
469 * ConcurrentHashMap list entry. Note that this is never exported
470 * out as a user-visible Map.Entry
471 */
472 private static class HashEntry<K,V> {
473 private final K key;
474 private V value;
475 private final int hash;
476 private final HashEntry<K,V> next;
477
478 HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
479 this.value = value;
480 this.hash = hash;
481 this.key = key;
482 this.next = next;
483 }
484 }
485
486
487 /* ---------------- Public operations -------------- */
488
489 /**
490 * Constructs a new, empty map with the specified initial
491 * capacity and the specified load factor.
492 *
493 * @param initialCapacity the initial capacity. The implementation
494 * performs internal sizing to accommodate this many elements.
495 * @param loadFactor the load factor threshold, used to control resizing.
496 * @param concurrencyLevel the estimated number of concurrently
497 * updating threads. The implementation performs internal sizing
498 * to try to accommodate this many threads.
499 * @throws IllegalArgumentException if the initial capacity is
500 * negative or the load factor or concurrencyLevel are
501 * nonpositive.
502 */
503 public ConcurrentHashMap(int initialCapacity,
504 float loadFactor, int concurrencyLevel) {
505 if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
506 throw new IllegalArgumentException();
507
508 if (concurrencyLevel > MAX_SEGMENTS)
509 concurrencyLevel = MAX_SEGMENTS;
510
511 // Find power-of-two sizes best matching arguments
512 int sshift = 0;
513 int ssize = 1;
514 while (ssize < concurrencyLevel) {
515 ++sshift;
516 ssize <<= 1;
517 }
518 segmentShift = 32 - sshift;
519 segmentMask = ssize - 1;
520 this.segments = new Segment[ssize];
521
522 if (initialCapacity > MAXIMUM_CAPACITY)
523 initialCapacity = MAXIMUM_CAPACITY;
524 int c = initialCapacity / ssize;
525 if (c * ssize < initialCapacity)
526 ++c;
527 int cap = 1;
528 while (cap < c)
529 cap <<= 1;
530
531 for (int i = 0; i < this.segments.length; ++i)
532 this.segments[i] = new Segment<K,V>(cap, loadFactor);
533 }
534
535 /**
536 * Constructs a new, empty map with the specified initial
537 * capacity, and with default load factor and concurrencyLevel.
538 *
539 * @param initialCapacity The implementation performs internal
540 * sizing to accommodate this many elements.
541 * @throws IllegalArgumentException if the initial capacity of
542 * elements is negative.
543 */
544 public ConcurrentHashMap(int initialCapacity) {
545 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
546 }
547
548 /**
549 * Constructs a new, empty map with a default initial capacity,
550 * load factor, and concurrencyLevel.
551 */
552 public ConcurrentHashMap() {
553 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
554 }
555
556 /**
557 * Constructs a new map with the same mappings as the given map. The
558 * map is created with a capacity of twice the number of mappings in
559 * the given map or 11 (whichever is greater), and a default load factor.
560 */
561 public <A extends K, B extends V> ConcurrentHashMap(Map<A,B> t) {
562 this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
563 11),
564 DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
565 putAll(t);
566 }
567
568 // inherit Map javadoc
569 public boolean isEmpty() {
570 /*
571 * We need to keep track of per-segment modCounts to avoid ABA
572 * problems in which an element in one segment was added and
573 * in another removed during traversal, in which case the
574 * table was never actually empty at any point. Note the
575 * similar use of modCounts in the size() and containsValue()
576 * methods, which are the only other methods also susceptible
577 * to ABA problems.
578 */
579 int[] mc = new int[segments.length];
580 int mcsum = 0;
581 for (int i = 0; i < segments.length; ++i) {
582 if (segments[i].count != 0)
583 return false;
584 else
585 mcsum += mc[i] = segments[i].modCount;
586 }
587 // If mcsum happens to be zero, then we know we got a snapshot
588 // before any modifications at all were made. This is
589 // probably common enough to bother tracking.
590 if (mcsum != 0) {
591 for (int i = 0; i < segments.length; ++i) {
592 if (segments[i].count != 0 ||
593 mc[i] != segments[i].modCount)
594 return false;
595 }
596 }
597 return true;
598 }
599
600 // inherit Map javadoc
601 public int size() {
602 int[] mc = new int[segments.length];
603 for (;;) {
604 long sum = 0;
605 int mcsum = 0;
606 for (int i = 0; i < segments.length; ++i) {
607 sum += segments[i].count;
608 mcsum += mc[i] = segments[i].modCount;
609 }
610 int check = 0;
611 if (mcsum != 0) {
612 for (int i = 0; i < segments.length; ++i) {
613 check += segments[i].count;
614 if (mc[i] != segments[i].modCount) {
615 check = -1; // force retry
616 break;
617 }
618 }
619 }
620 if (check == sum) {
621 if (sum > Integer.MAX_VALUE)
622 return Integer.MAX_VALUE;
623 else
624 return (int)sum;
625 }
626 }
627 }
628
629
630 /**
631 * Returns the value to which the specified key is mapped in this table.
632 *
633 * @param key a key in the table.
634 * @return the value to which the key is mapped in this table;
635 * <tt>null</tt> if the key is not mapped to any value in
636 * this table.
637 * @throws NullPointerException if the key is
638 * <tt>null</tt>.
639 */
640 public V get(Object key) {
641 int hash = hash(key); // throws NullPointerException if key null
642 return segmentFor(hash).get(key, hash);
643 }
644
645 /**
646 * Tests if the specified object is a key in this table.
647 *
648 * @param key possible key.
649 * @return <tt>true</tt> if and only if the specified object
650 * is a key in this table, as determined by the
651 * <tt>equals</tt> method; <tt>false</tt> otherwise.
652 * @throws NullPointerException if the key is
653 * <tt>null</tt>.
654 */
655 public boolean containsKey(Object key) {
656 int hash = hash(key); // throws NullPointerException if key null
657 return segmentFor(hash).containsKey(key, hash);
658 }
659
660 /**
661 * Returns <tt>true</tt> if this map maps one or more keys to the
662 * specified value. Note: This method requires a full internal
663 * traversal of the hash table, and so is much slower than
664 * method <tt>containsKey</tt>.
665 *
666 * @param value value whose presence in this map is to be tested.
667 * @return <tt>true</tt> if this map maps one or more keys to the
668 * specified value.
669 * @throws NullPointerException if the value is <tt>null</tt>.
670 */
671 public boolean containsValue(Object value) {
672 if (value == null)
673 throw new NullPointerException();
674
675 int[] mc = new int[segments.length];
676 for (;;) {
677 int sum = 0;
678 int mcsum = 0;
679 for (int i = 0; i < segments.length; ++i) {
680 int c = segments[i].count;
681 mcsum += mc[i] = segments[i].modCount;
682 if (segments[i].containsValue(value))
683 return true;
684 }
685 boolean cleanSweep = true;
686 if (mcsum != 0) {
687 for (int i = 0; i < segments.length; ++i) {
688 int c = segments[i].count;
689 if (mc[i] != segments[i].modCount) {
690 cleanSweep = false;
691 break;
692 }
693 }
694 }
695 if (cleanSweep)
696 return false;
697 }
698 }
699
700 /**
701 * Legacy method testing if some key maps into the specified value
702 * in this table. This method is identical in functionality to
703 * {@link #containsValue}, and exists solely to ensure
704 * full compatibility with class {@link java.util.Hashtable},
705 * which supported this method prior to introduction of the
706 * Java Collections framework.
707
708 * @param value a value to search for.
709 * @return <tt>true</tt> if and only if some key maps to the
710 * <tt>value</tt> argument in this table as
711 * determined by the <tt>equals</tt> method;
712 * <tt>false</tt> otherwise.
713 * @throws NullPointerException if the value is <tt>null</tt>.
714 */
715 public boolean contains(Object value) {
716 return containsValue(value);
717 }
718
719 /**
720 * Maps the specified <tt>key</tt> to the specified
721 * <tt>value</tt> in this table. Neither the key nor the
722 * value can be <tt>null</tt>. <p>
723 *
724 * The value can be retrieved by calling the <tt>get</tt> method
725 * with a key that is equal to the original key.
726 *
727 * @param key the table key.
728 * @param value the value.
729 * @return the previous value of the specified key in this table,
730 * or <tt>null</tt> if it did not have one.
731 * @throws NullPointerException if the key or value is
732 * <tt>null</tt>.
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 for (Iterator<Map.Entry<? extends K, ? extends V>> it = (Iterator<Map.Entry<? extends K, ? extends V>>) t.entrySet().iterator(); it.hasNext(); ) {
786 Entry<? extends K, ? extends V> e = it.next();
787 put(e.getKey(), e.getValue());
788 }
789 }
790
791 /**
792 * Removes the key (and its corresponding value) from this
793 * table. This method does nothing if the key is not in the table.
794 *
795 * @param key the key that needs to be removed.
796 * @return the value to which the key had been mapped in this table,
797 * or <tt>null</tt> if the key did not have a mapping.
798 * @throws NullPointerException if the key is
799 * <tt>null</tt>.
800 */
801 public V remove(Object key) {
802 int hash = hash(key);
803 return segmentFor(hash).remove(key, hash, null);
804 }
805
806 /**
807 * Remove entry for key only if currently mapped to given value.
808 * Acts as
809 * <pre>
810 * if (map.get(key).equals(value)) {
811 * map.remove(key);
812 * return true;
813 * } else return false;
814 * </pre>
815 * except that the action is performed atomically.
816 * @param key key with which the specified value is associated.
817 * @param value value associated with the specified key.
818 * @return true if the value was removed
819 * @throws NullPointerException if the specified key is
820 * <tt>null</tt>.
821 */
822 public boolean remove(Object key, Object value) {
823 int hash = hash(key);
824 return segmentFor(hash).remove(key, hash, value) != null;
825 }
826
827 /**
828 * Replace entry for key only if currently mapped to given value.
829 * Acts as
830 * <pre>
831 * if (map.get(key).equals(oldValue)) {
832 * map.put(key, newValue);
833 * return true;
834 * } else return false;
835 * </pre>
836 * except that the action is performed atomically.
837 * @param key key with which the specified value is associated.
838 * @param oldValue value expected to be associated with the specified key.
839 * @param newValue value to be associated with the specified key.
840 * @return true if the value was replaced
841 * @throws NullPointerException if the specified key or values are
842 * <tt>null</tt>.
843 */
844 public boolean replace(K key, V oldValue, V newValue) {
845 if (oldValue == null || newValue == null)
846 throw new NullPointerException();
847 int hash = hash(key);
848 return segmentFor(hash).replace(key, hash, oldValue, newValue);
849 }
850
851
852 /**
853 * Removes all mappings from this map.
854 */
855 public void clear() {
856 for (int i = 0; i < segments.length; ++i)
857 segments[i].clear();
858 }
859
860
861 /**
862 * Returns a shallow copy of this
863 * <tt>ConcurrentHashMap</tt> instance: the keys and
864 * values themselves are not cloned.
865 *
866 * @return a shallow copy of this map.
867 */
868 public Object clone() {
869 // We cannot call super.clone, since it would share final
870 // segments array, and there's no way to reassign finals.
871
872 float lf = segments[0].loadFactor;
873 int segs = segments.length;
874 int cap = (int)(size() / lf);
875 if (cap < segs) cap = segs;
876 ConcurrentHashMap<K,V> t = new ConcurrentHashMap<K,V>(cap, lf, segs);
877 t.putAll(this);
878 return t;
879 }
880
881 /**
882 * Returns a set view of the keys contained in this map. The set is
883 * backed by the map, so changes to the map are reflected in the set, and
884 * vice-versa. The set supports element removal, which removes the
885 * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
886 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
887 * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
888 * <tt>addAll</tt> operations.
889 * The returned <tt>iterator</tt> is a "weakly consistent" iterator that
890 * will never throw {@link java.util.ConcurrentModificationException},
891 * and guarantees to traverse elements as they existed upon
892 * construction of the iterator, and may (but is not guaranteed to)
893 * reflect any modifications subsequent to construction.
894 *
895 * @return a set view of the keys contained in this map.
896 */
897 public Set<K> keySet() {
898 Set<K> ks = keySet;
899 return (ks != null) ? ks : (keySet = new KeySet());
900 }
901
902
903 /**
904 * Returns a collection view of the values contained in this map. The
905 * collection is backed by the map, so changes to the map are reflected in
906 * the collection, and vice-versa. The collection supports element
907 * removal, which removes the corresponding mapping from this map, via the
908 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
909 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
910 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
911 * The returned <tt>iterator</tt> is a "weakly consistent" iterator that
912 * will never throw {@link java.util.ConcurrentModificationException},
913 * and guarantees to traverse elements as they existed upon
914 * construction of the iterator, and may (but is not guaranteed to)
915 * reflect any modifications subsequent to construction.
916 *
917 * @return a collection view of the values contained in this map.
918 */
919 public Collection<V> values() {
920 Collection<V> vs = values;
921 return (vs != null) ? vs : (values = new Values());
922 }
923
924
925 /**
926 * Returns a collection view of the mappings contained in this map. Each
927 * element in the returned collection is a <tt>Map.Entry</tt>. The
928 * collection is backed by the map, so changes to the map are reflected in
929 * the collection, and vice-versa. The collection supports element
930 * removal, which removes the corresponding mapping from the map, via the
931 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
932 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
933 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
934 * The returned <tt>iterator</tt> is a "weakly consistent" iterator that
935 * will never throw {@link java.util.ConcurrentModificationException},
936 * and guarantees to traverse elements as they existed upon
937 * construction of the iterator, and may (but is not guaranteed to)
938 * reflect any modifications subsequent to construction.
939 *
940 * @return a collection view of the mappings contained in this map.
941 */
942 public Set<Map.Entry<K,V>> entrySet() {
943 Set<Map.Entry<K,V>> es = entrySet;
944 return (es != null) ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet());
945 }
946
947
948 /**
949 * Returns an enumeration of the keys in this table.
950 *
951 * @return an enumeration of the keys in this table.
952 * @see #keySet
953 */
954 public Enumeration<K> keys() {
955 return new KeyIterator();
956 }
957
958 /**
959 * Returns an enumeration of the values in this table.
960 * Use the Enumeration methods on the returned object to fetch the elements
961 * sequentially.
962 *
963 * @return an enumeration of the values in this table.
964 * @see #values
965 */
966 public Enumeration<V> elements() {
967 return new ValueIterator();
968 }
969
970 /* ---------------- Iterator Support -------------- */
971
972 private abstract class HashIterator {
973 private int nextSegmentIndex;
974 private int nextTableIndex;
975 private HashEntry[] currentTable;
976 private HashEntry<K, V> nextEntry;
977 HashEntry<K, V> lastReturned;
978
979 private HashIterator() {
980 nextSegmentIndex = segments.length - 1;
981 nextTableIndex = -1;
982 advance();
983 }
984
985 public boolean hasMoreElements() { return hasNext(); }
986
987 private void advance() {
988 if (nextEntry != null && (nextEntry = nextEntry.next) != null)
989 return;
990
991 while (nextTableIndex >= 0) {
992 if ( (nextEntry = (HashEntry<K,V>)currentTable[nextTableIndex--]) != null)
993 return;
994 }
995
996 while (nextSegmentIndex >= 0) {
997 Segment<K,V> seg = (Segment<K,V>)segments[nextSegmentIndex--];
998 if (seg.count != 0) {
999 currentTable = seg.table;
1000 for (int j = currentTable.length - 1; j >= 0; --j) {
1001 if ( (nextEntry = (HashEntry<K,V>)currentTable[j]) != null) {
1002 nextTableIndex = j - 1;
1003 return;
1004 }
1005 }
1006 }
1007 }
1008 }
1009
1010 public boolean hasNext() { return nextEntry != null; }
1011
1012 HashEntry<K,V> nextEntry() {
1013 if (nextEntry == null)
1014 throw new NoSuchElementException();
1015 lastReturned = nextEntry;
1016 advance();
1017 return lastReturned;
1018 }
1019
1020 public void remove() {
1021 if (lastReturned == null)
1022 throw new IllegalStateException();
1023 ConcurrentHashMap.this.remove(lastReturned.key);
1024 lastReturned = null;
1025 }
1026 }
1027
1028 private class KeyIterator extends HashIterator implements Iterator<K>, Enumeration<K> {
1029 public K next() { return super.nextEntry().key; }
1030 public K nextElement() { return super.nextEntry().key; }
1031 }
1032
1033 private class ValueIterator extends HashIterator implements Iterator<V>, Enumeration<V> {
1034 public V next() { return super.nextEntry().value; }
1035 public V nextElement() { return super.nextEntry().value; }
1036 }
1037
1038
1039
1040 /**
1041 * Exported Entry objects must write-through changes in setValue,
1042 * even if the nodes have been cloned. So we cannot return
1043 * internal HashEntry objects. Instead, the iterator itself acts
1044 * as a forwarding pseudo-entry.
1045 */
1046 private class EntryIterator extends HashIterator implements Map.Entry<K,V>, Iterator<Entry<K,V>> {
1047 public Map.Entry<K,V> next() {
1048 nextEntry();
1049 return this;
1050 }
1051
1052 public K getKey() {
1053 if (lastReturned == null)
1054 throw new IllegalStateException("Entry was removed");
1055 return lastReturned.key;
1056 }
1057
1058 public V getValue() {
1059 if (lastReturned == null)
1060 throw new IllegalStateException("Entry was removed");
1061 return ConcurrentHashMap.this.get(lastReturned.key);
1062 }
1063
1064 public V setValue(V value) {
1065 if (lastReturned == null)
1066 throw new IllegalStateException("Entry was removed");
1067 return ConcurrentHashMap.this.put(lastReturned.key, value);
1068 }
1069
1070 public boolean equals(Object o) {
1071 if (!(o instanceof Map.Entry))
1072 return false;
1073 Map.Entry e = (Map.Entry)o;
1074 return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue());
1075 }
1076
1077 public int hashCode() {
1078 Object k = getKey();
1079 Object v = getValue();
1080 return ((k == null) ? 0 : k.hashCode()) ^
1081 ((v == null) ? 0 : v.hashCode());
1082 }
1083
1084 public String toString() {
1085 return getKey() + "=" + getValue();
1086 }
1087
1088 private boolean eq(Object o1, Object o2) {
1089 return (o1 == null ? o2 == null : o1.equals(o2));
1090 }
1091
1092 }
1093
1094 private class KeySet extends AbstractSet<K> {
1095 public Iterator<K> iterator() {
1096 return new KeyIterator();
1097 }
1098 public int size() {
1099 return ConcurrentHashMap.this.size();
1100 }
1101 public boolean contains(Object o) {
1102 return ConcurrentHashMap.this.containsKey(o);
1103 }
1104 public boolean remove(Object o) {
1105 return ConcurrentHashMap.this.remove(o) != null;
1106 }
1107 public void clear() {
1108 ConcurrentHashMap.this.clear();
1109 }
1110 }
1111
1112 private class Values extends AbstractCollection<V> {
1113 public Iterator<V> iterator() {
1114 return new ValueIterator();
1115 }
1116 public int size() {
1117 return ConcurrentHashMap.this.size();
1118 }
1119 public boolean contains(Object o) {
1120 return ConcurrentHashMap.this.containsValue(o);
1121 }
1122 public void clear() {
1123 ConcurrentHashMap.this.clear();
1124 }
1125 }
1126
1127 private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1128 public Iterator<Map.Entry<K,V>> iterator() {
1129 return new EntryIterator();
1130 }
1131 public boolean contains(Object o) {
1132 if (!(o instanceof Map.Entry))
1133 return false;
1134 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
1135 V v = ConcurrentHashMap.this.get(e.getKey());
1136 return v != null && v.equals(e.getValue());
1137 }
1138 public boolean remove(Object o) {
1139 if (!(o instanceof Map.Entry))
1140 return false;
1141 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
1142 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1143 }
1144 public int size() {
1145 return ConcurrentHashMap.this.size();
1146 }
1147 public void clear() {
1148 ConcurrentHashMap.this.clear();
1149 }
1150 public Object[] toArray() {
1151 // Since we don't ordinarily have distinct Entry objects, we
1152 // must pack elements using exportable SimpleEntry
1153 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
1154 for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
1155 c.add(new SimpleEntry<K,V>(i.next()));
1156 return c.toArray();
1157 }
1158 public <T> T[] toArray(T[] a) {
1159 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>(size());
1160 for (Iterator<Map.Entry<K,V>> i = iterator(); i.hasNext(); )
1161 c.add(new SimpleEntry<K,V>(i.next()));
1162 return c.toArray(a);
1163 }
1164
1165 }
1166
1167 /**
1168 * This duplicates java.util.AbstractMap.SimpleEntry until this class
1169 * is made accessible.
1170 */
1171 static class SimpleEntry<K,V> implements Entry<K,V> {
1172 K key;
1173 V value;
1174
1175 public SimpleEntry(K key, V value) {
1176 this.key = key;
1177 this.value = value;
1178 }
1179
1180 public SimpleEntry(Entry<K,V> e) {
1181 this.key = e.getKey();
1182 this.value = e.getValue();
1183 }
1184
1185 public K getKey() {
1186 return key;
1187 }
1188
1189 public V getValue() {
1190 return value;
1191 }
1192
1193 public V setValue(V value) {
1194 V oldValue = this.value;
1195 this.value = value;
1196 return oldValue;
1197 }
1198
1199 public boolean equals(Object o) {
1200 if (!(o instanceof Map.Entry))
1201 return false;
1202 Map.Entry e = (Map.Entry)o;
1203 return eq(key, e.getKey()) && eq(value, e.getValue());
1204 }
1205
1206 public int hashCode() {
1207 return ((key == null) ? 0 : key.hashCode()) ^
1208 ((value == null) ? 0 : value.hashCode());
1209 }
1210
1211 public String toString() {
1212 return key + "=" + value;
1213 }
1214
1215 private static boolean eq(Object o1, Object o2) {
1216 return (o1 == null ? o2 == null : o1.equals(o2));
1217 }
1218 }
1219
1220 /* ---------------- Serialization Support -------------- */
1221
1222 /**
1223 * Save the state of the <tt>ConcurrentHashMap</tt>
1224 * instance to a stream (i.e.,
1225 * serialize it).
1226 * @param s the stream
1227 * @serialData
1228 * the key (Object) and value (Object)
1229 * for each key-value mapping, followed by a null pair.
1230 * The key-value mappings are emitted in no particular order.
1231 */
1232 private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1233 s.defaultWriteObject();
1234
1235 for (int k = 0; k < segments.length; ++k) {
1236 Segment<K,V> seg = (Segment<K,V>)segments[k];
1237 seg.lock();
1238 try {
1239 HashEntry[] tab = seg.table;
1240 for (int i = 0; i < tab.length; ++i) {
1241 for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i]; e != null; e = e.next) {
1242 s.writeObject(e.key);
1243 s.writeObject(e.value);
1244 }
1245 }
1246 } finally {
1247 seg.unlock();
1248 }
1249 }
1250 s.writeObject(null);
1251 s.writeObject(null);
1252 }
1253
1254 /**
1255 * Reconstitute the <tt>ConcurrentHashMap</tt>
1256 * instance from a stream (i.e.,
1257 * deserialize it).
1258 * @param s the stream
1259 */
1260 private void readObject(java.io.ObjectInputStream s)
1261 throws IOException, ClassNotFoundException {
1262 s.defaultReadObject();
1263
1264 // Initialize each segment to be minimally sized, and let grow.
1265 for (int i = 0; i < segments.length; ++i) {
1266 segments[i].setTable(new HashEntry[1]);
1267 }
1268
1269 // Read the keys and values, and put the mappings in the table
1270 for (;;) {
1271 K key = (K) s.readObject();
1272 V value = (V) s.readObject();
1273 if (key == null)
1274 break;
1275 put(key, value);
1276 }
1277 }
1278 }
1279