ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.36
Committed: Sat Dec 27 19:26:25 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.35: +2 -2 lines
Log Message:
Headers reference Creative Commons

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