ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.19
Committed: Mon Aug 25 13:01:41 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.18: +54 -54 lines
Log Message:
Replaced overspecification of constructors with better wording

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