ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.14
Committed: Wed Aug 6 11:11:49 2003 UTC (20 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.13: +15 -0 lines
Log Message:
Clarify iterator semantics

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