ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.30
Committed: Fri Nov 21 17:50:28 2003 UTC (20 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.29: +126 -38 lines
Log Message:
Ensure EntrySet Entry setValue writes through to map

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