ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.24
Committed: Fri Oct 10 23:51:28 2003 UTC (20 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.23: +2 -0 lines
Log Message:
Rephrased by-permission clause

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