ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java
Revision: 1.104
Committed: Fri Apr 15 23:07:20 2011 UTC (13 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.103: +19 -12 lines
Log Message:
Improve containsValue

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 jsr166 1.101 return (tab == null) ? null :
218 dl 1.99 (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 dl 1.104 * The total number of mutative operations in this segment.
307     * Even though this may overflows 32 bits, it provides
308     * sufficient accuracy for stability checks in CHM isEmpty()
309     * and size() methods. Accessed only either within locks or
310     * among other volatile reads that maintain visibility.
311 dl 1.21 */
312     transient int modCount;
313    
314     /**
315 dl 1.4 * The table is rehashed when its size exceeds this threshold.
316 jsr166 1.68 * (The value of this field is always <tt>(int)(capacity *
317     * loadFactor)</tt>.)
318 dl 1.4 */
319 dl 1.41 transient int threshold;
320 dl 1.4
321     /**
322     * The load factor for the hash table. Even though this value
323     * is same for all segments, it is replicated to avoid needing
324     * links to outer object.
325     * @serial
326     */
327 dl 1.41 final float loadFactor;
328 tim 1.1
329 dl 1.99 Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
330     this.loadFactor = lf;
331     this.threshold = threshold;
332     this.table = tab;
333 dl 1.4 }
334 tim 1.1
335 dl 1.99 final V put(K key, int hash, V value, boolean onlyIfAbsent) {
336     HashEntry<K,V> node = tryLock() ? null :
337     scanAndLockForPut(key, hash, value);
338     V oldValue;
339 dl 1.45 try {
340 dl 1.99 HashEntry<K,V>[] tab = table;
341     int index = (tab.length - 1) & hash;
342     HashEntry<K,V> first = entryAt(tab, index);
343     for (HashEntry<K,V> e = first;;) {
344     if (e != null) {
345     K k;
346     if ((k = e.key) == key ||
347     (e.hash == hash && key.equals(k))) {
348     oldValue = e.value;
349 dl 1.104 if (!onlyIfAbsent) {
350 dl 1.99 e.value = value;
351 dl 1.104 ++modCount;
352     }
353 dl 1.99 break;
354     }
355     e = e.next;
356 dl 1.45 }
357 dl 1.99 else {
358     if (node != null)
359     node.setNext(first);
360     else
361     node = new HashEntry<K,V>(hash, key, value, first);
362     int c = count + 1;
363     if (c > threshold && first != null &&
364     tab.length < MAXIMUM_CAPACITY)
365     rehash(node);
366     else
367     setEntryAt(tab, index, node);
368     ++modCount;
369     count = c;
370     oldValue = null;
371     break;
372 dl 1.45 }
373     }
374 dl 1.33 } finally {
375     unlock();
376     }
377 dl 1.99 return oldValue;
378 dl 1.33 }
379    
380 dl 1.99 /**
381     * Doubles size of table and repacks entries, also adding the
382     * given node to new table
383     */
384     @SuppressWarnings("unchecked")
385     private void rehash(HashEntry<K,V> node) {
386     /*
387     * Reclassify nodes in each list to new table. Because we
388     * are using power-of-two expansion, the elements from
389     * each bin must either stay at same index, or move with a
390     * power of two offset. We eliminate unnecessary node
391     * creation by catching cases where old nodes can be
392     * reused because their next fields won't change.
393     * Statistically, at the default threshold, only about
394     * one-sixth of them need cloning when a table
395     * doubles. The nodes they replace will be garbage
396     * collectable as soon as they are no longer referenced by
397     * any reader thread that may be in the midst of
398     * concurrently traversing table. Entry accesses use plain
399     * array indexing because they are followed by volatile
400     * table write.
401     */
402 dl 1.71 HashEntry<K,V>[] oldTable = table;
403 dl 1.4 int oldCapacity = oldTable.length;
404 dl 1.99 int newCapacity = oldCapacity << 1;
405     threshold = (int)(newCapacity * loadFactor);
406     HashEntry<K,V>[] newTable =
407     (HashEntry<K,V>[]) new HashEntry[newCapacity];
408     int sizeMask = newCapacity - 1;
409 dl 1.4 for (int i = 0; i < oldCapacity ; i++) {
410 dl 1.71 HashEntry<K,V> e = oldTable[i];
411 dl 1.4 if (e != null) {
412     HashEntry<K,V> next = e.next;
413     int idx = e.hash & sizeMask;
414 dl 1.99 if (next == null) // Single node on list
415 dl 1.4 newTable[idx] = e;
416 dl 1.99 else { // Reuse consecutive sequence at same slot
417 dl 1.4 HashEntry<K,V> lastRun = e;
418     int lastIdx = idx;
419 tim 1.11 for (HashEntry<K,V> last = next;
420     last != null;
421 dl 1.4 last = last.next) {
422     int k = last.hash & sizeMask;
423     if (k != lastIdx) {
424     lastIdx = k;
425     lastRun = last;
426     }
427     }
428     newTable[lastIdx] = lastRun;
429 dl 1.99 // Clone remaining nodes
430 dl 1.4 for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
431 dl 1.99 V v = p.value;
432     int h = p.hash;
433     int k = h & sizeMask;
434 dl 1.71 HashEntry<K,V> n = newTable[k];
435 dl 1.99 newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
436 dl 1.4 }
437     }
438     }
439     }
440 dl 1.99 int nodeIndex = node.hash & sizeMask; // add the new node
441     node.setNext(newTable[nodeIndex]);
442     newTable[nodeIndex] = node;
443 dl 1.45 table = newTable;
444 dl 1.4 }
445 dl 1.6
446     /**
447 dl 1.99 * Scans for a node containing given key while trying to
448     * acquire lock, creating and returning one if not found. Upon
449 dl 1.104 * return, guarantees that lock is held. UNlike in most
450     * methods, calls to method equals are not screened: Since
451     * traversal speed doesn't matter, we might as well help warm
452     * up the associated code and accesses as well.
453 dl 1.99 *
454     * @return a new node if key not found, else null
455     */
456     private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
457     HashEntry<K,V> first = entryForHash(this, hash);
458     HashEntry<K,V> e = first;
459     HashEntry<K,V> node = null;
460     int retries = -1; // negative while locating node
461     while (!tryLock()) {
462     HashEntry<K,V> f; // to recheck first below
463     if (retries < 0) {
464     if (e == null) {
465     if (node == null) // speculatively create node
466     node = new HashEntry<K,V>(hash, key, value, null);
467     retries = 0;
468     }
469     else if (key.equals(e.key))
470     retries = 0;
471     else
472     e = e.next;
473     }
474     else if (++retries > MAX_SCAN_RETRIES) {
475     lock();
476     break;
477     }
478     else if ((retries & 1) == 0 &&
479     (f = entryForHash(this, hash)) != first) {
480     e = first = f; // re-traverse if entry changed
481     retries = -1;
482     }
483     }
484     return node;
485     }
486    
487     /**
488     * Scans for a node containing the given key while trying to
489     * acquire lock for a remove or replace operation. Upon
490     * return, guarantees that lock is held. Note that we must
491     * lock even if the key is not found, to ensure sequential
492     * consistency of updates.
493     */
494     private void scanAndLock(Object key, int hash) {
495     // similar to but simpler than scanAndLockForPut
496     HashEntry<K,V> first = entryForHash(this, hash);
497     HashEntry<K,V> e = first;
498     int retries = -1;
499     while (!tryLock()) {
500     HashEntry<K,V> f;
501     if (retries < 0) {
502     if (e == null || key.equals(e.key))
503     retries = 0;
504     else
505     e = e.next;
506     }
507     else if (++retries > MAX_SCAN_RETRIES) {
508     lock();
509     break;
510     }
511     else if ((retries & 1) == 0 &&
512     (f = entryForHash(this, hash)) != first) {
513     e = first = f;
514     retries = -1;
515     }
516     }
517     }
518    
519     /**
520 dl 1.6 * Remove; match on key only if value null, else match both.
521     */
522 dl 1.99 final V remove(Object key, int hash, Object value) {
523     if (!tryLock())
524     scanAndLock(key, hash);
525     V oldValue = null;
526 dl 1.4 try {
527 dl 1.71 HashEntry<K,V>[] tab = table;
528 dl 1.99 int index = (tab.length - 1) & hash;
529     HashEntry<K,V> e = entryAt(tab, index);
530     HashEntry<K,V> pred = null;
531     while (e != null) {
532     K k;
533     HashEntry<K,V> next = e.next;
534     if ((k = e.key) == key ||
535     (e.hash == hash && key.equals(k))) {
536     V v = e.value;
537     if (value == null || value == v || value.equals(v)) {
538     if (pred == null)
539     setEntryAt(tab, index, next);
540     else
541     pred.setNext(next);
542     ++modCount;
543     --count;
544     oldValue = v;
545     }
546     break;
547     }
548     pred = e;
549     e = next;
550     }
551     } finally {
552     unlock();
553     }
554     return oldValue;
555     }
556    
557     final boolean replace(K key, int hash, V oldValue, V newValue) {
558     if (!tryLock())
559     scanAndLock(key, hash);
560     boolean replaced = false;
561     try {
562     HashEntry<K,V> e;
563     for (e = entryForHash(this, hash); e != null; e = e.next) {
564     K k;
565     if ((k = e.key) == key ||
566     (e.hash == hash && key.equals(k))) {
567     if (oldValue.equals(e.value)) {
568     e.value = newValue;
569 dl 1.104 ++modCount;
570 dl 1.99 replaced = true;
571     }
572     break;
573     }
574     }
575     } finally {
576     unlock();
577     }
578     return replaced;
579     }
580 dl 1.45
581 dl 1.99 final V replace(K key, int hash, V value) {
582     if (!tryLock())
583     scanAndLock(key, hash);
584     V oldValue = null;
585     try {
586     HashEntry<K,V> e;
587     for (e = entryForHash(this, hash); e != null; e = e.next) {
588     K k;
589     if ((k = e.key) == key ||
590     (e.hash == hash && key.equals(k))) {
591     oldValue = e.value;
592     e.value = value;
593 dl 1.104 ++modCount;
594 dl 1.99 break;
595 dl 1.45 }
596 dl 1.4 }
597 dl 1.99 } finally {
598     unlock();
599     }
600     return oldValue;
601     }
602    
603     final void clear() {
604     lock();
605     try {
606     HashEntry<K,V>[] tab = table;
607     for (int i = 0; i < tab.length ; i++)
608     setEntryAt(tab, i, null);
609     ++modCount;
610     count = 0;
611 tim 1.16 } finally {
612 dl 1.4 unlock();
613     }
614     }
615 dl 1.99 }
616    
617     // Accessing segments
618 dl 1.4
619 dl 1.99 /**
620     * Gets the jth element of given segment array (if nonnull) with
621     * volatile element access semantics via Unsafe.
622     */
623     @SuppressWarnings("unchecked")
624     static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
625     long u = (j << SSHIFT) + SBASE;
626     return ss == null ? null :
627     (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
628     }
629    
630     /**
631     * Returns the segment for the given index, creating it and
632     * recording in segment table (via CAS) if not already present.
633     *
634     * @param k the index
635     * @return the segment
636     */
637     @SuppressWarnings("unchecked")
638     private Segment<K,V> ensureSegment(int k) {
639     final Segment<K,V>[] ss = this.segments;
640     long u = (k << SSHIFT) + SBASE; // raw offset
641     Segment<K,V> seg;
642     if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
643     Segment<K,V> proto = ss[0]; // use segment 0 as prototype
644     int cap = proto.table.length;
645     float lf = proto.loadFactor;
646     int threshold = (int)(cap * lf);
647     HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
648     if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
649     == null) { // recheck
650     Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
651     while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
652     == null) {
653     if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
654     break;
655 dl 1.45 }
656 dl 1.4 }
657     }
658 dl 1.99 return seg;
659 tim 1.1 }
660    
661 dl 1.99 // Hash-based segment and entry accesses
662 tim 1.1
663 dl 1.99 /**
664     * Get the segment for the given hash
665     */
666     @SuppressWarnings("unchecked")
667     private Segment<K,V> segmentForHash(int h) {
668     long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
669     return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
670     }
671    
672     /**
673     * Gets the table entry for the given segment and hash
674     */
675     @SuppressWarnings("unchecked")
676     static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
677     HashEntry<K,V>[] tab;
678 jsr166 1.101 return (seg == null || (tab = seg.table) == null) ? null :
679 dl 1.99 (HashEntry<K,V>) UNSAFE.getObjectVolatile
680     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
681     }
682 tim 1.11
683 dl 1.4 /* ---------------- Public operations -------------- */
684 tim 1.1
685     /**
686 dl 1.44 * Creates a new, empty map with the specified initial
687 dl 1.56 * capacity, load factor and concurrency level.
688 tim 1.1 *
689 dl 1.19 * @param initialCapacity the initial capacity. The implementation
690     * performs internal sizing to accommodate this many elements.
691 tim 1.1 * @param loadFactor the load factor threshold, used to control resizing.
692 dl 1.56 * Resizing may be performed when the average number of elements per
693     * bin exceeds this threshold.
694 dl 1.19 * @param concurrencyLevel the estimated number of concurrently
695     * updating threads. The implementation performs internal sizing
696 jsr166 1.64 * to try to accommodate this many threads.
697 dl 1.4 * @throws IllegalArgumentException if the initial capacity is
698 dl 1.19 * negative or the load factor or concurrencyLevel are
699 dl 1.4 * nonpositive.
700     */
701 dl 1.99 @SuppressWarnings("unchecked")
702 tim 1.11 public ConcurrentHashMap(int initialCapacity,
703 dl 1.19 float loadFactor, int concurrencyLevel) {
704     if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
705 dl 1.4 throw new IllegalArgumentException();
706 dl 1.21 if (concurrencyLevel > MAX_SEGMENTS)
707     concurrencyLevel = MAX_SEGMENTS;
708 dl 1.4 // Find power-of-two sizes best matching arguments
709     int sshift = 0;
710     int ssize = 1;
711 dl 1.19 while (ssize < concurrencyLevel) {
712 dl 1.4 ++sshift;
713     ssize <<= 1;
714     }
715 dl 1.99 this.segmentShift = 32 - sshift;
716     this.segmentMask = ssize - 1;
717 dl 1.4 if (initialCapacity > MAXIMUM_CAPACITY)
718     initialCapacity = MAXIMUM_CAPACITY;
719     int c = initialCapacity / ssize;
720 tim 1.11 if (c * ssize < initialCapacity)
721 dl 1.4 ++c;
722 dl 1.99 int cap = MIN_SEGMENT_TABLE_CAPACITY;
723 dl 1.4 while (cap < c)
724     cap <<= 1;
725 dl 1.99 // create segments and segments[0]
726     Segment<K,V> s0 =
727     new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
728     (HashEntry<K,V>[])new HashEntry[cap]);
729     Segment<K,V>[] ss = (Segment<K,V>[])new Segment[ssize];
730     UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
731     this.segments = ss;
732 tim 1.1 }
733    
734     /**
735 dl 1.55 * Creates a new, empty map with the specified initial capacity
736 jsr166 1.76 * and load factor and with the default concurrencyLevel (16).
737 dl 1.55 *
738     * @param initialCapacity The implementation performs internal
739     * sizing to accommodate this many elements.
740     * @param loadFactor the load factor threshold, used to control resizing.
741 jsr166 1.68 * Resizing may be performed when the average number of elements per
742     * bin exceeds this threshold.
743 dl 1.55 * @throws IllegalArgumentException if the initial capacity of
744     * elements is negative or the load factor is nonpositive
745 jsr166 1.78 *
746     * @since 1.6
747 dl 1.55 */
748     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
749 dl 1.56 this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
750 dl 1.55 }
751    
752     /**
753 dl 1.56 * Creates a new, empty map with the specified initial capacity,
754 jsr166 1.76 * and with default load factor (0.75) and concurrencyLevel (16).
755 tim 1.1 *
756 dl 1.58 * @param initialCapacity the initial capacity. The implementation
757     * performs internal sizing to accommodate this many elements.
758 dl 1.4 * @throws IllegalArgumentException if the initial capacity of
759     * elements is negative.
760 tim 1.1 */
761     public ConcurrentHashMap(int initialCapacity) {
762 dl 1.56 this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
763 tim 1.1 }
764    
765     /**
766 jsr166 1.76 * Creates a new, empty map with a default initial capacity (16),
767     * load factor (0.75) and concurrencyLevel (16).
768 tim 1.1 */
769     public ConcurrentHashMap() {
770 dl 1.56 this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
771 tim 1.1 }
772    
773     /**
774 jsr166 1.76 * Creates a new map with the same mappings as the given map.
775     * The map is created with a capacity of 1.5 times the number
776     * of mappings in the given map or 16 (whichever is greater),
777     * and a default load factor (0.75) and concurrencyLevel (16).
778     *
779 jsr166 1.68 * @param m the map
780 tim 1.1 */
781 jsr166 1.68 public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
782     this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
783 dl 1.56 DEFAULT_INITIAL_CAPACITY),
784     DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
785 jsr166 1.68 putAll(m);
786 tim 1.1 }
787    
788 dl 1.56 /**
789     * Returns <tt>true</tt> if this map contains no key-value mappings.
790     *
791 jsr166 1.68 * @return <tt>true</tt> if this map contains no key-value mappings
792 dl 1.56 */
793 tim 1.1 public boolean isEmpty() {
794 dl 1.21 /*
795 dl 1.99 * Sum per-segment modCounts to avoid mis-reporting when
796     * elements are concurrently added and removed in one segment
797     * while checking another, in which case the table was never
798     * actually empty at any point. (The sum ensures accuracy up
799     * through at least 1<<31 per-segment modifications before
800     * recheck.) Methods size() and containsValue() use similar
801     * constructions for stability checks.
802 dl 1.21 */
803 dl 1.99 long sum = 0L;
804     final Segment<K,V>[] segments = this.segments;
805     for (int j = 0; j < segments.length; ++j) {
806     Segment<K,V> seg = segmentAt(segments, j);
807     if (seg != null) {
808     if (seg.count != 0)
809     return false;
810     sum += seg.modCount;
811     }
812 dl 1.21 }
813 dl 1.99 if (sum != 0L) { // recheck unless no modifications
814     for (int j = 0; j < segments.length; ++j) {
815     Segment<K,V> seg = segmentAt(segments, j);
816     if (seg != null) {
817     if (seg.count != 0)
818     return false;
819     sum -= seg.modCount;
820     }
821 dl 1.21 }
822 dl 1.99 if (sum != 0L)
823     return false;
824 dl 1.21 }
825 tim 1.1 return true;
826     }
827    
828 dl 1.56 /**
829     * Returns the number of key-value mappings in this map. If the
830     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
831     * <tt>Integer.MAX_VALUE</tt>.
832     *
833 jsr166 1.68 * @return the number of key-value mappings in this map
834 dl 1.56 */
835 dl 1.21 public int size() {
836 dl 1.46 // Try a few times to get accurate count. On failure due to
837 dl 1.45 // continuous async changes in table, resort to locking.
838 dl 1.99 final Segment<K,V>[] segments = this.segments;
839     int size;
840     boolean overflow; // true if size overflows 32 bits
841     long sum; // sum of modCounts
842     long last = 0L; // previous sum
843     int retries = -1; // first iteration isn't retry
844     try {
845     for (;;) {
846     if (retries++ == RETRIES_BEFORE_LOCK) {
847     for (int j = 0; j < segments.length; ++j)
848     ensureSegment(j).lock(); // force creation
849     }
850     sum = 0L;
851     size = 0;
852     overflow = false;
853     for (int j = 0; j < segments.length; ++j) {
854     Segment<K,V> seg = segmentAt(segments, j);
855     if (seg != null) {
856     sum += seg.modCount;
857     int c = seg.count;
858     if (c < 0 || (size += c) < 0)
859     overflow = true;
860 dl 1.21 }
861     }
862 dl 1.99 if (sum == last)
863     break;
864     last = sum;
865     }
866     } finally {
867     if (retries > RETRIES_BEFORE_LOCK) {
868     for (int j = 0; j < segments.length; ++j)
869     segmentAt(segments, j).unlock();
870 dl 1.21 }
871 dl 1.45 }
872 dl 1.99 return overflow ? Integer.MAX_VALUE : size;
873 dl 1.21 }
874    
875 tim 1.1 /**
876 jsr166 1.85 * Returns the value to which the specified key is mapped,
877     * or {@code null} if this map contains no mapping for the key.
878     *
879     * <p>More formally, if this map contains a mapping from a key
880     * {@code k} to a value {@code v} such that {@code key.equals(k)},
881     * then this method returns {@code v}; otherwise it returns
882     * {@code null}. (There can be at most one such mapping.)
883 tim 1.1 *
884 jsr166 1.68 * @throws NullPointerException if the specified key is null
885 tim 1.1 */
886 tim 1.11 public V get(Object key) {
887 dl 1.89 int hash = hash(key.hashCode());
888 dl 1.99 for (HashEntry<K,V> e = entryForHash(segmentForHash(hash), hash);
889     e != null; e = e.next) {
890     K k;
891     if ((k = e.key) == key || (e.hash == hash && key.equals(k)))
892     return e.value;
893     }
894     return null;
895 tim 1.1 }
896    
897     /**
898     * Tests if the specified object is a key in this table.
899 tim 1.11 *
900 jsr166 1.68 * @param key possible key
901     * @return <tt>true</tt> if and only if the specified object
902     * is a key in this table, as determined by the
903     * <tt>equals</tt> method; <tt>false</tt> otherwise.
904     * @throws NullPointerException if the specified key is null
905 tim 1.1 */
906     public boolean containsKey(Object key) {
907 jsr166 1.91 int hash = hash(key.hashCode());
908 dl 1.99 for (HashEntry<K,V> e = entryForHash(segmentForHash(hash), hash);
909     e != null; e = e.next) {
910     K k;
911     if ((k = e.key) == key || (e.hash == hash && key.equals(k)))
912     return true;
913     }
914     return false;
915 tim 1.1 }
916    
917     /**
918     * Returns <tt>true</tt> if this map maps one or more keys to the
919     * specified value. Note: This method requires a full internal
920     * traversal of the hash table, and so is much slower than
921     * method <tt>containsKey</tt>.
922     *
923 jsr166 1.68 * @param value value whose presence in this map is to be tested
924 tim 1.1 * @return <tt>true</tt> if this map maps one or more keys to the
925 jsr166 1.68 * specified value
926     * @throws NullPointerException if the specified value is null
927 tim 1.1 */
928     public boolean containsValue(Object value) {
929 dl 1.104 // Same idea as size()
930 tim 1.11 if (value == null)
931 dl 1.4 throw new NullPointerException();
932 dl 1.71 final Segment<K,V>[] segments = this.segments;
933 dl 1.99 boolean found = false;
934 dl 1.104 long last = 0;
935 dl 1.99 int retries = -1;
936     try {
937     outer: for (;;) {
938     if (retries++ == RETRIES_BEFORE_LOCK) {
939     for (int j = 0; j < segments.length; ++j)
940     ensureSegment(j).lock(); // force creation
941     }
942 dl 1.104 long hashSum = 0L;
943     int sum = 0;
944 dl 1.99 for (int j = 0; j < segments.length; ++j) {
945     HashEntry<K,V>[] tab;
946     Segment<K,V> seg = segmentAt(segments, j);
947     if (seg != null && (tab = seg.table) != null) {
948     for (int i = 0 ; i < tab.length; i++) {
949     HashEntry<K,V> e;
950     for (e = entryAt(tab, i); e != null; e = e.next) {
951     V v = e.value;
952     if (v != null && value.equals(v)) {
953     found = true;
954     break outer;
955     }
956     }
957     }
958 dl 1.104 sum += seg.modCount;
959 dl 1.21 }
960     }
961 dl 1.103 if (retries > 0 && sum == last)
962 dl 1.45 break;
963 dl 1.99 last = sum;
964 dl 1.45 }
965     } finally {
966 dl 1.99 if (retries > RETRIES_BEFORE_LOCK) {
967     for (int j = 0; j < segments.length; ++j)
968     segmentAt(segments, j).unlock();
969     }
970 dl 1.45 }
971     return found;
972 tim 1.1 }
973 dl 1.19
974 tim 1.1 /**
975 dl 1.18 * Legacy method testing if some key maps into the specified value
976 dl 1.23 * in this table. This method is identical in functionality to
977 jsr166 1.68 * {@link #containsValue}, and exists solely to ensure
978 dl 1.19 * full compatibility with class {@link java.util.Hashtable},
979 dl 1.18 * which supported this method prior to introduction of the
980 dl 1.23 * Java Collections framework.
981 dl 1.17
982 jsr166 1.68 * @param value a value to search for
983     * @return <tt>true</tt> if and only if some key maps to the
984     * <tt>value</tt> argument in this table as
985     * determined by the <tt>equals</tt> method;
986     * <tt>false</tt> otherwise
987     * @throws NullPointerException if the specified value is null
988 tim 1.1 */
989 dl 1.4 public boolean contains(Object value) {
990 tim 1.1 return containsValue(value);
991     }
992    
993     /**
994 jsr166 1.75 * Maps the specified key to the specified value in this table.
995     * Neither the key nor the value can be null.
996 dl 1.4 *
997 dl 1.44 * <p> The value can be retrieved by calling the <tt>get</tt> method
998 tim 1.11 * with a key that is equal to the original key.
999 dl 1.4 *
1000 jsr166 1.68 * @param key key with which the specified value is to be associated
1001     * @param value value to be associated with the specified key
1002     * @return the previous value associated with <tt>key</tt>, or
1003     * <tt>null</tt> if there was no mapping for <tt>key</tt>
1004     * @throws NullPointerException if the specified key or value is null
1005 dl 1.4 */
1006 tim 1.11 public V put(K key, V value) {
1007     if (value == null)
1008 dl 1.4 throw new NullPointerException();
1009 dl 1.89 int hash = hash(key.hashCode());
1010 dl 1.99 int j = (hash >>> segmentShift) & segmentMask;
1011 jsr166 1.101 Segment<K,V> s = segmentAt(segments, j);
1012     if (s == null)
1013     s = ensureSegment(j);
1014     return s.put(key, hash, value, false);
1015 dl 1.4 }
1016    
1017     /**
1018 jsr166 1.68 * {@inheritDoc}
1019     *
1020     * @return the previous value associated with the specified key,
1021     * or <tt>null</tt> if there was no mapping for the key
1022     * @throws NullPointerException if the specified key or value is null
1023 dl 1.51 */
1024 tim 1.11 public V putIfAbsent(K key, V value) {
1025     if (value == null)
1026 dl 1.4 throw new NullPointerException();
1027 dl 1.89 int hash = hash(key.hashCode());
1028 dl 1.99 int j = (hash >>> segmentShift) & segmentMask;
1029 jsr166 1.101 Segment<K,V> s = segmentAt(segments, j);
1030     if (s == null)
1031     s = ensureSegment(j);
1032     return s.put(key, hash, value, true);
1033 dl 1.4 }
1034    
1035     /**
1036 tim 1.1 * Copies all of the mappings from the specified map to this one.
1037     * These mappings replace any mappings that this map had for any of the
1038 jsr166 1.68 * keys currently in the specified map.
1039 tim 1.1 *
1040 jsr166 1.68 * @param m mappings to be stored in this map
1041 tim 1.1 */
1042 jsr166 1.68 public void putAll(Map<? extends K, ? extends V> m) {
1043 jsr166 1.84 for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1044 dl 1.4 put(e.getKey(), e.getValue());
1045     }
1046    
1047     /**
1048 jsr166 1.68 * Removes the key (and its corresponding value) from this map.
1049     * This method does nothing if the key is not in the map.
1050 dl 1.4 *
1051 jsr166 1.68 * @param key the key that needs to be removed
1052     * @return the previous value associated with <tt>key</tt>, or
1053 jsr166 1.84 * <tt>null</tt> if there was no mapping for <tt>key</tt>
1054 jsr166 1.68 * @throws NullPointerException if the specified key is null
1055 dl 1.4 */
1056     public V remove(Object key) {
1057 jsr166 1.96 int hash = hash(key.hashCode());
1058 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1059     return s == null ? null : s.remove(key, hash, null);
1060 dl 1.4 }
1061 tim 1.1
1062 dl 1.4 /**
1063 jsr166 1.68 * {@inheritDoc}
1064     *
1065 jsr166 1.69 * @throws NullPointerException if the specified key is null
1066 dl 1.4 */
1067 dl 1.13 public boolean remove(Object key, Object value) {
1068 dl 1.89 int hash = hash(key.hashCode());
1069 dl 1.99 Segment<K,V> s;
1070     return value != null && (s = segmentForHash(hash)) != null &&
1071     s.remove(key, hash, value) != null;
1072 tim 1.1 }
1073 dl 1.31
1074     /**
1075 jsr166 1.68 * {@inheritDoc}
1076     *
1077     * @throws NullPointerException if any of the arguments are null
1078 dl 1.31 */
1079     public boolean replace(K key, V oldValue, V newValue) {
1080 dl 1.99 int hash = hash(key.hashCode());
1081 dl 1.31 if (oldValue == null || newValue == null)
1082     throw new NullPointerException();
1083 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1084     return s != null && s.replace(key, hash, oldValue, newValue);
1085 dl 1.32 }
1086    
1087     /**
1088 jsr166 1.68 * {@inheritDoc}
1089     *
1090     * @return the previous value associated with the specified key,
1091     * or <tt>null</tt> if there was no mapping for the key
1092     * @throws NullPointerException if the specified key or value is null
1093 dl 1.32 */
1094 dl 1.33 public V replace(K key, V value) {
1095 dl 1.99 int hash = hash(key.hashCode());
1096 dl 1.32 if (value == null)
1097     throw new NullPointerException();
1098 dl 1.99 Segment<K,V> s = segmentForHash(hash);
1099     return s == null ? null : s.replace(key, hash, value);
1100 dl 1.31 }
1101    
1102 tim 1.1 /**
1103 jsr166 1.68 * Removes all of the mappings from this map.
1104 tim 1.1 */
1105     public void clear() {
1106 dl 1.99 final Segment<K,V>[] segments = this.segments;
1107     for (int j = 0; j < segments.length; ++j) {
1108     Segment<K,V> s = segmentAt(segments, j);
1109     if (s != null)
1110     s.clear();
1111     }
1112 tim 1.1 }
1113    
1114     /**
1115 jsr166 1.68 * Returns a {@link Set} view of the keys contained in this map.
1116     * The set is backed by the map, so changes to the map are
1117     * reflected in the set, and vice-versa. The set supports element
1118     * removal, which removes the corresponding mapping from this map,
1119     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1120     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1121     * operations. It does not support the <tt>add</tt> or
1122 tim 1.1 * <tt>addAll</tt> operations.
1123 jsr166 1.68 *
1124     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1125     * that will never throw {@link ConcurrentModificationException},
1126 dl 1.14 * and guarantees to traverse elements as they existed upon
1127     * construction of the iterator, and may (but is not guaranteed to)
1128     * reflect any modifications subsequent to construction.
1129 tim 1.1 */
1130     public Set<K> keySet() {
1131     Set<K> ks = keySet;
1132 dl 1.8 return (ks != null) ? ks : (keySet = new KeySet());
1133 tim 1.1 }
1134    
1135     /**
1136 jsr166 1.68 * Returns a {@link Collection} view of the values contained in this map.
1137     * The collection is backed by the map, so changes to the map are
1138     * reflected in the collection, and vice-versa. The collection
1139     * supports element removal, which removes the corresponding
1140     * mapping from this map, via the <tt>Iterator.remove</tt>,
1141     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1142     * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
1143     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1144     *
1145     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1146     * that will never throw {@link ConcurrentModificationException},
1147 dl 1.14 * and guarantees to traverse elements as they existed upon
1148     * construction of the iterator, and may (but is not guaranteed to)
1149     * reflect any modifications subsequent to construction.
1150 tim 1.1 */
1151     public Collection<V> values() {
1152     Collection<V> vs = values;
1153 dl 1.8 return (vs != null) ? vs : (values = new Values());
1154 tim 1.1 }
1155    
1156     /**
1157 jsr166 1.68 * Returns a {@link Set} view of the mappings contained in this map.
1158     * The set is backed by the map, so changes to the map are
1159     * reflected in the set, and vice-versa. The set supports element
1160     * removal, which removes the corresponding mapping from the map,
1161     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1162     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1163     * operations. It does not support the <tt>add</tt> or
1164     * <tt>addAll</tt> operations.
1165     *
1166     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1167     * that will never throw {@link ConcurrentModificationException},
1168 dl 1.14 * and guarantees to traverse elements as they existed upon
1169     * construction of the iterator, and may (but is not guaranteed to)
1170     * reflect any modifications subsequent to construction.
1171 tim 1.1 */
1172     public Set<Map.Entry<K,V>> entrySet() {
1173     Set<Map.Entry<K,V>> es = entrySet;
1174 jsr166 1.65 return (es != null) ? es : (entrySet = new EntrySet());
1175 tim 1.1 }
1176    
1177     /**
1178     * Returns an enumeration of the keys in this table.
1179     *
1180 jsr166 1.70 * @return an enumeration of the keys in this table
1181 jsr166 1.94 * @see #keySet()
1182 tim 1.1 */
1183 dl 1.4 public Enumeration<K> keys() {
1184 tim 1.1 return new KeyIterator();
1185     }
1186    
1187     /**
1188     * Returns an enumeration of the values in this table.
1189     *
1190 jsr166 1.70 * @return an enumeration of the values in this table
1191 jsr166 1.94 * @see #values()
1192 tim 1.1 */
1193 dl 1.4 public Enumeration<V> elements() {
1194 tim 1.1 return new ValueIterator();
1195     }
1196    
1197 dl 1.4 /* ---------------- Iterator Support -------------- */
1198 tim 1.11
1199 jsr166 1.82 abstract class HashIterator {
1200 dl 1.41 int nextSegmentIndex;
1201     int nextTableIndex;
1202 dl 1.71 HashEntry<K,V>[] currentTable;
1203 dl 1.41 HashEntry<K, V> nextEntry;
1204 dl 1.30 HashEntry<K, V> lastReturned;
1205 tim 1.1
1206 dl 1.41 HashIterator() {
1207 dl 1.8 nextSegmentIndex = segments.length - 1;
1208 dl 1.4 nextTableIndex = -1;
1209     advance();
1210 tim 1.1 }
1211    
1212 dl 1.99 /**
1213     * Set nextEntry to first node of next non-empty table
1214     * (in backwards order, to simplify checks).
1215     */
1216 dl 1.41 final void advance() {
1217 dl 1.99 for (;;) {
1218     if (nextTableIndex >= 0) {
1219     if ((nextEntry = entryAt(currentTable,
1220     nextTableIndex--)) != null)
1221     break;
1222     }
1223     else if (nextSegmentIndex >= 0) {
1224     Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
1225     if (seg != null && (currentTable = seg.table) != null)
1226     nextTableIndex = currentTable.length - 1;
1227 tim 1.1 }
1228 dl 1.99 else
1229     break;
1230 tim 1.1 }
1231     }
1232    
1233 dl 1.99 final HashEntry<K,V> nextEntry() {
1234 dl 1.102 HashEntry<K,V> e = nextEntry;
1235 dl 1.99 if (e == null)
1236 tim 1.1 throw new NoSuchElementException();
1237 dl 1.102 lastReturned = e; // cannot assign until after null check
1238 dl 1.99 if ((nextEntry = e.next) == null)
1239     advance();
1240     return e;
1241 tim 1.1 }
1242    
1243 dl 1.99 public final boolean hasNext() { return nextEntry != null; }
1244     public final boolean hasMoreElements() { return nextEntry != null; }
1245    
1246     public final void remove() {
1247 tim 1.1 if (lastReturned == null)
1248     throw new IllegalStateException();
1249     ConcurrentHashMap.this.remove(lastReturned.key);
1250     lastReturned = null;
1251     }
1252 dl 1.4 }
1253    
1254 jsr166 1.82 final class KeyIterator
1255 jsr166 1.96 extends HashIterator
1256     implements Iterator<K>, Enumeration<K>
1257 jsr166 1.82 {
1258 dl 1.99 public final K next() { return super.nextEntry().key; }
1259     public final K nextElement() { return super.nextEntry().key; }
1260 dl 1.4 }
1261    
1262 jsr166 1.82 final class ValueIterator
1263 jsr166 1.96 extends HashIterator
1264     implements Iterator<V>, Enumeration<V>
1265 jsr166 1.82 {
1266 dl 1.99 public final V next() { return super.nextEntry().value; }
1267     public final V nextElement() { return super.nextEntry().value; }
1268 dl 1.4 }
1269 tim 1.1
1270 dl 1.30 /**
1271 dl 1.79 * Custom Entry class used by EntryIterator.next(), that relays
1272     * setValue changes to the underlying map.
1273 jsr166 1.80 */
1274 jsr166 1.83 final class WriteThroughEntry
1275 jsr166 1.96 extends AbstractMap.SimpleEntry<K,V>
1276 jsr166 1.81 {
1277 jsr166 1.83 WriteThroughEntry(K k, V v) {
1278 jsr166 1.80 super(k,v);
1279 dl 1.79 }
1280    
1281     /**
1282     * Set our entry's value and write through to the map. The
1283     * value to return is somewhat arbitrary here. Since a
1284     * WriteThroughEntry does not necessarily track asynchronous
1285     * changes, the most recent "previous" value could be
1286 jsr166 1.81 * different from what we return (or could even have been
1287 dl 1.79 * removed in which case the put will re-establish). We do not
1288     * and cannot guarantee more.
1289     */
1290 jsr166 1.96 public V setValue(V value) {
1291 dl 1.79 if (value == null) throw new NullPointerException();
1292     V v = super.setValue(value);
1293 jsr166 1.83 ConcurrentHashMap.this.put(getKey(), value);
1294 dl 1.79 return v;
1295 dl 1.30 }
1296 dl 1.79 }
1297 dl 1.30
1298 jsr166 1.82 final class EntryIterator
1299 jsr166 1.96 extends HashIterator
1300     implements Iterator<Entry<K,V>>
1301 jsr166 1.82 {
1302 dl 1.79 public Map.Entry<K,V> next() {
1303     HashEntry<K,V> e = super.nextEntry();
1304 jsr166 1.83 return new WriteThroughEntry(e.key, e.value);
1305 dl 1.30 }
1306 tim 1.1 }
1307    
1308 dl 1.41 final class KeySet extends AbstractSet<K> {
1309 dl 1.4 public Iterator<K> iterator() {
1310     return new KeyIterator();
1311     }
1312     public int size() {
1313     return ConcurrentHashMap.this.size();
1314     }
1315 jsr166 1.95 public boolean isEmpty() {
1316     return ConcurrentHashMap.this.isEmpty();
1317     }
1318 dl 1.4 public boolean contains(Object o) {
1319     return ConcurrentHashMap.this.containsKey(o);
1320     }
1321     public boolean remove(Object o) {
1322     return ConcurrentHashMap.this.remove(o) != null;
1323     }
1324     public void clear() {
1325     ConcurrentHashMap.this.clear();
1326     }
1327 tim 1.1 }
1328    
1329 dl 1.41 final class Values extends AbstractCollection<V> {
1330 dl 1.4 public Iterator<V> iterator() {
1331     return new ValueIterator();
1332     }
1333     public int size() {
1334     return ConcurrentHashMap.this.size();
1335     }
1336 jsr166 1.95 public boolean isEmpty() {
1337     return ConcurrentHashMap.this.isEmpty();
1338     }
1339 dl 1.4 public boolean contains(Object o) {
1340     return ConcurrentHashMap.this.containsValue(o);
1341     }
1342     public void clear() {
1343     ConcurrentHashMap.this.clear();
1344     }
1345 tim 1.1 }
1346    
1347 dl 1.41 final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1348 dl 1.4 public Iterator<Map.Entry<K,V>> iterator() {
1349     return new EntryIterator();
1350     }
1351     public boolean contains(Object o) {
1352     if (!(o instanceof Map.Entry))
1353     return false;
1354 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1355 dl 1.4 V v = ConcurrentHashMap.this.get(e.getKey());
1356     return v != null && v.equals(e.getValue());
1357     }
1358     public boolean remove(Object o) {
1359     if (!(o instanceof Map.Entry))
1360     return false;
1361 dl 1.71 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1362 dl 1.13 return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
1363 dl 1.4 }
1364     public int size() {
1365     return ConcurrentHashMap.this.size();
1366     }
1367 jsr166 1.95 public boolean isEmpty() {
1368     return ConcurrentHashMap.this.isEmpty();
1369     }
1370 dl 1.4 public void clear() {
1371     ConcurrentHashMap.this.clear();
1372 dl 1.30 }
1373     }
1374    
1375 dl 1.4 /* ---------------- Serialization Support -------------- */
1376    
1377 tim 1.1 /**
1378 jsr166 1.68 * Save the state of the <tt>ConcurrentHashMap</tt> instance to a
1379     * stream (i.e., serialize it).
1380 dl 1.8 * @param s the stream
1381 tim 1.1 * @serialData
1382     * the key (Object) and value (Object)
1383     * for each key-value mapping, followed by a null pair.
1384     * The key-value mappings are emitted in no particular order.
1385     */
1386 jsr166 1.97 private void writeObject(java.io.ObjectOutputStream s) throws IOException {
1387 dl 1.99 // force all segments for serialization compatibility
1388     for (int k = 0; k < segments.length; ++k)
1389     ensureSegment(k);
1390 tim 1.1 s.defaultWriteObject();
1391    
1392 dl 1.99 final Segment<K,V>[] segments = this.segments;
1393 tim 1.1 for (int k = 0; k < segments.length; ++k) {
1394 dl 1.99 Segment<K,V> seg = segmentAt(segments, k);
1395 dl 1.2 seg.lock();
1396     try {
1397 dl 1.71 HashEntry<K,V>[] tab = seg.table;
1398 dl 1.4 for (int i = 0; i < tab.length; ++i) {
1399 dl 1.99 HashEntry<K,V> e;
1400     for (e = entryAt(tab, i); e != null; e = e.next) {
1401 dl 1.4 s.writeObject(e.key);
1402     s.writeObject(e.value);
1403     }
1404     }
1405 tim 1.16 } finally {
1406 dl 1.2 seg.unlock();
1407     }
1408 tim 1.1 }
1409     s.writeObject(null);
1410     s.writeObject(null);
1411     }
1412    
1413     /**
1414 jsr166 1.68 * Reconstitute the <tt>ConcurrentHashMap</tt> instance from a
1415     * stream (i.e., deserialize it).
1416 dl 1.8 * @param s the stream
1417 tim 1.1 */
1418 dl 1.99 @SuppressWarnings("unchecked")
1419 tim 1.1 private void readObject(java.io.ObjectInputStream s)
1420 jsr166 1.97 throws IOException, ClassNotFoundException {
1421 tim 1.1 s.defaultReadObject();
1422    
1423 dl 1.99 // Re-initialize segments to be minimally sized, and let grow.
1424     int cap = MIN_SEGMENT_TABLE_CAPACITY;
1425     final Segment<K,V>[] segments = this.segments;
1426     for (int k = 0; k < segments.length; ++k) {
1427     Segment<K,V> seg = segments[k];
1428     if (seg != null) {
1429     seg.threshold = (int)(cap * seg.loadFactor);
1430     seg.table = (HashEntry<K,V>[]) new HashEntry[cap];
1431     }
1432 dl 1.4 }
1433 tim 1.1
1434     // Read the keys and values, and put the mappings in the table
1435 dl 1.9 for (;;) {
1436 tim 1.1 K key = (K) s.readObject();
1437     V value = (V) s.readObject();
1438     if (key == null)
1439     break;
1440     put(key, value);
1441     }
1442     }
1443 dl 1.99
1444     // Unsafe mechanics
1445     private static final sun.misc.Unsafe UNSAFE;
1446     private static final long SBASE;
1447     private static final int SSHIFT;
1448     private static final long TBASE;
1449     private static final int TSHIFT;
1450    
1451     static {
1452     int ss, ts;
1453     try {
1454     UNSAFE = sun.misc.Unsafe.getUnsafe();
1455     Class tc = HashEntry[].class;
1456     Class sc = Segment[].class;
1457     TBASE = UNSAFE.arrayBaseOffset(tc);
1458     SBASE = UNSAFE.arrayBaseOffset(sc);
1459     ts = UNSAFE.arrayIndexScale(tc);
1460     ss = UNSAFE.arrayIndexScale(sc);
1461     } catch (Exception e) {
1462     throw new Error(e);
1463     }
1464     if ((ss & (ss-1)) != 0 || (ts & (ts-1)) != 0)
1465     throw new Error("data type scale not a power of two");
1466     SSHIFT = 31 - Integer.numberOfLeadingZeros(ss);
1467     TSHIFT = 31 - Integer.numberOfLeadingZeros(ts);
1468     }
1469    
1470 tim 1.1 }