ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.21
Committed: Fri Aug 29 14:09:52 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.20: +107 -27 lines
Log Message:
Avoid ABA problem in CHP; fix other javadocs

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