ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
Revision: 1.37
Committed: Sun Mar 4 20:34:27 2012 UTC (12 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.36: +5 -2 lines
Log Message:
Better spin control

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/publicdomain/zero/1.0/
5     */
6    
7     package jsr166e;
8     import jsr166e.LongAdder;
9 dl 1.24 import java.util.Arrays;
10 dl 1.1 import java.util.Map;
11     import java.util.Set;
12     import java.util.Collection;
13     import java.util.AbstractMap;
14     import java.util.AbstractSet;
15     import java.util.AbstractCollection;
16     import java.util.Hashtable;
17     import java.util.HashMap;
18     import java.util.Iterator;
19     import java.util.Enumeration;
20     import java.util.ConcurrentModificationException;
21     import java.util.NoSuchElementException;
22     import java.util.concurrent.ConcurrentMap;
23 dl 1.37 import java.util.concurrent.ThreadLocalRandom;
24 dl 1.24 import java.util.concurrent.locks.LockSupport;
25 dl 1.1 import java.io.Serializable;
26    
27     /**
28     * A hash table supporting full concurrency of retrievals and
29     * high expected concurrency for updates. This class obeys the
30     * same functional specification as {@link java.util.Hashtable}, and
31     * includes versions of methods corresponding to each method of
32     * {@code Hashtable}. However, even though all operations are
33     * thread-safe, retrieval operations do <em>not</em> entail locking,
34     * and there is <em>not</em> any support for locking the entire table
35     * in a way that prevents all access. This class is fully
36     * interoperable with {@code Hashtable} in programs that rely on its
37     * thread safety but not on its synchronization details.
38     *
39     * <p> Retrieval operations (including {@code get}) generally do not
40     * block, so may overlap with update operations (including {@code put}
41     * and {@code remove}). Retrievals reflect the results of the most
42     * recently <em>completed</em> update operations holding upon their
43     * onset. For aggregate operations such as {@code putAll} and {@code
44     * clear}, concurrent retrievals may reflect insertion or removal of
45     * only some entries. Similarly, Iterators and Enumerations return
46     * elements reflecting the state of the hash table at some point at or
47     * since the creation of the iterator/enumeration. They do
48     * <em>not</em> throw {@link ConcurrentModificationException}.
49     * However, iterators are designed to be used by only one thread at a
50     * time. Bear in mind that the results of aggregate status methods
51     * including {@code size}, {@code isEmpty}, and {@code containsValue}
52     * are typically useful only when a map is not undergoing concurrent
53     * updates in other threads. Otherwise the results of these methods
54     * reflect transient states that may be adequate for monitoring
55 dl 1.16 * or estimation purposes, but not for program control.
56 dl 1.1 *
57 dl 1.16 * <p> The table is dynamically expanded when there are too many
58     * collisions (i.e., keys that have distinct hash codes but fall into
59     * the same slot modulo the table size), with the expected average
60 dl 1.24 * effect of maintaining roughly two bins per mapping (corresponding
61     * to a 0.75 load factor threshold for resizing). There may be much
62     * variance around this average as mappings are added and removed, but
63     * overall, this maintains a commonly accepted time/space tradeoff for
64     * hash tables. However, resizing this or any other kind of hash
65     * table may be a relatively slow operation. When possible, it is a
66     * good idea to provide a size estimate as an optional {@code
67 dl 1.16 * initialCapacity} constructor argument. An additional optional
68     * {@code loadFactor} constructor argument provides a further means of
69     * customizing initial table capacity by specifying the table density
70     * to be used in calculating the amount of space to allocate for the
71     * given number of elements. Also, for compatibility with previous
72     * versions of this class, constructors may optionally specify an
73     * expected {@code concurrencyLevel} as an additional hint for
74     * internal sizing. Note that using many keys with exactly the same
75 jsr166 1.31 * {@code hashCode()} is a sure way to slow down performance of any
76 dl 1.16 * hash table.
77 dl 1.1 *
78     * <p>This class and its views and iterators implement all of the
79     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
80     * interfaces.
81     *
82     * <p> Like {@link Hashtable} but unlike {@link HashMap}, this class
83     * does <em>not</em> allow {@code null} to be used as a key or value.
84     *
85     * <p>This class is a member of the
86     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
87     * Java Collections Framework</a>.
88     *
89     * <p><em>jsr166e note: This class is a candidate replacement for
90     * java.util.concurrent.ConcurrentHashMap.<em>
91     *
92 jsr166 1.22 * @since 1.5
93 dl 1.1 * @author Doug Lea
94     * @param <K> the type of keys maintained by this map
95     * @param <V> the type of mapped values
96     */
97     public class ConcurrentHashMapV8<K, V>
98     implements ConcurrentMap<K, V>, Serializable {
99     private static final long serialVersionUID = 7249069246763182397L;
100    
101     /**
102 dl 1.27 * A function computing a mapping from the given key to a value.
103     * This is a place-holder for an upcoming JDK8 interface.
104 dl 1.1 */
105     public static interface MappingFunction<K, V> {
106     /**
107 dl 1.27 * Returns a non-null value for the given key.
108 dl 1.1 *
109     * @param key the (non-null) key
110 dl 1.27 * @return a non-null value
111 dl 1.1 */
112     V map(K key);
113     }
114    
115 dl 1.27 /**
116     * A function computing a new mapping given a key and its current
117     * mapped value (or {@code null} if there is no current
118     * mapping). This is a place-holder for an upcoming JDK8
119     * interface.
120     */
121     public static interface RemappingFunction<K, V> {
122     /**
123     * Returns a new value given a key and its current value.
124     *
125     * @param key the (non-null) key
126     * @param value the current value, or null if there is no mapping
127     * @return a non-null value
128     */
129     V remap(K key, V value);
130     }
131    
132 dl 1.1 /*
133     * Overview:
134     *
135     * The primary design goal of this hash table is to maintain
136     * concurrent readability (typically method get(), but also
137     * iterators and related methods) while minimizing update
138 dl 1.24 * contention. Secondary goals are to keep space consumption about
139     * the same or better than java.util.HashMap, and to support high
140     * initial insertion rates on an empty table by many threads.
141 dl 1.1 *
142     * Each key-value mapping is held in a Node. Because Node fields
143     * can contain special values, they are defined using plain Object
144     * types. Similarly in turn, all internal methods that use them
145 dl 1.14 * work off Object types. And similarly, so do the internal
146     * methods of auxiliary iterator and view classes. All public
147     * generic typed methods relay in/out of these internal methods,
148 dl 1.27 * supplying null-checks and casts as needed. This also allows
149     * many of the public methods to be factored into a smaller number
150     * of internal methods (although sadly not so for the five
151     * sprawling variants of put-related operations).
152 dl 1.1 *
153     * The table is lazily initialized to a power-of-two size upon the
154 dl 1.14 * first insertion. Each bin in the table contains a list of
155 dl 1.27 * Nodes (most often, the list has only zero or one Node). Table
156     * accesses require volatile/atomic reads, writes, and CASes.
157     * Because there is no other way to arrange this without adding
158     * further indirections, we use intrinsics (sun.misc.Unsafe)
159     * operations. The lists of nodes within bins are always
160     * accurately traversable under volatile reads, so long as lookups
161     * check hash code and non-nullness of value before checking key
162     * equality.
163 dl 1.24 *
164     * We use the top two bits of Node hash fields for control
165     * purposes -- they are available anyway because of addressing
166     * constraints. As explained further below, these top bits are
167 dl 1.27 * used as follows:
168 dl 1.24 * 00 - Normal
169     * 01 - Locked
170     * 11 - Locked and may have a thread waiting for lock
171     * 10 - Node is a forwarding node
172     *
173     * The lower 30 bits of each Node's hash field contain a
174     * transformation (for better randomization -- method "spread") of
175     * the key's hash code, except for forwarding nodes, for which the
176 dl 1.27 * lower bits are zero (and so always have hash field == MOVED).
177 dl 1.14 *
178 dl 1.27 * Insertion (via put or its variants) of the first node in an
179 dl 1.14 * empty bin is performed by just CASing it to the bin. This is
180 dl 1.24 * by far the most common case for put operations. Other update
181     * operations (insert, delete, and replace) require locks. We do
182     * not want to waste the space required to associate a distinct
183     * lock object with each bin, so instead use the first node of a
184     * bin list itself as a lock. Blocking support for these locks
185     * relies on the builtin "synchronized" monitors. However, we
186     * also need a tryLock construction, so we overlay these by using
187     * bits of the Node hash field for lock control (see above), and
188     * so normally use builtin monitors only for blocking and
189     * signalling using wait/notifyAll constructions. See
190     * Node.tryAwaitLock.
191     *
192     * Using the first node of a list as a lock does not by itself
193     * suffice though: When a node is locked, any update must first
194     * validate that it is still the first node after locking it, and
195     * retry if not. Because new nodes are always appended to lists,
196     * once a node is first in a bin, it remains first until deleted
197 dl 1.27 * or the bin becomes invalidated (upon resizing). However,
198     * operations that only conditionally update may inspect nodes
199     * until the point of update. This is a converse of sorts to the
200     * lazy locking technique described by Herlihy & Shavit.
201 dl 1.14 *
202 dl 1.24 * The main disadvantage of per-bin locks is that other update
203 dl 1.14 * operations on other nodes in a bin list protected by the same
204     * lock can stall, for example when user equals() or mapping
205     * functions take a long time. However, statistically, this is
206     * not a common enough problem to outweigh the time/space overhead
207     * of alternatives: Under random hash codes, the frequency of
208     * nodes in bins follows a Poisson distribution
209     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
210 dl 1.16 * parameter of about 0.5 on average, given the resizing threshold
211     * of 0.75, although with a large variance because of resizing
212     * granularity. Ignoring variance, the expected occurrences of
213     * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
214     * first few values are:
215     *
216     * 0: 0.607
217     * 1: 0.303
218     * 2: 0.076
219     * 3: 0.012
220     * more: 0.002
221     *
222     * Lock contention probability for two threads accessing distinct
223     * elements is roughly 1 / (8 * #elements). Function "spread"
224     * performs hashCode randomization that improves the likelihood
225     * that these assumptions hold unless users define exactly the
226     * same value for too many hashCodes.
227 dl 1.1 *
228 dl 1.24 * The table is resized when occupancy exceeds an occupancy
229     * threshold (nominally, 0.75, but see below). Only a single
230     * thread performs the resize (using field "sizeCtl", to arrange
231     * exclusion), but the table otherwise remains usable for reads
232     * and updates. Resizing proceeds by transferring bins, one by
233     * one, from the table to the next table. Because we are using
234     * power-of-two expansion, the elements from each bin must either
235     * stay at same index, or move with a power of two offset. We
236     * eliminate unnecessary node creation by catching cases where old
237     * nodes can be reused because their next fields won't change. On
238     * average, only about one-sixth of them need cloning when a table
239     * doubles. The nodes they replace will be garbage collectable as
240     * soon as they are no longer referenced by any reader thread that
241     * may be in the midst of concurrently traversing table. Upon
242     * transfer, the old table bin contains only a special forwarding
243     * node (with hash field "MOVED") that contains the next table as
244     * its key. On encountering a forwarding node, access and update
245     * operations restart, using the new table.
246     *
247     * Each bin transfer requires its bin lock. However, unlike other
248     * cases, a transfer can skip a bin if it fails to acquire its
249     * lock, and revisit it later. Method rebuild maintains a buffer
250     * of TRANSFER_BUFFER_SIZE bins that have been skipped because of
251     * failure to acquire a lock, and blocks only if none are
252     * available (i.e., only very rarely). The transfer operation
253     * must also ensure that all accessible bins in both the old and
254     * new table are usable by any traversal. When there are no lock
255     * acquisition failures, this is arranged simply by proceeding
256     * from the last bin (table.length - 1) up towards the first.
257     * Upon seeing a forwarding node, traversals (see class
258     * InternalIterator) arrange to move to the new table without
259     * revisiting nodes. However, when any node is skipped during a
260     * transfer, all earlier table bins may have become visible, so
261     * are initialized with a reverse-forwarding node back to the old
262     * table until the new ones are established. (This sometimes
263     * requires transiently locking a forwarding node, which is
264     * possible under the above encoding.) These more expensive
265     * mechanics trigger only when necessary.
266 dl 1.14 *
267 dl 1.24 * The traversal scheme also applies to partial traversals of
268 dl 1.14 * ranges of bins (via an alternate InternalIterator constructor)
269     * to support partitioned aggregate operations (that are not
270     * otherwise implemented yet). Also, read-only operations give up
271     * if ever forwarded to a null table, which provides support for
272     * shutdown-style clearing, which is also not currently
273     * implemented.
274     *
275     * Lazy table initialization minimizes footprint until first use,
276     * and also avoids resizings when the first operation is from a
277     * putAll, constructor with map argument, or deserialization.
278 dl 1.24 * These cases attempt to override the initial capacity settings,
279     * but harmlessly fail to take effect in cases of races.
280 dl 1.1 *
281     * The element count is maintained using a LongAdder, which avoids
282     * contention on updates but can encounter cache thrashing if read
283 dl 1.14 * too frequently during concurrent access. To avoid reading so
284 dl 1.27 * often, resizing is attempted either when a bin lock is
285     * contended, or upon adding to a bin already holding two or more
286     * nodes (checked before adding in the xIfAbsent methods, after
287     * adding in others). Under uniform hash distributions, the
288     * probability of this occurring at threshold is around 13%,
289     * meaning that only about 1 in 8 puts check threshold (and after
290     * resizing, many fewer do so). But this approximation has high
291     * variance for small table sizes, so we check on any collision
292     * for sizes <= 64. The bulk putAll operation further reduces
293     * contention by only committing count updates upon these size
294     * checks.
295 dl 1.14 *
296     * Maintaining API and serialization compatibility with previous
297     * versions of this class introduces several oddities. Mainly: We
298     * leave untouched but unused constructor arguments refering to
299 dl 1.24 * concurrencyLevel. We accept a loadFactor constructor argument,
300     * but apply it only to initial table capacity (which is the only
301     * time that we can guarantee to honor it.) We also declare an
302     * unused "Segment" class that is instantiated in minimal form
303     * only when serializing.
304 dl 1.1 */
305    
306     /* ---------------- Constants -------------- */
307    
308     /**
309 dl 1.16 * The largest possible table capacity. This value must be
310     * exactly 1<<30 to stay within Java array allocation and indexing
311 dl 1.24 * bounds for power of two table sizes, and is further required
312     * because the top two bits of 32bit hash fields are used for
313     * control purposes.
314 dl 1.1 */
315 dl 1.14 private static final int MAXIMUM_CAPACITY = 1 << 30;
316 dl 1.1
317     /**
318 dl 1.14 * The default initial table capacity. Must be a power of 2
319     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
320 dl 1.1 */
321 dl 1.14 private static final int DEFAULT_CAPACITY = 16;
322 dl 1.1
323     /**
324 dl 1.24 * The largest possible (non-power of two) array size.
325     * Needed by toArray and related methods.
326     */
327     static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
328    
329     /**
330     * The default concurrency level for this table. Unused but
331     * defined for compatibility with previous versions of this class.
332     */
333     private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
334    
335     /**
336 dl 1.16 * The load factor for this table. Overrides of this value in
337     * constructors affect only the initial table capacity. The
338 dl 1.24 * actual floating point value isn't normally used -- it is
339     * simpler to use expressions such as {@code n - (n >>> 2)} for
340     * the associated resizing threshold.
341 dl 1.1 */
342 dl 1.16 private static final float LOAD_FACTOR = 0.75f;
343 dl 1.1
344     /**
345 dl 1.24 * The buffer size for skipped bins during transfers. The
346     * value is arbitrary but should be large enough to avoid
347     * most locking stalls during resizes.
348     */
349     private static final int TRANSFER_BUFFER_SIZE = 32;
350    
351     /*
352     * Encodings for special uses of Node hash fields. See above for
353     * explanation.
354 dl 1.1 */
355 jsr166 1.35 static final int MOVED = 0x80000000; // hash field for forwarding nodes
356 dl 1.24 static final int LOCKED = 0x40000000; // set/tested only as a bit
357     static final int WAITING = 0xc0000000; // both bits set/tested together
358     static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
359    
360     /* ---------------- Fields -------------- */
361    
362     /**
363     * The array of bins. Lazily initialized upon first insertion.
364     * Size is always a power of two. Accessed directly by iterators.
365     */
366     transient volatile Node[] table;
367 dl 1.14
368 dl 1.16 /**
369 dl 1.24 * The counter maintaining number of elements.
370 dl 1.16 */
371 dl 1.24 private transient final LongAdder counter;
372    
373     /**
374     * Table initialization and resizing control. When negative, the
375     * table is being initialized or resized. Otherwise, when table is
376     * null, holds the initial table size to use upon creation, or 0
377     * for default. After initialization, holds the next element count
378     * value upon which to resize the table.
379     */
380     private transient volatile int sizeCtl;
381    
382     // views
383     private transient KeySet<K,V> keySet;
384     private transient Values<K,V> values;
385     private transient EntrySet<K,V> entrySet;
386    
387     /** For serialization compatibility. Null unless serialized; see below */
388     private Segment<K,V>[] segments;
389 dl 1.16
390 dl 1.14 /* ---------------- Nodes -------------- */
391 dl 1.1
392     /**
393 dl 1.14 * Key-value entry. Note that this is never exported out as a
394 dl 1.24 * user-visible Map.Entry (see WriteThroughEntry and SnapshotEntry
395 dl 1.29 * below). Nodes with a hash field of MOVED are special, and do
396 dl 1.24 * not contain user keys or values. Otherwise, keys are never
397     * null, and null val fields indicate that a node is in the
398     * process of being deleted or created. For purposes of read-only
399     * access, a key may be read before a val, but can only be used
400     * after checking val to be non-null.
401 dl 1.1 */
402 dl 1.14 static final class Node {
403 dl 1.24 volatile int hash;
404 dl 1.14 final Object key;
405     volatile Object val;
406     volatile Node next;
407    
408     Node(int hash, Object key, Object val, Node next) {
409     this.hash = hash;
410     this.key = key;
411     this.val = val;
412     this.next = next;
413     }
414    
415 dl 1.24 /** CompareAndSet the hash field */
416     final boolean casHash(int cmp, int val) {
417     return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
418     }
419 dl 1.1
420 dl 1.24 /** The number of spins before blocking for a lock */
421     static final int MAX_SPINS =
422     Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
423 dl 1.1
424 dl 1.24 /**
425     * Spins a while if LOCKED bit set and this node is the first
426     * of its bin, and then sets WAITING bits on hash field and
427     * blocks (once) if they are still set. It is OK for this
428     * method to return even if lock is not available upon exit,
429     * which enables these simple single-wait mechanics.
430     *
431     * The corresponding signalling operation is performed within
432     * callers: Upon detecting that WAITING has been set when
433     * unlocking lock (via a failed CAS from non-waiting LOCKED
434     * state), unlockers acquire the sync lock and perform a
435     * notifyAll.
436     */
437     final void tryAwaitLock(Node[] tab, int i) {
438     if (tab != null && i >= 0 && i < tab.length) { // bounds check
439 dl 1.37 int r = ThreadLocalRandom.current().nextInt(); // randomize spins
440 dl 1.24 int spins = MAX_SPINS, h;
441     while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
442     if (spins >= 0) {
443 dl 1.37 r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
444     if (r >= 0 && --spins == 0)
445     Thread.yield(); // yield before block
446 dl 1.24 }
447     else if (casHash(h, h | WAITING)) {
448 jsr166 1.26 synchronized (this) {
449 dl 1.24 if (tabAt(tab, i) == this &&
450     (hash & WAITING) == WAITING) {
451     try {
452     wait();
453     } catch (InterruptedException ie) {
454     Thread.currentThread().interrupt();
455     }
456     }
457     else
458     notifyAll(); // possibly won race vs signaller
459     }
460     break;
461     }
462     }
463     }
464     }
465 dl 1.1
466 dl 1.24 // Unsafe mechanics for casHash
467     private static final sun.misc.Unsafe UNSAFE;
468     private static final long hashOffset;
469 dl 1.1
470 dl 1.24 static {
471     try {
472     UNSAFE = getUnsafe();
473     Class<?> k = Node.class;
474     hashOffset = UNSAFE.objectFieldOffset
475     (k.getDeclaredField("hash"));
476     } catch (Exception e) {
477     throw new Error(e);
478     }
479     }
480     }
481 dl 1.1
482 dl 1.14 /* ---------------- Table element access -------------- */
483 dl 1.1
484     /*
485 jsr166 1.7 * Volatile access methods are used for table elements as well as
486 dl 1.14 * elements of in-progress next table while resizing. Uses are
487     * null checked by callers, and implicitly bounds-checked, relying
488     * on the invariants that tab arrays have non-zero size, and all
489     * indices are masked with (tab.length - 1) which is never
490     * negative and always less than length. Note that, to be correct
491     * wrt arbitrary concurrency errors by users, bounds checks must
492     * operate on local variables, which accounts for some odd-looking
493     * inline assignments below.
494 dl 1.1 */
495    
496 dl 1.14 static final Node tabAt(Node[] tab, int i) { // used by InternalIterator
497 dl 1.1 return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
498     }
499    
500     private static final boolean casTabAt(Node[] tab, int i, Node c, Node v) {
501     return UNSAFE.compareAndSwapObject(tab, ((long)i<<ASHIFT)+ABASE, c, v);
502     }
503    
504     private static final void setTabAt(Node[] tab, int i, Node v) {
505     UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
506     }
507    
508 dl 1.14 /* ---------------- Internal access and update methods -------------- */
509    
510     /**
511     * Applies a supplemental hash function to a given hashCode, which
512     * defends against poor quality hash functions. The result must
513 dl 1.24 * be have the top 2 bits clear. For reasonable performance, this
514     * function must have good avalanche properties; i.e., that each
515     * bit of the argument affects each bit of the result. (Although
516     * we don't care about the unused top 2 bits.)
517 dl 1.14 */
518     private static final int spread(int h) {
519     // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
520 dl 1.27 // Despite two multiplies, this is often faster than others
521     // with comparable bit-spread properties.
522 dl 1.14 h ^= h >>> 16;
523     h *= 0x85ebca6b;
524     h ^= h >>> 13;
525     h *= 0xc2b2ae35;
526 dl 1.24 return ((h >>> 16) ^ h) & HASH_BITS; // mask out top bits
527 dl 1.14 }
528 dl 1.1
529 dl 1.14 /** Implementation for get and containsKey */
530 jsr166 1.4 private final Object internalGet(Object k) {
531 dl 1.1 int h = spread(k.hashCode());
532 dl 1.14 retry: for (Node[] tab = table; tab != null;) {
533 dl 1.24 Node e; Object ek, ev; int eh; // locals to read fields once
534 dl 1.14 for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
535 dl 1.24 if ((eh = e.hash) == MOVED) {
536     tab = (Node[])e.key; // restart with new table
537 dl 1.1 continue retry;
538     }
539 dl 1.24 if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
540     ((ek = e.key) == k || k.equals(ek)))
541     return ev;
542 dl 1.1 }
543     break;
544     }
545     return null;
546     }
547    
548 dl 1.27 /**
549     * Implementation for the four public remove/replace methods:
550     * Replaces node value with v, conditional upon match of cv if
551     * non-null. If resulting value is null, delete.
552     */
553     private final Object internalReplace(Object k, Object v, Object cv) {
554     int h = spread(k.hashCode());
555     Object oldVal = null;
556     for (Node[] tab = table;;) {
557     Node f; int i, fh;
558     if (tab == null ||
559     (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
560     break;
561     else if ((fh = f.hash) == MOVED)
562     tab = (Node[])f.key;
563     else if ((fh & HASH_BITS) != h && f.next == null) // precheck
564     break; // rules out possible existence
565     else if ((fh & LOCKED) != 0) {
566     checkForResize(); // try resizing if can't get lock
567     f.tryAwaitLock(tab, i);
568     }
569     else if (f.casHash(fh, fh | LOCKED)) {
570     boolean validated = false;
571     boolean deleted = false;
572     try {
573     if (tabAt(tab, i) == f) {
574     validated = true;
575     for (Node e = f, pred = null;;) {
576     Object ek, ev;
577     if ((e.hash & HASH_BITS) == h &&
578     ((ev = e.val) != null) &&
579     ((ek = e.key) == k || k.equals(ek))) {
580     if (cv == null || cv == ev || cv.equals(ev)) {
581     oldVal = ev;
582     if ((e.val = v) == null) {
583     deleted = true;
584     Node en = e.next;
585     if (pred != null)
586     pred.next = en;
587     else
588     setTabAt(tab, i, en);
589     }
590     }
591     break;
592     }
593     pred = e;
594     if ((e = e.next) == null)
595     break;
596     }
597     }
598     } finally {
599     if (!f.casHash(fh | LOCKED, fh)) {
600     f.hash = fh;
601 jsr166 1.30 synchronized (f) { f.notifyAll(); };
602 dl 1.27 }
603     }
604     if (validated) {
605     if (deleted)
606     counter.add(-1L);
607     break;
608     }
609     }
610     }
611     return oldVal;
612     }
613    
614     /*
615     * Internal versions of the five insertion methods, each a
616     * little more complicated than the last. All have
617     * the same basic structure as the first (internalPut):
618     * 1. If table uninitialized, create
619     * 2. If bin empty, try to CAS new node
620     * 3. If bin stale, use new table
621     * 4. Lock and validate; if valid, scan and add or update
622     *
623     * The others interweave other checks and/or alternative actions:
624     * * Plain put checks for and performs resize after insertion.
625     * * putIfAbsent prescans for mapping without lock (and fails to add
626     * if present), which also makes pre-emptive resize checks worthwhile.
627     * * computeIfAbsent extends form used in putIfAbsent with additional
628     * mechanics to deal with, calls, potential exceptions and null
629     * returns from function call.
630     * * compute uses the same function-call mechanics, but without
631     * the prescans
632     * * putAll attempts to pre-allocate enough table space
633     * and more lazily performs count updates and checks.
634     *
635     * Someday when details settle down a bit more, it might be worth
636     * some factoring to reduce sprawl.
637     */
638    
639     /** Implementation for put */
640     private final Object internalPut(Object k, Object v) {
641 dl 1.1 int h = spread(k.hashCode());
642 dl 1.27 boolean checkSize = false;
643 dl 1.14 for (Node[] tab = table;;) {
644 dl 1.27 int i; Node f; int fh;
645 dl 1.1 if (tab == null)
646 dl 1.24 tab = initTable();
647     else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
648 dl 1.2 if (casTabAt(tab, i, null, new Node(h, k, v, null)))
649 dl 1.14 break; // no lock when adding to empty bin
650     }
651 dl 1.24 else if ((fh = f.hash) == MOVED)
652     tab = (Node[])f.key;
653 dl 1.27 else if ((fh & LOCKED) != 0) {
654     checkForResize();
655     f.tryAwaitLock(tab, i);
656 dl 1.1 }
657 dl 1.24 else if (f.casHash(fh, fh | LOCKED)) {
658 dl 1.27 Object oldVal = null;
659 dl 1.1 boolean validated = false;
660 dl 1.27 try { // needed in case equals() throws
661 dl 1.24 if (tabAt(tab, i) == f) {
662 dl 1.14 validated = true; // retry if 1st already deleted
663 dl 1.24 for (Node e = f;;) {
664     Object ek, ev;
665     if ((e.hash & HASH_BITS) == h &&
666     (ev = e.val) != null &&
667     ((ek = e.key) == k || k.equals(ek))) {
668 dl 1.1 oldVal = ev;
669 dl 1.27 e.val = v;
670 dl 1.10 break;
671 dl 1.1 }
672 dl 1.10 Node last = e;
673     if ((e = e.next) == null) {
674 dl 1.2 last.next = new Node(h, k, v, null);
675 dl 1.24 if (last != f || tab.length <= 64)
676 dl 1.1 checkSize = true;
677 dl 1.10 break;
678 dl 1.1 }
679     }
680     }
681 dl 1.24 } finally { // unlock and signal if needed
682     if (!f.casHash(fh | LOCKED, fh)) {
683     f.hash = fh;
684 jsr166 1.26 synchronized (f) { f.notifyAll(); };
685 dl 1.24 }
686 dl 1.1 }
687     if (validated) {
688 dl 1.27 if (oldVal != null)
689     return oldVal;
690 dl 1.1 break;
691     }
692     }
693     }
694 dl 1.27 counter.add(1L);
695     if (checkSize)
696     checkForResize();
697     return null;
698 dl 1.1 }
699    
700 dl 1.27 /** Implementation for putIfAbsent */
701     private final Object internalPutIfAbsent(Object k, Object v) {
702 dl 1.1 int h = spread(k.hashCode());
703 dl 1.14 for (Node[] tab = table;;) {
704 dl 1.27 int i; Node f; int fh; Object fk, fv;
705     if (tab == null)
706     tab = initTable();
707     else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
708     if (casTabAt(tab, i, null, new Node(h, k, v, null)))
709     break;
710     }
711 dl 1.24 else if ((fh = f.hash) == MOVED)
712     tab = (Node[])f.key;
713 dl 1.27 else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
714     ((fk = f.key) == k || k.equals(fk)))
715     return fv;
716     else {
717     Node g = f.next;
718     if (g != null) { // at least 2 nodes -- search and maybe resize
719     for (Node e = g;;) {
720     Object ek, ev;
721     if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
722     ((ek = e.key) == k || k.equals(ek)))
723     return ev;
724     if ((e = e.next) == null) {
725     checkForResize();
726     break;
727     }
728     }
729     }
730     if (((fh = f.hash) & LOCKED) != 0) {
731     checkForResize();
732     f.tryAwaitLock(tab, i);
733     }
734     else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
735     Object oldVal = null;
736     boolean validated = false;
737     try {
738     if (tabAt(tab, i) == f) {
739     validated = true;
740     for (Node e = f;;) {
741     Object ek, ev;
742     if ((e.hash & HASH_BITS) == h &&
743     (ev = e.val) != null &&
744     ((ek = e.key) == k || k.equals(ek))) {
745 dl 1.1 oldVal = ev;
746 dl 1.27 break;
747     }
748     Node last = e;
749     if ((e = e.next) == null) {
750     last.next = new Node(h, k, v, null);
751     break;
752 dl 1.1 }
753     }
754 dl 1.27 }
755     } finally {
756     if (!f.casHash(fh | LOCKED, fh)) {
757     f.hash = fh;
758 jsr166 1.30 synchronized (f) { f.notifyAll(); };
759 dl 1.24 }
760     }
761 dl 1.27 if (validated) {
762     if (oldVal != null)
763     return oldVal;
764     break;
765     }
766     }
767     }
768     }
769     counter.add(1L);
770     return null;
771     }
772    
773     /** Implementation for computeIfAbsent */
774     private final Object internalComputeIfAbsent(K k,
775     MappingFunction<? super K, ?> mf) {
776     int h = spread(k.hashCode());
777     Object val = null;
778     for (Node[] tab = table;;) {
779     Node f; int i, fh; Object fk, fv;
780     if (tab == null)
781     tab = initTable();
782     else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
783     Node node = new Node(fh = h | LOCKED, k, null, null);
784     boolean validated = false;
785     if (casTabAt(tab, i, null, node)) {
786     validated = true;
787     try {
788     if ((val = mf.map(k)) != null)
789     node.val = val;
790     } finally {
791     if (val == null)
792     setTabAt(tab, i, null);
793     if (!node.casHash(fh, h)) {
794     node.hash = h;
795 jsr166 1.30 synchronized (node) { node.notifyAll(); };
796 dl 1.27 }
797 dl 1.1 }
798     }
799 dl 1.27 if (validated)
800 dl 1.24 break;
801 dl 1.27 }
802     else if ((fh = f.hash) == MOVED)
803     tab = (Node[])f.key;
804     else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
805     ((fk = f.key) == k || k.equals(fk)))
806     return fv;
807     else {
808     Node g = f.next;
809     if (g != null) {
810     for (Node e = g;;) {
811     Object ek, ev;
812     if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
813     ((ek = e.key) == k || k.equals(ek)))
814     return ev;
815     if ((e = e.next) == null) {
816     checkForResize();
817     break;
818     }
819     }
820     }
821     if (((fh = f.hash) & LOCKED) != 0) {
822     checkForResize();
823     f.tryAwaitLock(tab, i);
824     }
825     else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
826     boolean validated = false;
827     try {
828     if (tabAt(tab, i) == f) {
829     validated = true;
830     for (Node e = f;;) {
831     Object ek, ev;
832     if ((e.hash & HASH_BITS) == h &&
833     (ev = e.val) != null &&
834     ((ek = e.key) == k || k.equals(ek))) {
835     val = ev;
836     break;
837     }
838     Node last = e;
839     if ((e = e.next) == null) {
840     if ((val = mf.map(k)) != null)
841     last.next = new Node(h, k, val, null);
842     break;
843     }
844     }
845     }
846     } finally {
847     if (!f.casHash(fh | LOCKED, fh)) {
848     f.hash = fh;
849 jsr166 1.30 synchronized (f) { f.notifyAll(); };
850 dl 1.27 }
851     }
852     if (validated)
853     break;
854 dl 1.1 }
855     }
856     }
857 dl 1.27 if (val == null)
858     throw new NullPointerException();
859     counter.add(1L);
860     return val;
861 dl 1.1 }
862    
863 dl 1.27 /** Implementation for compute */
864 dl 1.1 @SuppressWarnings("unchecked")
865 dl 1.27 private final Object internalCompute(K k,
866     RemappingFunction<? super K, V> mf) {
867 dl 1.1 int h = spread(k.hashCode());
868 dl 1.27 Object val = null;
869 dl 1.1 boolean added = false;
870 dl 1.27 boolean checkSize = false;
871     for (Node[] tab = table;;) {
872     Node f; int i, fh;
873 dl 1.1 if (tab == null)
874 dl 1.24 tab = initTable();
875     else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
876     Node node = new Node(fh = h | LOCKED, k, null, null);
877 dl 1.10 boolean validated = false;
878 dl 1.24 if (casTabAt(tab, i, null, node)) {
879     validated = true;
880     try {
881 dl 1.27 if ((val = mf.remap(k, null)) != null) {
882 dl 1.24 node.val = val;
883     added = true;
884     }
885     } finally {
886     if (!added)
887     setTabAt(tab, i, null);
888     if (!node.casHash(fh, h)) {
889 dl 1.25 node.hash = h;
890 jsr166 1.26 synchronized (node) { node.notifyAll(); };
891 dl 1.1 }
892     }
893     }
894 dl 1.10 if (validated)
895     break;
896 dl 1.1 }
897 dl 1.24 else if ((fh = f.hash) == MOVED)
898     tab = (Node[])f.key;
899 dl 1.27 else if ((fh & LOCKED) != 0) {
900     checkForResize();
901     f.tryAwaitLock(tab, i);
902 dl 1.14 }
903 dl 1.24 else if (f.casHash(fh, fh | LOCKED)) {
904 dl 1.10 boolean validated = false;
905 dl 1.24 try {
906     if (tabAt(tab, i) == f) {
907 dl 1.10 validated = true;
908 dl 1.24 for (Node e = f;;) {
909 dl 1.27 Object ek, ev;
910 dl 1.24 if ((e.hash & HASH_BITS) == h &&
911     (ev = e.val) != null &&
912     ((ek = e.key) == k || k.equals(ek))) {
913 dl 1.27 val = mf.remap(k, (V)ev);
914     if (val != null)
915     e.val = val;
916 dl 1.10 break;
917 dl 1.1 }
918 dl 1.10 Node last = e;
919     if ((e = e.next) == null) {
920 dl 1.27 if ((val = mf.remap(k, null)) != null) {
921 dl 1.2 last.next = new Node(h, k, val, null);
922     added = true;
923 dl 1.24 if (last != f || tab.length <= 64)
924 dl 1.1 checkSize = true;
925     }
926 dl 1.10 break;
927 dl 1.1 }
928     }
929     }
930 dl 1.24 } finally {
931     if (!f.casHash(fh | LOCKED, fh)) {
932     f.hash = fh;
933 jsr166 1.26 synchronized (f) { f.notifyAll(); };
934 dl 1.24 }
935 dl 1.1 }
936 dl 1.27 if (validated)
937 dl 1.10 break;
938 dl 1.1 }
939 dl 1.10 }
940 dl 1.29 if (val == null)
941     throw new NullPointerException();
942 dl 1.27 if (added) {
943     counter.add(1L);
944     if (checkSize)
945     checkForResize();
946     }
947 dl 1.1 return val;
948     }
949    
950 dl 1.27 /** Implementation for putAll */
951     private final void internalPutAll(Map<?, ?> m) {
952     tryPresize(m.size());
953     long delta = 0L; // number of uncommitted additions
954     boolean npe = false; // to throw exception on exit for nulls
955     try { // to clean up counts on other exceptions
956     for (Map.Entry<?, ?> entry : m.entrySet()) {
957     Object k, v;
958     if (entry == null || (k = entry.getKey()) == null ||
959     (v = entry.getValue()) == null) {
960     npe = true;
961     break;
962     }
963     int h = spread(k.hashCode());
964     for (Node[] tab = table;;) {
965     int i; Node f; int fh;
966     if (tab == null)
967     tab = initTable();
968     else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
969     if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
970     ++delta;
971     break;
972     }
973     }
974     else if ((fh = f.hash) == MOVED)
975     tab = (Node[])f.key;
976     else if ((fh & LOCKED) != 0) {
977     counter.add(delta);
978     delta = 0L;
979     checkForResize();
980     f.tryAwaitLock(tab, i);
981     }
982     else if (f.casHash(fh, fh | LOCKED)) {
983     boolean validated = false;
984     boolean tooLong = false;
985     try {
986     if (tabAt(tab, i) == f) {
987     validated = true;
988     for (Node e = f;;) {
989     Object ek, ev;
990     if ((e.hash & HASH_BITS) == h &&
991     (ev = e.val) != null &&
992     ((ek = e.key) == k || k.equals(ek))) {
993     e.val = v;
994     break;
995     }
996     Node last = e;
997     if ((e = e.next) == null) {
998     ++delta;
999     last.next = new Node(h, k, v, null);
1000     break;
1001     }
1002     tooLong = true;
1003     }
1004     }
1005     } finally {
1006     if (!f.casHash(fh | LOCKED, fh)) {
1007     f.hash = fh;
1008 jsr166 1.30 synchronized (f) { f.notifyAll(); };
1009 dl 1.27 }
1010     }
1011     if (validated) {
1012     if (tooLong) {
1013     counter.add(delta);
1014     delta = 0L;
1015     checkForResize();
1016 dl 1.1 }
1017 dl 1.27 break;
1018 dl 1.24 }
1019     }
1020 dl 1.1 }
1021     }
1022 dl 1.27 } finally {
1023     if (delta != 0)
1024     counter.add(delta);
1025 dl 1.1 }
1026 dl 1.27 if (npe)
1027     throw new NullPointerException();
1028 dl 1.1 }
1029    
1030 dl 1.27 /* ---------------- Table Initialization and Resizing -------------- */
1031 dl 1.24
1032     /**
1033     * Returns a power of two table size for the given desired capacity.
1034     * See Hackers Delight, sec 3.2
1035     */
1036     private static final int tableSizeFor(int c) {
1037     int n = c - 1;
1038     n |= n >>> 1;
1039     n |= n >>> 2;
1040     n |= n >>> 4;
1041     n |= n >>> 8;
1042     n |= n >>> 16;
1043     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
1044     }
1045    
1046     /**
1047     * Initializes table, using the size recorded in sizeCtl.
1048     */
1049     private final Node[] initTable() {
1050     Node[] tab; int sc;
1051     while ((tab = table) == null) {
1052     if ((sc = sizeCtl) < 0)
1053     Thread.yield(); // lost initialization race; just spin
1054     else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1055     try {
1056     if ((tab = table) == null) {
1057     int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1058     tab = table = new Node[n];
1059 dl 1.27 sc = n - (n >>> 2);
1060 dl 1.24 }
1061     } finally {
1062     sizeCtl = sc;
1063     }
1064     break;
1065     }
1066     }
1067     return tab;
1068     }
1069    
1070     /**
1071 dl 1.27 * If table is too small and not already resizing, creates next
1072     * table and transfers bins. Rechecks occupancy after a transfer
1073     * to see if another resize is already needed because resizings
1074     * are lagging additions.
1075     */
1076     private final void checkForResize() {
1077     Node[] tab; int n, sc;
1078     while ((tab = table) != null &&
1079     (n = tab.length) < MAXIMUM_CAPACITY &&
1080     (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1081     UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1082 dl 1.24 try {
1083 dl 1.27 if (tab == table) {
1084 dl 1.24 table = rebuild(tab);
1085 dl 1.27 sc = (n << 1) - (n >>> 1);
1086 dl 1.24 }
1087     } finally {
1088     sizeCtl = sc;
1089     }
1090     }
1091     }
1092    
1093 dl 1.27 /**
1094     * Tries to presize table to accommodate the given number of elements.
1095     *
1096     * @param size number of elements (doesn't need to be perfectly accurate)
1097     */
1098     private final void tryPresize(int size) {
1099     int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1100     tableSizeFor(size + (size >>> 1) + 1);
1101     int sc;
1102     while ((sc = sizeCtl) >= 0) {
1103     Node[] tab = table; int n;
1104     if (tab == null || (n = tab.length) == 0) {
1105 jsr166 1.30 n = (sc > c) ? sc : c;
1106 dl 1.27 if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1107     try {
1108     if (table == tab) {
1109     table = new Node[n];
1110     sc = n - (n >>> 2);
1111     }
1112     } finally {
1113     sizeCtl = sc;
1114     }
1115     }
1116     }
1117     else if (c <= sc || n >= MAXIMUM_CAPACITY)
1118     break;
1119     else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1120     try {
1121     if (table == tab) {
1122     table = rebuild(tab);
1123     sc = (n << 1) - (n >>> 1);
1124     }
1125     } finally {
1126     sizeCtl = sc;
1127     }
1128     }
1129     }
1130     }
1131    
1132 dl 1.24 /*
1133     * Moves and/or copies the nodes in each bin to new table. See
1134     * above for explanation.
1135     *
1136     * @return the new table
1137     */
1138     private static final Node[] rebuild(Node[] tab) {
1139     int n = tab.length;
1140     Node[] nextTab = new Node[n << 1];
1141     Node fwd = new Node(MOVED, nextTab, null, null);
1142     int[] buffer = null; // holds bins to revisit; null until needed
1143     Node rev = null; // reverse forwarder; null until needed
1144     int nbuffered = 0; // the number of bins in buffer list
1145     int bufferIndex = 0; // buffer index of current buffered bin
1146     int bin = n - 1; // current non-buffered bin or -1 if none
1147    
1148     for (int i = bin;;) { // start upwards sweep
1149     int fh; Node f;
1150     if ((f = tabAt(tab, i)) == null) {
1151     if (bin >= 0) { // no lock needed (or available)
1152     if (!casTabAt(tab, i, f, fwd))
1153     continue;
1154     }
1155     else { // transiently use a locked forwarding node
1156 jsr166 1.33 Node g = new Node(MOVED|LOCKED, nextTab, null, null);
1157 dl 1.24 if (!casTabAt(tab, i, f, g))
1158     continue;
1159     setTabAt(nextTab, i, null);
1160     setTabAt(nextTab, i + n, null);
1161     setTabAt(tab, i, fwd);
1162     if (!g.casHash(MOVED|LOCKED, MOVED)) {
1163     g.hash = MOVED;
1164 jsr166 1.26 synchronized (g) { g.notifyAll(); }
1165 dl 1.24 }
1166     }
1167     }
1168     else if (((fh = f.hash) & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
1169     boolean validated = false;
1170     try { // split to lo and hi lists; copying as needed
1171     if (tabAt(tab, i) == f) {
1172     validated = true;
1173     Node e = f, lastRun = f;
1174     Node lo = null, hi = null;
1175     int runBit = e.hash & n;
1176     for (Node p = e.next; p != null; p = p.next) {
1177     int b = p.hash & n;
1178     if (b != runBit) {
1179     runBit = b;
1180     lastRun = p;
1181     }
1182     }
1183     if (runBit == 0)
1184     lo = lastRun;
1185     else
1186     hi = lastRun;
1187     for (Node p = e; p != lastRun; p = p.next) {
1188     int ph = p.hash & HASH_BITS;
1189     Object pk = p.key, pv = p.val;
1190     if ((ph & n) == 0)
1191     lo = new Node(ph, pk, pv, lo);
1192     else
1193     hi = new Node(ph, pk, pv, hi);
1194     }
1195     setTabAt(nextTab, i, lo);
1196     setTabAt(nextTab, i + n, hi);
1197     setTabAt(tab, i, fwd);
1198     }
1199     } finally {
1200     if (!f.casHash(fh | LOCKED, fh)) {
1201     f.hash = fh;
1202 jsr166 1.26 synchronized (f) { f.notifyAll(); };
1203 dl 1.24 }
1204     }
1205     if (!validated)
1206     continue;
1207     }
1208     else {
1209     if (buffer == null) // initialize buffer for revisits
1210     buffer = new int[TRANSFER_BUFFER_SIZE];
1211     if (bin < 0 && bufferIndex > 0) {
1212     int j = buffer[--bufferIndex];
1213     buffer[bufferIndex] = i;
1214     i = j; // swap with another bin
1215     continue;
1216     }
1217     if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
1218     f.tryAwaitLock(tab, i);
1219     continue; // no other options -- block
1220     }
1221     if (rev == null) // initialize reverse-forwarder
1222     rev = new Node(MOVED, tab, null, null);
1223     if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
1224     continue; // recheck before adding to list
1225     buffer[nbuffered++] = i;
1226     setTabAt(nextTab, i, rev); // install place-holders
1227     setTabAt(nextTab, i + n, rev);
1228     }
1229    
1230     if (bin > 0)
1231     i = --bin;
1232     else if (buffer != null && nbuffered > 0) {
1233     bin = -1;
1234     i = buffer[bufferIndex = --nbuffered];
1235     }
1236     else
1237     return nextTab;
1238     }
1239     }
1240    
1241 dl 1.27 /**
1242     * Implementation for clear. Steps through each bin, removing all
1243     * nodes.
1244     */
1245     private final void internalClear() {
1246     long delta = 0L; // negative number of deletions
1247     int i = 0;
1248     Node[] tab = table;
1249     while (tab != null && i < tab.length) {
1250     int fh;
1251     Node f = tabAt(tab, i);
1252     if (f == null)
1253     ++i;
1254     else if ((fh = f.hash) == MOVED)
1255     tab = (Node[])f.key;
1256     else if ((fh & LOCKED) != 0) {
1257     counter.add(delta); // opportunistically update count
1258     delta = 0L;
1259     f.tryAwaitLock(tab, i);
1260     }
1261     else if (f.casHash(fh, fh | LOCKED)) {
1262     boolean validated = false;
1263     try {
1264     if (tabAt(tab, i) == f) {
1265     validated = true;
1266     for (Node e = f; e != null; e = e.next) {
1267     if (e.val != null) { // currently always true
1268     e.val = null;
1269     --delta;
1270     }
1271     }
1272     setTabAt(tab, i, null);
1273     }
1274     } finally {
1275     if (!f.casHash(fh | LOCKED, fh)) {
1276     f.hash = fh;
1277 jsr166 1.30 synchronized (f) { f.notifyAll(); };
1278 dl 1.27 }
1279     }
1280     if (validated)
1281     ++i;
1282     }
1283     }
1284     if (delta != 0)
1285     counter.add(delta);
1286     }
1287    
1288    
1289 dl 1.14 /* ----------------Table Traversal -------------- */
1290    
1291 dl 1.1 /**
1292 dl 1.14 * Encapsulates traversal for methods such as containsValue; also
1293     * serves as a base class for other iterators.
1294     *
1295     * At each step, the iterator snapshots the key ("nextKey") and
1296     * value ("nextVal") of a valid node (i.e., one that, at point of
1297 jsr166 1.36 * snapshot, has a non-null user value). Because val fields can
1298 dl 1.14 * change (including to null, indicating deletion), field nextVal
1299     * might not be accurate at point of use, but still maintains the
1300     * weak consistency property of holding a value that was once
1301     * valid.
1302     *
1303     * Internal traversals directly access these fields, as in:
1304 jsr166 1.23 * {@code while (it.next != null) { process(it.nextKey); it.advance(); }}
1305 dl 1.14 *
1306     * Exported iterators (subclasses of ViewIterator) extract key,
1307     * value, or key-value pairs as return values of Iterator.next(),
1308 jsr166 1.17 * and encapsulate the it.next check as hasNext();
1309 dl 1.14 *
1310 dl 1.27 * The iterator visits once each still-valid node that was
1311     * reachable upon iterator construction. It might miss some that
1312     * were added to a bin after the bin was visited, which is OK wrt
1313     * consistency guarantees. Maintaining this property in the face
1314     * of possible ongoing resizes requires a fair amount of
1315     * bookkeeping state that is difficult to optimize away amidst
1316     * volatile accesses. Even so, traversal maintains reasonable
1317     * throughput.
1318 dl 1.14 *
1319     * Normally, iteration proceeds bin-by-bin traversing lists.
1320     * However, if the table has been resized, then all future steps
1321     * must traverse both the bin at the current index as well as at
1322     * (index + baseSize); and so on for further resizings. To
1323     * paranoically cope with potential sharing by users of iterators
1324     * across threads, iteration terminates if a bounds checks fails
1325     * for a table read.
1326     *
1327     * The range-based constructor enables creation of parallel
1328     * range-splitting traversals. (Not yet implemented.)
1329     */
1330     static class InternalIterator {
1331     Node next; // the next entry to use
1332     Node last; // the last entry used
1333     Object nextKey; // cached key field of next
1334     Object nextVal; // cached val field of next
1335     Node[] tab; // current table; updated if resized
1336     int index; // index of bin to use next
1337     int baseIndex; // current index of initial table
1338     final int baseLimit; // index bound for initial table
1339     final int baseSize; // initial table size
1340    
1341     /** Creates iterator for all entries in the table. */
1342     InternalIterator(Node[] tab) {
1343     this.tab = tab;
1344     baseLimit = baseSize = (tab == null) ? 0 : tab.length;
1345     index = baseIndex = 0;
1346     next = null;
1347     advance();
1348     }
1349    
1350     /** Creates iterator for the given range of the table */
1351     InternalIterator(Node[] tab, int lo, int hi) {
1352     this.tab = tab;
1353     baseSize = (tab == null) ? 0 : tab.length;
1354 jsr166 1.15 baseLimit = (hi <= baseSize) ? hi : baseSize;
1355 dl 1.27 index = baseIndex = (lo >= 0) ? lo : 0;
1356 dl 1.14 next = null;
1357     advance();
1358     }
1359    
1360     /** Advances next. See above for explanation. */
1361     final void advance() {
1362     Node e = last = next;
1363     outer: do {
1364 dl 1.24 if (e != null) // advance past used/skipped node
1365 dl 1.1 e = e.next;
1366 dl 1.24 while (e == null) { // get to next non-null bin
1367     Node[] t; int b, i, n; // checks must use locals
1368 dl 1.14 if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
1369     (t = tab) == null || i >= (n = t.length))
1370     break outer;
1371 dl 1.24 else if ((e = tabAt(t, i)) != null && e.hash == MOVED)
1372     tab = (Node[])e.key; // restarts due to null val
1373     else // visit upper slots if present
1374 dl 1.14 index = (i += baseSize) < n ? i : (baseIndex = b + 1);
1375 dl 1.1 }
1376 dl 1.14 nextKey = e.key;
1377 dl 1.24 } while ((nextVal = e.val) == null);// skip deleted or special nodes
1378 dl 1.14 next = e;
1379 dl 1.1 }
1380     }
1381    
1382     /* ---------------- Public operations -------------- */
1383    
1384     /**
1385 dl 1.16 * Creates a new, empty map with the default initial table size (16),
1386 dl 1.1 */
1387 dl 1.16 public ConcurrentHashMapV8() {
1388 dl 1.14 this.counter = new LongAdder();
1389 dl 1.1 }
1390    
1391     /**
1392 dl 1.16 * Creates a new, empty map with an initial table size
1393     * accommodating the specified number of elements without the need
1394     * to dynamically resize.
1395 dl 1.1 *
1396     * @param initialCapacity The implementation performs internal
1397     * sizing to accommodate this many elements.
1398     * @throws IllegalArgumentException if the initial capacity of
1399 jsr166 1.18 * elements is negative
1400 dl 1.1 */
1401 dl 1.16 public ConcurrentHashMapV8(int initialCapacity) {
1402     if (initialCapacity < 0)
1403     throw new IllegalArgumentException();
1404     int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
1405     MAXIMUM_CAPACITY :
1406     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
1407     this.counter = new LongAdder();
1408 dl 1.24 this.sizeCtl = cap;
1409 dl 1.1 }
1410    
1411     /**
1412 dl 1.16 * Creates a new map with the same mappings as the given map.
1413 dl 1.1 *
1414 dl 1.16 * @param m the map
1415 dl 1.1 */
1416 dl 1.16 public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
1417     this.counter = new LongAdder();
1418 dl 1.24 this.sizeCtl = DEFAULT_CAPACITY;
1419 dl 1.27 internalPutAll(m);
1420 dl 1.1 }
1421    
1422     /**
1423 dl 1.16 * Creates a new, empty map with an initial table size based on
1424     * the given number of elements ({@code initialCapacity}) and
1425     * initial table density ({@code loadFactor}).
1426     *
1427     * @param initialCapacity the initial capacity. The implementation
1428     * performs internal sizing to accommodate this many elements,
1429     * given the specified load factor.
1430     * @param loadFactor the load factor (table density) for
1431 jsr166 1.18 * establishing the initial table size
1432 dl 1.16 * @throws IllegalArgumentException if the initial capacity of
1433     * elements is negative or the load factor is nonpositive
1434 jsr166 1.22 *
1435     * @since 1.6
1436 dl 1.1 */
1437 dl 1.16 public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
1438     this(initialCapacity, loadFactor, 1);
1439 dl 1.1 }
1440    
1441     /**
1442 dl 1.16 * Creates a new, empty map with an initial table size based on
1443     * the given number of elements ({@code initialCapacity}), table
1444     * density ({@code loadFactor}), and number of concurrently
1445     * updating threads ({@code concurrencyLevel}).
1446 dl 1.1 *
1447 dl 1.16 * @param initialCapacity the initial capacity. The implementation
1448     * performs internal sizing to accommodate this many elements,
1449     * given the specified load factor.
1450     * @param loadFactor the load factor (table density) for
1451 jsr166 1.18 * establishing the initial table size
1452 dl 1.16 * @param concurrencyLevel the estimated number of concurrently
1453     * updating threads. The implementation may use this value as
1454     * a sizing hint.
1455     * @throws IllegalArgumentException if the initial capacity is
1456     * negative or the load factor or concurrencyLevel are
1457 jsr166 1.18 * nonpositive
1458 dl 1.1 */
1459 dl 1.16 public ConcurrentHashMapV8(int initialCapacity,
1460     float loadFactor, int concurrencyLevel) {
1461     if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
1462     throw new IllegalArgumentException();
1463     if (initialCapacity < concurrencyLevel) // Use at least as many bins
1464     initialCapacity = concurrencyLevel; // as estimated threads
1465     long size = (long)(1.0 + (long)initialCapacity / loadFactor);
1466 jsr166 1.33 int cap = ((size >= (long)MAXIMUM_CAPACITY) ?
1467     MAXIMUM_CAPACITY: tableSizeFor((int)size));
1468 dl 1.16 this.counter = new LongAdder();
1469 dl 1.24 this.sizeCtl = cap;
1470 dl 1.1 }
1471    
1472     /**
1473 dl 1.14 * {@inheritDoc}
1474 dl 1.1 */
1475     public boolean isEmpty() {
1476 dl 1.2 return counter.sum() <= 0L; // ignore transient negative values
1477 dl 1.1 }
1478    
1479     /**
1480 dl 1.14 * {@inheritDoc}
1481 dl 1.1 */
1482     public int size() {
1483     long n = counter.sum();
1484 jsr166 1.15 return ((n < 0L) ? 0 :
1485     (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
1486 dl 1.14 (int)n);
1487 dl 1.1 }
1488    
1489 dl 1.24 final long longSize() { // accurate version of size needed for views
1490     long n = counter.sum();
1491     return (n < 0L) ? 0L : n;
1492     }
1493    
1494 dl 1.1 /**
1495     * Returns the value to which the specified key is mapped,
1496     * or {@code null} if this map contains no mapping for the key.
1497     *
1498     * <p>More formally, if this map contains a mapping from a key
1499     * {@code k} to a value {@code v} such that {@code key.equals(k)},
1500     * then this method returns {@code v}; otherwise it returns
1501     * {@code null}. (There can be at most one such mapping.)
1502     *
1503     * @throws NullPointerException if the specified key is null
1504     */
1505     @SuppressWarnings("unchecked")
1506     public V get(Object key) {
1507     if (key == null)
1508     throw new NullPointerException();
1509     return (V)internalGet(key);
1510     }
1511    
1512     /**
1513     * Tests if the specified object is a key in this table.
1514     *
1515     * @param key possible key
1516     * @return {@code true} if and only if the specified object
1517     * is a key in this table, as determined by the
1518 jsr166 1.18 * {@code equals} method; {@code false} otherwise
1519 dl 1.1 * @throws NullPointerException if the specified key is null
1520     */
1521     public boolean containsKey(Object key) {
1522     if (key == null)
1523     throw new NullPointerException();
1524     return internalGet(key) != null;
1525     }
1526    
1527     /**
1528     * Returns {@code true} if this map maps one or more keys to the
1529 dl 1.14 * specified value. Note: This method may require a full traversal
1530     * of the map, and is much slower than method {@code containsKey}.
1531 dl 1.1 *
1532     * @param value value whose presence in this map is to be tested
1533     * @return {@code true} if this map maps one or more keys to the
1534     * specified value
1535     * @throws NullPointerException if the specified value is null
1536     */
1537     public boolean containsValue(Object value) {
1538     if (value == null)
1539     throw new NullPointerException();
1540 dl 1.14 Object v;
1541     InternalIterator it = new InternalIterator(table);
1542     while (it.next != null) {
1543     if ((v = it.nextVal) == value || value.equals(v))
1544     return true;
1545     it.advance();
1546     }
1547     return false;
1548 dl 1.1 }
1549    
1550     /**
1551     * Legacy method testing if some key maps into the specified value
1552     * in this table. This method is identical in functionality to
1553     * {@link #containsValue}, and exists solely to ensure
1554     * full compatibility with class {@link java.util.Hashtable},
1555     * which supported this method prior to introduction of the
1556     * Java Collections framework.
1557     *
1558     * @param value a value to search for
1559     * @return {@code true} if and only if some key maps to the
1560     * {@code value} argument in this table as
1561     * determined by the {@code equals} method;
1562     * {@code false} otherwise
1563     * @throws NullPointerException if the specified value is null
1564     */
1565     public boolean contains(Object value) {
1566     return containsValue(value);
1567     }
1568    
1569     /**
1570     * Maps the specified key to the specified value in this table.
1571     * Neither the key nor the value can be null.
1572     *
1573     * <p> The value can be retrieved by calling the {@code get} method
1574     * with a key that is equal to the original key.
1575     *
1576     * @param key key with which the specified value is to be associated
1577     * @param value value to be associated with the specified key
1578     * @return the previous value associated with {@code key}, or
1579     * {@code null} if there was no mapping for {@code key}
1580     * @throws NullPointerException if the specified key or value is null
1581     */
1582     @SuppressWarnings("unchecked")
1583     public V put(K key, V value) {
1584     if (key == null || value == null)
1585     throw new NullPointerException();
1586 dl 1.27 return (V)internalPut(key, value);
1587 dl 1.1 }
1588    
1589     /**
1590     * {@inheritDoc}
1591     *
1592     * @return the previous value associated with the specified key,
1593     * or {@code null} if there was no mapping for the key
1594     * @throws NullPointerException if the specified key or value is null
1595     */
1596     @SuppressWarnings("unchecked")
1597     public V putIfAbsent(K key, V value) {
1598     if (key == null || value == null)
1599     throw new NullPointerException();
1600 dl 1.27 return (V)internalPutIfAbsent(key, value);
1601 dl 1.1 }
1602    
1603     /**
1604     * Copies all of the mappings from the specified map to this one.
1605     * These mappings replace any mappings that this map had for any of the
1606     * keys currently in the specified map.
1607     *
1608     * @param m mappings to be stored in this map
1609     */
1610     public void putAll(Map<? extends K, ? extends V> m) {
1611 dl 1.27 internalPutAll(m);
1612 dl 1.1 }
1613    
1614     /**
1615     * If the specified key is not already associated with a value,
1616 dl 1.27 * computes its value using the given mappingFunction and
1617     * enters it into the map. This is equivalent to
1618     * <pre> {@code
1619 jsr166 1.13 * if (map.containsKey(key))
1620     * return map.get(key);
1621     * value = mappingFunction.map(key);
1622 dl 1.27 * map.put(key, value);
1623 jsr166 1.13 * return value;}</pre>
1624 dl 1.1 *
1625 dl 1.27 * except that the action is performed atomically. If the
1626     * function returns {@code null} (in which case a {@code
1627     * NullPointerException} is thrown), or the function itself throws
1628     * an (unchecked) exception, the exception is rethrown to its
1629     * caller, and no mapping is recorded. Some attempted update
1630     * operations on this map by other threads may be blocked while
1631     * computation is in progress, so the computation should be short
1632     * and simple, and must not attempt to update any other mappings
1633     * of this Map. The most appropriate usage is to construct a new
1634     * object serving as an initial mapped value, or memoized result,
1635     * as in:
1636     *
1637 jsr166 1.13 * <pre> {@code
1638 dl 1.5 * map.computeIfAbsent(key, new MappingFunction<K, V>() {
1639 jsr166 1.13 * public V map(K k) { return new Value(f(k)); }});}</pre>
1640 dl 1.1 *
1641     * @param key key with which the specified value is to be associated
1642     * @param mappingFunction the function to compute a value
1643     * @return the current (existing or computed) value associated with
1644 dl 1.27 * the specified key.
1645     * @throws NullPointerException if the specified key, mappingFunction,
1646     * or computed value is null
1647 dl 1.5 * @throws IllegalStateException if the computation detectably
1648     * attempts a recursive update to this map that would
1649 jsr166 1.18 * otherwise never complete
1650 dl 1.1 * @throws RuntimeException or Error if the mappingFunction does so,
1651 jsr166 1.18 * in which case the mapping is left unestablished
1652 dl 1.1 */
1653 dl 1.27 @SuppressWarnings("unchecked")
1654 dl 1.1 public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1655     if (key == null || mappingFunction == null)
1656     throw new NullPointerException();
1657 dl 1.27 return (V)internalComputeIfAbsent(key, mappingFunction);
1658 dl 1.2 }
1659    
1660     /**
1661 dl 1.27 * Computes and enters a new mapping value given a key and
1662     * its current mapped value (or {@code null} if there is no current
1663     * mapping). This is equivalent to
1664 jsr166 1.13 * <pre> {@code
1665 dl 1.27 * map.put(key, remappingFunction.remap(key, map.get(key));
1666     * }</pre>
1667 dl 1.2 *
1668 dl 1.27 * except that the action is performed atomically. If the
1669     * function returns {@code null} (in which case a {@code
1670     * NullPointerException} is thrown), or the function itself throws
1671     * an (unchecked) exception, the exception is rethrown to its
1672     * caller, and current mapping is left unchanged. Some attempted
1673 dl 1.5 * update operations on this map by other threads may be blocked
1674     * while computation is in progress, so the computation should be
1675     * short and simple, and must not attempt to update any other
1676 dl 1.27 * mappings of this Map. For example, to either create or
1677     * append new messages to a value mapping:
1678     *
1679     * <pre> {@code
1680     * Map<Key, String> map = ...;
1681     * final String msg = ...;
1682     * map.compute(key, new RemappingFunction<Key, String>() {
1683     * public String remap(Key k, String v) {
1684 dl 1.28 * return (v == null) ? msg : v + msg;});}}</pre>
1685 dl 1.2 *
1686     * @param key key with which the specified value is to be associated
1687 dl 1.27 * @param remappingFunction the function to compute a value
1688     * @return the new value associated with
1689     * the specified key.
1690     * @throws NullPointerException if the specified key or remappingFunction
1691     * or computed value is null
1692 dl 1.5 * @throws IllegalStateException if the computation detectably
1693     * attempts a recursive update to this map that would
1694 jsr166 1.18 * otherwise never complete
1695 dl 1.29 * @throws RuntimeException or Error if the remappingFunction does so,
1696 jsr166 1.18 * in which case the mapping is unchanged
1697 dl 1.2 */
1698 dl 1.27 @SuppressWarnings("unchecked")
1699     public V compute(K key, RemappingFunction<? super K, V> remappingFunction) {
1700     if (key == null || remappingFunction == null)
1701 dl 1.2 throw new NullPointerException();
1702 dl 1.27 return (V)internalCompute(key, remappingFunction);
1703 dl 1.1 }
1704    
1705     /**
1706     * Removes the key (and its corresponding value) from this map.
1707     * This method does nothing if the key is not in the map.
1708     *
1709     * @param key the key that needs to be removed
1710     * @return the previous value associated with {@code key}, or
1711     * {@code null} if there was no mapping for {@code key}
1712     * @throws NullPointerException if the specified key is null
1713     */
1714     @SuppressWarnings("unchecked")
1715     public V remove(Object key) {
1716     if (key == null)
1717     throw new NullPointerException();
1718 jsr166 1.3 return (V)internalReplace(key, null, null);
1719 dl 1.1 }
1720    
1721     /**
1722     * {@inheritDoc}
1723     *
1724     * @throws NullPointerException if the specified key is null
1725     */
1726     public boolean remove(Object key, Object value) {
1727     if (key == null)
1728     throw new NullPointerException();
1729     if (value == null)
1730     return false;
1731     return internalReplace(key, null, value) != null;
1732     }
1733    
1734     /**
1735     * {@inheritDoc}
1736     *
1737     * @throws NullPointerException if any of the arguments are null
1738     */
1739     public boolean replace(K key, V oldValue, V newValue) {
1740     if (key == null || oldValue == null || newValue == null)
1741     throw new NullPointerException();
1742 jsr166 1.3 return internalReplace(key, newValue, oldValue) != null;
1743 dl 1.1 }
1744    
1745     /**
1746     * {@inheritDoc}
1747     *
1748     * @return the previous value associated with the specified key,
1749     * or {@code null} if there was no mapping for the key
1750     * @throws NullPointerException if the specified key or value is null
1751     */
1752     @SuppressWarnings("unchecked")
1753     public V replace(K key, V value) {
1754     if (key == null || value == null)
1755     throw new NullPointerException();
1756 jsr166 1.3 return (V)internalReplace(key, value, null);
1757 dl 1.1 }
1758    
1759     /**
1760     * Removes all of the mappings from this map.
1761     */
1762     public void clear() {
1763     internalClear();
1764     }
1765    
1766     /**
1767     * Returns a {@link Set} view of the keys contained in this map.
1768     * The set is backed by the map, so changes to the map are
1769     * reflected in the set, and vice-versa. The set supports element
1770     * removal, which removes the corresponding mapping from this map,
1771     * via the {@code Iterator.remove}, {@code Set.remove},
1772     * {@code removeAll}, {@code retainAll}, and {@code clear}
1773     * operations. It does not support the {@code add} or
1774     * {@code addAll} operations.
1775     *
1776     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1777     * that will never throw {@link ConcurrentModificationException},
1778     * and guarantees to traverse elements as they existed upon
1779     * construction of the iterator, and may (but is not guaranteed to)
1780     * reflect any modifications subsequent to construction.
1781     */
1782     public Set<K> keySet() {
1783 dl 1.14 KeySet<K,V> ks = keySet;
1784     return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
1785 dl 1.1 }
1786    
1787     /**
1788     * Returns a {@link Collection} view of the values contained in this map.
1789     * The collection is backed by the map, so changes to the map are
1790     * reflected in the collection, and vice-versa. The collection
1791     * supports element removal, which removes the corresponding
1792     * mapping from this map, via the {@code Iterator.remove},
1793     * {@code Collection.remove}, {@code removeAll},
1794     * {@code retainAll}, and {@code clear} operations. It does not
1795     * support the {@code add} or {@code addAll} operations.
1796     *
1797     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1798     * that will never throw {@link ConcurrentModificationException},
1799     * and guarantees to traverse elements as they existed upon
1800     * construction of the iterator, and may (but is not guaranteed to)
1801     * reflect any modifications subsequent to construction.
1802     */
1803     public Collection<V> values() {
1804 dl 1.14 Values<K,V> vs = values;
1805     return (vs != null) ? vs : (values = new Values<K,V>(this));
1806 dl 1.1 }
1807    
1808     /**
1809     * Returns a {@link Set} view of the mappings contained in this map.
1810     * The set is backed by the map, so changes to the map are
1811     * reflected in the set, and vice-versa. The set supports element
1812     * removal, which removes the corresponding mapping from the map,
1813     * via the {@code Iterator.remove}, {@code Set.remove},
1814     * {@code removeAll}, {@code retainAll}, and {@code clear}
1815     * operations. It does not support the {@code add} or
1816     * {@code addAll} operations.
1817     *
1818     * <p>The view's {@code iterator} is a "weakly consistent" iterator
1819     * that will never throw {@link ConcurrentModificationException},
1820     * and guarantees to traverse elements as they existed upon
1821     * construction of the iterator, and may (but is not guaranteed to)
1822     * reflect any modifications subsequent to construction.
1823     */
1824     public Set<Map.Entry<K,V>> entrySet() {
1825 dl 1.14 EntrySet<K,V> es = entrySet;
1826     return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
1827 dl 1.1 }
1828    
1829     /**
1830     * Returns an enumeration of the keys in this table.
1831     *
1832     * @return an enumeration of the keys in this table
1833     * @see #keySet()
1834     */
1835     public Enumeration<K> keys() {
1836 dl 1.14 return new KeyIterator<K,V>(this);
1837 dl 1.1 }
1838    
1839     /**
1840     * Returns an enumeration of the values in this table.
1841     *
1842     * @return an enumeration of the values in this table
1843     * @see #values()
1844     */
1845     public Enumeration<V> elements() {
1846 dl 1.14 return new ValueIterator<K,V>(this);
1847 dl 1.1 }
1848    
1849     /**
1850 dl 1.2 * Returns the hash code value for this {@link Map}, i.e.,
1851     * the sum of, for each key-value pair in the map,
1852     * {@code key.hashCode() ^ value.hashCode()}.
1853     *
1854     * @return the hash code value for this map
1855 dl 1.1 */
1856     public int hashCode() {
1857 dl 1.14 int h = 0;
1858     InternalIterator it = new InternalIterator(table);
1859     while (it.next != null) {
1860     h += it.nextKey.hashCode() ^ it.nextVal.hashCode();
1861     it.advance();
1862     }
1863     return h;
1864 dl 1.1 }
1865    
1866     /**
1867 dl 1.2 * Returns a string representation of this map. The string
1868     * representation consists of a list of key-value mappings (in no
1869     * particular order) enclosed in braces ("{@code {}}"). Adjacent
1870     * mappings are separated by the characters {@code ", "} (comma
1871     * and space). Each key-value mapping is rendered as the key
1872     * followed by an equals sign ("{@code =}") followed by the
1873     * associated value.
1874     *
1875     * @return a string representation of this map
1876 dl 1.1 */
1877     public String toString() {
1878 dl 1.14 InternalIterator it = new InternalIterator(table);
1879     StringBuilder sb = new StringBuilder();
1880     sb.append('{');
1881     if (it.next != null) {
1882     for (;;) {
1883     Object k = it.nextKey, v = it.nextVal;
1884     sb.append(k == this ? "(this Map)" : k);
1885     sb.append('=');
1886     sb.append(v == this ? "(this Map)" : v);
1887     it.advance();
1888     if (it.next == null)
1889     break;
1890     sb.append(',').append(' ');
1891     }
1892     }
1893     return sb.append('}').toString();
1894 dl 1.1 }
1895    
1896     /**
1897 dl 1.2 * Compares the specified object with this map for equality.
1898     * Returns {@code true} if the given object is a map with the same
1899     * mappings as this map. This operation may return misleading
1900     * results if either map is concurrently modified during execution
1901     * of this method.
1902     *
1903     * @param o object to be compared for equality with this map
1904     * @return {@code true} if the specified object is equal to this map
1905 dl 1.1 */
1906     public boolean equals(Object o) {
1907 dl 1.14 if (o != this) {
1908     if (!(o instanceof Map))
1909     return false;
1910     Map<?,?> m = (Map<?,?>) o;
1911     InternalIterator it = new InternalIterator(table);
1912     while (it.next != null) {
1913     Object val = it.nextVal;
1914     Object v = m.get(it.nextKey);
1915     if (v == null || (v != val && !v.equals(val)))
1916 dl 1.1 return false;
1917 dl 1.14 it.advance();
1918     }
1919 dl 1.1 for (Map.Entry<?,?> e : m.entrySet()) {
1920 dl 1.14 Object mk, mv, v;
1921     if ((mk = e.getKey()) == null ||
1922     (mv = e.getValue()) == null ||
1923     (v = internalGet(mk)) == null ||
1924     (mv != v && !mv.equals(v)))
1925 dl 1.1 return false;
1926     }
1927 dl 1.14 }
1928     return true;
1929     }
1930    
1931     /* ----------------Iterators -------------- */
1932    
1933     /**
1934     * Base class for key, value, and entry iterators. Adds a map
1935     * reference to InternalIterator to support Iterator.remove.
1936     */
1937     static abstract class ViewIterator<K,V> extends InternalIterator {
1938     final ConcurrentHashMapV8<K, V> map;
1939     ViewIterator(ConcurrentHashMapV8<K, V> map) {
1940     super(map.table);
1941     this.map = map;
1942     }
1943    
1944     public final void remove() {
1945     if (last == null)
1946     throw new IllegalStateException();
1947     map.remove(last.key);
1948     last = null;
1949     }
1950    
1951     public final boolean hasNext() { return next != null; }
1952     public final boolean hasMoreElements() { return next != null; }
1953     }
1954    
1955     static final class KeyIterator<K,V> extends ViewIterator<K,V>
1956     implements Iterator<K>, Enumeration<K> {
1957     KeyIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1958    
1959     @SuppressWarnings("unchecked")
1960     public final K next() {
1961     if (next == null)
1962     throw new NoSuchElementException();
1963     Object k = nextKey;
1964     advance();
1965     return (K)k;
1966     }
1967    
1968     public final K nextElement() { return next(); }
1969     }
1970    
1971     static final class ValueIterator<K,V> extends ViewIterator<K,V>
1972     implements Iterator<V>, Enumeration<V> {
1973     ValueIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1974    
1975     @SuppressWarnings("unchecked")
1976     public final V next() {
1977     if (next == null)
1978     throw new NoSuchElementException();
1979     Object v = nextVal;
1980     advance();
1981     return (V)v;
1982     }
1983    
1984     public final V nextElement() { return next(); }
1985     }
1986    
1987     static final class EntryIterator<K,V> extends ViewIterator<K,V>
1988     implements Iterator<Map.Entry<K,V>> {
1989     EntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
1990    
1991     @SuppressWarnings("unchecked")
1992     public final Map.Entry<K,V> next() {
1993     if (next == null)
1994     throw new NoSuchElementException();
1995     Object k = nextKey;
1996     Object v = nextVal;
1997     advance();
1998 dl 1.24 return new WriteThroughEntry<K,V>((K)k, (V)v, map);
1999     }
2000     }
2001    
2002     static final class SnapshotEntryIterator<K,V> extends ViewIterator<K,V>
2003     implements Iterator<Map.Entry<K,V>> {
2004     SnapshotEntryIterator(ConcurrentHashMapV8<K, V> map) { super(map); }
2005    
2006     @SuppressWarnings("unchecked")
2007     public final Map.Entry<K,V> next() {
2008     if (next == null)
2009     throw new NoSuchElementException();
2010     Object k = nextKey;
2011     Object v = nextVal;
2012     advance();
2013     return new SnapshotEntry<K,V>((K)k, (V)v);
2014 dl 1.1 }
2015     }
2016    
2017     /**
2018 dl 1.24 * Base of writeThrough and Snapshot entry classes
2019 dl 1.1 */
2020 dl 1.24 static abstract class MapEntry<K,V> implements Map.Entry<K, V> {
2021 dl 1.14 final K key; // non-null
2022     V val; // non-null
2023 dl 1.24 MapEntry(K key, V val) { this.key = key; this.val = val; }
2024 dl 1.14 public final K getKey() { return key; }
2025     public final V getValue() { return val; }
2026     public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
2027     public final String toString(){ return key + "=" + val; }
2028    
2029     public final boolean equals(Object o) {
2030     Object k, v; Map.Entry<?,?> e;
2031     return ((o instanceof Map.Entry) &&
2032     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2033     (v = e.getValue()) != null &&
2034     (k == key || k.equals(key)) &&
2035     (v == val || v.equals(val)));
2036 dl 1.1 }
2037    
2038 dl 1.24 public abstract V setValue(V value);
2039     }
2040    
2041     /**
2042     * Entry used by EntryIterator.next(), that relays setValue
2043     * changes to the underlying map.
2044     */
2045     static final class WriteThroughEntry<K,V> extends MapEntry<K,V>
2046     implements Map.Entry<K, V> {
2047     final ConcurrentHashMapV8<K, V> map;
2048     WriteThroughEntry(K key, V val, ConcurrentHashMapV8<K, V> map) {
2049     super(key, val);
2050     this.map = map;
2051     }
2052    
2053 dl 1.1 /**
2054     * Sets our entry's value and writes through to the map. The
2055     * value to return is somewhat arbitrary here. Since a
2056     * WriteThroughEntry does not necessarily track asynchronous
2057     * changes, the most recent "previous" value could be
2058     * different from what we return (or could even have been
2059     * removed in which case the put will re-establish). We do not
2060     * and cannot guarantee more.
2061     */
2062 dl 1.14 public final V setValue(V value) {
2063 dl 1.1 if (value == null) throw new NullPointerException();
2064 dl 1.14 V v = val;
2065     val = value;
2066     map.put(key, value);
2067 dl 1.1 return v;
2068     }
2069     }
2070    
2071 dl 1.24 /**
2072     * Internal version of entry, that doesn't write though changes
2073     */
2074     static final class SnapshotEntry<K,V> extends MapEntry<K,V>
2075     implements Map.Entry<K, V> {
2076     SnapshotEntry(K key, V val) { super(key, val); }
2077     public final V setValue(V value) { // only locally update
2078     if (value == null) throw new NullPointerException();
2079     V v = val;
2080     val = value;
2081     return v;
2082     }
2083     }
2084    
2085 dl 1.14 /* ----------------Views -------------- */
2086 dl 1.1
2087 dl 1.24 /**
2088     * Base class for views. This is done mainly to allow adding
2089     * customized parallel traversals (not yet implemented.)
2090 dl 1.14 */
2091 dl 1.24 static abstract class MapView<K, V> {
2092 dl 1.14 final ConcurrentHashMapV8<K, V> map;
2093 dl 1.24 MapView(ConcurrentHashMapV8<K, V> map) { this.map = map; }
2094 dl 1.14 public final int size() { return map.size(); }
2095     public final boolean isEmpty() { return map.isEmpty(); }
2096     public final void clear() { map.clear(); }
2097 dl 1.24
2098     // implementations below rely on concrete classes supplying these
2099     abstract Iterator<?> iter();
2100     abstract public boolean contains(Object o);
2101     abstract public boolean remove(Object o);
2102    
2103     private static final String oomeMsg = "Required array size too large";
2104    
2105     public final Object[] toArray() {
2106     long sz = map.longSize();
2107     if (sz > (long)(MAX_ARRAY_SIZE))
2108     throw new OutOfMemoryError(oomeMsg);
2109     int n = (int)sz;
2110     Object[] r = new Object[n];
2111     int i = 0;
2112     Iterator<?> it = iter();
2113     while (it.hasNext()) {
2114     if (i == n) {
2115     if (n >= MAX_ARRAY_SIZE)
2116     throw new OutOfMemoryError(oomeMsg);
2117     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2118     n = MAX_ARRAY_SIZE;
2119     else
2120     n += (n >>> 1) + 1;
2121     r = Arrays.copyOf(r, n);
2122     }
2123     r[i++] = it.next();
2124     }
2125     return (i == n) ? r : Arrays.copyOf(r, i);
2126     }
2127    
2128     @SuppressWarnings("unchecked")
2129     public final <T> T[] toArray(T[] a) {
2130     long sz = map.longSize();
2131     if (sz > (long)(MAX_ARRAY_SIZE))
2132     throw new OutOfMemoryError(oomeMsg);
2133     int m = (int)sz;
2134     T[] r = (a.length >= m) ? a :
2135     (T[])java.lang.reflect.Array
2136     .newInstance(a.getClass().getComponentType(), m);
2137     int n = r.length;
2138     int i = 0;
2139     Iterator<?> it = iter();
2140     while (it.hasNext()) {
2141     if (i == n) {
2142     if (n >= MAX_ARRAY_SIZE)
2143     throw new OutOfMemoryError(oomeMsg);
2144     if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2145     n = MAX_ARRAY_SIZE;
2146     else
2147     n += (n >>> 1) + 1;
2148     r = Arrays.copyOf(r, n);
2149     }
2150     r[i++] = (T)it.next();
2151     }
2152     if (a == r && i < n) {
2153     r[i] = null; // null-terminate
2154     return r;
2155     }
2156     return (i == n) ? r : Arrays.copyOf(r, i);
2157     }
2158    
2159     public final int hashCode() {
2160     int h = 0;
2161     for (Iterator<?> it = iter(); it.hasNext();)
2162     h += it.next().hashCode();
2163     return h;
2164     }
2165    
2166     public final String toString() {
2167     StringBuilder sb = new StringBuilder();
2168     sb.append('[');
2169     Iterator<?> it = iter();
2170     if (it.hasNext()) {
2171     for (;;) {
2172     Object e = it.next();
2173     sb.append(e == this ? "(this Collection)" : e);
2174     if (!it.hasNext())
2175     break;
2176     sb.append(',').append(' ');
2177     }
2178     }
2179     return sb.append(']').toString();
2180     }
2181    
2182     public final boolean containsAll(Collection<?> c) {
2183     if (c != this) {
2184     for (Iterator<?> it = c.iterator(); it.hasNext();) {
2185     Object e = it.next();
2186     if (e == null || !contains(e))
2187     return false;
2188     }
2189     }
2190     return true;
2191     }
2192    
2193 jsr166 1.32 public final boolean removeAll(Collection<?> c) {
2194 dl 1.24 boolean modified = false;
2195     for (Iterator<?> it = iter(); it.hasNext();) {
2196     if (c.contains(it.next())) {
2197     it.remove();
2198     modified = true;
2199     }
2200     }
2201     return modified;
2202     }
2203    
2204     public final boolean retainAll(Collection<?> c) {
2205     boolean modified = false;
2206     for (Iterator<?> it = iter(); it.hasNext();) {
2207     if (!c.contains(it.next())) {
2208     it.remove();
2209     modified = true;
2210     }
2211     }
2212     return modified;
2213     }
2214    
2215     }
2216    
2217     static final class KeySet<K,V> extends MapView<K,V> implements Set<K> {
2218     KeySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2219 dl 1.14 public final boolean contains(Object o) { return map.containsKey(o); }
2220     public final boolean remove(Object o) { return map.remove(o) != null; }
2221 dl 1.24
2222 dl 1.14 public final Iterator<K> iterator() {
2223     return new KeyIterator<K,V>(map);
2224 dl 1.1 }
2225 dl 1.24 final Iterator<?> iter() {
2226     return new KeyIterator<K,V>(map);
2227     }
2228     public final boolean add(K e) {
2229     throw new UnsupportedOperationException();
2230     }
2231     public final boolean addAll(Collection<? extends K> c) {
2232     throw new UnsupportedOperationException();
2233     }
2234     public boolean equals(Object o) {
2235     Set<?> c;
2236     return ((o instanceof Set) &&
2237     ((c = (Set<?>)o) == this ||
2238     (containsAll(c) && c.containsAll(this))));
2239     }
2240 dl 1.1 }
2241    
2242 dl 1.24 static final class Values<K,V> extends MapView<K,V>
2243 jsr166 1.34 implements Collection<V> {
2244 dl 1.24 Values(ConcurrentHashMapV8<K, V> map) { super(map); }
2245     public final boolean contains(Object o) { return map.containsValue(o); }
2246 dl 1.14
2247 dl 1.24 public final boolean remove(Object o) {
2248     if (o != null) {
2249     Iterator<V> it = new ValueIterator<K,V>(map);
2250     while (it.hasNext()) {
2251     if (o.equals(it.next())) {
2252     it.remove();
2253     return true;
2254     }
2255     }
2256     }
2257     return false;
2258     }
2259 dl 1.14 public final Iterator<V> iterator() {
2260     return new ValueIterator<K,V>(map);
2261 dl 1.1 }
2262 dl 1.24 final Iterator<?> iter() {
2263     return new ValueIterator<K,V>(map);
2264     }
2265     public final boolean add(V e) {
2266     throw new UnsupportedOperationException();
2267     }
2268     public final boolean addAll(Collection<? extends V> c) {
2269     throw new UnsupportedOperationException();
2270     }
2271 dl 1.1 }
2272    
2273 jsr166 1.33 static final class EntrySet<K,V> extends MapView<K,V>
2274 dl 1.24 implements Set<Map.Entry<K,V>> {
2275     EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2276 dl 1.14
2277     public final boolean contains(Object o) {
2278     Object k, v, r; Map.Entry<?,?> e;
2279     return ((o instanceof Map.Entry) &&
2280     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2281     (r = map.get(k)) != null &&
2282     (v = e.getValue()) != null &&
2283     (v == r || v.equals(r)));
2284 dl 1.1 }
2285 dl 1.14
2286     public final boolean remove(Object o) {
2287     Object k, v; Map.Entry<?,?> e;
2288     return ((o instanceof Map.Entry) &&
2289     (k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
2290     (v = e.getValue()) != null &&
2291     map.remove(k, v));
2292 dl 1.1 }
2293 dl 1.24
2294     public final Iterator<Map.Entry<K,V>> iterator() {
2295     return new EntryIterator<K,V>(map);
2296     }
2297     final Iterator<?> iter() {
2298     return new SnapshotEntryIterator<K,V>(map);
2299     }
2300     public final boolean add(Entry<K,V> e) {
2301     throw new UnsupportedOperationException();
2302     }
2303     public final boolean addAll(Collection<? extends Entry<K,V>> c) {
2304     throw new UnsupportedOperationException();
2305     }
2306     public boolean equals(Object o) {
2307     Set<?> c;
2308     return ((o instanceof Set) &&
2309     ((c = (Set<?>)o) == this ||
2310     (containsAll(c) && c.containsAll(this))));
2311     }
2312 dl 1.1 }
2313    
2314     /* ---------------- Serialization Support -------------- */
2315    
2316     /**
2317 dl 1.14 * Stripped-down version of helper class used in previous version,
2318     * declared for the sake of serialization compatibility
2319 dl 1.1 */
2320 dl 1.14 static class Segment<K,V> implements Serializable {
2321 dl 1.1 private static final long serialVersionUID = 2249069246763182397L;
2322     final float loadFactor;
2323     Segment(float lf) { this.loadFactor = lf; }
2324     }
2325    
2326     /**
2327     * Saves the state of the {@code ConcurrentHashMapV8} instance to a
2328     * stream (i.e., serializes it).
2329     * @param s the stream
2330     * @serialData
2331     * the key (Object) and value (Object)
2332     * for each key-value mapping, followed by a null pair.
2333     * The key-value mappings are emitted in no particular order.
2334     */
2335     @SuppressWarnings("unchecked")
2336     private void writeObject(java.io.ObjectOutputStream s)
2337     throws java.io.IOException {
2338     if (segments == null) { // for serialization compatibility
2339     segments = (Segment<K,V>[])
2340     new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
2341     for (int i = 0; i < segments.length; ++i)
2342 dl 1.16 segments[i] = new Segment<K,V>(LOAD_FACTOR);
2343 dl 1.1 }
2344     s.defaultWriteObject();
2345 dl 1.14 InternalIterator it = new InternalIterator(table);
2346     while (it.next != null) {
2347     s.writeObject(it.nextKey);
2348     s.writeObject(it.nextVal);
2349     it.advance();
2350     }
2351 dl 1.1 s.writeObject(null);
2352     s.writeObject(null);
2353     segments = null; // throw away
2354     }
2355    
2356     /**
2357 jsr166 1.9 * Reconstitutes the instance from a stream (that is, deserializes it).
2358 dl 1.1 * @param s the stream
2359     */
2360     @SuppressWarnings("unchecked")
2361     private void readObject(java.io.ObjectInputStream s)
2362     throws java.io.IOException, ClassNotFoundException {
2363     s.defaultReadObject();
2364     this.segments = null; // unneeded
2365 jsr166 1.21 // initialize transient final field
2366 dl 1.14 UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
2367    
2368     // Create all nodes, then place in table once size is known
2369     long size = 0L;
2370     Node p = null;
2371 dl 1.1 for (;;) {
2372 dl 1.14 K k = (K) s.readObject();
2373     V v = (V) s.readObject();
2374     if (k != null && v != null) {
2375     p = new Node(spread(k.hashCode()), k, v, p);
2376     ++size;
2377     }
2378     else
2379 dl 1.1 break;
2380 dl 1.14 }
2381     if (p != null) {
2382     boolean init = false;
2383 dl 1.24 int n;
2384     if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
2385     n = MAXIMUM_CAPACITY;
2386     else {
2387     int sz = (int)size;
2388     n = tableSizeFor(sz + (sz >>> 1) + 1);
2389     }
2390     int sc = sizeCtl;
2391     if (n > sc &&
2392     UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
2393 dl 1.14 try {
2394     if (table == null) {
2395     init = true;
2396     Node[] tab = new Node[n];
2397     int mask = n - 1;
2398     while (p != null) {
2399     int j = p.hash & mask;
2400     Node next = p.next;
2401     p.next = tabAt(tab, j);
2402     setTabAt(tab, j, p);
2403     p = next;
2404     }
2405     table = tab;
2406     counter.add(size);
2407 dl 1.29 sc = n - (n >>> 2);
2408 dl 1.14 }
2409     } finally {
2410 dl 1.24 sizeCtl = sc;
2411 dl 1.14 }
2412     }
2413     if (!init) { // Can only happen if unsafely published.
2414     while (p != null) {
2415 dl 1.27 internalPut(p.key, p.val);
2416 dl 1.14 p = p.next;
2417     }
2418     }
2419 dl 1.1 }
2420     }
2421    
2422     // Unsafe mechanics
2423     private static final sun.misc.Unsafe UNSAFE;
2424     private static final long counterOffset;
2425 dl 1.24 private static final long sizeCtlOffset;
2426 dl 1.1 private static final long ABASE;
2427     private static final int ASHIFT;
2428    
2429     static {
2430     int ss;
2431     try {
2432     UNSAFE = getUnsafe();
2433     Class<?> k = ConcurrentHashMapV8.class;
2434     counterOffset = UNSAFE.objectFieldOffset
2435     (k.getDeclaredField("counter"));
2436 dl 1.24 sizeCtlOffset = UNSAFE.objectFieldOffset
2437     (k.getDeclaredField("sizeCtl"));
2438 dl 1.1 Class<?> sc = Node[].class;
2439     ABASE = UNSAFE.arrayBaseOffset(sc);
2440     ss = UNSAFE.arrayIndexScale(sc);
2441     } catch (Exception e) {
2442     throw new Error(e);
2443     }
2444     if ((ss & (ss-1)) != 0)
2445     throw new Error("data type scale not a power of two");
2446     ASHIFT = 31 - Integer.numberOfLeadingZeros(ss);
2447     }
2448    
2449     /**
2450     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
2451     * Replace with a simple call to Unsafe.getUnsafe when integrating
2452     * into a jdk.
2453     *
2454     * @return a sun.misc.Unsafe
2455     */
2456     private static sun.misc.Unsafe getUnsafe() {
2457     try {
2458     return sun.misc.Unsafe.getUnsafe();
2459     } catch (SecurityException se) {
2460     try {
2461     return java.security.AccessController.doPrivileged
2462     (new java.security
2463     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
2464     public sun.misc.Unsafe run() throws Exception {
2465     java.lang.reflect.Field f = sun.misc
2466     .Unsafe.class.getDeclaredField("theUnsafe");
2467     f.setAccessible(true);
2468     return (sun.misc.Unsafe) f.get(null);
2469     }});
2470     } catch (java.security.PrivilegedActionException e) {
2471     throw new RuntimeException("Could not initialize intrinsics",
2472     e.getCause());
2473     }
2474     }
2475     }
2476    
2477     }