ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.22
Committed: Sun Aug 31 13:33:13 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.21: +5 -4 lines
Log Message:
Removed non-standard tags and misc javadoc cleanup

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