ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.23
Committed: Sat Sep 13 18:51:10 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.22: +18 -28 lines
Log Message:
Proofreading pass -- many minor adjustments

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