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

File Contents

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