ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.26
Committed: Sat Oct 18 12:29:33 2003 UTC (20 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.25: +2 -0 lines
Log Message:
Added docs for type params

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