ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.100
Committed: Wed Apr 13 13:23:56 2011 UTC (13 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.99: +2 -2 lines
Log Message:
Typos

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 dl 1.100 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 dl 1.10 import java.util.concurrent.locks.*;
9 tim 1.1 import java.util.*;
10     import java.io.Serializable;
11     import java.io.IOException;
12     import java.io.ObjectInputStream;
13     import java.io.ObjectOutputStream;
14    
15     /**
16 dl 1.4 * A hash table supporting full concurrency of retrievals and
17     * adjustable expected concurrency for updates. This class obeys the
18 dl 1.22 * same functional specification as {@link java.util.Hashtable}, and
19 dl 1.19 * includes versions of methods corresponding to each method of
20 dl 1.25 * <tt>Hashtable</tt>. However, even though all operations are
21 dl 1.19 * thread-safe, retrieval operations do <em>not</em> entail locking,
22     * and there is <em>not</em> any support for locking the entire table
23     * in a way that prevents all access. This class is fully
24     * interoperable with <tt>Hashtable</tt> in programs that rely on its
25 dl 1.4 * thread safety but not on its synchronization details.
26 tim 1.11 *
27 dl 1.25 * <p> Retrieval operations (including <tt>get</tt>) generally do not
28     * block, so may overlap with update operations (including
29     * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
30     * of the most recently <em>completed</em> update operations holding
31     * upon their onset. For aggregate operations such as <tt>putAll</tt>
32     * and <tt>clear</tt>, concurrent retrievals may reflect insertion or
33 dl 1.4 * removal of only some entries. Similarly, Iterators and
34     * Enumerations return elements reflecting the state of the hash table
35     * at some point at or since the creation of the iterator/enumeration.
36 jsr166 1.68 * They do <em>not</em> throw {@link ConcurrentModificationException}.
37     * However, iterators are designed to be used by only one thread at a time.
38 tim 1.1 *
39 dl 1.19 * <p> The allowed concurrency among update operations is guided by
40     * the optional <tt>concurrencyLevel</tt> constructor argument
41 dl 1.57 * (default <tt>16</tt>), which is used as a hint for internal sizing. The
42 dl 1.21 * table is internally partitioned to try to permit the indicated
43     * number of concurrent updates without contention. Because placement
44     * in hash tables is essentially random, the actual concurrency will
45     * vary. Ideally, you should choose a value to accommodate as many
46 dl 1.25 * threads as will ever concurrently modify the table. Using a
47 dl 1.21 * significantly higher value than you need can waste space and time,
48     * and a significantly lower value can lead to thread contention. But
49     * overestimates and underestimates within an order of magnitude do
50 dl 1.25 * not usually have much noticeable impact. A value of one is
51 dl 1.45 * appropriate when it is known that only one thread will modify and
52     * all others will only read. Also, resizing this or any other kind of
53     * hash table is a relatively slow operation, so, when possible, it is
54     * a good idea to provide estimates of expected table sizes in
55     * constructors.
56 tim 1.1 *
57 dl 1.45 * <p>This class and its views and iterators implement all of the
58     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
59     * interfaces.
60 dl 1.23 *
61 jsr166 1.68 * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
62     * does <em>not</em> allow <tt>null</tt> to be used as a key or value.
63 tim 1.1 *
64 dl 1.42 * <p>This class is a member of the
65 jsr166 1.88 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
66 dl 1.42 * Java Collections Framework</a>.
67     *
68 dl 1.8 * @since 1.5
69     * @author Doug Lea
70 dl 1.27 * @param <K> the type of keys maintained by this map
71 jsr166 1.64 * @param <V> the type of mapped values
72 dl 1.8 */
73 tim 1.1 public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
74 dl 1.48 implements ConcurrentMap<K, V>, Serializable {
75 dl 1.20 private static final long serialVersionUID = 7249069246763182397L;
76 tim 1.1
77     /*
78 dl 1.4 * The basic strategy is to subdivide the table among Segments,
79 dl 1.99 * each of which itself is a concurrently readable hash table. To
80     * reduce footprint, all but one segments are constructed only
81     * when first needed (see ensureSegment). To maintain visibility
82     * in the presence of lazy construction, accesses to segments as
83     * well as elements of segment's table must use volatile access,
84     * which is done via Unsafe within methods segmentAt etc
85     * below. These provide the functionality of AtomicReferenceArrays
86     * but reduce the levels of indirection. Additionally,
87     * volatile-writes of table elements and entry "next" fields
88     * within locked operations use the cheaper "lazySet" forms of
89 dl 1.100 * writes (via putOrderedObject) because these writes are always
90 dl 1.99 * followed by lock releases that maintain sequential consistency
91     * of table updates.
92     *
93     * Historical note: The previous version of this class relied
94     * heavily on "final" fields, which avoided some volatile reads at
95     * the expense of a large initial footprint. Some remnants of
96     * that design (including forced construction of segment 0) exist
97     * to ensure serialization compatibility.
98 dl 1.4 */
99 tim 1.1
100 dl 1.4 /* ---------------- Constants -------------- */
101 tim 1.11
102 dl 1.4 /**
103 dl 1.56 * The default initial capacity for this table,
104     * used when not otherwise specified in a constructor.
105 dl 1.4 */
106 dl 1.57 static final int DEFAULT_INITIAL_CAPACITY = 16;
107 dl 1.56
108     /**
109     * The default load factor for this table, used when not
110     * otherwise specified in a constructor.
111     */
112 dl 1.57 static final float DEFAULT_LOAD_FACTOR = 0.75f;
113 dl 1.56
114     /**
115     * The default concurrency level for this table, used when not
116     * otherwise specified in a constructor.
117 jsr166 1.59 */
118 dl 1.57 static final int DEFAULT_CONCURRENCY_LEVEL = 16;
119 tim 1.1
120     /**
121 dl 1.4 * The maximum capacity, used if a higher value is implicitly
122     * specified by either of the constructors with arguments. MUST
123 jsr166 1.68 * be a power of two <= 1<<30 to ensure that entries are indexable
124 dl 1.21 * using ints.
125 dl 1.4 */
126 jsr166 1.64 static final int MAXIMUM_CAPACITY = 1 << 30;
127 tim 1.11
128 tim 1.1 /**
129 dl 1.99 * The minimum capacity for per-segment tables. Must be a power
130     * of two, at least two to avoid immediate resizing on next use
131     * after lazy construction.
132     */
133     static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
134    
135     /**
136 dl 1.37 * The maximum number of segments to allow; used to bound
137 dl 1.99 * constructor arguments. Must be power of two less than 1 << 24.
138 dl 1.21 */
139 dl 1.41 static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
140 dl 1.21
141 dl 1.46 /**
142     * Number of unsynchronized retries in size and containsValue
143     * methods before resorting to locking. This is used to avoid
144     * unbounded retries if tables undergo continuous modification
145     * which would make it impossible to obtain an accurate result.
146     */
147     static final int RETRIES_BEFORE_LOCK = 2;
148    
149 dl 1.4 /* ---------------- Fields -------------- */
150 tim 1.1
151     /**
152 dl 1.9 * Mask value for indexing into segments. The upper bits of a
153     * key's hash code are used to choose the segment.
154 jsr166 1.59 */
155 dl 1.41 final int segmentMask;
156 tim 1.1
157     /**
158 dl 1.4 * Shift value for indexing within segments.
159 jsr166 1.59 */
160 dl 1.41 final int segmentShift;
161 tim 1.1
162     /**
163 dl 1.99 * The segments, each of which is a specialized hash table.
164 tim 1.1 */
165 dl 1.71 final Segment<K,V>[] segments;
166 dl 1.4
167 dl 1.41 transient Set<K> keySet;
168     transient Set<Map.Entry<K,V>> entrySet;
169     transient Collection<V> values;
170 dl 1.4
171 dl 1.99 /**
172     * ConcurrentHashMap list entry. Note that this is never exported
173     * out as a user-visible Map.Entry.
174     */
175     static final class HashEntry<K,V> {
176     final int hash;
177     final K key;
178     volatile V value;
179     volatile HashEntry<K,V> next;
180    
181     HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
182     this.hash = hash;
183     this.key = key;
184     this.value = value;
185     this.next = next;
186     }
187    
188     /**
189     * Sets next field with volatile write semantics. (See above
190     * about use of putOrderedObject.)
191     */
192     final void setNext(HashEntry<K,V> n) {
193     UNSAFE.putOrderedObject(this, nextOffset, n);
194     }
195    
196     // Unsafe mechanics
197     static final sun.misc.Unsafe UNSAFE;
198     static final long nextOffset;
199     static {
200     try {
201     UNSAFE = sun.misc.Unsafe.getUnsafe();
202     Class k = HashEntry.class;
203     nextOffset = UNSAFE.objectFieldOffset
204     (k.getDeclaredField("next"));
205     } catch (Exception e) {
206     throw new Error(e);
207     }
208     }
209     }
210    
211     /**
212     * Gets the ith element of given table (if nonnull) with volatile
213     * read semantics.
214     */
215     @SuppressWarnings("unchecked")
216     static final <K,V> HashEntry<K,V> entryAt(HashEntry<K,V>[] tab, int i) {
217     return tab == null? null :
218     (HashEntry<K,V>) UNSAFE.getObjectVolatile
219     (tab, ((long)i << TSHIFT) + TBASE);
220     }
221    
222     /**
223     * Sets the ith element of given table, with volatile write
224     * semantics. (See above about use of putOrderedObject.)
225     */
226     static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
227     HashEntry<K,V> e) {
228     UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
229     }
230 tim 1.1
231     /**
232 dl 1.89 * Applies a supplemental hash function to a given hashCode, which
233     * defends against poor quality hash functions. This is critical
234 jsr166 1.90 * because ConcurrentHashMap uses power-of-two length hash tables,
235     * that otherwise encounter collisions for hashCodes that do not
236 dl 1.93 * differ in lower or upper bits.
237 dl 1.89 */
238 jsr166 1.90 private static int hash(int h) {
239 dl 1.92 // Spread bits to regularize both segment and index locations,
240 dl 1.93 // using variant of single-word Wang/Jenkins hash.
241     h += (h << 15) ^ 0xffffcd7d;
242     h ^= (h >>> 10);
243     h += (h << 3);
244     h ^= (h >>> 6);
245     h += (h << 2) + (h << 14);
246     return h ^ (h >>> 16);
247 dl 1.4 }
248    
249 tim 1.1 /**
250 dl 1.6 * Segments are specialized versions of hash tables. This
251 dl 1.4 * subclasses from ReentrantLock opportunistically, just to
252     * simplify some locking and avoid separate construction.
253 jsr166 1.59 */
254 dl 1.41 static final class Segment<K,V> extends ReentrantLock implements Serializable {
255 dl 1.4 /*
256 dl 1.99 * Segments maintain a table of entry lists that are always
257     * kept in a consistent state, so can be read (via volatile
258     * reads of segments and tables) without locking. This
259     * requires replicating nodes when necessary during table
260     * resizing, so the old lists can be traversed by readers
261     * still using old version of table.
262 dl 1.4 *
263 dl 1.99 * This class defines only mutative methods requiring locking.
264     * Except as noted, the methods of this class perform the
265     * per-segment versions of ConcurrentHashMap methods. (Other
266     * methods are integrated directly into ConcurrentHashMap
267     * methods.) These mutative methods use a form of controlled
268     * spinning on contention via methods scanAndLock and
269     * scanAndLockForPut. These intersperse tryLocks with
270     * traversals to locate nodes. The main benefit is to absorb
271     * cache misses (which are very common for hash tables) while
272     * obtaining locks so that traversal is faster once
273     * acquired. We do not actually use the found nodes since they
274     * must be re-acquired under lock anyway to ensure sequential
275     * consistency of updates (and in any case may be undetectably
276     * stale), but they will normally be much faster to re-locate.
277     * Also, scanAndLockForPut speculatively creates a fresh node
278     * to use in put if no node is found.
279 dl 1.4 */
280 tim 1.11
281 dl 1.24 private static final long serialVersionUID = 2249069246763182397L;
282    
283 dl 1.4 /**
284 dl 1.99 * The maximum number of times to tryLock in a prescan before
285     * possibly blocking on acquire in preparation for a locked
286     * segment operation. On multiprocessors, using a bounded
287     * number of retries maintains cache acquired while locating
288     * nodes.
289 jsr166 1.59 */
290 dl 1.99 static final int MAX_SCAN_RETRIES =
291     Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
292 dl 1.4
293     /**
294 dl 1.99 * The per-segment table. Elements are accessed via
295     * entryAt/setEntryAt providing volatile semantics.
296     */
297     transient volatile HashEntry<K,V>[] table;
298    
299     /**
300     * The number of elements. Accessed only either within locks
301     * or among other volatile reads that maintain visibility.
302     */
303     transient int count;
304    
305     /**
306     * The total number of insertions and removals in this
307     * segment. Even though this may overflows 32 bits, it
308     * provides sufficient accuracy for stability checks in CHM
309     * isEmpty() and size() methods. Accessed only either within
310     * locks or among other volatile reads that maintain
311     * visibility.
312 dl 1.21 */
313     transient int modCount;
314    
315     /**
316 dl 1.4 * The table is rehashed when its size exceeds this threshold.
317 jsr166 1.68 * (The value of this field is always <tt>(int)(capacity *
318     * loadFactor)</tt>.)
319 dl 1.4 */
320 dl 1.41 transient int threshold;
321 dl 1.4
322     /**
323     * The load factor for the hash table. Even though this value
324     * is same for all segments, it is replicated to avoid needing
325     * links to outer object.
326     * @serial
327     */
328 dl 1.41 final float loadFactor;
329 tim 1.1
330 dl 1.99 Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
331     this.loadFactor = lf;
332     this.threshold = threshold;
333     this.table = tab;
334 dl 1.4 }
335 tim 1.1
336 dl 1.99 final V put(K key, int hash, V value, boolean onlyIfAbsent) {
337     HashEntry<K,V> node = tryLock() ? null :
338     scanAndLockForPut(key, hash, value);
339     V oldValue;
340 dl 1.45 try {
341 dl 1.99 HashEntry<K,V>[] tab = table;
342     int index = (tab.length - 1) & hash;
343     HashEntry<K,V> first = entryAt(tab, index);
344     for (HashEntry<K,V> e = first;;) {
345     if (e != null) {
346     K k;
347     if ((k = e.key) == key ||
348     (e.hash == hash && key.equals(k))) {
349     oldValue = e.value;
350     if (!onlyIfAbsent)
351     e.value = value;
352     break;
353     }
354     e = e.next;
355 dl 1.45 }
356 dl 1.99 else {
357     if (node != null)
358     node.setNext(first);
359     else
360     node = new HashEntry<K,V>(hash, key, value, first);
361     int c = count + 1;
362     if (c > threshold && first != null &&
363     tab.length < MAXIMUM_CAPACITY)
364     rehash(node);
365     else
366     setEntryAt(tab, index, node);
367     ++modCount;
368     count = c;
369     oldValue = null;
370     break;
371 dl 1.45 }
372     }
373 dl 1.33 } finally {
374     unlock();
375     }
376 dl 1.99 return oldValue;
377 dl 1.33 }
378    
379 dl 1.99 /**
380     * Doubles size of table and repacks entries, also adding the
381     * given node to new table
382     */
383     @SuppressWarnings("unchecked")
384     private void rehash(HashEntry<K,V> node) {
385     /*
386     * Reclassify nodes in each list to new table. Because we
387     * are using power-of-two expansion, the elements from
388     * each bin must either stay at same index, or move with a
389     * power of two offset. We eliminate unnecessary node
390     * creation by catching cases where old nodes can be
391     * reused because their next fields won't change.
392     * Statistically, at the default threshold, only about
393     * one-sixth of them need cloning when a table
394     * doubles. The nodes they replace will be garbage
395     * collectable as soon as they are no longer referenced by
396     * any reader thread that may be in the midst of
397     * concurrently traversing table. Entry accesses use plain
398     * array indexing because they are followed by volatile
399     * table write.
400     */
401 dl 1.71 HashEntry<K,V>[] oldTable = table;
402 dl 1.4 int oldCapacity = oldTable.length;
403 dl 1.99 int newCapacity = oldCapacity << 1;
404     threshold = (int)(newCapacity * loadFactor);
405     HashEntry<K,V>[] newTable =
406     (HashEntry<K,V>[]) new HashEntry[newCapacity];
407     int sizeMask = newCapacity - 1;
408 dl 1.4 for (int i = 0; i < oldCapacity ; i++) {
409 dl 1.71 HashEntry<K,V> e = oldTable[i];
410 dl 1.4 if (e != null) {
411     HashEntry<K,V> next = e.next;
412     int idx = e.hash & sizeMask;
413 dl 1.99 if (next == null) // Single node on list
414 dl 1.4 newTable[idx] = e;
415 dl 1.99 else { // Reuse consecutive sequence at same slot
416 dl 1.4 HashEntry<K,V> lastRun = e;
417     int lastIdx = idx;
418 tim 1.11 for (HashEntry<K,V> last = next;
419     last != null;
420 dl 1.4 last = last.next) {
421     int k = last.hash & sizeMask;
422     if (k != lastIdx) {
423     lastIdx = k;
424     lastRun = last;
425     }
426     }
427     newTable[lastIdx] = lastRun;
428 dl 1.99 // Clone remaining nodes
429 dl 1.4 for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
430 dl 1.99 V v = p.value;
431     int h = p.hash;
432     int k = h & sizeMask;
433 dl 1.71 HashEntry<K,V> n = newTable[k];
434 dl 1.99 newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
435 dl 1.4 }
436     }
437     }
438     }
439 dl 1.99 int nodeIndex = node.hash & sizeMask; // add the new node
440     node.setNext(newTable[nodeIndex]);
441     newTable[nodeIndex] = node;
442 dl 1.45 table = newTable;
443 dl 1.4 }
444 dl 1.6
445     /**
446 dl 1.99 * Scans for a node containing given key while trying to
447     * acquire lock, creating and returning one if not found. Upon
448     * return, guarantees that lock is held.
449     *
450     * @return a new node if key not found, else null
451     */
452     private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
453     HashEntry<K,V> first = entryForHash(this, hash);
454     HashEntry<K,V> e = first;
455     HashEntry<K,V> node = null;
456     int retries = -1; // negative while locating node
457     while (!tryLock()) {
458     HashEntry<K,V> f; // to recheck first below
459     if (retries < 0) {
460     if (e == null) {
461     if (node == null) // speculatively create node
462     node = new HashEntry<K,V>(hash, key, value, null);
463     retries = 0;
464     }
465     else if (key.equals(e.key))
466     retries = 0;
467     else
468     e = e.next;
469     }
470     else if (++retries > MAX_SCAN_RETRIES) {
471     lock();
472     break;
473     }
474     else if ((retries & 1) == 0 &&
475     (f = entryForHash(this, hash)) != first) {
476     e = first = f; // re-traverse if entry changed
477     retries = -1;
478     }
479     }
480     return node;
481     }
482    
483     /**
484     * Scans for a node containing the given key while trying to
485     * acquire lock for a remove or replace operation. Upon
486     * return, guarantees that lock is held. Note that we must
487     * lock even if the key is not found, to ensure sequential
488     * consistency of updates.
489     */
490     private void scanAndLock(Object key, int hash) {
491     // similar to but simpler than scanAndLockForPut
492     HashEntry<K,V> first = entryForHash(this, hash);
493     HashEntry<K,V> e = first;
494     int retries = -1;
495     while (!tryLock()) {
496     HashEntry<K,V> f;
497     if (retries < 0) {
498     if (e == null || key.equals(e.key))
499     retries = 0;
500     else
501     e = e.next;
502     }
503     else if (++retries > MAX_SCAN_RETRIES) {
504     lock();
505     break;
506     }
507     else if ((retries & 1) == 0 &&
508     (f = entryForHash(this, hash)) != first) {
509     e = first = f;
510     retries = -1;
511     }
512     }
513     }
514    
515     /**
516 dl 1.6 * Remove; match on key only if value null, else match both.
517     */
518 dl 1.99 final V remove(Object key, int hash, Object value) {
519     if (!tryLock())
520     scanAndLock(key, hash);
521     V oldValue = null;
522 dl 1.4 try {
523 dl 1.71 HashEntry<K,V>[] tab = table;
524 dl 1.99 int index = (tab.length - 1) & hash;
525     HashEntry<K,V> e = entryAt(tab, index);
526     HashEntry<K,V> pred = null;
527     while (e != null) {
528     K k;
529     HashEntry<K,V> next = e.next;
530     if ((k = e.key) == key ||
531     (e.hash == hash && key.equals(k))) {
532     V v = e.value;
533     if (value == null || value == v || value.equals(v)) {
534     if (pred == null)
535     setEntryAt(tab, index, next);
536     else
537     pred.setNext(next);
538     ++modCount;
539     --count;
540     oldValue = v;
541     }
542     break;
543     }
544     pred = e;
545     e = next;
546     }
547     } finally {
548     unlock();
549     }
550     return oldValue;
551     }
552    
553     final boolean replace(K key, int hash, V oldValue, V newValue) {
554     if (!tryLock())
555     scanAndLock(key, hash);
556     boolean replaced = false;
557     try {
558     HashEntry<K,V> e;
559     for (e = entryForHash(this, hash); e != null; e = e.next) {
560     K k;
561     if ((k = e.key) == key ||
562     (e.hash == hash && key.equals(k))) {
563     if (oldValue.equals(e.value)) {
564     e.value = newValue;
565     replaced = true;
566     }
567     break;
568     }
569     }
570     } finally {
571     unlock();
572     }
573     return replaced;
574     }
575 dl 1.45
576 dl 1.99 final V replace(K key, int hash, V value) {
577     if (!tryLock())
578     scanAndLock(key, hash);
579     V oldValue = null;
580     try {
581     HashEntry<K,V> e;
582     for (e = entryForHash(this, hash); e != null; e = e.next) {
583     K k;
584     if ((k = e.key) == key ||
585     (e.hash == hash && key.equals(k))) {
586     oldValue = e.value;
587     e.value = value;
588     break;
589 dl 1.45 }
590 dl 1.4 }
591 dl 1.99 } finally {
592     unlock();
593     }
594     return oldValue;
595     }
596    
597     final void clear() {
598     lock();
599     try {
600     HashEntry<K,V>[] tab = table;
601     for (int i = 0; i < tab.length ; i++)
602     setEntryAt(tab, i, null);
603     ++modCount;
604     count = 0;
605 tim 1.16 } finally {
606 dl 1.4 unlock();
607     }
608     }
609 dl 1.99 }
610    
611     // Accessing segments
612 dl 1.4
613 dl 1.99 /**
614     * Gets the jth element of given segment array (if nonnull) with
615     * volatile element access semantics via Unsafe.
616     */
617     @SuppressWarnings("unchecked")
618     static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
619     long u = (j << SSHIFT) + SBASE;
620     return ss == null ? null :
621     (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
622     }
623    
624     /**
625     * Returns the segment for the given index, creating it and
626     * recording in segment table (via CAS) if not already present.
627     *
628     * @param k the index
629     * @return the segment
630     */
631     @SuppressWarnings("unchecked")
632     private Segment<K,V> ensureSegment(int k) {
633     final Segment<K,V>[] ss = this.segments;
634     long u = (k << SSHIFT) + SBASE; // raw offset
635     Segment<K,V> seg;
636     if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
637     Segment<K,V> proto = ss[0]; // use segment 0 as prototype
638     int cap = proto.table.length;
639     float lf = proto.loadFactor;
640     int threshold = (int)(cap * lf);
641     HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
642     if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
643     == null) { // recheck
644     Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
645     while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
646     == null) {
647     if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
648     break;
649 dl 1.45 }
650 dl 1.4 }
651     }
652 dl 1.99 return seg;
653 tim 1.1 }
654    
655 dl 1.99 // Hash-based segment and entry accesses
656 tim 1.1
657 dl 1.99 /**
658     * Get the segment for the given hash
659     */
660     @SuppressWarnings("unchecked")
661     private Segment<K,V> segmentForHash(int h) {
662     long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
663     return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
664     }
665    
666     /**
667     * Gets the table entry for the given segment and hash
668     */
669     @SuppressWarnings("unchecked")
670     static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
671     HashEntry<K,V>[] tab;
672     return seg == null || (tab = seg.table) == null? null :
673     (HashEntry<K,V>) UNSAFE.getObjectVolatile
674     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
675     }
676 tim 1.11
677 dl 1.4 /* ---------------- Public operations -------------- */
678 tim 1.1
679     /**
680 dl 1.44 * Creates a new, empty map with the specified initial
681 dl 1.56 * capacity, load factor and concurrency level.
682 tim 1.1 *
683 dl 1.19 * @param initialCapacity the initial capacity. The implementation
684     * performs internal sizing to accommodate this many elements.
685 tim 1.1 * @param loadFactor the load factor threshold, used to control resizing.
686 dl 1.56 * Resizing may be performed when the average number of elements per
687     * bin exceeds this threshold.
688 dl 1.19 * @param concurrencyLevel the estimated number of concurrently
689     * updating threads. The implementation performs internal sizing
690 jsr166 1.64 * to try to accommodate this many threads.
691 dl 1.4 * @throws IllegalArgumentException if the initial capacity is
692 dl 1.19 * negative or the load factor or concurrencyLevel are
693 dl 1.4 * nonpositive.
694     */
695 dl 1.99 @SuppressWarnings("unchecked")
696 tim 1.11 public ConcurrentHashMap(int initialCapacity,
697 dl 1.19 float loadFactor, int concurrencyLevel) {
698     if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
699 dl 1.4 throw new IllegalArgumentException();
700 dl 1.21 if (concurrencyLevel > MAX_SEGMENTS)
701     concurrencyLevel = MAX_SEGMENTS;
702 dl 1.4 // Find power-of-two sizes best matching arguments
703     int sshift = 0;
704     int ssize = 1;
705 dl 1.19 while (ssize < concurrencyLevel) {
706 dl 1.4 ++sshift;
707     ssize <<= 1;
708     }
709 dl 1.99 this.segmentShift = 32 - sshift;
710     this.segmentMask = ssize - 1;
711 dl 1.4 if (initialCapacity > MAXIMUM_CAPACITY)
712     initialCapacity = MAXIMUM_CAPACITY;
713     int c = initialCapacity / ssize;
714 tim 1.11 if (c * ssize < initialCapacity)
715 dl 1.4 ++c;
716 dl 1.99 int cap = MIN_SEGMENT_TABLE_CAPACITY;
717 dl 1.4 while (cap < c)
718     cap <<= 1;
719 dl 1.99 // create segments and segments[0]
720     Segment<K,V> s0 =
721     new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
722     (HashEntry<K,V>[])new HashEntry[cap]);
723     Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
724     UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
725     this.segments = ss;
726 tim 1.1 }
727    
728     /**
729 dl 1.55 * Creates a new, empty map with the specified initial capacity
730 jsr166 1.76 * and load factor and with the default concurrencyLevel (16).
731 dl 1.55 *
732     * @param initialCapacity The implementation performs internal
733     * sizing to accommodate this many elements.
734     * @param loadFactor the load factor threshold, used to control resizing.
735 jsr166 1.68 * Resizing may be performed when the average number of elements per
736     * bin exceeds this threshold.
737 dl 1.55 * @throws IllegalArgumentException if the initial capacity of
738     * elements is negative or the load factor is nonpositive
739 jsr166 1.78 *
740     * @since 1.6
741 dl 1.55 */
742     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
743 dl 1.56 this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
744 dl 1.55 }
745    
746     /**
747 dl 1.56 * Creates a new, empty map with the specified initial capacity,
748 jsr166 1.76 * and with default load factor (0.75) and concurrencyLevel (16).
749 tim 1.1 *
750 dl 1.58 * @param initialCapacity the initial capacity. The implementation
751     * performs internal sizing to accommodate this many elements.
752 dl 1.4 * @throws IllegalArgumentException if the initial capacity of
753     * elements is negative.
754 tim 1.1 */
755     public ConcurrentHashMap(int initialCapacity) {
756 dl 1.56 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
757 tim 1.1 }
758    
759     /**
760 jsr166 1.76 * Creates a new, empty map with a default initial capacity (16),
761     * load factor (0.75) and concurrencyLevel (16).
762 tim 1.1 */
763     public ConcurrentHashMap() {
764 dl 1.56 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
765 tim 1.1 }
766    
767     /**
768 jsr166 1.76 * Creates a new map with the same mappings as the given map.
769     * The map is created with a capacity of 1.5 times the number
770     * of mappings in the given map or 16 (whichever is greater),
771     * and a default load factor (0.75) and concurrencyLevel (16).
772     *
773 jsr166 1.68 * @param m the map
774 tim 1.1 */
775 jsr166 1.68 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
776     this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
777 dl 1.56 DEFAULT_INITIAL_CAPACITY),
778     DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
779 jsr166 1.68 putAll(m);
780 tim 1.1 }
781    
782 dl 1.56 /**
783     * Returns <tt>true</tt> if this map contains no key-value mappings.
784     *
785 jsr166 1.68 * @return <tt>true</tt> if this map contains no key-value mappings
786 dl 1.56 */
787 tim 1.1 public boolean isEmpty() {
788 dl 1.21 /*
789 dl 1.99 * Sum per-segment modCounts to avoid mis-reporting when
790     * elements are concurrently added and removed in one segment
791     * while checking another, in which case the table was never
792     * actually empty at any point. (The sum ensures accuracy up
793     * through at least 1<<31 per-segment modifications before
794     * recheck.) Methods size() and containsValue() use similar
795     * constructions for stability checks.
796 dl 1.21 */
797 dl 1.99 long sum = 0L;
798     final Segment<K,V>[] segments = this.segments;
799     for (int j = 0; j < segments.length; ++j) {
800     Segment<K,V> seg = segmentAt(segments, j);
801     if (seg != null) {
802     if (seg.count != 0)
803     return false;
804     sum += seg.modCount;
805     }
806 dl 1.21 }
807 dl 1.99 if (sum != 0L) { // recheck unless no modifications
808     for (int j = 0; j < segments.length; ++j) {
809     Segment<K,V> seg = segmentAt(segments, j);
810     if (seg != null) {
811     if (seg.count != 0)
812     return false;
813     sum -= seg.modCount;
814     }
815 dl 1.21 }
816 dl 1.99 if (sum != 0L)
817     return false;
818 dl 1.21 }
819 tim 1.1 return true;
820     }
821    
822 dl 1.56 /**
823     * Returns the number of key-value mappings in this map. If the
824     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
825     * <tt>Integer.MAX_VALUE</tt>.
826     *
827 jsr166 1.68 * @return the number of key-value mappings in this map
828 dl 1.56 */
829 dl 1.21 public int size() {
830 dl 1.46 // Try a few times to get accurate count. On failure due to
831 dl 1.45 // continuous async changes in table, resort to locking.
832 dl 1.99 final Segment<K,V>[] segments = this.segments;
833     int size;
834     boolean overflow; // true if size overflows 32 bits
835     long sum; // sum of modCounts
836     long last = 0L; // previous sum
837     int retries = -1; // first iteration isn't retry
838     try {
839     for (;;) {
840     if (retries++ == RETRIES_BEFORE_LOCK) {
841     for (int j = 0; j < segments.length; ++j)
842     ensureSegment(j).lock(); // force creation
843     }
844     sum = 0L;
845     size = 0;
846     overflow = false;
847     for (int j = 0; j < segments.length; ++j) {
848     Segment<K,V> seg = segmentAt(segments, j);
849     if (seg != null) {
850     sum += seg.modCount;
851     int c = seg.count;
852     if (c < 0 || (size += c) < 0)
853     overflow = true;
854 dl 1.21 }
855     }
856 dl 1.99 if (sum == last)
857     break;
858     last = sum;
859     }
860     } finally {
861     if (retries > RETRIES_BEFORE_LOCK) {
862     for (int j = 0; j < segments.length; ++j)
863     segmentAt(segments, j).unlock();
864 dl 1.21 }
865 dl 1.45 }
866 dl 1.99 return overflow ? Integer.MAX_VALUE : size;
867 dl 1.21 }
868    
869 tim 1.1 /**
870 jsr166 1.85 * Returns the value to which the specified key is mapped,
871     * or {@code null} if this map contains no mapping for the key.
872     *
873     * <p>More formally, if this map contains a mapping from a key
874     * {@code k} to a value {@code v} such that {@code key.equals(k)},
875     * then this method returns {@code v}; otherwise it returns
876     * {@code null}. (There can be at most one such mapping.)
877 tim 1.1 *
878 jsr166 1.68 * @throws NullPointerException if the specified key is null
879 tim 1.1 */
880 tim 1.11 public V get(Object key) {
881 dl 1.89 int hash = hash(key.hashCode());
882 dl 1.99 for (HashEntry<K,V> e = entryForHash(segmentForHash(hash), hash);
883     e != null; e = e.next) {
884     K k;
885     if ((k = e.key) == key || (e.hash == hash && key.equals(k)))
886     return e.value;
887     }
888     return null;
889 tim 1.1 }
890    
891     /**
892     * Tests if the specified object is a key in this table.
893 tim 1.11 *
894 jsr166 1.68 * @param key possible key
895     * @return <tt>true</tt> if and only if the specified object
896     * is a key in this table, as determined by the
897     * <tt>equals</tt> method; <tt>false</tt> otherwise.
898     * @throws NullPointerException if the specified key is null
899 tim 1.1 */
900     public boolean containsKey(Object key) {
901 jsr166 1.91 int hash = hash(key.hashCode());
902 dl 1.99 for (HashEntry<K,V> e = entryForHash(segmentForHash(hash), hash);
903     e != null; e = e.next) {
904     K k;
905     if ((k = e.key) == key || (e.hash == hash && key.equals(k)))
906     return true;
907     }
908     return false;
909 tim 1.1 }
910    
911     /**
912     * Returns <tt>true</tt> if this map maps one or more keys to the
913     * specified value. Note: This method requires a full internal
914     * traversal of the hash table, and so is much slower than
915     * method <tt>containsKey</tt>.
916     *
917 jsr166 1.68 * @param value value whose presence in this map is to be tested
918 tim 1.1 * @return <tt>true</tt> if this map maps one or more keys to the
919 jsr166 1.68 * specified value
920     * @throws NullPointerException if the specified value is null
921 tim 1.1 */
922     public boolean containsValue(Object value) {
923 dl 1.99 // Same idea as size() but using hashes as checksum
924 tim 1.11 if (value == null)
925 dl 1.4 throw new NullPointerException();
926 dl 1.71 final Segment<K,V>[] segments = this.segments;
927 dl 1.99 boolean found = false;
928     long last = 0L;
929     int retries = -1;
930     try {
931     outer: for (;;) {
932     if (retries++ == RETRIES_BEFORE_LOCK) {
933     for (int j = 0; j < segments.length; ++j)
934     ensureSegment(j).lock(); // force creation
935     }
936     long sum = 0L;
937     for (int j = 0; j < segments.length; ++j) {
938     HashEntry<K,V>[] tab;
939     Segment<K,V> seg = segmentAt(segments, j);
940     if (seg != null && (tab = seg.table) != null) {
941     for (int i = 0 ; i < tab.length; i++) {
942     HashEntry<K,V> e;
943     for (e = entryAt(tab, i); e != null; e = e.next) {
944     V v = e.value;
945     if (v != null && value.equals(v)) {
946     found = true;
947     break outer;
948     }
949     sum += e.hash;
950     }
951     }
952 dl 1.21 }
953     }
954 dl 1.99 if (sum == last)
955 dl 1.45 break;
956 dl 1.99 last = sum;
957 dl 1.45 }
958     } finally {
959 dl 1.99 if (retries > RETRIES_BEFORE_LOCK) {
960     for (int j = 0; j < segments.length; ++j)
961     segmentAt(segments, j).unlock();
962     }
963 dl 1.45 }
964     return found;
965 tim 1.1 }
966 dl 1.19
967 tim 1.1 /**
968 dl 1.18 * Legacy method testing if some key maps into the specified value
969 dl 1.23 * in this table. This method is identical in functionality to
970 jsr166 1.68 * {@link #containsValue}, and exists solely to ensure
971 dl 1.19 * full compatibility with class {@link java.util.Hashtable},
972 dl 1.18 * which supported this method prior to introduction of the
973 dl 1.23 * Java Collections framework.
974 dl 1.17
975 jsr166 1.68 * @param value a value to search for
976     * @return <tt>true</tt> if and only if some key maps to the
977     * <tt>value</tt> argument in this table as
978     * determined by the <tt>equals</tt> method;
979     * <tt>false</tt> otherwise
980     * @throws NullPointerException if the specified value is null
981 tim 1.1 */
982 dl 1.4 public boolean contains(Object value) {
983 tim 1.1 return containsValue(value);
984     }
985    
986     /**
987 jsr166 1.75 * Maps the specified key to the specified value in this table.
988     * Neither the key nor the value can be null.
989 dl 1.4 *
990 dl 1.44 * <p> The value can be retrieved by calling the <tt>get</tt> method
991 tim 1.11 * with a key that is equal to the original key.
992 dl 1.4 *
993 jsr166 1.68 * @param key key with which the specified value is to be associated
994     * @param value value to be associated with the specified key
995     * @return the previous value associated with <tt>key</tt>, or
996     * <tt>null</tt> if there was no mapping for <tt>key</tt>
997     * @throws NullPointerException if the specified key or value is null
998 dl 1.4 */
999 tim 1.11 public V put(K key, V value) {
1000 dl 1.99 Segment<K,V> s;
1001 tim 1.11 if (value == null)
1002 dl 1.4 throw new NullPointerException();
1003 dl 1.89 int hash = hash(key.hashCode());
1004 dl 1.99 int j = (hash >>> segmentShift) & segmentMask;
1005     return ((s = segmentAt(segments, j)) == null? ensureSegment(j) : s).
1006     put(key, hash, value, false);
1007 dl 1.4 }
1008    
1009     /**
1010 jsr166 1.68 * {@inheritDoc}
1011     *
1012     * @return the previous value associated with the specified key,
1013     * or <tt>null</tt> if there was no mapping for the key
1014     * @throws NullPointerException if the specified key or value is null
1015 dl 1.51 */
1016 tim 1.11 public V putIfAbsent(K key, V value) {
1017 dl 1.99 Segment<K,V> s;
1018 tim 1.11 if (value == null)
1019 dl 1.4 throw new NullPointerException();
1020 dl 1.89 int hash = hash(key.hashCode());
1021 dl 1.99 int j = (hash >>> segmentShift) & segmentMask;
1022     return ((s = segmentAt(segments, j)) == null? ensureSegment(j) : s).
1023     put(key, hash, value, true);
1024 dl 1.4 }
1025    
1026     /**
1027 tim 1.1 * Copies all of the mappings from the specified map to this one.
1028     * These mappings replace any mappings that this map had for any of the
1029 jsr166 1.68 * keys currently in the specified map.
1030 tim 1.1 *
1031 jsr166 1.68 * @param m mappings to be stored in this map
1032 tim 1.1 */
1033 jsr166 1.68 public void putAll(Map<? extends K, ? extends V> m) {
1034 jsr166 1.84 for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1035 dl 1.4 put(e.getKey(), e.getValue());
1036     }
1037    
1038     /**
1039 jsr166 1.68 * Removes the key (and its corresponding value) from this map.
1040     * This method does nothing if the key is not in the map.
1041 dl 1.4 *
1042 jsr166 1.68 * @param key the key that needs to be removed
1043     * @return the previous value associated with <tt>key</tt>, or
1044 jsr166 1.84 * <tt>null</tt> if there was no mapping for <tt>key</tt>
1045 jsr166 1.68 * @throws NullPointerException if the specified key is null
1046 dl 1.4 */
1047     public V remove(Object key) {
1048 jsr166 1.96 int hash = hash(key.hashCode());
1049 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1050     return s == null ? null : s.remove(key, hash, null);
1051 dl 1.4 }
1052 tim 1.1
1053 dl 1.4 /**
1054 jsr166 1.68 * {@inheritDoc}
1055     *
1056 jsr166 1.69 * @throws NullPointerException if the specified key is null
1057 dl 1.4 */
1058 dl 1.13 public boolean remove(Object key, Object value) {
1059 dl 1.89 int hash = hash(key.hashCode());
1060 dl 1.99 Segment<K,V> s;
1061     return value != null && (s = segmentForHash(hash)) != null &&
1062     s.remove(key, hash, value) != null;
1063 tim 1.1 }
1064 dl 1.31
1065     /**
1066 jsr166 1.68 * {@inheritDoc}
1067     *
1068     * @throws NullPointerException if any of the arguments are null
1069 dl 1.31 */
1070     public boolean replace(K key, V oldValue, V newValue) {
1071 dl 1.99 int hash = hash(key.hashCode());
1072 dl 1.31 if (oldValue == null || newValue == null)
1073     throw new NullPointerException();
1074 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1075     return s != null && s.replace(key, hash, oldValue, newValue);
1076 dl 1.32 }
1077    
1078     /**
1079 jsr166 1.68 * {@inheritDoc}
1080     *
1081     * @return the previous value associated with the specified key,
1082     * or <tt>null</tt> if there was no mapping for the key
1083     * @throws NullPointerException if the specified key or value is null
1084 dl 1.32 */
1085 dl 1.33 public V replace(K key, V value) {
1086 dl 1.99 int hash = hash(key.hashCode());
1087 dl 1.32 if (value == null)
1088     throw new NullPointerException();
1089 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1090     return s == null ? null : s.replace(key, hash, value);
1091 dl 1.31 }
1092    
1093 tim 1.1 /**
1094 jsr166 1.68 * Removes all of the mappings from this map.
1095 tim 1.1 */
1096     public void clear() {
1097 dl 1.99 final Segment<K,V>[] segments = this.segments;
1098     for (int j = 0; j < segments.length; ++j) {
1099     Segment<K,V> s = segmentAt(segments, j);
1100     if (s != null)
1101     s.clear();
1102     }
1103 tim 1.1 }
1104    
1105     /**
1106 jsr166 1.68 * Returns a {@link Set} view of the keys contained in this map.
1107     * The set is backed by the map, so changes to the map are
1108     * reflected in the set, and vice-versa. The set supports element
1109     * removal, which removes the corresponding mapping from this map,
1110     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1111     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1112     * operations. It does not support the <tt>add</tt> or
1113 tim 1.1 * <tt>addAll</tt> operations.
1114 jsr166 1.68 *
1115     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1116     * that will never throw {@link ConcurrentModificationException},
1117 dl 1.14 * and guarantees to traverse elements as they existed upon
1118     * construction of the iterator, and may (but is not guaranteed to)
1119     * reflect any modifications subsequent to construction.
1120 tim 1.1 */
1121     public Set<K> keySet() {
1122     Set<K> ks = keySet;
1123 dl 1.8 return (ks != null) ? ks : (keySet = new KeySet());
1124 tim 1.1 }
1125    
1126     /**
1127 jsr166 1.68 * Returns a {@link Collection} view of the values contained in this map.
1128     * The collection is backed by the map, so changes to the map are
1129     * reflected in the collection, and vice-versa. The collection
1130     * supports element removal, which removes the corresponding
1131     * mapping from this map, via the <tt>Iterator.remove</tt>,
1132     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1133     * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
1134     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1135     *
1136     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1137     * that will never throw {@link ConcurrentModificationException},
1138 dl 1.14 * and guarantees to traverse elements as they existed upon
1139     * construction of the iterator, and may (but is not guaranteed to)
1140     * reflect any modifications subsequent to construction.
1141 tim 1.1 */
1142     public Collection<V> values() {
1143     Collection<V> vs = values;
1144 dl 1.8 return (vs != null) ? vs : (values = new Values());
1145 tim 1.1 }
1146    
1147     /**
1148 jsr166 1.68 * Returns a {@link Set} view of the mappings contained in this map.
1149     * The set is backed by the map, so changes to the map are
1150     * reflected in the set, and vice-versa. The set supports element
1151     * removal, which removes the corresponding mapping from the map,
1152     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1153     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1154     * operations. It does not support the <tt>add</tt> or
1155     * <tt>addAll</tt> operations.
1156     *
1157     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1158     * that will never throw {@link ConcurrentModificationException},
1159 dl 1.14 * and guarantees to traverse elements as they existed upon
1160     * construction of the iterator, and may (but is not guaranteed to)
1161     * reflect any modifications subsequent to construction.
1162 tim 1.1 */
1163     public Set<Map.Entry<K,V>> entrySet() {
1164     Set<Map.Entry<K,V>> es = entrySet;
1165 jsr166 1.65 return (es != null) ? es : (entrySet = new EntrySet());
1166 tim 1.1 }
1167    
1168     /**
1169     * Returns an enumeration of the keys in this table.
1170     *
1171 jsr166 1.70 * @return an enumeration of the keys in this table
1172 jsr166 1.94 * @see #keySet()
1173 tim 1.1 */
1174 dl 1.4 public Enumeration<K> keys() {
1175 tim 1.1 return new KeyIterator();
1176     }
1177    
1178     /**
1179     * Returns an enumeration of the values in this table.
1180     *
1181 jsr166 1.70 * @return an enumeration of the values in this table
1182 jsr166 1.94 * @see #values()
1183 tim 1.1 */
1184 dl 1.4 public Enumeration<V> elements() {
1185 tim 1.1 return new ValueIterator();
1186     }
1187    
1188 dl 1.4 /* ---------------- Iterator Support -------------- */
1189 tim 1.11
1190 jsr166 1.82 abstract class HashIterator {
1191 dl 1.41 int nextSegmentIndex;
1192     int nextTableIndex;
1193 dl 1.71 HashEntry<K,V>[] currentTable;
1194 dl 1.41 HashEntry<K, V> nextEntry;
1195 dl 1.30 HashEntry<K, V> lastReturned;
1196 tim 1.1
1197 dl 1.41 HashIterator() {
1198 dl 1.8 nextSegmentIndex = segments.length - 1;
1199 dl 1.4 nextTableIndex = -1;
1200     advance();
1201 tim 1.1 }
1202    
1203 dl 1.99 /**
1204     * Set nextEntry to first node of next non-empty table
1205     * (in backwards order, to simplify checks).
1206     */
1207 dl 1.41 final void advance() {
1208 dl 1.99 for (;;) {
1209     if (nextTableIndex >= 0) {
1210     if ((nextEntry = entryAt(currentTable,
1211     nextTableIndex--)) != null)
1212     break;
1213     }
1214     else if (nextSegmentIndex >= 0) {
1215     Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
1216     if (seg != null && (currentTable = seg.table) != null)
1217     nextTableIndex = currentTable.length - 1;
1218 tim 1.1 }
1219 dl 1.99 else
1220     break;
1221 tim 1.1 }
1222     }
1223    
1224 dl 1.99 final HashEntry<K,V> nextEntry() {
1225     HashEntry<K,V> e = lastReturned = nextEntry;
1226     if (e == null)
1227 tim 1.1 throw new NoSuchElementException();
1228 dl 1.99 if ((nextEntry = e.next) == null)
1229     advance();
1230     return e;
1231 tim 1.1 }
1232    
1233 dl 1.99 public final boolean hasNext() { return nextEntry != null; }
1234     public final boolean hasMoreElements() { return nextEntry != null; }
1235    
1236     public final void remove() {
1237 tim 1.1 if (lastReturned == null)
1238     throw new IllegalStateException();
1239     ConcurrentHashMap.this.remove(lastReturned.key);
1240     lastReturned = null;
1241     }
1242 dl 1.4 }
1243    
1244 jsr166 1.82 final class KeyIterator
1245 jsr166 1.96 extends HashIterator
1246     implements Iterator<K>, Enumeration<K>
1247 jsr166 1.82 {
1248 dl 1.99 public final K next() { return super.nextEntry().key; }
1249     public final K nextElement() { return super.nextEntry().key; }
1250 dl 1.4 }
1251    
1252 jsr166 1.82 final class ValueIterator
1253 jsr166 1.96 extends HashIterator
1254     implements Iterator<V>, Enumeration<V>
1255 jsr166 1.82 {
1256 dl 1.99 public final V next() { return super.nextEntry().value; }
1257     public final V nextElement() { return super.nextEntry().value; }
1258 dl 1.4 }
1259 tim 1.1
1260 dl 1.30 /**
1261 dl 1.79 * Custom Entry class used by EntryIterator.next(), that relays
1262     * setValue changes to the underlying map.
1263 jsr166 1.80 */
1264 jsr166 1.83 final class WriteThroughEntry
1265 jsr166 1.96 extends AbstractMap.SimpleEntry<K,V>
1266 jsr166 1.81 {
1267 jsr166 1.83 WriteThroughEntry(K k, V v) {
1268 jsr166 1.80 super(k,v);
1269 dl 1.79 }
1270    
1271     /**
1272     * Set our entry's value and write through to the map. The
1273     * value to return is somewhat arbitrary here. Since a
1274     * WriteThroughEntry does not necessarily track asynchronous
1275     * changes, the most recent "previous" value could be
1276 jsr166 1.81 * different from what we return (or could even have been
1277 dl 1.79 * removed in which case the put will re-establish). We do not
1278     * and cannot guarantee more.
1279     */
1280 jsr166 1.96 public V setValue(V value) {
1281 dl 1.79 if (value == null) throw new NullPointerException();
1282     V v = super.setValue(value);
1283 jsr166 1.83 ConcurrentHashMap.this.put(getKey(), value);
1284 dl 1.79 return v;
1285 dl 1.30 }
1286 dl 1.79 }
1287 dl 1.30
1288 jsr166 1.82 final class EntryIterator
1289 jsr166 1.96 extends HashIterator
1290     implements Iterator<Entry<K,V>>
1291 jsr166 1.82 {
1292 dl 1.79 public Map.Entry<K,V> next() {
1293     HashEntry<K,V> e = super.nextEntry();
1294 jsr166 1.83 return new WriteThroughEntry(e.key, e.value);
1295 dl 1.30 }
1296 tim 1.1 }
1297    
1298 dl 1.41 final class KeySet extends AbstractSet<K> {
1299 dl 1.4 public Iterator<K> iterator() {
1300     return new KeyIterator();
1301     }
1302     public int size() {
1303     return ConcurrentHashMap.this.size();
1304     }
1305 jsr166 1.95 public boolean isEmpty() {
1306     return ConcurrentHashMap.this.isEmpty();
1307     }
1308 dl 1.4 public boolean contains(Object o) {
1309     return ConcurrentHashMap.this.containsKey(o);
1310     }
1311     public boolean remove(Object o) {
1312     return ConcurrentHashMap.this.remove(o) != null;
1313     }
1314     public void clear() {
1315     ConcurrentHashMap.this.clear();
1316     }
1317 tim 1.1 }
1318    
1319 dl 1.41 final class Values extends AbstractCollection<V> {
1320 dl 1.4 public Iterator<V> iterator() {
1321     return new ValueIterator();
1322     }
1323     public int size() {
1324     return ConcurrentHashMap.this.size();
1325     }
1326 jsr166 1.95 public boolean isEmpty() {
1327     return ConcurrentHashMap.this.isEmpty();
1328     }
1329 dl 1.4 public boolean contains(Object o) {
1330     return ConcurrentHashMap.this.containsValue(o);
1331     }
1332     public void clear() {
1333     ConcurrentHashMap.this.clear();
1334     }
1335 tim 1.1 }
1336    
1337 dl 1.41 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1338 dl 1.4 public Iterator<Map.Entry<K,V>> iterator() {
1339     return new EntryIterator();
1340     }
1341     public boolean contains(Object o) {
1342     if (!(o instanceof Map.Entry))
1343     return false;
1344 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1345 dl 1.4 V v = ConcurrentHashMap.this.get(e.getKey());
1346     return v != null && v.equals(e.getValue());
1347     }
1348     public boolean remove(Object o) {
1349     if (!(o instanceof Map.Entry))
1350     return false;
1351 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1352 dl 1.13 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1353 dl 1.4 }
1354     public int size() {
1355     return ConcurrentHashMap.this.size();
1356     }
1357 jsr166 1.95 public boolean isEmpty() {
1358     return ConcurrentHashMap.this.isEmpty();
1359     }
1360 dl 1.4 public void clear() {
1361     ConcurrentHashMap.this.clear();
1362 dl 1.30 }
1363     }
1364    
1365 dl 1.4 /* ---------------- Serialization Support -------------- */
1366    
1367 tim 1.1 /**
1368 jsr166 1.68 * Save the state of the <tt>ConcurrentHashMap</tt> instance to a
1369     * stream (i.e., serialize it).
1370 dl 1.8 * @param s the stream
1371 tim 1.1 * @serialData
1372     * the key (Object) and value (Object)
1373     * for each key-value mapping, followed by a null pair.
1374     * The key-value mappings are emitted in no particular order.
1375     */
1376 jsr166 1.97 private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1377 dl 1.99 // force all segments for serialization compatibility
1378     for (int k = 0; k < segments.length; ++k)
1379     ensureSegment(k);
1380 tim 1.1 s.defaultWriteObject();
1381    
1382 dl 1.99 final Segment<K,V>[] segments = this.segments;
1383 tim 1.1 for (int k = 0; k < segments.length; ++k) {
1384 dl 1.99 Segment<K,V> seg = segmentAt(segments, k);
1385 dl 1.2 seg.lock();
1386     try {
1387 dl 1.71 HashEntry<K,V>[] tab = seg.table;
1388 dl 1.4 for (int i = 0; i < tab.length; ++i) {
1389 dl 1.99 HashEntry<K,V> e;
1390     for (e = entryAt(tab, i); e != null; e = e.next) {
1391 dl 1.4 s.writeObject(e.key);
1392     s.writeObject(e.value);
1393     }
1394     }
1395 tim 1.16 } finally {
1396 dl 1.2 seg.unlock();
1397     }
1398 tim 1.1 }
1399     s.writeObject(null);
1400     s.writeObject(null);
1401     }
1402    
1403     /**
1404 jsr166 1.68 * Reconstitute the <tt>ConcurrentHashMap</tt> instance from a
1405     * stream (i.e., deserialize it).
1406 dl 1.8 * @param s the stream
1407 tim 1.1 */
1408 dl 1.99 @SuppressWarnings("unchecked")
1409 tim 1.1 private void readObject(java.io.ObjectInputStream s)
1410 jsr166 1.97 throws IOException, ClassNotFoundException {
1411 tim 1.1 s.defaultReadObject();
1412    
1413 dl 1.99 // Re-initialize segments to be minimally sized, and let grow.
1414     int cap = MIN_SEGMENT_TABLE_CAPACITY;
1415     final Segment<K,V>[] segments = this.segments;
1416     for (int k = 0; k < segments.length; ++k) {
1417     Segment<K,V> seg = segments[k];
1418     if (seg != null) {
1419     seg.threshold = (int)(cap * seg.loadFactor);
1420     seg.table = (HashEntry<K,V>[]) new HashEntry[cap];
1421     }
1422 dl 1.4 }
1423 tim 1.1
1424     // Read the keys and values, and put the mappings in the table
1425 dl 1.9 for (;;) {
1426 tim 1.1 K key = (K) s.readObject();
1427     V value = (V) s.readObject();
1428     if (key == null)
1429     break;
1430     put(key, value);
1431     }
1432     }
1433 dl 1.99
1434     // Unsafe mechanics
1435     private static final sun.misc.Unsafe UNSAFE;
1436     private static final long SBASE;
1437     private static final int SSHIFT;
1438     private static final long TBASE;
1439     private static final int TSHIFT;
1440    
1441     static {
1442     int ss, ts;
1443     try {
1444     UNSAFE = sun.misc.Unsafe.getUnsafe();
1445     Class tc = HashEntry[].class;
1446     Class sc = Segment[].class;
1447     TBASE = UNSAFE.arrayBaseOffset(tc);
1448     SBASE = UNSAFE.arrayBaseOffset(sc);
1449     ts = UNSAFE.arrayIndexScale(tc);
1450     ss = UNSAFE.arrayIndexScale(sc);
1451     } catch (Exception e) {
1452     throw new Error(e);
1453     }
1454     if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
1455     throw new Error("data type scale not a power of two");
1456     SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1457     TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
1458     }
1459    
1460 tim 1.1 }