ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.96
Committed: Sun May 18 23:47:56 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.95: +15 -15 lines
Log Message:
Sync with OpenJDK; untabify

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.36 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 dl 1.2 */
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 jsr166 1.68 * They do <em>not</em> throw {@link ConcurrentModificationException}.
37     * However, iterators are designed to be used by only one thread at a time.
38 tim 1.1 *
39 dl 1.19 * <p> The allowed concurrency among update operations is guided by
40     * the optional <tt>concurrencyLevel</tt> constructor argument
41 dl 1.57 * (default <tt>16</tt>), which is used as a hint for internal sizing. The
42 dl 1.21 * table is internally partitioned to try to permit the indicated
43     * number of concurrent updates without contention. Because placement
44     * in hash tables is essentially random, the actual concurrency will
45     * vary. Ideally, you should choose a value to accommodate as many
46 dl 1.25 * threads as will ever concurrently modify the table. Using a
47 dl 1.21 * significantly higher value than you need can waste space and time,
48     * and a significantly lower value can lead to thread contention. But
49     * overestimates and underestimates within an order of magnitude do
50 dl 1.25 * not usually have much noticeable impact. A value of one is
51 dl 1.45 * appropriate when it is known that only one thread will modify and
52     * all others will only read. Also, resizing this or any other kind of
53     * hash table is a relatively slow operation, so, when possible, it is
54     * a good idea to provide estimates of expected table sizes in
55     * constructors.
56 tim 1.1 *
57 dl 1.45 * <p>This class and its views and iterators implement all of the
58     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
59     * interfaces.
60 dl 1.23 *
61 jsr166 1.68 * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
62     * does <em>not</em> allow <tt>null</tt> to be used as a key or value.
63 tim 1.1 *
64 dl 1.42 * <p>This class is a member of the
65 jsr166 1.88 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
66 dl 1.42 * Java Collections Framework</a>.
67     *
68 dl 1.8 * @since 1.5
69     * @author Doug Lea
70 dl 1.27 * @param <K> the type of keys maintained by this map
71 jsr166 1.64 * @param <V> the type of mapped values
72 dl 1.8 */
73 tim 1.1 public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
74 dl 1.48 implements ConcurrentMap<K, V>, Serializable {
75 dl 1.20 private static final long serialVersionUID = 7249069246763182397L;
76 tim 1.1
77     /*
78 dl 1.4 * The basic strategy is to subdivide the table among Segments,
79     * each of which itself is a concurrently readable hash table.
80     */
81 tim 1.1
82 dl 1.4 /* ---------------- Constants -------------- */
83 tim 1.11
84 dl 1.4 /**
85 dl 1.56 * The default initial capacity for this table,
86     * used when not otherwise specified in a constructor.
87 dl 1.4 */
88 dl 1.57 static final int DEFAULT_INITIAL_CAPACITY = 16;
89 dl 1.56
90     /**
91     * The default load factor for this table, used when not
92     * otherwise specified in a constructor.
93     */
94 dl 1.57 static final float DEFAULT_LOAD_FACTOR = 0.75f;
95 dl 1.56
96     /**
97     * The default concurrency level for this table, used when not
98     * otherwise specified in a constructor.
99 jsr166 1.59 */
100 dl 1.57 static final int DEFAULT_CONCURRENCY_LEVEL = 16;
101 tim 1.1
102     /**
103 dl 1.4 * The maximum capacity, used if a higher value is implicitly
104     * specified by either of the constructors with arguments. MUST
105 jsr166 1.68 * be a power of two <= 1<<30 to ensure that entries are indexable
106 dl 1.21 * using ints.
107 dl 1.4 */
108 jsr166 1.64 static final int MAXIMUM_CAPACITY = 1 << 30;
109 tim 1.11
110 tim 1.1 /**
111 dl 1.37 * The maximum number of segments to allow; used to bound
112     * constructor arguments.
113 dl 1.21 */
114 dl 1.41 static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
115 dl 1.21
116 dl 1.46 /**
117     * Number of unsynchronized retries in size and containsValue
118     * methods before resorting to locking. This is used to avoid
119     * unbounded retries if tables undergo continuous modification
120     * which would make it impossible to obtain an accurate result.
121     */
122     static final int RETRIES_BEFORE_LOCK = 2;
123    
124 dl 1.4 /* ---------------- Fields -------------- */
125 tim 1.1
126     /**
127 dl 1.9 * Mask value for indexing into segments. The upper bits of a
128     * key's hash code are used to choose the segment.
129 jsr166 1.59 */
130 dl 1.41 final int segmentMask;
131 tim 1.1
132     /**
133 dl 1.4 * Shift value for indexing within segments.
134 jsr166 1.59 */
135 dl 1.41 final int segmentShift;
136 tim 1.1
137     /**
138 dl 1.4 * The segments, each of which is a specialized hash table
139 tim 1.1 */
140 dl 1.71 final Segment<K,V>[] segments;
141 dl 1.4
142 dl 1.41 transient Set<K> keySet;
143     transient Set<Map.Entry<K,V>> entrySet;
144     transient Collection<V> values;
145 dl 1.4
146     /* ---------------- Small Utilities -------------- */
147 tim 1.1
148     /**
149 dl 1.89 * Applies a supplemental hash function to a given hashCode, which
150     * defends against poor quality hash functions. This is critical
151 jsr166 1.90 * because ConcurrentHashMap uses power-of-two length hash tables,
152     * that otherwise encounter collisions for hashCodes that do not
153 dl 1.93 * differ in lower or upper bits.
154 dl 1.89 */
155 jsr166 1.90 private static int hash(int h) {
156 dl 1.92 // Spread bits to regularize both segment and index locations,
157 dl 1.93 // using variant of single-word Wang/Jenkins hash.
158     h += (h << 15) ^ 0xffffcd7d;
159     h ^= (h >>> 10);
160     h += (h << 3);
161     h ^= (h >>> 6);
162     h += (h << 2) + (h << 14);
163     return h ^ (h >>> 16);
164 dl 1.4 }
165    
166 tim 1.1 /**
167 dl 1.44 * Returns the segment that should be used for key with given hash
168     * @param hash the hash code for the key
169     * @return the segment
170 tim 1.1 */
171 dl 1.41 final Segment<K,V> segmentFor(int hash) {
172 dl 1.71 return segments[(hash >>> segmentShift) & segmentMask];
173 dl 1.4 }
174 tim 1.1
175 dl 1.4 /* ---------------- Inner Classes -------------- */
176 tim 1.1
177     /**
178 dl 1.46 * ConcurrentHashMap list entry. Note that this is never exported
179 jsr166 1.64 * out as a user-visible Map.Entry.
180     *
181 dl 1.46 * Because the value field is volatile, not final, it is legal wrt
182     * the Java Memory Model for an unsynchronized reader to see null
183     * instead of initial value when read via a data race. Although a
184     * reordering leading to this is not likely to ever actually
185     * occur, the Segment.readValueUnderLock method is used as a
186     * backup in case a null (pre-initialized) value is ever seen in
187     * an unsynchronized access method.
188     */
189     static final class HashEntry<K,V> {
190     final K key;
191     final int hash;
192     volatile V value;
193     final HashEntry<K,V> next;
194    
195     HashEntry(K key, int hash, HashEntry<K,V> next, V value) {
196     this.key = key;
197     this.hash = hash;
198     this.next = next;
199     this.value = value;
200     }
201 dl 1.72
202 jsr166 1.96 @SuppressWarnings("unchecked")
203     static final <K,V> HashEntry<K,V>[] newArray(int i) {
204     return new HashEntry[i];
205     }
206 dl 1.46 }
207    
208     /**
209 dl 1.6 * Segments are specialized versions of hash tables. This
210 dl 1.4 * subclasses from ReentrantLock opportunistically, just to
211     * simplify some locking and avoid separate construction.
212 jsr166 1.59 */
213 dl 1.41 static final class Segment<K,V> extends ReentrantLock implements Serializable {
214 dl 1.4 /*
215     * Segments maintain a table of entry lists that are ALWAYS
216     * kept in a consistent state, so can be read without locking.
217     * Next fields of nodes are immutable (final). All list
218     * additions are performed at the front of each bin. This
219     * makes it easy to check changes, and also fast to traverse.
220     * When nodes would otherwise be changed, new nodes are
221     * created to replace them. This works well for hash tables
222     * since the bin lists tend to be short. (The average length
223     * is less than two for the default load factor threshold.)
224     *
225     * Read operations can thus proceed without locking, but rely
226 dl 1.45 * on selected uses of volatiles to ensure that completed
227     * write operations performed by other threads are
228     * noticed. For most purposes, the "count" field, tracking the
229     * number of elements, serves as that volatile variable
230     * ensuring visibility. This is convenient because this field
231     * needs to be read in many read operations anyway:
232 dl 1.4 *
233 dl 1.45 * - All (unsynchronized) read operations must first read the
234 dl 1.4 * "count" field, and should not look at table entries if
235     * it is 0.
236 tim 1.11 *
237 dl 1.45 * - All (synchronized) write operations should write to
238     * the "count" field after structurally changing any bin.
239     * The operations must not take any action that could even
240     * momentarily cause a concurrent read operation to see
241     * inconsistent data. This is made easier by the nature of
242     * the read operations in Map. For example, no operation
243 dl 1.4 * can reveal that the table has grown but the threshold
244     * has not yet been updated, so there are no atomicity
245     * requirements for this with respect to reads.
246     *
247 dl 1.45 * As a guide, all critical volatile reads and writes to the
248     * count field are marked in code comments.
249 dl 1.4 */
250 tim 1.11
251 dl 1.24 private static final long serialVersionUID = 2249069246763182397L;
252    
253 dl 1.4 /**
254     * The number of elements in this segment's region.
255 jsr166 1.59 */
256 dl 1.4 transient volatile int count;
257    
258     /**
259 dl 1.45 * Number of updates that alter the size of the table. This is
260     * used during bulk-read methods to make sure they see a
261     * consistent snapshot: If modCounts change during a traversal
262 dl 1.46 * of segments computing size or checking containsValue, then
263 dl 1.45 * we might have an inconsistent view of state so (usually)
264     * must retry.
265 dl 1.21 */
266     transient int modCount;
267    
268     /**
269 dl 1.4 * The table is rehashed when its size exceeds this threshold.
270 jsr166 1.68 * (The value of this field is always <tt>(int)(capacity *
271     * loadFactor)</tt>.)
272 dl 1.4 */
273 dl 1.41 transient int threshold;
274 dl 1.4
275     /**
276 jsr166 1.74 * The per-segment table.
277 dl 1.73 */
278 dl 1.71 transient volatile HashEntry<K,V>[] table;
279 dl 1.4
280     /**
281     * The load factor for the hash table. Even though this value
282     * is same for all segments, it is replicated to avoid needing
283     * links to outer object.
284     * @serial
285     */
286 dl 1.41 final float loadFactor;
287 tim 1.1
288 dl 1.4 Segment(int initialCapacity, float lf) {
289     loadFactor = lf;
290 dl 1.72 setTable(HashEntry.<K,V>newArray(initialCapacity));
291     }
292    
293 jsr166 1.96 @SuppressWarnings("unchecked")
294 dl 1.72 static final <K,V> Segment<K,V>[] newArray(int i) {
295 jsr166 1.96 return new Segment[i];
296 dl 1.4 }
297 tim 1.1
298 dl 1.4 /**
299 jsr166 1.60 * Sets table to new HashEntry array.
300 dl 1.4 * Call only while holding lock or in constructor.
301 jsr166 1.59 */
302 dl 1.71 void setTable(HashEntry<K,V>[] newTable) {
303 dl 1.45 threshold = (int)(newTable.length * loadFactor);
304 dl 1.4 table = newTable;
305 dl 1.45 }
306    
307     /**
308 jsr166 1.60 * Returns properly casted first entry of bin for given hash.
309 dl 1.45 */
310     HashEntry<K,V> getFirst(int hash) {
311 dl 1.71 HashEntry<K,V>[] tab = table;
312     return tab[hash & (tab.length - 1)];
313 dl 1.45 }
314    
315     /**
316 jsr166 1.62 * Reads value field of an entry under lock. Called if value
317 dl 1.45 * field ever appears to be null. This is possible only if a
318     * compiler happens to reorder a HashEntry initialization with
319     * its table assignment, which is legal under memory model
320     * but is not known to ever occur.
321     */
322     V readValueUnderLock(HashEntry<K,V> e) {
323     lock();
324     try {
325     return e.value;
326     } finally {
327     unlock();
328     }
329 tim 1.11 }
330 dl 1.4
331     /* Specialized implementations of map methods */
332 tim 1.11
333 dl 1.29 V get(Object key, int hash) {
334 dl 1.4 if (count != 0) { // read-volatile
335 dl 1.45 HashEntry<K,V> e = getFirst(hash);
336 dl 1.4 while (e != null) {
337 dl 1.45 if (e.hash == hash && key.equals(e.key)) {
338     V v = e.value;
339     if (v != null)
340     return v;
341     return readValueUnderLock(e); // recheck
342     }
343 dl 1.4 e = e.next;
344     }
345     }
346     return null;
347     }
348    
349     boolean containsKey(Object key, int hash) {
350     if (count != 0) { // read-volatile
351 dl 1.45 HashEntry<K,V> e = getFirst(hash);
352 dl 1.4 while (e != null) {
353 tim 1.11 if (e.hash == hash && key.equals(e.key))
354 dl 1.4 return true;
355     e = e.next;
356     }
357     }
358     return false;
359     }
360 tim 1.11
361 dl 1.4 boolean containsValue(Object value) {
362     if (count != 0) { // read-volatile
363 dl 1.71 HashEntry<K,V>[] tab = table;
364 dl 1.4 int len = tab.length;
365 dl 1.45 for (int i = 0 ; i < len; i++) {
366 dl 1.72 for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
367 dl 1.45 V v = e.value;
368     if (v == null) // recheck
369     v = readValueUnderLock(e);
370     if (value.equals(v))
371 dl 1.4 return true;
372 dl 1.45 }
373     }
374 dl 1.4 }
375     return false;
376     }
377    
378 dl 1.31 boolean replace(K key, int hash, V oldValue, V newValue) {
379     lock();
380     try {
381 dl 1.45 HashEntry<K,V> e = getFirst(hash);
382     while (e != null && (e.hash != hash || !key.equals(e.key)))
383 dl 1.31 e = e.next;
384 dl 1.45
385     boolean replaced = false;
386     if (e != null && oldValue.equals(e.value)) {
387     replaced = true;
388     e.value = newValue;
389 dl 1.31 }
390 dl 1.45 return replaced;
391 dl 1.33 } finally {
392     unlock();
393     }
394     }
395    
396     V replace(K key, int hash, V newValue) {
397     lock();
398     try {
399 dl 1.45 HashEntry<K,V> e = getFirst(hash);
400     while (e != null && (e.hash != hash || !key.equals(e.key)))
401 dl 1.33 e = e.next;
402 dl 1.45
403     V oldValue = null;
404     if (e != null) {
405     oldValue = e.value;
406     e.value = newValue;
407 dl 1.32 }
408 dl 1.45 return oldValue;
409 dl 1.31 } finally {
410     unlock();
411     }
412     }
413    
414 dl 1.32
415 tim 1.11 V put(K key, int hash, V value, boolean onlyIfAbsent) {
416 dl 1.4 lock();
417     try {
418 dl 1.9 int c = count;
419 dl 1.45 if (c++ > threshold) // ensure capacity
420     rehash();
421 dl 1.71 HashEntry<K,V>[] tab = table;
422 dl 1.9 int index = hash & (tab.length - 1);
423 dl 1.71 HashEntry<K,V> first = tab[index];
424 dl 1.45 HashEntry<K,V> e = first;
425     while (e != null && (e.hash != hash || !key.equals(e.key)))
426     e = e.next;
427 tim 1.11
428 dl 1.45 V oldValue;
429     if (e != null) {
430     oldValue = e.value;
431     if (!onlyIfAbsent)
432     e.value = value;
433     }
434     else {
435     oldValue = null;
436     ++modCount;
437     tab[index] = new HashEntry<K,V>(key, hash, first, value);
438     count = c; // write-volatile
439 dl 1.4 }
440 dl 1.45 return oldValue;
441 tim 1.16 } finally {
442 dl 1.4 unlock();
443     }
444     }
445    
446 dl 1.45 void rehash() {
447 dl 1.71 HashEntry<K,V>[] oldTable = table;
448 dl 1.4 int oldCapacity = oldTable.length;
449     if (oldCapacity >= MAXIMUM_CAPACITY)
450 dl 1.45 return;
451 dl 1.4
452     /*
453     * Reclassify nodes in each list to new Map. Because we are
454     * using power-of-two expansion, the elements from each bin
455     * must either stay at same index, or move with a power of two
456     * offset. We eliminate unnecessary node creation by catching
457     * cases where old nodes can be reused because their next
458     * fields won't change. Statistically, at the default
459 dl 1.29 * threshold, only about one-sixth of them need cloning when
460 dl 1.4 * a table doubles. The nodes they replace will be garbage
461     * collectable as soon as they are no longer referenced by any
462     * reader thread that may be in the midst of traversing table
463     * right now.
464     */
465 tim 1.11
466 dl 1.72 HashEntry<K,V>[] newTable = HashEntry.newArray(oldCapacity<<1);
467 dl 1.45 threshold = (int)(newTable.length * loadFactor);
468 dl 1.4 int sizeMask = newTable.length - 1;
469     for (int i = 0; i < oldCapacity ; i++) {
470     // We need to guarantee that any existing reads of old Map can
471 tim 1.11 // proceed. So we cannot yet null out each bin.
472 dl 1.71 HashEntry<K,V> e = oldTable[i];
473 tim 1.11
474 dl 1.4 if (e != null) {
475     HashEntry<K,V> next = e.next;
476     int idx = e.hash & sizeMask;
477 tim 1.11
478 dl 1.4 // Single node on list
479 tim 1.11 if (next == null)
480 dl 1.4 newTable[idx] = e;
481 tim 1.11
482     else {
483 dl 1.4 // Reuse trailing consecutive sequence at same slot
484     HashEntry<K,V> lastRun = e;
485     int lastIdx = idx;
486 tim 1.11 for (HashEntry<K,V> last = next;
487     last != null;
488 dl 1.4 last = last.next) {
489     int k = last.hash & sizeMask;
490     if (k != lastIdx) {
491     lastIdx = k;
492     lastRun = last;
493     }
494     }
495     newTable[lastIdx] = lastRun;
496 tim 1.11
497 dl 1.4 // Clone all remaining nodes
498     for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
499     int k = p.hash & sizeMask;
500 dl 1.71 HashEntry<K,V> n = newTable[k];
501 dl 1.45 newTable[k] = new HashEntry<K,V>(p.key, p.hash,
502     n, p.value);
503 dl 1.4 }
504     }
505     }
506     }
507 dl 1.45 table = newTable;
508 dl 1.4 }
509 dl 1.6
510     /**
511     * Remove; match on key only if value null, else match both.
512     */
513 dl 1.4 V remove(Object key, int hash, Object value) {
514 tim 1.11 lock();
515 dl 1.4 try {
516 dl 1.45 int c = count - 1;
517 dl 1.71 HashEntry<K,V>[] tab = table;
518 dl 1.9 int index = hash & (tab.length - 1);
519 dl 1.71 HashEntry<K,V> first = tab[index];
520 dl 1.4 HashEntry<K,V> e = first;
521 dl 1.45 while (e != null && (e.hash != hash || !key.equals(e.key)))
522 dl 1.4 e = e.next;
523 dl 1.45
524     V oldValue = null;
525     if (e != null) {
526     V v = e.value;
527     if (value == null || value.equals(v)) {
528     oldValue = v;
529     // All entries following removed node can stay
530     // in list, but all preceding ones need to be
531     // cloned.
532     ++modCount;
533     HashEntry<K,V> newFirst = e.next;
534     for (HashEntry<K,V> p = first; p != e; p = p.next)
535 jsr166 1.64 newFirst = new HashEntry<K,V>(p.key, p.hash,
536 dl 1.45 newFirst, p.value);
537     tab[index] = newFirst;
538     count = c; // write-volatile
539     }
540 dl 1.4 }
541 dl 1.9 return oldValue;
542 tim 1.16 } finally {
543 dl 1.4 unlock();
544     }
545     }
546    
547     void clear() {
548 dl 1.45 if (count != 0) {
549     lock();
550     try {
551 dl 1.71 HashEntry<K,V>[] tab = table;
552 dl 1.45 for (int i = 0; i < tab.length ; i++)
553     tab[i] = null;
554     ++modCount;
555     count = 0; // write-volatile
556     } finally {
557     unlock();
558     }
559 dl 1.4 }
560     }
561 tim 1.1 }
562    
563    
564 tim 1.11
565 dl 1.4 /* ---------------- Public operations -------------- */
566 tim 1.1
567     /**
568 dl 1.44 * Creates a new, empty map with the specified initial
569 dl 1.56 * capacity, load factor and concurrency level.
570 tim 1.1 *
571 dl 1.19 * @param initialCapacity the initial capacity. The implementation
572     * performs internal sizing to accommodate this many elements.
573 tim 1.1 * @param loadFactor the load factor threshold, used to control resizing.
574 dl 1.56 * Resizing may be performed when the average number of elements per
575     * bin exceeds this threshold.
576 dl 1.19 * @param concurrencyLevel the estimated number of concurrently
577     * updating threads. The implementation performs internal sizing
578 jsr166 1.64 * to try to accommodate this many threads.
579 dl 1.4 * @throws IllegalArgumentException if the initial capacity is
580 dl 1.19 * negative or the load factor or concurrencyLevel are
581 dl 1.4 * nonpositive.
582     */
583 tim 1.11 public ConcurrentHashMap(int initialCapacity,
584 dl 1.19 float loadFactor, int concurrencyLevel) {
585     if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
586 dl 1.4 throw new IllegalArgumentException();
587    
588 dl 1.21 if (concurrencyLevel > MAX_SEGMENTS)
589     concurrencyLevel = MAX_SEGMENTS;
590    
591 dl 1.4 // Find power-of-two sizes best matching arguments
592     int sshift = 0;
593     int ssize = 1;
594 dl 1.19 while (ssize < concurrencyLevel) {
595 dl 1.4 ++sshift;
596     ssize <<= 1;
597     }
598 dl 1.9 segmentShift = 32 - sshift;
599 dl 1.8 segmentMask = ssize - 1;
600 dl 1.72 this.segments = Segment.newArray(ssize);
601 dl 1.4
602     if (initialCapacity > MAXIMUM_CAPACITY)
603     initialCapacity = MAXIMUM_CAPACITY;
604     int c = initialCapacity / ssize;
605 tim 1.11 if (c * ssize < initialCapacity)
606 dl 1.4 ++c;
607     int cap = 1;
608     while (cap < c)
609     cap <<= 1;
610    
611     for (int i = 0; i < this.segments.length; ++i)
612     this.segments[i] = new Segment<K,V>(cap, loadFactor);
613 tim 1.1 }
614    
615     /**
616 dl 1.55 * Creates a new, empty map with the specified initial capacity
617 jsr166 1.76 * and load factor and with the default concurrencyLevel (16).
618 dl 1.55 *
619     * @param initialCapacity The implementation performs internal
620     * sizing to accommodate this many elements.
621     * @param loadFactor the load factor threshold, used to control resizing.
622 jsr166 1.68 * Resizing may be performed when the average number of elements per
623     * bin exceeds this threshold.
624 dl 1.55 * @throws IllegalArgumentException if the initial capacity of
625     * elements is negative or the load factor is nonpositive
626 jsr166 1.78 *
627     * @since 1.6
628 dl 1.55 */
629     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
630 dl 1.56 this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
631 dl 1.55 }
632    
633     /**
634 dl 1.56 * Creates a new, empty map with the specified initial capacity,
635 jsr166 1.76 * and with default load factor (0.75) and concurrencyLevel (16).
636 tim 1.1 *
637 dl 1.58 * @param initialCapacity the initial capacity. The implementation
638     * performs internal sizing to accommodate this many elements.
639 dl 1.4 * @throws IllegalArgumentException if the initial capacity of
640     * elements is negative.
641 tim 1.1 */
642     public ConcurrentHashMap(int initialCapacity) {
643 dl 1.56 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
644 tim 1.1 }
645    
646     /**
647 jsr166 1.76 * Creates a new, empty map with a default initial capacity (16),
648     * load factor (0.75) and concurrencyLevel (16).
649 tim 1.1 */
650     public ConcurrentHashMap() {
651 dl 1.56 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
652 tim 1.1 }
653    
654     /**
655 jsr166 1.76 * Creates a new map with the same mappings as the given map.
656     * The map is created with a capacity of 1.5 times the number
657     * of mappings in the given map or 16 (whichever is greater),
658     * and a default load factor (0.75) and concurrencyLevel (16).
659     *
660 jsr166 1.68 * @param m the map
661 tim 1.1 */
662 jsr166 1.68 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
663     this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
664 dl 1.56 DEFAULT_INITIAL_CAPACITY),
665     DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
666 jsr166 1.68 putAll(m);
667 tim 1.1 }
668    
669 dl 1.56 /**
670     * Returns <tt>true</tt> if this map contains no key-value mappings.
671     *
672 jsr166 1.68 * @return <tt>true</tt> if this map contains no key-value mappings
673 dl 1.56 */
674 tim 1.1 public boolean isEmpty() {
675 dl 1.71 final Segment<K,V>[] segments = this.segments;
676 dl 1.21 /*
677 dl 1.45 * We keep track of per-segment modCounts to avoid ABA
678 dl 1.21 * problems in which an element in one segment was added and
679     * in another removed during traversal, in which case the
680     * table was never actually empty at any point. Note the
681     * similar use of modCounts in the size() and containsValue()
682     * methods, which are the only other methods also susceptible
683     * to ABA problems.
684     */
685     int[] mc = new int[segments.length];
686     int mcsum = 0;
687     for (int i = 0; i < segments.length; ++i) {
688 dl 1.4 if (segments[i].count != 0)
689 tim 1.1 return false;
690 jsr166 1.64 else
691 dl 1.21 mcsum += mc[i] = segments[i].modCount;
692     }
693     // If mcsum happens to be zero, then we know we got a snapshot
694     // before any modifications at all were made. This is
695     // probably common enough to bother tracking.
696     if (mcsum != 0) {
697     for (int i = 0; i < segments.length; ++i) {
698     if (segments[i].count != 0 ||
699 jsr166 1.64 mc[i] != segments[i].modCount)
700 dl 1.21 return false;
701     }
702     }
703 tim 1.1 return true;
704     }
705    
706 dl 1.56 /**
707     * Returns the number of key-value mappings in this map. If the
708     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
709     * <tt>Integer.MAX_VALUE</tt>.
710     *
711 jsr166 1.68 * @return the number of key-value mappings in this map
712 dl 1.56 */
713 dl 1.21 public int size() {
714 dl 1.71 final Segment<K,V>[] segments = this.segments;
715 dl 1.45 long sum = 0;
716     long check = 0;
717 dl 1.21 int[] mc = new int[segments.length];
718 dl 1.46 // Try a few times to get accurate count. On failure due to
719 dl 1.45 // continuous async changes in table, resort to locking.
720 dl 1.46 for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
721 dl 1.45 check = 0;
722     sum = 0;
723 dl 1.21 int mcsum = 0;
724     for (int i = 0; i < segments.length; ++i) {
725     sum += segments[i].count;
726     mcsum += mc[i] = segments[i].modCount;
727     }
728     if (mcsum != 0) {
729     for (int i = 0; i < segments.length; ++i) {
730     check += segments[i].count;
731     if (mc[i] != segments[i].modCount) {
732     check = -1; // force retry
733     break;
734     }
735     }
736     }
737 jsr166 1.64 if (check == sum)
738 dl 1.45 break;
739     }
740     if (check != sum) { // Resort to locking all segments
741     sum = 0;
742 jsr166 1.64 for (int i = 0; i < segments.length; ++i)
743 dl 1.45 segments[i].lock();
744 jsr166 1.64 for (int i = 0; i < segments.length; ++i)
745 dl 1.45 sum += segments[i].count;
746 jsr166 1.64 for (int i = 0; i < segments.length; ++i)
747 dl 1.45 segments[i].unlock();
748 dl 1.21 }
749 dl 1.45 if (sum > Integer.MAX_VALUE)
750     return Integer.MAX_VALUE;
751     else
752     return (int)sum;
753 dl 1.21 }
754    
755 tim 1.1 /**
756 jsr166 1.85 * Returns the value to which the specified key is mapped,
757     * or {@code null} if this map contains no mapping for the key.
758     *
759     * <p>More formally, if this map contains a mapping from a key
760     * {@code k} to a value {@code v} such that {@code key.equals(k)},
761     * then this method returns {@code v}; otherwise it returns
762     * {@code null}. (There can be at most one such mapping.)
763 tim 1.1 *
764 jsr166 1.68 * @throws NullPointerException if the specified key is null
765 tim 1.1 */
766 tim 1.11 public V get(Object key) {
767 dl 1.89 int hash = hash(key.hashCode());
768 dl 1.29 return segmentFor(hash).get(key, hash);
769 tim 1.1 }
770    
771     /**
772     * Tests if the specified object is a key in this table.
773 tim 1.11 *
774 jsr166 1.68 * @param key possible key
775     * @return <tt>true</tt> if and only if the specified object
776     * is a key in this table, as determined by the
777     * <tt>equals</tt> method; <tt>false</tt> otherwise.
778     * @throws NullPointerException if the specified key is null
779 tim 1.1 */
780     public boolean containsKey(Object key) {
781 jsr166 1.91 int hash = hash(key.hashCode());
782 dl 1.9 return segmentFor(hash).containsKey(key, hash);
783 tim 1.1 }
784    
785     /**
786     * Returns <tt>true</tt> if this map maps one or more keys to the
787     * specified value. Note: This method requires a full internal
788     * traversal of the hash table, and so is much slower than
789     * method <tt>containsKey</tt>.
790     *
791 jsr166 1.68 * @param value value whose presence in this map is to be tested
792 tim 1.1 * @return <tt>true</tt> if this map maps one or more keys to the
793 jsr166 1.68 * specified value
794     * @throws NullPointerException if the specified value is null
795 tim 1.1 */
796     public boolean containsValue(Object value) {
797 tim 1.11 if (value == null)
798 dl 1.4 throw new NullPointerException();
799 jsr166 1.64
800 dl 1.45 // See explanation of modCount use above
801 tim 1.1
802 dl 1.71 final Segment<K,V>[] segments = this.segments;
803 dl 1.21 int[] mc = new int[segments.length];
804 dl 1.45
805 dl 1.46 // Try a few times without locking
806     for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
807 dl 1.21 int sum = 0;
808     int mcsum = 0;
809     for (int i = 0; i < segments.length; ++i) {
810     int c = segments[i].count;
811     mcsum += mc[i] = segments[i].modCount;
812     if (segments[i].containsValue(value))
813     return true;
814     }
815     boolean cleanSweep = true;
816     if (mcsum != 0) {
817     for (int i = 0; i < segments.length; ++i) {
818     int c = segments[i].count;
819     if (mc[i] != segments[i].modCount) {
820     cleanSweep = false;
821     break;
822     }
823     }
824     }
825     if (cleanSweep)
826     return false;
827 tim 1.1 }
828 dl 1.45 // Resort to locking all segments
829 jsr166 1.64 for (int i = 0; i < segments.length; ++i)
830 dl 1.45 segments[i].lock();
831     boolean found = false;
832     try {
833     for (int i = 0; i < segments.length; ++i) {
834     if (segments[i].containsValue(value)) {
835     found = true;
836     break;
837     }
838     }
839     } finally {
840 jsr166 1.64 for (int i = 0; i < segments.length; ++i)
841 dl 1.45 segments[i].unlock();
842     }
843     return found;
844 tim 1.1 }
845 dl 1.19
846 tim 1.1 /**
847 dl 1.18 * Legacy method testing if some key maps into the specified value
848 dl 1.23 * in this table. This method is identical in functionality to
849 jsr166 1.68 * {@link #containsValue}, and exists solely to ensure
850 dl 1.19 * full compatibility with class {@link java.util.Hashtable},
851 dl 1.18 * which supported this method prior to introduction of the
852 dl 1.23 * Java Collections framework.
853 dl 1.17
854 jsr166 1.68 * @param value a value to search for
855     * @return <tt>true</tt> if and only if some key maps to the
856     * <tt>value</tt> argument in this table as
857     * determined by the <tt>equals</tt> method;
858     * <tt>false</tt> otherwise
859     * @throws NullPointerException if the specified value is null
860 tim 1.1 */
861 dl 1.4 public boolean contains(Object value) {
862 tim 1.1 return containsValue(value);
863     }
864    
865     /**
866 jsr166 1.75 * Maps the specified key to the specified value in this table.
867     * Neither the key nor the value can be null.
868 dl 1.4 *
869 dl 1.44 * <p> The value can be retrieved by calling the <tt>get</tt> method
870 tim 1.11 * with a key that is equal to the original key.
871 dl 1.4 *
872 jsr166 1.68 * @param key key with which the specified value is to be associated
873     * @param value value to be associated with the specified key
874     * @return the previous value associated with <tt>key</tt>, or
875     * <tt>null</tt> if there was no mapping for <tt>key</tt>
876     * @throws NullPointerException if the specified key or value is null
877 dl 1.4 */
878 tim 1.11 public V put(K key, V value) {
879     if (value == null)
880 dl 1.4 throw new NullPointerException();
881 dl 1.89 int hash = hash(key.hashCode());
882 dl 1.9 return segmentFor(hash).put(key, hash, value, false);
883 dl 1.4 }
884    
885     /**
886 jsr166 1.68 * {@inheritDoc}
887     *
888     * @return the previous value associated with the specified key,
889     * or <tt>null</tt> if there was no mapping for the key
890     * @throws NullPointerException if the specified key or value is null
891 dl 1.51 */
892 tim 1.11 public V putIfAbsent(K key, V value) {
893     if (value == null)
894 dl 1.4 throw new NullPointerException();
895 dl 1.89 int hash = hash(key.hashCode());
896 dl 1.9 return segmentFor(hash).put(key, hash, value, true);
897 dl 1.4 }
898    
899     /**
900 tim 1.1 * Copies all of the mappings from the specified map to this one.
901     * These mappings replace any mappings that this map had for any of the
902 jsr166 1.68 * keys currently in the specified map.
903 tim 1.1 *
904 jsr166 1.68 * @param m mappings to be stored in this map
905 tim 1.1 */
906 jsr166 1.68 public void putAll(Map<? extends K, ? extends V> m) {
907 jsr166 1.84 for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
908 dl 1.4 put(e.getKey(), e.getValue());
909     }
910    
911     /**
912 jsr166 1.68 * Removes the key (and its corresponding value) from this map.
913     * This method does nothing if the key is not in the map.
914 dl 1.4 *
915 jsr166 1.68 * @param key the key that needs to be removed
916     * @return the previous value associated with <tt>key</tt>, or
917 jsr166 1.84 * <tt>null</tt> if there was no mapping for <tt>key</tt>
918 jsr166 1.68 * @throws NullPointerException if the specified key is null
919 dl 1.4 */
920     public V remove(Object key) {
921 jsr166 1.96 int hash = hash(key.hashCode());
922 dl 1.9 return segmentFor(hash).remove(key, hash, null);
923 dl 1.4 }
924 tim 1.1
925 dl 1.4 /**
926 jsr166 1.68 * {@inheritDoc}
927     *
928 jsr166 1.69 * @throws NullPointerException if the specified key is null
929 dl 1.4 */
930 dl 1.13 public boolean remove(Object key, Object value) {
931 dl 1.89 int hash = hash(key.hashCode());
932 jsr166 1.68 if (value == null)
933 jsr166 1.69 return false;
934 dl 1.13 return segmentFor(hash).remove(key, hash, value) != null;
935 tim 1.1 }
936 dl 1.31
937     /**
938 jsr166 1.68 * {@inheritDoc}
939     *
940     * @throws NullPointerException if any of the arguments are null
941 dl 1.31 */
942     public boolean replace(K key, V oldValue, V newValue) {
943     if (oldValue == null || newValue == null)
944     throw new NullPointerException();
945 dl 1.89 int hash = hash(key.hashCode());
946 dl 1.31 return segmentFor(hash).replace(key, hash, oldValue, newValue);
947 dl 1.32 }
948    
949     /**
950 jsr166 1.68 * {@inheritDoc}
951     *
952     * @return the previous value associated with the specified key,
953     * or <tt>null</tt> if there was no mapping for the key
954     * @throws NullPointerException if the specified key or value is null
955 dl 1.32 */
956 dl 1.33 public V replace(K key, V value) {
957 dl 1.32 if (value == null)
958     throw new NullPointerException();
959 dl 1.89 int hash = hash(key.hashCode());
960 dl 1.33 return segmentFor(hash).replace(key, hash, value);
961 dl 1.31 }
962    
963 tim 1.1 /**
964 jsr166 1.68 * Removes all of the mappings from this map.
965 tim 1.1 */
966     public void clear() {
967 tim 1.11 for (int i = 0; i < segments.length; ++i)
968 dl 1.4 segments[i].clear();
969 tim 1.1 }
970    
971     /**
972 jsr166 1.68 * Returns a {@link Set} view of the keys contained in this map.
973     * The set is backed by the map, so changes to the map are
974     * reflected in the set, and vice-versa. The set supports element
975     * removal, which removes the corresponding mapping from this map,
976     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
977     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
978     * operations. It does not support the <tt>add</tt> or
979 tim 1.1 * <tt>addAll</tt> operations.
980 jsr166 1.68 *
981     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
982     * that will never throw {@link ConcurrentModificationException},
983 dl 1.14 * and guarantees to traverse elements as they existed upon
984     * construction of the iterator, and may (but is not guaranteed to)
985     * reflect any modifications subsequent to construction.
986 tim 1.1 */
987     public Set<K> keySet() {
988     Set<K> ks = keySet;
989 dl 1.8 return (ks != null) ? ks : (keySet = new KeySet());
990 tim 1.1 }
991    
992     /**
993 jsr166 1.68 * Returns a {@link Collection} view of the values contained in this map.
994     * The collection is backed by the map, so changes to the map are
995     * reflected in the collection, and vice-versa. The collection
996     * supports element removal, which removes the corresponding
997     * mapping from this map, via the <tt>Iterator.remove</tt>,
998     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
999     * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
1000     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1001     *
1002     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1003     * that will never throw {@link ConcurrentModificationException},
1004 dl 1.14 * and guarantees to traverse elements as they existed upon
1005     * construction of the iterator, and may (but is not guaranteed to)
1006     * reflect any modifications subsequent to construction.
1007 tim 1.1 */
1008     public Collection<V> values() {
1009     Collection<V> vs = values;
1010 dl 1.8 return (vs != null) ? vs : (values = new Values());
1011 tim 1.1 }
1012    
1013     /**
1014 jsr166 1.68 * Returns a {@link Set} view of the mappings contained in this map.
1015     * The set is backed by the map, so changes to the map are
1016     * reflected in the set, and vice-versa. The set supports element
1017     * removal, which removes the corresponding mapping from the map,
1018     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1019     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1020     * operations. It does not support the <tt>add</tt> or
1021     * <tt>addAll</tt> operations.
1022     *
1023     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1024     * that will never throw {@link ConcurrentModificationException},
1025 dl 1.14 * and guarantees to traverse elements as they existed upon
1026     * construction of the iterator, and may (but is not guaranteed to)
1027     * reflect any modifications subsequent to construction.
1028 tim 1.1 */
1029     public Set<Map.Entry<K,V>> entrySet() {
1030     Set<Map.Entry<K,V>> es = entrySet;
1031 jsr166 1.65 return (es != null) ? es : (entrySet = new EntrySet());
1032 tim 1.1 }
1033    
1034     /**
1035     * Returns an enumeration of the keys in this table.
1036     *
1037 jsr166 1.70 * @return an enumeration of the keys in this table
1038 jsr166 1.94 * @see #keySet()
1039 tim 1.1 */
1040 dl 1.4 public Enumeration<K> keys() {
1041 tim 1.1 return new KeyIterator();
1042     }
1043    
1044     /**
1045     * Returns an enumeration of the values in this table.
1046     *
1047 jsr166 1.70 * @return an enumeration of the values in this table
1048 jsr166 1.94 * @see #values()
1049 tim 1.1 */
1050 dl 1.4 public Enumeration<V> elements() {
1051 tim 1.1 return new ValueIterator();
1052     }
1053    
1054 dl 1.4 /* ---------------- Iterator Support -------------- */
1055 tim 1.11
1056 jsr166 1.82 abstract class HashIterator {
1057 dl 1.41 int nextSegmentIndex;
1058     int nextTableIndex;
1059 dl 1.71 HashEntry<K,V>[] currentTable;
1060 dl 1.41 HashEntry<K, V> nextEntry;
1061 dl 1.30 HashEntry<K, V> lastReturned;
1062 tim 1.1
1063 dl 1.41 HashIterator() {
1064 dl 1.8 nextSegmentIndex = segments.length - 1;
1065 dl 1.4 nextTableIndex = -1;
1066     advance();
1067 tim 1.1 }
1068    
1069     public boolean hasMoreElements() { return hasNext(); }
1070    
1071 dl 1.41 final void advance() {
1072 dl 1.4 if (nextEntry != null && (nextEntry = nextEntry.next) != null)
1073     return;
1074 tim 1.11
1075 dl 1.4 while (nextTableIndex >= 0) {
1076 dl 1.71 if ( (nextEntry = currentTable[nextTableIndex--]) != null)
1077 dl 1.4 return;
1078     }
1079 tim 1.11
1080 dl 1.4 while (nextSegmentIndex >= 0) {
1081 dl 1.71 Segment<K,V> seg = segments[nextSegmentIndex--];
1082 dl 1.4 if (seg.count != 0) {
1083     currentTable = seg.table;
1084 dl 1.8 for (int j = currentTable.length - 1; j >= 0; --j) {
1085 dl 1.71 if ( (nextEntry = currentTable[j]) != null) {
1086 dl 1.8 nextTableIndex = j - 1;
1087 dl 1.4 return;
1088     }
1089 tim 1.1 }
1090     }
1091     }
1092     }
1093    
1094 dl 1.4 public boolean hasNext() { return nextEntry != null; }
1095 tim 1.1
1096 dl 1.4 HashEntry<K,V> nextEntry() {
1097     if (nextEntry == null)
1098 tim 1.1 throw new NoSuchElementException();
1099 dl 1.4 lastReturned = nextEntry;
1100     advance();
1101     return lastReturned;
1102 tim 1.1 }
1103    
1104     public void remove() {
1105     if (lastReturned == null)
1106     throw new IllegalStateException();
1107     ConcurrentHashMap.this.remove(lastReturned.key);
1108     lastReturned = null;
1109     }
1110 dl 1.4 }
1111    
1112 jsr166 1.82 final class KeyIterator
1113 jsr166 1.96 extends HashIterator
1114     implements Iterator<K>, Enumeration<K>
1115 jsr166 1.82 {
1116     public K next() { return super.nextEntry().key; }
1117 dl 1.4 public K nextElement() { return super.nextEntry().key; }
1118     }
1119    
1120 jsr166 1.82 final class ValueIterator
1121 jsr166 1.96 extends HashIterator
1122     implements Iterator<V>, Enumeration<V>
1123 jsr166 1.82 {
1124     public V next() { return super.nextEntry().value; }
1125 dl 1.4 public V nextElement() { return super.nextEntry().value; }
1126     }
1127 tim 1.1
1128 dl 1.30 /**
1129 dl 1.79 * Custom Entry class used by EntryIterator.next(), that relays
1130     * setValue changes to the underlying map.
1131 jsr166 1.80 */
1132 jsr166 1.83 final class WriteThroughEntry
1133 jsr166 1.96 extends AbstractMap.SimpleEntry<K,V>
1134 jsr166 1.81 {
1135 jsr166 1.83 WriteThroughEntry(K k, V v) {
1136 jsr166 1.80 super(k,v);
1137 dl 1.79 }
1138    
1139     /**
1140     * Set our entry's value and write through to the map. The
1141     * value to return is somewhat arbitrary here. Since a
1142     * WriteThroughEntry does not necessarily track asynchronous
1143     * changes, the most recent "previous" value could be
1144 jsr166 1.81 * different from what we return (or could even have been
1145 dl 1.79 * removed in which case the put will re-establish). We do not
1146     * and cannot guarantee more.
1147     */
1148 jsr166 1.96 public V setValue(V value) {
1149 dl 1.79 if (value == null) throw new NullPointerException();
1150     V v = super.setValue(value);
1151 jsr166 1.83 ConcurrentHashMap.this.put(getKey(), value);
1152 dl 1.79 return v;
1153 dl 1.30 }
1154 dl 1.79 }
1155 dl 1.30
1156 jsr166 1.82 final class EntryIterator
1157 jsr166 1.96 extends HashIterator
1158     implements Iterator<Entry<K,V>>
1159 jsr166 1.82 {
1160 dl 1.79 public Map.Entry<K,V> next() {
1161     HashEntry<K,V> e = super.nextEntry();
1162 jsr166 1.83 return new WriteThroughEntry(e.key, e.value);
1163 dl 1.30 }
1164 tim 1.1 }
1165    
1166 dl 1.41 final class KeySet extends AbstractSet<K> {
1167 dl 1.4 public Iterator<K> iterator() {
1168     return new KeyIterator();
1169     }
1170     public int size() {
1171     return ConcurrentHashMap.this.size();
1172     }
1173 jsr166 1.95 public boolean isEmpty() {
1174     return ConcurrentHashMap.this.isEmpty();
1175     }
1176 dl 1.4 public boolean contains(Object o) {
1177     return ConcurrentHashMap.this.containsKey(o);
1178     }
1179     public boolean remove(Object o) {
1180     return ConcurrentHashMap.this.remove(o) != null;
1181     }
1182     public void clear() {
1183     ConcurrentHashMap.this.clear();
1184     }
1185 tim 1.1 }
1186    
1187 dl 1.41 final class Values extends AbstractCollection<V> {
1188 dl 1.4 public Iterator<V> iterator() {
1189     return new ValueIterator();
1190     }
1191     public int size() {
1192     return ConcurrentHashMap.this.size();
1193     }
1194 jsr166 1.95 public boolean isEmpty() {
1195     return ConcurrentHashMap.this.isEmpty();
1196     }
1197 dl 1.4 public boolean contains(Object o) {
1198     return ConcurrentHashMap.this.containsValue(o);
1199     }
1200     public void clear() {
1201     ConcurrentHashMap.this.clear();
1202     }
1203 tim 1.1 }
1204    
1205 dl 1.41 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1206 dl 1.4 public Iterator<Map.Entry<K,V>> iterator() {
1207     return new EntryIterator();
1208     }
1209     public boolean contains(Object o) {
1210     if (!(o instanceof Map.Entry))
1211     return false;
1212 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1213 dl 1.4 V v = ConcurrentHashMap.this.get(e.getKey());
1214     return v != null && v.equals(e.getValue());
1215     }
1216     public boolean remove(Object o) {
1217     if (!(o instanceof Map.Entry))
1218     return false;
1219 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1220 dl 1.13 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1221 dl 1.4 }
1222     public int size() {
1223     return ConcurrentHashMap.this.size();
1224     }
1225 jsr166 1.95 public boolean isEmpty() {
1226     return ConcurrentHashMap.this.isEmpty();
1227     }
1228 dl 1.4 public void clear() {
1229     ConcurrentHashMap.this.clear();
1230 dl 1.30 }
1231     }
1232    
1233 dl 1.4 /* ---------------- Serialization Support -------------- */
1234    
1235 tim 1.1 /**
1236 jsr166 1.68 * Save the state of the <tt>ConcurrentHashMap</tt> instance to a
1237     * stream (i.e., serialize it).
1238 dl 1.8 * @param s the stream
1239 tim 1.1 * @serialData
1240     * the key (Object) and value (Object)
1241     * for each key-value mapping, followed by a null pair.
1242     * The key-value mappings are emitted in no particular order.
1243     */
1244     private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1245     s.defaultWriteObject();
1246    
1247     for (int k = 0; k < segments.length; ++k) {
1248 dl 1.71 Segment<K,V> seg = segments[k];
1249 dl 1.2 seg.lock();
1250     try {
1251 dl 1.71 HashEntry<K,V>[] tab = seg.table;
1252 dl 1.4 for (int i = 0; i < tab.length; ++i) {
1253 dl 1.71 for (HashEntry<K,V> e = tab[i]; e != null; e = e.next) {
1254 dl 1.4 s.writeObject(e.key);
1255     s.writeObject(e.value);
1256     }
1257     }
1258 tim 1.16 } finally {
1259 dl 1.2 seg.unlock();
1260     }
1261 tim 1.1 }
1262     s.writeObject(null);
1263     s.writeObject(null);
1264     }
1265    
1266     /**
1267 jsr166 1.68 * Reconstitute the <tt>ConcurrentHashMap</tt> instance from a
1268     * stream (i.e., deserialize it).
1269 dl 1.8 * @param s the stream
1270 tim 1.1 */
1271     private void readObject(java.io.ObjectInputStream s)
1272     throws IOException, ClassNotFoundException {
1273     s.defaultReadObject();
1274    
1275 dl 1.4 // Initialize each segment to be minimally sized, and let grow.
1276     for (int i = 0; i < segments.length; ++i) {
1277 dl 1.73 segments[i].setTable(new HashEntry[1]);
1278 dl 1.4 }
1279 tim 1.1
1280     // Read the keys and values, and put the mappings in the table
1281 dl 1.9 for (;;) {
1282 tim 1.1 K key = (K) s.readObject();
1283     V value = (V) s.readObject();
1284     if (key == null)
1285     break;
1286     put(key, value);
1287     }
1288     }
1289     }