ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.18
Committed: Sun Aug 24 23:32:25 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.17: +6 -5 lines
Log Message:
Kill ScheduledExecutor Date methods; Documentation clarifications

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     * 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 tim 1.11 *
26 dl 1.4 * <p> Retrieval operations (including <tt>get</tt>) ordinarily
27 dl 1.5 * overlap with update operations (including <tt>put</tt> and
28 dl 1.4 * <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 tim 1.1 *
39 dl 1.4 * <p> The allowed concurrency among update operations is controlled
40     * by the optional <tt>segments</tt> constructor argument (default
41 brian 1.7 * 16). The table is divided into this many independent parts, each of
42 dl 1.4 * 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 tim 1.1 *
50 dl 1.4 * <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 tim 1.1 *
53 dl 1.8 * @since 1.5
54     * @author Doug Lea
55     */
56 tim 1.1 public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
57     implements ConcurrentMap<K, V>, Cloneable, Serializable {
58    
59     /*
60 dl 1.4 * The basic strategy is to subdivide the table among Segments,
61     * each of which itself is a concurrently readable hash table.
62     */
63 tim 1.1
64 dl 1.4 /* ---------------- Constants -------------- */
65 tim 1.11
66 dl 1.4 /**
67 dl 1.17 * The default initial number of table slots for this table (16).
68 dl 1.4 * Used when not otherwise specified in constructor.
69     */
70 tim 1.11 private static int DEFAULT_INITIAL_CAPACITY = 16;
71 tim 1.1
72     /**
73 dl 1.4 * The maximum capacity, used if a higher value is implicitly
74     * specified by either of the constructors with arguments. MUST
75     * be a power of two <= 1<<30.
76     */
77     static final int MAXIMUM_CAPACITY = 1 << 30;
78 tim 1.11
79 tim 1.1 /**
80 dl 1.4 * The default load factor for this table. Used when not
81     * otherwise specified in constructor.
82     */
83 tim 1.11 static final float DEFAULT_LOAD_FACTOR = 0.75f;
84 tim 1.1
85     /**
86 dl 1.4 * The default number of concurrency control segments.
87 tim 1.1 **/
88 dl 1.4 private static final int DEFAULT_SEGMENTS = 16;
89 tim 1.1
90 dl 1.4 /* ---------------- Fields -------------- */
91 tim 1.1
92     /**
93 dl 1.9 * Mask value for indexing into segments. The upper bits of a
94     * key's hash code are used to choose the segment.
95 tim 1.1 **/
96 dl 1.4 private final int segmentMask;
97 tim 1.1
98     /**
99 dl 1.4 * Shift value for indexing within segments.
100 tim 1.1 **/
101 dl 1.4 private final int segmentShift;
102 tim 1.1
103     /**
104 dl 1.4 * The segments, each of which is a specialized hash table
105 tim 1.1 */
106 tim 1.11 private final Segment[] segments;
107 dl 1.4
108 dl 1.6 private transient Set<K> keySet;
109 tim 1.12 private transient Set<Map.Entry<K,V>> entrySet;
110 dl 1.6 private transient Collection<V> values;
111 dl 1.4
112     /* ---------------- Small Utilities -------------- */
113 tim 1.1
114     /**
115 tim 1.11 * Return a hash code for non-null Object x.
116 dl 1.4 * Uses the same hash code spreader as most other j.u hash tables.
117 dl 1.8 * @param x the object serving as a key
118     * @return the hash code
119 tim 1.1 */
120 dl 1.4 private static int hash(Object x) {
121     int h = x.hashCode();
122     h += ~(h << 9);
123     h ^= (h >>> 14);
124     h += (h << 4);
125     h ^= (h >>> 10);
126     return h;
127     }
128    
129 tim 1.1 /**
130 dl 1.4 * Return the segment that should be used for key with given hash
131 tim 1.1 */
132 dl 1.4 private Segment<K,V> segmentFor(int hash) {
133 tim 1.12 return (Segment<K,V>) segments[(hash >>> segmentShift) & segmentMask];
134 dl 1.4 }
135 tim 1.1
136 dl 1.4 /* ---------------- Inner Classes -------------- */
137 tim 1.1
138     /**
139 dl 1.6 * Segments are specialized versions of hash tables. This
140 dl 1.4 * subclasses from ReentrantLock opportunistically, just to
141     * simplify some locking and avoid separate construction.
142 tim 1.1 **/
143 dl 1.8 private static final class Segment<K,V> extends ReentrantLock implements Serializable {
144 dl 1.4 /*
145     * Segments maintain a table of entry lists that are ALWAYS
146     * kept in a consistent state, so can be read without locking.
147     * Next fields of nodes are immutable (final). All list
148     * additions are performed at the front of each bin. This
149     * makes it easy to check changes, and also fast to traverse.
150     * When nodes would otherwise be changed, new nodes are
151     * created to replace them. This works well for hash tables
152     * since the bin lists tend to be short. (The average length
153     * is less than two for the default load factor threshold.)
154     *
155     * Read operations can thus proceed without locking, but rely
156     * on a memory barrier to ensure that completed write
157     * operations performed by other threads are
158     * noticed. Conveniently, the "count" field, tracking the
159     * number of elements, can also serve as the volatile variable
160     * providing proper read/write barriers. This is convenient
161     * because this field needs to be read in many read operations
162     * anyway. The use of volatiles for this purpose is only
163     * guaranteed to work in accord with reuirements in
164     * multithreaded environments when run on JVMs conforming to
165     * the clarified JSR133 memory model specification. This true
166     * for hotspot as of release 1.4.
167     *
168     * Implementors note. The basic rules for all this are:
169     *
170     * - All unsynchronized read operations must first read the
171     * "count" field, and should not look at table entries if
172     * it is 0.
173 tim 1.11 *
174 dl 1.4 * - All synchronized write operations should write to
175     * the "count" field after updating. The operations must not
176     * take any action that could even momentarily cause
177     * a concurrent read operation to see inconsistent
178     * data. This is made easier by the nature of the read
179     * operations in Map. For example, no operation
180     * can reveal that the table has grown but the threshold
181     * has not yet been updated, so there are no atomicity
182     * requirements for this with respect to reads.
183     *
184     * As a guide, all critical volatile reads and writes are marked
185     * in code comments.
186     */
187 tim 1.11
188 dl 1.4 /**
189     * The number of elements in this segment's region.
190     **/
191     transient volatile int count;
192    
193     /**
194     * The table is rehashed when its size exceeds this threshold.
195     * (The value of this field is always (int)(capacity *
196     * loadFactor).)
197     */
198 dl 1.8 private transient int threshold;
199 dl 1.4
200     /**
201     * The per-segment table
202     */
203 tim 1.11 transient HashEntry[] table;
204 dl 1.4
205     /**
206     * The load factor for the hash table. Even though this value
207     * is same for all segments, it is replicated to avoid needing
208     * links to outer object.
209     * @serial
210     */
211     private final float loadFactor;
212 tim 1.1
213 dl 1.4 Segment(int initialCapacity, float lf) {
214     loadFactor = lf;
215 tim 1.11 setTable(new HashEntry[initialCapacity]);
216 dl 1.4 }
217 tim 1.1
218 dl 1.4 /**
219 tim 1.11 * Set table to new HashEntry array.
220 dl 1.4 * Call only while holding lock or in constructor.
221     **/
222 tim 1.11 private void setTable(HashEntry[] newTable) {
223 dl 1.4 table = newTable;
224     threshold = (int)(newTable.length * loadFactor);
225     count = count; // write-volatile
226 tim 1.11 }
227 dl 1.4
228     /* Specialized implementations of map methods */
229 tim 1.11
230     V get(K key, int hash) {
231 dl 1.4 if (count != 0) { // read-volatile
232 tim 1.11 HashEntry[] tab = table;
233 dl 1.9 int index = hash & (tab.length - 1);
234 tim 1.11 HashEntry<K,V> e = (HashEntry<K,V>) tab[index];
235 dl 1.4 while (e != null) {
236 tim 1.11 if (e.hash == hash && key.equals(e.key))
237 dl 1.4 return e.value;
238     e = e.next;
239     }
240     }
241     return null;
242     }
243    
244     boolean containsKey(Object key, int hash) {
245     if (count != 0) { // read-volatile
246 tim 1.11 HashEntry[] tab = table;
247 dl 1.9 int index = hash & (tab.length - 1);
248 tim 1.11 HashEntry<K,V> e = (HashEntry<K,V>) tab[index];
249 dl 1.4 while (e != null) {
250 tim 1.11 if (e.hash == hash && key.equals(e.key))
251 dl 1.4 return true;
252     e = e.next;
253     }
254     }
255     return false;
256     }
257 tim 1.11
258 dl 1.4 boolean containsValue(Object value) {
259     if (count != 0) { // read-volatile
260 tim 1.11 HashEntry[] tab = table;
261 dl 1.4 int len = tab.length;
262 tim 1.11 for (int i = 0 ; i < len; i++)
263 tim 1.12 for (HashEntry<K,V> e = (HashEntry<K,V>)tab[i] ; e != null ; e = e.next)
264 dl 1.4 if (value.equals(e.value))
265     return true;
266     }
267     return false;
268     }
269    
270 tim 1.11 V put(K key, int hash, V value, boolean onlyIfAbsent) {
271 dl 1.4 lock();
272     try {
273 dl 1.9 int c = count;
274 tim 1.11 HashEntry[] tab = table;
275 dl 1.9 int index = hash & (tab.length - 1);
276 tim 1.11 HashEntry<K,V> first = (HashEntry<K,V>) tab[index];
277    
278     for (HashEntry<K,V> e = first; e != null; e = (HashEntry<K,V>) e.next) {
279 dl 1.9 if (e.hash == hash && key.equals(e.key)) {
280 tim 1.11 V oldValue = e.value;
281 dl 1.4 if (!onlyIfAbsent)
282     e.value = value;
283 dl 1.9 count = c; // write-volatile
284 dl 1.4 return oldValue;
285     }
286     }
287 tim 1.11
288 dl 1.4 tab[index] = new HashEntry<K,V>(hash, key, value, first);
289 dl 1.9 ++c;
290     count = c; // write-volatile
291 tim 1.11 if (c > threshold)
292 dl 1.9 setTable(rehash(tab));
293 dl 1.4 return null;
294 tim 1.16 } finally {
295 dl 1.4 unlock();
296     }
297     }
298    
299 tim 1.11 private HashEntry[] rehash(HashEntry[] oldTable) {
300 dl 1.4 int oldCapacity = oldTable.length;
301     if (oldCapacity >= MAXIMUM_CAPACITY)
302 dl 1.9 return oldTable;
303 dl 1.4
304     /*
305     * Reclassify nodes in each list to new Map. Because we are
306     * using power-of-two expansion, the elements from each bin
307     * must either stay at same index, or move with a power of two
308     * offset. We eliminate unnecessary node creation by catching
309     * cases where old nodes can be reused because their next
310     * fields won't change. Statistically, at the default
311     * threshhold, only about one-sixth of them need cloning when
312     * a table doubles. The nodes they replace will be garbage
313     * collectable as soon as they are no longer referenced by any
314     * reader thread that may be in the midst of traversing table
315     * right now.
316     */
317 tim 1.11
318     HashEntry[] newTable = new HashEntry[oldCapacity << 1];
319 dl 1.4 int sizeMask = newTable.length - 1;
320     for (int i = 0; i < oldCapacity ; i++) {
321     // We need to guarantee that any existing reads of old Map can
322 tim 1.11 // proceed. So we cannot yet null out each bin.
323 tim 1.12 HashEntry<K,V> e = (HashEntry<K,V>)oldTable[i];
324 tim 1.11
325 dl 1.4 if (e != null) {
326     HashEntry<K,V> next = e.next;
327     int idx = e.hash & sizeMask;
328 tim 1.11
329 dl 1.4 // Single node on list
330 tim 1.11 if (next == null)
331 dl 1.4 newTable[idx] = e;
332 tim 1.11
333     else {
334 dl 1.4 // Reuse trailing consecutive sequence at same slot
335     HashEntry<K,V> lastRun = e;
336     int lastIdx = idx;
337 tim 1.11 for (HashEntry<K,V> last = next;
338     last != null;
339 dl 1.4 last = last.next) {
340     int k = last.hash & sizeMask;
341     if (k != lastIdx) {
342     lastIdx = k;
343     lastRun = last;
344     }
345     }
346     newTable[lastIdx] = lastRun;
347 tim 1.11
348 dl 1.4 // Clone all remaining nodes
349     for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
350     int k = p.hash & sizeMask;
351 tim 1.11 newTable[k] = new HashEntry<K,V>(p.hash,
352     p.key,
353     p.value,
354     (HashEntry<K,V>) newTable[k]);
355 dl 1.4 }
356     }
357     }
358     }
359 dl 1.9 return newTable;
360 dl 1.4 }
361 dl 1.6
362     /**
363     * Remove; match on key only if value null, else match both.
364     */
365 dl 1.4 V remove(Object key, int hash, Object value) {
366 tim 1.11 lock();
367 dl 1.4 try {
368 dl 1.9 int c = count;
369 dl 1.4 HashEntry[] tab = table;
370 dl 1.9 int index = hash & (tab.length - 1);
371 tim 1.12 HashEntry<K,V> first = (HashEntry<K,V>)tab[index];
372 tim 1.11
373 dl 1.4 HashEntry<K,V> e = first;
374 dl 1.9 for (;;) {
375 dl 1.4 if (e == null)
376     return null;
377 dl 1.9 if (e.hash == hash && key.equals(e.key))
378 dl 1.4 break;
379     e = e.next;
380     }
381    
382     V oldValue = e.value;
383     if (value != null && !value.equals(oldValue))
384     return null;
385 dl 1.9
386 dl 1.4 // All entries following removed node can stay in list, but
387 tim 1.11 // all preceeding ones need to be cloned.
388 dl 1.4 HashEntry<K,V> newFirst = e.next;
389 tim 1.11 for (HashEntry<K,V> p = first; p != e; p = p.next)
390     newFirst = new HashEntry<K,V>(p.hash, p.key,
391 dl 1.8 p.value, newFirst);
392 dl 1.4 tab[index] = newFirst;
393 dl 1.9 count = c-1; // write-volatile
394     return oldValue;
395 tim 1.16 } finally {
396 dl 1.4 unlock();
397     }
398     }
399    
400     void clear() {
401     lock();
402     try {
403 tim 1.11 HashEntry[] tab = table;
404     for (int i = 0; i < tab.length ; i++)
405 dl 1.4 tab[i] = null;
406     count = 0; // write-volatile
407 tim 1.16 } finally {
408 dl 1.4 unlock();
409     }
410     }
411 tim 1.1 }
412    
413     /**
414 dl 1.4 * ConcurrentReaderHashMap list entry.
415 tim 1.1 */
416 dl 1.4 private static class HashEntry<K,V> implements Entry<K,V> {
417     private final K key;
418     private V value;
419     private final int hash;
420     private final HashEntry<K,V> next;
421    
422     HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
423     this.value = value;
424     this.hash = hash;
425     this.key = key;
426     this.next = next;
427     }
428    
429     public K getKey() {
430     return key;
431     }
432 tim 1.1
433 dl 1.4 public V getValue() {
434 tim 1.11 return value;
435 tim 1.1 }
436    
437 dl 1.4 public V setValue(V newValue) {
438     // We aren't required to, and don't provide any
439     // visibility barriers for setting value.
440     if (newValue == null)
441     throw new NullPointerException();
442     V oldValue = this.value;
443     this.value = newValue;
444     return oldValue;
445     }
446 tim 1.1
447 dl 1.4 public boolean equals(Object o) {
448     if (!(o instanceof Entry))
449     return false;
450 tim 1.12 Entry<K,V> e = (Entry<K,V>)o;
451 dl 1.4 return (key.equals(e.getKey()) && value.equals(e.getValue()));
452     }
453 tim 1.11
454 dl 1.4 public int hashCode() {
455     return key.hashCode() ^ value.hashCode();
456     }
457 tim 1.1
458 dl 1.4 public String toString() {
459     return key + "=" + value;
460     }
461 tim 1.1 }
462    
463 tim 1.11
464 dl 1.4 /* ---------------- Public operations -------------- */
465 tim 1.1
466     /**
467     * Constructs a new, empty map with the specified initial
468     * capacity and the specified load factor.
469     *
470 dl 1.4 * @param initialCapacity the initial capacity. The actual
471     * initial capacity is rounded up to the nearest power of two.
472 tim 1.1 * @param loadFactor the load factor threshold, used to control resizing.
473 dl 1.4 * @param segments the number of concurrently accessible segments. the
474     * actual number of segments is rounded to the next power of two.
475     * @throws IllegalArgumentException if the initial capacity is
476     * negative or the load factor or number of segments are
477     * nonpositive.
478     */
479 tim 1.11 public ConcurrentHashMap(int initialCapacity,
480 dl 1.8 float loadFactor, int segments) {
481 dl 1.4 if (!(loadFactor > 0) || initialCapacity < 0 || segments <= 0)
482     throw new IllegalArgumentException();
483    
484     // Find power-of-two sizes best matching arguments
485     int sshift = 0;
486     int ssize = 1;
487     while (ssize < segments) {
488     ++sshift;
489     ssize <<= 1;
490     }
491 dl 1.9 segmentShift = 32 - sshift;
492 dl 1.8 segmentMask = ssize - 1;
493 tim 1.11 this.segments = new Segment[ssize];
494 dl 1.4
495     if (initialCapacity > MAXIMUM_CAPACITY)
496     initialCapacity = MAXIMUM_CAPACITY;
497     int c = initialCapacity / ssize;
498 tim 1.11 if (c * ssize < initialCapacity)
499 dl 1.4 ++c;
500     int cap = 1;
501     while (cap < c)
502     cap <<= 1;
503    
504     for (int i = 0; i < this.segments.length; ++i)
505     this.segments[i] = new Segment<K,V>(cap, loadFactor);
506 tim 1.1 }
507    
508     /**
509     * Constructs a new, empty map with the specified initial
510 dl 1.4 * capacity, and with default load factor and segments.
511 tim 1.1 *
512 dl 1.4 * @param initialCapacity the initial capacity of the
513     * ConcurrentHashMap.
514     * @throws IllegalArgumentException if the initial capacity of
515     * elements is negative.
516 tim 1.1 */
517     public ConcurrentHashMap(int initialCapacity) {
518 dl 1.4 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
519 tim 1.1 }
520    
521     /**
522 dl 1.4 * Constructs a new, empty map with a default initial capacity,
523 tim 1.15 * load factor, and number of segments.
524 tim 1.1 */
525     public ConcurrentHashMap() {
526 dl 1.4 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
527 tim 1.1 }
528    
529     /**
530     * Constructs a new map with the same mappings as the given map. The
531     * map is created with a capacity of twice the number of mappings in
532 dl 1.4 * the given map or 11 (whichever is greater), and a default load factor.
533 tim 1.1 */
534     public <A extends K, B extends V> ConcurrentHashMap(Map<A,B> t) {
535     this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
536 dl 1.4 11),
537     DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
538     putAll(t);
539 tim 1.1 }
540    
541 dl 1.4 // inherit Map javadoc
542 tim 1.1 public int size() {
543     int c = 0;
544     for (int i = 0; i < segments.length; ++i)
545 dl 1.4 c += segments[i].count;
546 tim 1.1 return c;
547     }
548    
549 dl 1.4 // inherit Map javadoc
550 tim 1.1 public boolean isEmpty() {
551     for (int i = 0; i < segments.length; ++i)
552 dl 1.4 if (segments[i].count != 0)
553 tim 1.1 return false;
554     return true;
555     }
556    
557     /**
558     * Returns the value to which the specified key is mapped in this table.
559     *
560     * @param key a key in the table.
561     * @return the value to which the key is mapped in this table;
562     * <code>null</code> if the key is not mapped to any value in
563     * this table.
564 dl 1.8 * @throws NullPointerException if the key is
565 tim 1.1 * <code>null</code>.
566     * @see #put(Object, Object)
567     */
568 tim 1.11 public V get(Object key) {
569 dl 1.4 int hash = hash(key); // throws NullPointerException if key null
570 tim 1.11 return segmentFor(hash).get((K) key, hash);
571 tim 1.1 }
572    
573     /**
574     * Tests if the specified object is a key in this table.
575 tim 1.11 *
576 tim 1.1 * @param key possible key.
577 tim 1.11 * @return <code>true</code> if and only if the specified object
578     * is a key in this table, as determined by the
579 tim 1.1 * <tt>equals</tt> method; <code>false</code> otherwise.
580 dl 1.8 * @throws NullPointerException if the key is
581 tim 1.1 * <code>null</code>.
582     * @see #contains(Object)
583     */
584     public boolean containsKey(Object key) {
585 dl 1.4 int hash = hash(key); // throws NullPointerException if key null
586 dl 1.9 return segmentFor(hash).containsKey(key, hash);
587 tim 1.1 }
588    
589     /**
590     * Returns <tt>true</tt> if this map maps one or more keys to the
591     * specified value. Note: This method requires a full internal
592     * traversal of the hash table, and so is much slower than
593     * method <tt>containsKey</tt>.
594     *
595     * @param value value whose presence in this map is to be tested.
596     * @return <tt>true</tt> if this map maps one or more keys to the
597 tim 1.11 * specified value.
598 dl 1.8 * @throws NullPointerException if the value is <code>null</code>.
599 tim 1.1 */
600     public boolean containsValue(Object value) {
601 tim 1.11 if (value == null)
602 dl 1.4 throw new NullPointerException();
603 tim 1.1
604 dl 1.4 for (int i = 0; i < segments.length; ++i) {
605     if (segments[i].containsValue(value))
606     return true;
607 tim 1.1 }
608     return false;
609     }
610     /**
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.17 * <code>containsKey</code> method.
614     *
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     * plug-in compatibility with class {@link java.util.Hashtable},
618     * 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     * @return <code>true</code> if and only if some key maps to the
623 tim 1.11 * <code>value</code> argument in this table as
624 tim 1.1 * determined by the <tt>equals</tt> method;
625     * <code>false</code> otherwise.
626 dl 1.8 * @throws NullPointerException if the value is <code>null</code>.
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 tim 1.11 * Maps the specified <code>key</code> to the specified
637     * <code>value</code> in this table. Neither the key nor the
638 dl 1.4 * value can be <code>null</code>. <p>
639     *
640 tim 1.11 * The value can be retrieved by calling the <code>get</code> method
641     * 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     * or <code>null</code> if it did not have one.
647 dl 1.8 * @throws NullPointerException if the key or value is
648 dl 1.4 * <code>null</code>.
649     * @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     * or <code>null</code> if the key did not have a mapping.
717 dl 1.8 * @throws NullPointerException if the key is
718 dl 1.4 * <code>null</code>.
719     */
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