ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.4
Committed: Fri Jun 6 14:17:16 2003 UTC (21 years ago) by dl
Branch: MAIN
Changes since 1.3: +703 -951 lines
Log Message:
New CHM class with variable segments.

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 = null;
109 private transient Set/*<Map.Entry<K,V>>*/ entrySet = null;
110 private transient Collection<V> values = null;
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 V remove(Object key, int hash, Object value) {
379 lock();
380 try {
381 HashEntry[] tab = table;
382 int index = indexFor(hash, tab.length);
383 HashEntry<K,V> first = tab[index];
384
385 HashEntry<K,V> e = first;
386 while (true) {
387 if (e == null)
388 return null;
389 if (e.hash == hash && eq(key, e.key))
390 break;
391 e = e.next;
392 }
393
394 V oldValue = e.value;
395 if (value != null && !value.equals(oldValue))
396 return null;
397
398 // All entries following removed node can stay in list, but
399 // all preceeding ones need to be cloned.
400 HashEntry<K,V> newFirst = e.next;
401 for (HashEntry<K,V> p = first; p != e; p = p.next)
402 newFirst = new HashEntry<K,V>(p.hash, p.key, p.value, newFirst);
403 tab[index] = newFirst;
404
405 count--; // write-volatile
406 return e.value;
407 }
408 finally {
409 unlock();
410 }
411 }
412
413 void clear() {
414 lock();
415 try {
416 HashEntry<K,V> tab[] = table;
417 for (int i = 0; i < tab.length ; i++)
418 tab[i] = null;
419 count = 0; // write-volatile
420 }
421 finally {
422 unlock();
423 }
424 }
425 }
426
427 /**
428 * ConcurrentReaderHashMap list entry.
429 */
430 private static class HashEntry<K,V> implements Entry<K,V> {
431 private final K key;
432 private V value;
433 private final int hash;
434 private final HashEntry<K,V> next;
435
436 HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
437 this.value = value;
438 this.hash = hash;
439 this.key = key;
440 this.next = next;
441 }
442
443 public K getKey() {
444 return key;
445 }
446
447 public V getValue() {
448 return value;
449 }
450
451 public V setValue(V newValue) {
452 // We aren't required to, and don't provide any
453 // visibility barriers for setting value.
454 if (newValue == null)
455 throw new NullPointerException();
456 V oldValue = this.value;
457 this.value = newValue;
458 return oldValue;
459 }
460
461 public boolean equals(Object o) {
462 if (!(o instanceof Entry))
463 return false;
464 Entry<K,V> e = (Entry)o;
465 return (key.equals(e.getKey()) && value.equals(e.getValue()));
466 }
467
468 public int hashCode() {
469 return key.hashCode() ^ value.hashCode();
470 }
471
472 public String toString() {
473 return key + "=" + value;
474 }
475 }
476
477
478 /* ---------------- Public operations -------------- */
479
480 /**
481 * Constructs a new, empty map with the specified initial
482 * capacity and the specified load factor.
483 *
484 * @param initialCapacity the initial capacity. The actual
485 * initial capacity is rounded up to the nearest power of two.
486 * @param loadFactor the load factor threshold, used to control resizing.
487 * @param segments the number of concurrently accessible segments. the
488 * actual number of segments is rounded to the next power of two.
489 * @throws IllegalArgumentException if the initial capacity is
490 * negative or the load factor or number of segments are
491 * nonpositive.
492 */
493 public ConcurrentHashMap(int initialCapacity, float loadFactor, int segments) {
494 if (!(loadFactor > 0) || initialCapacity < 0 || segments <= 0)
495 throw new IllegalArgumentException();
496
497 // Find power-of-two sizes best matching arguments
498 int sshift = 0;
499 int ssize = 1;
500 while (ssize < segments) {
501 ++sshift;
502 ssize <<= 1;
503 }
504 segmentShift = sshift;
505 segmentMask = ssize-1;
506 this.segments = new Segment<K,V>[ssize];
507
508 if (initialCapacity > MAXIMUM_CAPACITY)
509 initialCapacity = MAXIMUM_CAPACITY;
510 int c = initialCapacity / ssize;
511 if (c * ssize < initialCapacity)
512 ++c;
513 int cap = 1;
514 while (cap < c)
515 cap <<= 1;
516
517 for (int i = 0; i < this.segments.length; ++i)
518 this.segments[i] = new Segment<K,V>(cap, loadFactor);
519 }
520
521 /**
522 * Constructs a new, empty map with the specified initial
523 * capacity, and with default load factor and segments.
524 *
525 * @param initialCapacity the initial capacity of the
526 * ConcurrentHashMap.
527 * @throws IllegalArgumentException if the initial capacity of
528 * elements is negative.
529 */
530 public ConcurrentHashMap(int initialCapacity) {
531 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
532 }
533
534 /**
535 * Constructs a new, empty map with a default initial capacity,
536 * load factor, and number of segments
537 */
538 public ConcurrentHashMap() {
539 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
540 }
541
542 /**
543 * Constructs a new map with the same mappings as the given map. The
544 * map is created with a capacity of twice the number of mappings in
545 * the given map or 11 (whichever is greater), and a default load factor.
546 */
547 public <A extends K, B extends V> ConcurrentHashMap(Map<A,B> t) {
548 this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
549 11),
550 DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
551 putAll(t);
552 }
553
554 // inherit Map javadoc
555 public int size() {
556 int c = 0;
557 for (int i = 0; i < segments.length; ++i)
558 c += segments[i].count;
559 return c;
560 }
561
562 // inherit Map javadoc
563 public boolean isEmpty() {
564 for (int i = 0; i < segments.length; ++i)
565 if (segments[i].count != 0)
566 return false;
567 return true;
568 }
569
570 /**
571 * Returns the value to which the specified key is mapped in this table.
572 *
573 * @param key a key in the table.
574 * @return the value to which the key is mapped in this table;
575 * <code>null</code> if the key is not mapped to any value in
576 * this table.
577 * @exception NullPointerException if the key is
578 * <code>null</code>.
579 * @see #put(Object, Object)
580 */
581 public V get(K key) {
582 int hash = hash(key); // throws NullPointerException if key null
583 return segmentFor(hash).get(key, segmentHashFor(hash));
584 }
585
586 /**
587 * Tests if the specified object is a key in this table.
588 *
589 * @param key possible key.
590 * @return <code>true</code> if and only if the specified object
591 * is a key in this table, as determined by the
592 * <tt>equals</tt> method; <code>false</code> otherwise.
593 * @exception NullPointerException if the key is
594 * <code>null</code>.
595 * @see #contains(Object)
596 */
597 public boolean containsKey(Object key) {
598 int hash = hash(key); // throws NullPointerException if key null
599 return segmentFor(hash).containsKey(key, segmentHashFor(hash));
600 }
601
602 /**
603 * Returns <tt>true</tt> if this map maps one or more keys to the
604 * specified value. Note: This method requires a full internal
605 * traversal of the hash table, and so is much slower than
606 * method <tt>containsKey</tt>.
607 *
608 * @param value value whose presence in this map is to be tested.
609 * @return <tt>true</tt> if this map maps one or more keys to the
610 * specified value.
611 * @exception NullPointerException if the value is <code>null</code>.
612 */
613 public boolean containsValue(Object value) {
614 if (value == null)
615 throw new NullPointerException();
616
617 for (int i = 0; i < segments.length; ++i) {
618 if (segments[i].containsValue(value))
619 return true;
620 }
621 return false;
622 }
623 /**
624 * Tests if some key maps into the specified value in this table.
625 * This operation is more expensive than the <code>containsKey</code>
626 * method.<p>
627 *
628 * Note that this method is identical in functionality to containsValue,
629 * (which is part of the Map interface in the collections framework).
630 *
631 * @param value a value to search for.
632 * @return <code>true</code> if and only if some key maps to the
633 * <code>value</code> argument in this table as
634 * determined by the <tt>equals</tt> method;
635 * <code>false</code> otherwise.
636 * @exception NullPointerException if the value is <code>null</code>.
637 * @see #containsKey(Object)
638 * @see #containsValue(Object)
639 * @see Map
640 */
641 public boolean contains(Object value) {
642 return containsValue(value);
643 }
644
645 /**
646 * Maps the specified <code>key</code> to the specified
647 * <code>value</code> in this table. Neither the key nor the
648 * value can be <code>null</code>. <p>
649 *
650 * The value can be retrieved by calling the <code>get</code> method
651 * with a key that is equal to the original key.
652 *
653 * @param key the table key.
654 * @param value the value.
655 * @return the previous value of the specified key in this table,
656 * or <code>null</code> if it did not have one.
657 * @exception NullPointerException if the key or value is
658 * <code>null</code>.
659 * @see Object#equals(Object)
660 * @see #get(Object)
661 */
662 public V put(K key, V value) {
663 if (value == null)
664 throw new NullPointerException();
665 int hash = hash(key);
666 return segmentFor(hash).put(key, segmentHashFor(hash), value, false);
667 }
668
669 /**
670 * If the specified key is not already associated
671 * with a value, associate it with the given value.
672 * This is equivalent to
673 * <pre>
674 * if (!map.containsKey(key)) map.put(key, value);
675 * return get(key);
676 * </pre>
677 * Except that the action is performed atomically.
678 * @param key key with which the specified value is to be associated.
679 * @param value value to be associated with the specified key.
680 * @return previous value associated with specified key, or <tt>null</tt>
681 * if there was no mapping for key. A <tt>null</tt> return can
682 * also indicate that the map previously associated <tt>null</tt>
683 * with the specified key, if the implementation supports
684 * <tt>null</tt> values.
685 *
686 * @throws NullPointerException this map does not permit <tt>null</tt>
687 * keys or values, and the specified key or value is
688 * <tt>null</tt>.
689 *
690 **/
691 public V putIfAbsent(K key, V value) {
692 if (value == null)
693 throw new NullPointerException();
694 int hash = hash(key);
695 return segmentFor(hash).put(key, segmentHashFor(hash), value, true);
696 }
697
698
699 /**
700 * Copies all of the mappings from the specified map to this one.
701 *
702 * These mappings replace any mappings that this map had for any of the
703 * keys currently in the specified Map.
704 *
705 * @param t Mappings to be stored in this map.
706 */
707 public <K1 extends K, V1 extends V> void putAll(Map<K1,V1> t) {
708 Iterator<Map.Entry<K1,V1>> it = t.entrySet().iterator();
709 while (it.hasNext()) {
710 Entry<K,V> e = (Entry) it.next();
711 put(e.getKey(), e.getValue());
712 }
713 }
714
715 /**
716 * Removes the key (and its corresponding value) from this
717 * table. This method does nothing if the key is not in the table.
718 *
719 * @param key the key that needs to be removed.
720 * @return the value to which the key had been mapped in this table,
721 * or <code>null</code> if the key did not have a mapping.
722 * @exception NullPointerException if the key is
723 * <code>null</code>.
724 */
725 public V remove(Object key) {
726 int hash = hash(key);
727 return segmentFor(hash).remove(key, segmentHashFor(hash), null);
728 }
729
730 /**
731 * Removes the (key, value) pair from this
732 * table. This method does nothing if the key is not in the table,
733 * or if the key is associated with a different value. This method
734 * is needed by EntrySet.
735 *
736 * @param key the key that needs to be removed.
737 * @param value the associated value. If the value is null,
738 * it means "any value".
739 * @return the value to which the key had been mapped in this table,
740 * or <code>null</code> if the key did not have a mapping.
741 * @exception NullPointerException if the key is
742 * <code>null</code>.
743 */
744 public V remove(Object key, Object value) {
745 if (value == null)
746 return null;
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