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