ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.76
Committed: Mon Jun 20 18:05:45 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.75: +9 -14 lines
Log Message:
doc fixes

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