ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.43
Committed: Sat Feb 7 13:03:59 2004 UTC (20 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.42: +8 -1 lines
Log Message:
Match iterator-as-entry behavior to changes in java.util versions

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