ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.6
Committed: Mon Jun 9 02:32:05 2003 UTC (20 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.5: +9 -9 lines
Log Message:
New ScheduledExecuor methods; minor javadoc cleanup

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