ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.44
Committed: Mon Feb 9 13:28:47 2004 UTC (20 years, 3 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_PFD
Changes since 1.43: +10 -8 lines
Log Message:
Wording fixes and improvements

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