ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
(Generate patch)

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.8 by jsr166, Tue Aug 30 13:49:10 2011 UTC vs.
Revision 1.37 by dl, Sun Mar 4 20:34:27 2012 UTC

# Line 6 | Line 6
6  
7   package jsr166e;
8   import jsr166e.LongAdder;
9 + import java.util.Arrays;
10   import java.util.Map;
11   import java.util.Set;
12   import java.util.Collection;
# Line 19 | Line 20 | import java.util.Enumeration;
20   import java.util.ConcurrentModificationException;
21   import java.util.NoSuchElementException;
22   import java.util.concurrent.ConcurrentMap;
23 + import java.util.concurrent.ThreadLocalRandom;
24 + import java.util.concurrent.locks.LockSupport;
25   import java.io.Serializable;
26  
27   /**
# Line 49 | Line 52 | import java.io.Serializable;
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 < * purposes, but not for program control.
55 > * or estimation purposes, but not for program control.
56   *
57 < * <p> Resizing this or any other kind of hash table is a relatively
58 < * slow operation, so, when possible, it is a good idea to provide
59 < * estimates of expected table sizes in constructors. Also, for
60 < * compatibility with previous versions of this class, constructors
61 < * may optionally specify an expected {@code concurrencyLevel} as an
62 < * additional hint for internal sizing.
57 > * <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 > * 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 > * 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 > * {@code hashCode()} is a sure way to slow down performance of any
76 > * hash table.
77   *
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}
# Line 82 | Line 99 | public class ConcurrentHashMapV8<K, V>
99      private static final long serialVersionUID = 7249069246763182397L;
100  
101      /**
102 <     * A function computing a mapping from the given key to a value,
103 <     * or {@code null} if there is no mapping. This is a place-holder
87 <     * for an upcoming JDK8 interface.
102 >     * A function computing a mapping from the given key to a value.
103 >     * This is a place-holder for an upcoming JDK8 interface.
104       */
105      public static interface MappingFunction<K, V> {
106          /**
107 <         * Returns a value for the given key, or null if there is no
92 <         * mapping. If this function throws an (unchecked) exception,
93 <         * the exception is rethrown to its caller, and no mapping is
94 <         * recorded.  Because this function is invoked within
95 <         * atomicity control, the computation should be short and
96 <         * simple. The most common usage is to construct a new object
97 <         * serving as an initial mapped value.
107 >         * Returns a non-null value for the given key.
108           *
109           * @param key the (non-null) key
110 <         * @return a value, or null if none
110 >         * @return a non-null value
111           */
112          V map(K key);
113      }
114  
115 +    /**
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      /*
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 <     * contention.
138 >     * 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       *
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 <     * work off Object types. All public generic-typed methods relay
146 <     * in/out of these internal methods, supplying casts as needed.
145 >     * 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 >     * 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       *
153       * The table is lazily initialized to a power-of-two size upon the
154 <     * first insertion.  Each bin in the table contains a (typically
155 <     * short) list of Nodes.  Table accesses require volatile/atomic
156 <     * reads, writes, and CASes.  Because there is no other way to
157 <     * arrange this without adding further indirections, we use
158 <     * intrinsics (sun.misc.Unsafe) operations.  The lists of nodes
159 <     * within bins are always accurately traversable under volatile
160 <     * reads, so long as lookups check hash code and non-nullness of
161 <     * key and value before checking key equality. (All valid hash
162 <     * codes are nonnegative. Negative values are reserved for special
163 <     * forwarding nodes; see below.)
164 <     *
165 <     * A bin may be locked during update (insert, delete, and replace)
166 <     * operations.  We do not want to waste the space required to
167 <     * associate a distinct lock object with each bin, so instead use
168 <     * the first node of a bin list itself as a lock, using builtin
169 <     * "synchronized" locks. These save space and we can live with
170 <     * only plain block-structured lock/unlock operations. Using the
171 <     * first node of a list as a lock does not by itself suffice
172 <     * though: When a node is locked, any update must first validate
173 <     * that it is still the first node, and retry if not. (Because new
174 <     * nodes are always appended to lists, once a node is first in a
175 <     * bin, it remains first until deleted or the bin becomes
176 <     * invalidated.)  However, update operations can and usually do
177 <     * still traverse the bin until the point of update, which helps
178 <     * reduce cache misses on retries.  This is a converse of sorts to
179 <     * the lazy locking technique described by Herlihy & Shavit. If
180 <     * there is no existing node during a put operation, then one can
181 <     * be CAS'ed in (without need for lock except in computeIfAbsent);
182 <     * the CAS serves as validation. This is on average the most
183 <     * common case for put operations -- under random hash codes, the
184 <     * distribution of nodes in bins follows a Poisson distribution
185 <     * (see http://en.wikipedia.org/wiki/Poisson_distribution) with a
186 <     * parameter of 0.5 on average under the default loadFactor of
187 <     * 0.75.  The expected number of locks covering different elements
188 <     * (i.e., bins with 2 or more nodes) is approximately 10% at
189 <     * steady state under default settings.  Lock contention
190 <     * probability for two threads accessing arbitrary distinct
191 <     * elements is, roughly, 1 / (8 * #elements).
192 <     *
193 <     * The table is resized when occupancy exceeds a threshold.  Only
194 <     * a single thread performs the resize (using field "resizing", to
195 <     * arrange exclusion), but the table otherwise remains usable for
196 <     * both reads and updates. Resizing proceeds by transferring bins,
197 <     * one by one, from the table to the next table.  Upon transfer,
198 <     * the old table bin contains only a special forwarding node (with
199 <     * negative hash code ("MOVED")) that contains the next table as
154 >     * first insertion.  Each bin in the table contains a list of
155 >     * 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 >     *
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 >     * used as follows:
168 >     *  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 >     * lower bits are zero (and so always have hash field == MOVED).
177 >     *
178 >     * Insertion (via put or its variants) of the first node in an
179 >     * empty bin is performed by just CASing it to the bin.  This is
180 >     * 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 >     * 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 >     *
202 >     * The main disadvantage of per-bin locks is that other update
203 >     * 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 >     * 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 >     *
228 >     * 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. To ensure concurrent
246 <     * readability of traversals, transfers must proceed from the last
247 <     * bin (table.length - 1) up towards the first.  Any traversal
248 <     * starting from the first bin can then arrange to move to the new
249 <     * table for the rest of the traversal without revisiting nodes.
250 <     * This constrains bin transfers to a particular order, and so can
251 <     * block indefinitely waiting for the next lock, and other threads
252 <     * cannot help with the transfer. However, expected stalls are
253 <     * infrequent enough to not warrant the additional overhead and
254 <     * complexity of access and iteration schemes that could admit
255 <     * out-of-order or concurrent bin transfers.
256 <     *
257 <     * A similar traversal scheme (not yet implemented) can apply to
258 <     * partial traversals during partitioned aggregate operations.
259 <     * Also, read-only operations give up if ever forwarded to a null
260 <     * table, which provides support for shutdown-style clearing,
261 <     * which is also not currently implemented.
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 >     *
267 >     * The traversal scheme also applies to partial traversals of
268 >     * 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 >     * These cases attempt to override the initial capacity settings,
279 >     * but harmlessly fail to take effect in cases of races.
280       *
281       * The element count is maintained using a LongAdder, which avoids
282       * contention on updates but can encounter cache thrashing if read
283 <     * too frequently during concurrent updates. To avoid reading so
284 <     * often, resizing is normally attempted only upon adding to a bin
285 <     * already holding two or more nodes. Under the default threshold
286 <     * (0.75), and uniform hash distributions, the probability of this
287 <     * occurring at threshold is around 13%, meaning that only about 1
288 <     * in 8 puts check threshold (and after resizing, many fewer do
289 <     * so). But this approximation has high variance for small table
290 <     * sizes, so we check on any collision for sizes <= 64.  Further,
291 <     * to increase the probability that a resize occurs soon enough, we
292 <     * offset the threshold (see THRESHOLD_OFFSET) by the expected
293 <     * number of puts between checks. This is currently set to 8, in
294 <     * accord with the default load factor. In practice, this is
295 <     * rarely overridden, and in any case is close enough to other
296 <     * plausible values not to waste dynamic probability computation
297 <     * for more precision.
283 >     * too frequently during concurrent access. To avoid reading so
284 >     * 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 >     *
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 >     * 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       */
305  
306      /* ---------------- Constants -------------- */
307  
308      /**
309 <     * The smallest allowed table capacity.  Must be a power of 2, at
310 <     * least 2.
309 >     * The largest possible table capacity.  This value must be
310 >     * exactly 1<<30 to stay within Java array allocation and indexing
311 >     * 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       */
315 <    static final int MINIMUM_CAPACITY = 2;
315 >    private static final int MAXIMUM_CAPACITY = 1 << 30;
316  
317      /**
318 <     * The largest allowed table capacity.  Must be a power of 2, at
319 <     * most 1<<30.
318 >     * The default initial table capacity.  Must be a power of 2
319 >     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
320       */
321 <    static final int MAXIMUM_CAPACITY = 1 << 30;
321 >    private static final int DEFAULT_CAPACITY = 16;
322  
323      /**
324 <     * The default initial table capacity.  Must be a power of 2, at
325 <     * least MINIMUM_CAPACITY and at most MAXIMUM_CAPACITY
324 >     * The largest possible (non-power of two) array size.
325 >     * Needed by toArray and related methods.
326       */
327 <    static final int DEFAULT_CAPACITY = 16;
327 >    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
328  
329      /**
330 <     * The default load factor for this table, used when not otherwise
331 <     * specified in a constructor.
330 >     * The default concurrency level for this table. Unused but
331 >     * defined for compatibility with previous versions of this class.
332       */
333 <    static final float DEFAULT_LOAD_FACTOR = 0.75f;
333 >    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
334  
335      /**
336 <     * The default concurrency level for this table. Unused, but
337 <     * defined for compatibility with previous versions of this class.
336 >     * The load factor for this table. Overrides of this value in
337 >     * constructors affect only the initial table capacity.  The
338 >     * 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       */
342 <    static final int DEFAULT_CONCURRENCY_LEVEL = 16;
342 >    private static final float LOAD_FACTOR = 0.75f;
343  
344      /**
345 <     * The count value to offset thresholds to compensate for checking
346 <     * for resizing only when inserting into bins with two or more
347 <     * elements. See above for explanation.
345 >     * 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 <    static final int THRESHOLD_OFFSET = 8;
349 >    private static final int TRANSFER_BUFFER_SIZE = 32;
350  
351 <    /**
352 <     * Special node hash value indicating to use table in node.key
353 <     * Must be negative.
351 >    /*
352 >     * Encodings for special uses of Node hash fields. See above for
353 >     * explanation.
354       */
355 <    static final int MOVED = -1;
355 >    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
356 >    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 inner
254 <     * classes.
364 >     * Size is always a power of two. Accessed directly by iterators.
365       */
366      transient volatile Node[] table;
367  
368 <    /** The counter maintaining number of elements. */
368 >    /**
369 >     * The counter maintaining number of elements.
370 >     */
371      private transient final LongAdder counter;
372 <    /** Nonzero when table is being initialized or resized. Updated via CAS. */
373 <    private transient volatile int resizing;
374 <    /** The target load factor for the table. */
375 <    private transient float loadFactor;
376 <    /** The next element count value upon which to resize the table. */
377 <    private transient int threshold;
378 <    /** The initial capacity of the table. */
379 <    private transient int initCap;
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 <    transient Set<K> keySet;
384 <    transient Set<Map.Entry<K,V>> entrySet;
385 <    transient Collection<V> values;
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 <    Segment<K,V>[] segments;
388 >    private Segment<K,V>[] segments;
389  
390 <    /**
278 <     * Applies a supplemental hash function to a given hashCode, which
279 <     * defends against poor quality hash functions.  The result must
280 <     * be non-negative, and for reasonable performance must have good
281 <     * avalanche properties; i.e., that each bit of the argument
282 <     * affects each bit (except sign bit) of the result.
283 <     */
284 <    private static final int spread(int h) {
285 <        // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
286 <        h ^= h >>> 16;
287 <        h *= 0x85ebca6b;
288 <        h ^= h >>> 13;
289 <        h *= 0xc2b2ae35;
290 <        return (h >>> 16) ^ (h & 0x7fffffff); // mask out sign bit
291 <    }
390 >    /* ---------------- Nodes -------------- */
391  
392      /**
393       * Key-value entry. Note that this is never exported out as a
394 <     * user-visible Map.Entry.
394 >     * user-visible Map.Entry (see WriteThroughEntry and SnapshotEntry
395 >     * below). Nodes with a hash field of MOVED are special, and do
396 >     * 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       */
402      static final class Node {
403 <        final int hash;
403 >        volatile int hash;
404          final Object key;
405          volatile Object val;
406          volatile Node next;
# Line 306 | Line 411 | public class ConcurrentHashMapV8<K, V>
411              this.val = val;
412              this.next = next;
413          }
414 +
415 +        /** CompareAndSet the hash field */
416 +        final boolean casHash(int cmp, int val) {
417 +            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
418 +        }
419 +
420 +        /** The number of spins before blocking for a lock */
421 +        static final int MAX_SPINS =
422 +            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
423 +
424 +        /**
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 +                int r = ThreadLocalRandom.current().nextInt(); // randomize spins
440 +                int spins = MAX_SPINS, h;
441 +                while (tabAt(tab, i) == this && ((h = hash) & LOCKED) != 0) {
442 +                    if (spins >= 0) {
443 +                        r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
444 +                        if (r >= 0 && --spins == 0)
445 +                            Thread.yield();  // yield before block
446 +                    }
447 +                    else if (casHash(h, h | WAITING)) {
448 +                        synchronized (this) {
449 +                            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 +
466 +        // Unsafe mechanics for casHash
467 +        private static final sun.misc.Unsafe UNSAFE;
468 +        private static final long hashOffset;
469 +
470 +        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  
482 +    /* ---------------- Table element access -------------- */
483 +
484      /*
485       * Volatile access methods are used for table elements as well as
486 <     * elements of in-progress next table while resizing.  Uses in
487 <     * access and update methods are null checked by callers, and
488 <     * implicitly bounds-checked, relying on the invariants that tab
489 <     * arrays have non-zero size, and all indices are masked with
490 <     * (tab.length - 1) which is never negative and always less than
491 <     * length. The "relaxed" non-volatile forms are used only during
492 <     * table initialization. The only other usage is in
493 <     * HashIterator.advance, which performs explicit checks.
486 >     * 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       */
495  
496 <    static final Node tabAt(Node[] tab, int i) { // used in HashIterator
496 >    static final Node tabAt(Node[] tab, int i) { // used by InternalIterator
497          return (Node)UNSAFE.getObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE);
498      }
499  
# Line 332 | Line 505 | public class ConcurrentHashMapV8<K, V>
505          UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
506      }
507  
508 <    private static final Node relaxedTabAt(Node[] tab, int i) {
336 <        return (Node)UNSAFE.getObject(tab, ((long)i<<ASHIFT)+ABASE);
337 <    }
508 >    /* ---------------- Internal access and update methods -------------- */
509  
510 <    private static final void relaxedSetTabAt(Node[] tab, int i, Node v) {
511 <        UNSAFE.putObject(tab, ((long)i<<ASHIFT)+ABASE, v);
510 >    /**
511 >     * Applies a supplemental hash function to a given hashCode, which
512 >     * defends against poor quality hash functions.  The result must
513 >     * 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 >     */
518 >    private static final int spread(int h) {
519 >        // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
520 >        // Despite two multiplies, this is often faster than others
521 >        // with comparable bit-spread properties.
522 >        h ^= h >>> 16;
523 >        h *= 0x85ebca6b;
524 >        h ^= h >>> 13;
525 >        h *= 0xc2b2ae35;
526 >        return ((h >>> 16) ^ h) & HASH_BITS; // mask out top bits
527      }
528  
529 <    /* ---------------- Access and update operations -------------- */
344 <
345 <    /** Implementation for get and containsKey **/
529 >    /** Implementation for get and containsKey */
530      private final Object internalGet(Object k) {
531          int h = spread(k.hashCode());
532 <        Node[] tab = table;
533 <        retry: while (tab != null) {
534 <            Node e = tabAt(tab, (tab.length - 1) & h);
535 <            while (e != null) {
536 <                int eh = e.hash;
353 <                if (eh == h) {
354 <                    Object ek = e.key, ev = e.val;
355 <                    if (ev != null && ek != null && (k == ek || k.equals(ek)))
356 <                        return ev;
357 <                }
358 <                else if (eh < 0) { // bin was moved during resize
359 <                    tab = (Node[])e.key;
532 >        retry: for (Node[] tab = table; tab != null;) {
533 >            Node e; Object ek, ev; int eh;    // locals to read fields once
534 >            for (e = tabAt(tab, (tab.length - 1) & h); e != null; e = e.next) {
535 >                if ((eh = e.hash) == MOVED) {
536 >                    tab = (Node[])e.key;      // restart with new table
537                      continue retry;
538                  }
539 <                e = e.next;
539 >                if ((eh & HASH_BITS) == h && (ev = e.val) != null &&
540 >                    ((ek = e.key) == k || k.equals(ek)))
541 >                    return ev;
542              }
543              break;
544          }
545          return null;
546      }
547  
548 <    /** Implementation for put and putIfAbsent **/
549 <    private final Object internalPut(Object k, Object v, boolean replace) {
548 >    /**
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;  // the previous value or null if none
556 <        Node[] tab = table;
557 <        for (;;) {
558 <            Node e; int i;
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 >                        synchronized (f) { f.notifyAll(); };
602 >                    }
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 >        int h = spread(k.hashCode());
642 >        boolean checkSize = false;
643 >        for (Node[] tab = table;;) {
644 >            int i; Node f; int fh;
645              if (tab == null)
646 <                tab = grow(0);
647 <            else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
646 >                tab = initTable();
647 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
648                  if (casTabAt(tab, i, null, new Node(h, k, v, null)))
649 <                    break;
649 >                    break;                   // no lock when adding to empty bin
650              }
651 <            else if (e.hash < 0)
652 <                tab = (Node[])e.key;
653 <            else {
651 >            else if ((fh = f.hash) == MOVED)
652 >                tab = (Node[])f.key;
653 >            else if ((fh & LOCKED) != 0) {
654 >                checkForResize();
655 >                f.tryAwaitLock(tab, i);
656 >            }
657 >            else if (f.casHash(fh, fh | LOCKED)) {
658 >                Object oldVal = null;
659                  boolean validated = false;
660 <                boolean checkSize = false;
661 <                synchronized (e) {
662 <                    Node first = e;
663 <                    for (;;) {
664 <                        Object ek, ev;
665 <                        if ((ev = e.val) == null)
666 <                            break;
667 <                        if (e.hash == h && (ek = e.key) != null &&
394 <                            (k == ek || k.equals(ek))) {
395 <                            if (tabAt(tab, i) == first) {
396 <                                validated = true;
660 >                try {                        // needed in case equals() throws
661 >                    if (tabAt(tab, i) == f) {
662 >                        validated = true;    // retry if 1st already deleted
663 >                        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                                  oldVal = ev;
669 <                                if (replace)
670 <                                    e.val = v;
669 >                                e.val = v;
670 >                                break;
671                              }
672 <                            break;
673 <                        }
403 <                        Node last = e;
404 <                        if ((e = e.next) == null) {
405 <                            if (tabAt(tab, i) == first) {
406 <                                validated = true;
672 >                            Node last = e;
673 >                            if ((e = e.next) == null) {
674                                  last.next = new Node(h, k, v, null);
675 <                                if (last != first || tab.length <= 64)
675 >                                if (last != f || tab.length <= 64)
676                                      checkSize = true;
677 +                                break;
678                              }
411                            break;
679                          }
680                      }
681 +                } finally {                  // unlock and signal if needed
682 +                    if (!f.casHash(fh | LOCKED, fh)) {
683 +                        f.hash = fh;
684 +                        synchronized (f) { f.notifyAll(); };
685 +                    }
686                  }
687                  if (validated) {
688 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
689 <                        resizing == 0 && counter.sum() >= threshold)
418 <                        grow(0);
688 >                    if (oldVal != null)
689 >                        return oldVal;
690                      break;
691                  }
692              }
693          }
694 <        if (oldVal == null)
695 <            counter.increment();
696 <        return oldVal;
694 >        counter.add(1L);
695 >        if (checkSize)
696 >            checkForResize();
697 >        return null;
698      }
699  
700 <    /**
701 <     * Covers the four public remove/replace methods: Replaces node
430 <     * value with v, conditional upon match of cv if non-null.  If
431 <     * resulting value is null, delete.
432 <     */
433 <    private final Object internalReplace(Object k, Object v, Object cv) {
700 >    /** Implementation for putIfAbsent */
701 >    private final Object internalPutIfAbsent(Object k, Object v) {
702          int h = spread(k.hashCode());
703 <        Object oldVal = null;
704 <        Node e; int i;
705 <        Node[] tab = table;
706 <        while (tab != null &&
707 <               (e = tabAt(tab, i = (tab.length - 1) & h)) != null) {
708 <            if (e.hash < 0)
709 <                tab = (Node[])e.key;
703 >        for (Node[] tab = table;;) {
704 >            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 >            else if ((fh = f.hash) == MOVED)
712 >                tab = (Node[])f.key;
713 >            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
714 >                     ((fk = f.key) == k || k.equals(fk)))
715 >                return fv;
716              else {
717 <                boolean validated = false;
718 <                boolean deleted = false;
719 <                synchronized (e) {
446 <                    Node pred = null;
447 <                    Node first = e;
448 <                    for (;;) {
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 ((ev = e.val) == null)
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 <                        if (e.hash == h && (ek = e.key) != null &&
728 <                            (k == ek || k.equals(ek))) {
729 <                            if (tabAt(tab, i) == first) {
730 <                                validated = true;
731 <                                if (cv == null || cv == ev || cv.equals(ev)) {
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                                      oldVal = ev;
746 <                                    if ((e.val = v) == null) {
747 <                                        deleted = true;
748 <                                        Node en = e.next;
749 <                                        if (pred != null)
750 <                                            pred.next = en;
751 <                                        else
464 <                                            setTabAt(tab, i, en);
465 <                                    }
746 >                                    break;
747 >                                }
748 >                                Node last = e;
749 >                                if ((e = e.next) == null) {
750 >                                    last.next = new Node(h, k, v, null);
751 >                                    break;
752                                  }
753                              }
468                            break;
754                          }
755 <                        pred = e;
755 >                    } finally {
756 >                        if (!f.casHash(fh | LOCKED, fh)) {
757 >                            f.hash = fh;
758 >                            synchronized (f) { f.notifyAll(); };
759 >                        }
760 >                    }
761 >                    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 >                            synchronized (node) { node.notifyAll(); };
796 >                        }
797 >                    }
798 >                }
799 >                if (validated)
800 >                    break;
801 >            }
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 <                            if (tabAt(tab, i) == first)
473 <                                validated = true;
816 >                            checkForResize();
817                              break;
818                          }
819                      }
820                  }
821 <                if (validated) {
822 <                    if (deleted)
823 <                        counter.decrement();
824 <                    break;
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 >                            synchronized (f) { f.notifyAll(); };
850 >                        }
851 >                    }
852 >                    if (validated)
853 >                        break;
854                  }
855              }
856          }
857 <        return oldVal;
857 >        if (val == null)
858 >            throw new NullPointerException();
859 >        counter.add(1L);
860 >        return val;
861      }
862  
863 <    /** Implementation for computeIfAbsent and compute */
863 >    /** Implementation for compute */
864      @SuppressWarnings("unchecked")
865 <    private final V internalCompute(K k,
866 <                                    MappingFunction<? super K, ? extends V> f,
492 <                                    boolean replace) {
865 >    private final Object internalCompute(K k,
866 >                                         RemappingFunction<? super K, V> mf) {
867          int h = spread(k.hashCode());
868 <        V val = null;
868 >        Object val = null;
869          boolean added = false;
870 <        boolean validated = false;
871 <        Node[] tab = table;
872 <        do {
499 <            Node e; int i;
870 >        boolean checkSize = false;
871 >        for (Node[] tab = table;;) {
872 >            Node f; int i, fh;
873              if (tab == null)
874 <                tab = grow(0);
875 <            else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
876 <                Node node = new Node(h, k, null, null);
877 <                synchronized (node) {
878 <                    if (casTabAt(tab, i, null, node)) {
879 <                        validated = true;
880 <                        try {
881 <                            val = f.map(k);
882 <                            if (val != null) {
883 <                                node.val = val;
884 <                                added = true;
885 <                            }
886 <                        } finally {
887 <                            if (!added)
888 <                                setTabAt(tab, i, null);
874 >                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 >                boolean validated = false;
878 >                if (casTabAt(tab, i, null, node)) {
879 >                    validated = true;
880 >                    try {
881 >                        if ((val = mf.remap(k, null)) != null) {
882 >                            node.val = val;
883 >                            added = true;
884 >                        }
885 >                    } finally {
886 >                        if (!added)
887 >                            setTabAt(tab, i, null);
888 >                        if (!node.casHash(fh, h)) {
889 >                            node.hash = h;
890 >                            synchronized (node) { node.notifyAll(); };
891                          }
892                      }
893                  }
894 +                if (validated)
895 +                    break;
896              }
897 <            else if (e.hash < 0)
898 <                tab = (Node[])e.key;
899 <            else if (Thread.holdsLock(e))
900 <                throw new IllegalStateException("Recursive map computation");
901 <            else {
902 <                boolean checkSize = false;
903 <                synchronized (e) {
904 <                    Node first = e;
905 <                    for (;;) {
906 <                        Object ek, ev;
907 <                        if ((ev = e.val) == null)
908 <                            break;
909 <                        if (e.hash == h && (ek = e.key) != null &&
910 <                            (k == ek || k.equals(ek))) {
911 <                            if (tabAt(tab, i) == first) {
912 <                                validated = true;
913 <                                if (replace && (ev = f.map(k)) != null)
914 <                                    e.val = ev;
915 <                                val = (V)ev;
897 >            else if ((fh = f.hash) == MOVED)
898 >                tab = (Node[])f.key;
899 >            else if ((fh & LOCKED) != 0) {
900 >                checkForResize();
901 >                f.tryAwaitLock(tab, i);
902 >            }
903 >            else if (f.casHash(fh, fh | LOCKED)) {
904 >                boolean validated = false;
905 >                try {
906 >                    if (tabAt(tab, i) == f) {
907 >                        validated = true;
908 >                        for (Node e = f;;) {
909 >                            Object ek, ev;
910 >                            if ((e.hash & HASH_BITS) == h &&
911 >                                (ev = e.val) != null &&
912 >                                ((ek = e.key) == k || k.equals(ek))) {
913 >                                val = mf.remap(k, (V)ev);
914 >                                if (val != null)
915 >                                    e.val = val;
916 >                                break;
917                              }
918 <                            break;
919 <                        }
920 <                        Node last = e;
543 <                        if ((e = e.next) == null) {
544 <                            if (tabAt(tab, i) == first) {
545 <                                validated = true;
546 <                                if ((val = f.map(k)) != null) {
918 >                            Node last = e;
919 >                            if ((e = e.next) == null) {
920 >                                if ((val = mf.remap(k, null)) != null) {
921                                      last.next = new Node(h, k, val, null);
922                                      added = true;
923 <                                    if (last != first || tab.length <= 64)
923 >                                    if (last != f || tab.length <= 64)
924                                          checkSize = true;
925                                  }
926 +                                break;
927                              }
553                            break;
928                          }
929                      }
930 +                } finally {
931 +                    if (!f.casHash(fh | LOCKED, fh)) {
932 +                        f.hash = fh;
933 +                        synchronized (f) { f.notifyAll(); };
934 +                    }
935                  }
936 <                if (checkSize && tab.length < MAXIMUM_CAPACITY &&
937 <                    resizing == 0 && counter.sum() >= threshold)
938 <                    grow(0);
939 <            }
940 <        } while (!validated);
941 <        if (added)
942 <            counter.increment();
936 >                if (validated)
937 >                    break;
938 >            }
939 >        }
940 >        if (val == null)
941 >            throw new NullPointerException();
942 >        if (added) {
943 >            counter.add(1L);
944 >            if (checkSize)
945 >                checkForResize();
946 >        }
947          return val;
948      }
949  
950 <    /*
951 <     * Reclassifies nodes in each bin to new table.  Because we are
952 <     * using power-of-two expansion, the elements from each bin must
953 <     * either stay at same index, or move with a power of two
954 <     * offset. We eliminate unnecessary node creation by catching
955 <     * cases where old nodes can be reused because their next fields
956 <     * won't change.  Statistically, at the default threshold, only
957 <     * about one-sixth of them need cloning when a table doubles. The
958 <     * nodes they replace will be garbage collectable as soon as they
959 <     * are no longer referenced by any reader thread that may be in
960 <     * the midst of concurrently traversing table.
961 <     *
579 <     * Transfers are done from the bottom up to preserve iterator
580 <     * traversability. On each step, the old bin is locked,
581 <     * moved/copied, and then replaced with a forwarding node.
582 <     */
583 <    private static final void transfer(Node[] tab, Node[] nextTab) {
584 <        int n = tab.length;
585 <        int mask = nextTab.length - 1;
586 <        Node fwd = new Node(MOVED, nextTab, null, null);
587 <        for (int i = n - 1; i >= 0; --i) {
588 <            for (Node e;;) {
589 <                if ((e = tabAt(tab, i)) == null) {
590 <                    if (casTabAt(tab, i, e, fwd))
591 <                        break;
950 >    /** 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 <                else {
964 <                    boolean validated = false;
965 <                    synchronized (e) {
966 <                        int idx = e.hash & mask;
967 <                        Node lastRun = e;
968 <                        for (Node p = e.next; p != null; p = p.next) {
969 <                            int j = p.hash & mask;
970 <                            if (j != idx) {
971 <                                idx = j;
972 <                                lastRun = p;
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 >                                synchronized (f) { f.notifyAll(); };
1009                              }
1010                          }
1011 <                        if (tabAt(tab, i) == e) {
1012 <                            validated = true;
1013 <                            relaxedSetTabAt(nextTab, idx, lastRun);
1014 <                            for (Node p = e; p != lastRun; p = p.next) {
1015 <                                int h = p.hash;
610 <                                int j = h & mask;
611 <                                Node r = relaxedTabAt(nextTab, j);
612 <                                relaxedSetTabAt(nextTab, j,
613 <                                                new Node(h, p.key, p.val, r));
1011 >                        if (validated) {
1012 >                            if (tooLong) {
1013 >                                counter.add(delta);
1014 >                                delta = 0L;
1015 >                                checkForResize();
1016                              }
1017 <                            setTabAt(tab, i, fwd);
1017 >                            break;
1018                          }
1019                      }
618                    if (validated)
619                        break;
1020                  }
1021              }
1022 +        } finally {
1023 +            if (delta != 0)
1024 +                counter.add(delta);
1025          }
1026 +        if (npe)
1027 +            throw new NullPointerException();
1028      }
1029  
1030 +    /* ---------------- Table Initialization and Resizing -------------- */
1031 +
1032      /**
1033 <     * If not already resizing, initializes or creates next table and
1034 <     * transfers bins. Rechecks occupancy after a transfer to see if
1035 <     * another resize is already needed because resizings are lagging
1036 <     * additions.
1037 <     *
1038 <     * @param sizeHint overridden capacity target (nonzero only from putAll)
1039 <     * @return current table
1040 <     */
1041 <    private final Node[] grow(int sizeHint) {
1042 <        if (resizing == 0 &&
1043 <            UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
1044 <            try {
1045 <                for (;;) {
1046 <                    int cap, n;
1047 <                    Node[] tab = table;
1048 <                    if (tab == null) {
1049 <                        int c = initCap;
1050 <                        if (c < sizeHint)
1051 <                            c = sizeHint;
1052 <                        if (c == DEFAULT_CAPACITY)
1053 <                            cap = c;
1054 <                        else if (c >= MAXIMUM_CAPACITY)
1055 <                            cap = MAXIMUM_CAPACITY;
1056 <                        else {
1057 <                            cap = MINIMUM_CAPACITY;
1058 <                            while (cap < c)
1059 <                                cap <<= 1;
1060 <                        }
1061 <                    }
1062 <                    else if ((n = tab.length) < MAXIMUM_CAPACITY &&
656 <                             (sizeHint <= 0 || n < sizeHint))
657 <                        cap = n << 1;
658 <                    else
659 <                        break;
660 <                    threshold = (int)(cap * loadFactor) - THRESHOLD_OFFSET;
661 <                    Node[] nextTab = new Node[cap];
662 <                    if (tab != null)
663 <                        transfer(tab, nextTab);
664 <                    table = nextTab;
665 <                    if (tab == null || cap >= MAXIMUM_CAPACITY ||
666 <                        (sizeHint > 0 && cap >= sizeHint) ||
667 <                        counter.sum() < threshold)
668 <                        break;
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 >                        sc = n - (n >>> 2);
1060 >                    }
1061 >                } finally {
1062 >                    sizeCtl = sc;
1063                  }
1064 <            } finally {
671 <                resizing = 0;
1064 >                break;
1065              }
1066          }
1067 <        else if (table == null)
675 <            Thread.yield(); // lost initialization race; just spin
676 <        return table;
1067 >        return tab;
1068      }
1069  
1070      /**
1071 <     * Implementation for putAll and constructor with Map
1072 <     * argument. Tries to first override initial capacity or grow
1073 <     * based on map size to pre-allocate table space.
1071 >     * 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 internalPutAll(Map<? extends K, ? extends V> m) {
1077 <        int s = m.size();
1078 <        grow((s >= (MAXIMUM_CAPACITY >>> 1)) ? s : s + (s >>> 1));
1079 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
1080 <            Object k = e.getKey();
1081 <            Object v = e.getValue();
1082 <            if (k == null || v == null)
1083 <                throw new NullPointerException();
1084 <            internalPut(k, v, true);
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 >            try {
1083 >                if (tab == table) {
1084 >                    table = rebuild(tab);
1085 >                    sc = (n << 1) - (n >>> 1);
1086 >                }
1087 >            } finally {
1088 >                sizeCtl = sc;
1089 >            }
1090          }
1091      }
1092  
1093      /**
1094 <     * Implementation for clear. Steps through each bin, removing all nodes.
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 internalClear() {
1099 <        long deletions = 0L;
1100 <        int i = 0;
1101 <        Node[] tab = table;
1102 <        while (tab != null && i < tab.length) {
1103 <            Node e = tabAt(tab, i);
1104 <            if (e == null)
1105 <                ++i;
1106 <            else if (e.hash < 0)
1107 <                tab = (Node[])e.key;
1108 <            else {
1109 <                boolean validated = false;
1110 <                synchronized (e) {
1111 <                    if (tabAt(tab, i) == e) {
1112 <                        validated = true;
1113 <                        do {
715 <                            if (e.val != null) {
716 <                                e.val = null;
717 <                                ++deletions;
718 <                            }
719 <                        } while ((e = e.next) != null);
720 <                        setTabAt(tab, i, null);
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 >                n = (sc > c) ? sc : c;
1106 >                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 <                if (validated) {
1117 <                    ++i;
1118 <                    if (deletions > THRESHOLD_OFFSET) { // bound lag in counts
1119 <                        counter.add(-deletions);
1120 <                        deletions = 0L;
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          }
732        if (deletions != 0L)
733            counter.add(-deletions);
1130      }
1131  
1132 <    /**
1133 <     * Base class for key, value, and entry iterators, plus internal
1134 <     * implementations of public traversal-based methods, to avoid
1135 <     * duplicating traversal code.
1132 >    /*
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 <    class HashIterator {
1139 <        private Node next;          // the next entry to return
1140 <        private Node[] tab;         // current table; updated if resized
1141 <        private Node lastReturned;  // the last entry returned, for remove
1142 <        private Object nextVal;     // cached value of next
1143 <        private int index;          // index of bin to use next
1144 <        private int baseIndex;      // current index of initial table
1145 <        private final int baseSize; // initial table size
1146 <
1147 <        HashIterator() {
1148 <            Node[] t = tab = table;
1149 <            if (t == null)
1150 <                baseSize = 0;
1151 <            else {
1152 <                baseSize = t.length;
1153 <                advance(null);
1154 <            }
1155 <        }
1156 <
1157 <        public final boolean hasNext()         { return next != null; }
1158 <        public final boolean hasMoreElements() { return next != null; }
1159 <
1160 <        /**
1161 <         * Advances next.  Normally, iteration proceeds bin-by-bin
1162 <         * traversing lists.  However, if the table has been resized,
1163 <         * then all future steps must traverse both the bin at the
1164 <         * current index as well as at (index + baseSize); and so on
768 <         * for further resizings. To paranoically cope with potential
769 <         * (improper) sharing of iterators across threads, table reads
770 <         * are bounds-checked.
771 <         */
772 <        final void advance(Node e) {
773 <            for (;;) {
774 <                Node[] t; int i; // for bounds checks
775 <                if (e != null) {
776 <                    Object ek = e.key, ev = e.val;
777 <                    if (ev != null && ek != null) {
778 <                        nextVal = ev;
779 <                        next = e;
780 <                        break;
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 >                    Node g = new Node(MOVED|LOCKED, nextTab, null, null);
1157 >                    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 >                        synchronized (g) { g.notifyAll(); }
1165                      }
782                    e = e.next;
1166                  }
1167 <                else if (baseIndex < baseSize && (t = tab) != null &&
1168 <                         t.length > (i = index) && i >= 0) {
1169 <                    if ((e = tabAt(t, i)) != null && e.hash < 0) {
1170 <                        tab = (Node[])e.key;
1171 <                        e = null;
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 >                        synchronized (f) { f.notifyAll(); };
1203                      }
790                    else if (i + baseSize < t.length)
791                        index += baseSize;    // visit forwarded upper slots
792                    else
793                        index = ++baseIndex;
1204                  }
1205 <                else {
1206 <                    next = null;
1207 <                    break;
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              }
800        }
801
802        final Object nextKey() {
803            Node e = next;
804            if (e == null)
805                throw new NoSuchElementException();
806            Object k = e.key;
807            advance((lastReturned = e).next);
808            return k;
809        }
810
811        final Object nextValue() {
812            Node e = next;
813            if (e == null)
814                throw new NoSuchElementException();
815            Object v = nextVal;
816            advance((lastReturned = e).next);
817            return v;
818        }
819
820        final WriteThroughEntry nextEntry() {
821            Node e = next;
822            if (e == null)
823                throw new NoSuchElementException();
824            WriteThroughEntry entry =
825                new WriteThroughEntry(e.key, nextVal);
826            advance((lastReturned = e).next);
827            return entry;
828        }
1229  
1230 <        public final void remove() {
1231 <            if (lastReturned == null)
1232 <                throw new IllegalStateException();
1233 <            ConcurrentHashMapV8.this.remove(lastReturned.key);
1234 <            lastReturned = null;
835 <        }
836 <
837 <        /** Helper for serialization */
838 <        final void writeEntries(java.io.ObjectOutputStream s)
839 <            throws java.io.IOException {
840 <            Node e;
841 <            while ((e = next) != null) {
842 <                s.writeObject(e.key);
843 <                s.writeObject(nextVal);
844 <                advance(e.next);
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 <        /** Helper for containsValue */
1242 <        final boolean containsVal(Object value) {
1243 <            if (value != null) {
1244 <                Node e;
1245 <                while ((e = next) != null) {
1246 <                    Object v = nextVal;
1247 <                    if (value == v || value.equals(v))
1248 <                        return true;
1249 <                    advance(e.next);
1241 >    /**
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 >                        synchronized (f) { f.notifyAll(); };
1278 >                    }
1279                  }
1280 +                if (validated)
1281 +                    ++i;
1282              }
859            return false;
1283          }
1284 +        if (delta != 0)
1285 +            counter.add(delta);
1286 +    }
1287  
862        /** Helper for Map.hashCode */
863        final int mapHashCode() {
864            int h = 0;
865            Node e;
866            while ((e = next) != null) {
867                h += e.key.hashCode() ^ nextVal.hashCode();
868                advance(e.next);
869            }
870            return h;
871        }
1288  
1289 <        /** Helper for Map.toString */
1290 <        final String mapToString() {
1291 <            Node e = next;
1292 <            if (e == null)
1293 <                return "{}";
1294 <            StringBuilder sb = new StringBuilder();
1295 <            sb.append('{');
1296 <            for (;;) {
1297 <                sb.append(e.key   == this ? "(this Map)" : e.key);
1298 <                sb.append('=');
1299 <                sb.append(nextVal == this ? "(this Map)" : nextVal);
1300 <                advance(e.next);
1301 <                if ((e = next) != null)
1302 <                    sb.append(',').append(' ');
1303 <                else
1304 <                    return sb.append('}').toString();
1305 <            }
1289 >    /* ----------------Table Traversal -------------- */
1290 >
1291 >    /**
1292 >     * 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 >     * snapshot, has a non-null user value). Because val fields can
1298 >     * 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 >     * {@code while (it.next != null) { process(it.nextKey); it.advance(); }}
1305 >     *
1306 >     * Exported iterators (subclasses of ViewIterator) extract key,
1307 >     * value, or key-value pairs as return values of Iterator.next(),
1308 >     * and encapsulate the it.next check as hasNext();
1309 >     *
1310 >     * 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 >     *
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 >            baseLimit = (hi <= baseSize) ? hi : baseSize;
1355 >            index = baseIndex = (lo >= 0) ? lo : 0;
1356 >            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 >                if (e != null)                  // advance past used/skipped node
1365 >                    e = e.next;
1366 >                while (e == null) {             // get to next non-null bin
1367 >                    Node[] t; int b, i, n;      // checks must use locals
1368 >                    if ((b = baseIndex) >= baseLimit || (i = index) < 0 ||
1369 >                        (t = tab) == null || i >= (n = t.length))
1370 >                        break outer;
1371 >                    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 >                        index = (i += baseSize) < n ? i : (baseIndex = b + 1);
1375 >                }
1376 >                nextKey = e.key;
1377 >            } while ((nextVal = e.val) == null);// skip deleted or special nodes
1378 >            next = e;
1379          }
1380      }
1381  
1382      /* ---------------- Public operations -------------- */
1383  
1384      /**
1385 <     * Creates a new, empty map with the specified initial
897 <     * capacity, load factor and concurrency level.
898 <     *
899 <     * @param initialCapacity the initial capacity. The implementation
900 <     * performs internal sizing to accommodate this many elements.
901 <     * @param loadFactor  the load factor threshold, used to control resizing.
902 <     * Resizing may be performed when the average number of elements per
903 <     * bin exceeds this threshold.
904 <     * @param concurrencyLevel the estimated number of concurrently
905 <     * updating threads. The implementation may use this value as
906 <     * a sizing hint.
907 <     * @throws IllegalArgumentException if the initial capacity is
908 <     * negative or the load factor or concurrencyLevel are
909 <     * nonpositive.
1385 >     * Creates a new, empty map with the default initial table size (16),
1386       */
1387 <    public ConcurrentHashMapV8(int initialCapacity,
912 <                             float loadFactor, int concurrencyLevel) {
913 <        if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
914 <            throw new IllegalArgumentException();
915 <        this.initCap = initialCapacity;
916 <        this.loadFactor = loadFactor;
1387 >    public ConcurrentHashMapV8() {
1388          this.counter = new LongAdder();
1389      }
1390  
1391      /**
1392 <     * Creates a new, empty map with the specified initial capacity
1393 <     * and load factor and with the default concurrencyLevel (16).
1392 >     * 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       *
1396       * @param initialCapacity The implementation performs internal
1397       * sizing to accommodate this many elements.
926     * @param loadFactor  the load factor threshold, used to control resizing.
927     * Resizing may be performed when the average number of elements per
928     * bin exceeds this threshold.
1398       * @throws IllegalArgumentException if the initial capacity of
1399 <     * elements is negative or the load factor is nonpositive
931 <     *
932 <     * @since 1.6
1399 >     * elements is negative
1400       */
1401 <    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
1402 <        this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
1401 >    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 >        this.sizeCtl = cap;
1409      }
1410  
1411      /**
1412 <     * Creates a new, empty map with the specified initial capacity,
940 <     * and with default load factor (0.75) and concurrencyLevel (16).
1412 >     * Creates a new map with the same mappings as the given map.
1413       *
1414 <     * @param initialCapacity the initial capacity. The implementation
943 <     * performs internal sizing to accommodate this many elements.
944 <     * @throws IllegalArgumentException if the initial capacity of
945 <     * elements is negative.
1414 >     * @param m the map
1415       */
1416 <    public ConcurrentHashMapV8(int initialCapacity) {
1417 <        this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
1416 >    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
1417 >        this.counter = new LongAdder();
1418 >        this.sizeCtl = DEFAULT_CAPACITY;
1419 >        internalPutAll(m);
1420      }
1421  
1422      /**
1423 <     * Creates a new, empty map with a default initial capacity (16),
1424 <     * load factor (0.75) and concurrencyLevel (16).
1423 >     * 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 >     * establishing the initial table size
1432 >     * @throws IllegalArgumentException if the initial capacity of
1433 >     * elements is negative or the load factor is nonpositive
1434 >     *
1435 >     * @since 1.6
1436       */
1437 <    public ConcurrentHashMapV8() {
1438 <        this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
1437 >    public ConcurrentHashMapV8(int initialCapacity, float loadFactor) {
1438 >        this(initialCapacity, loadFactor, 1);
1439      }
1440  
1441      /**
1442 <     * Creates a new map with the same mappings as the given map.
1443 <     * The map is created with a capacity of 1.5 times the number
1444 <     * of mappings in the given map or 16 (whichever is greater),
1445 <     * and a default load factor (0.75) and concurrencyLevel (16).
1442 >     * 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       *
1447 <     * @param m the map
1447 >     * @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 >     * establishing the initial table size
1452 >     * @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 >     * nonpositive
1458       */
1459 <    public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
1460 <        this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
1461 <        if (m == null)
1462 <            throw new NullPointerException();
1463 <        internalPutAll(m);
1459 >    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 >        int cap = ((size >= (long)MAXIMUM_CAPACITY) ?
1467 >                   MAXIMUM_CAPACITY: tableSizeFor((int)size));
1468 >        this.counter = new LongAdder();
1469 >        this.sizeCtl = cap;
1470      }
1471  
1472      /**
1473 <     * Returns {@code true} if this map contains no key-value mappings.
976 <     *
977 <     * @return {@code true} if this map contains no key-value mappings
1473 >     * {@inheritDoc}
1474       */
1475      public boolean isEmpty() {
1476          return counter.sum() <= 0L; // ignore transient negative values
1477      }
1478  
1479      /**
1480 <     * Returns the number of key-value mappings in this map.  If the
985 <     * map contains more than {@code Integer.MAX_VALUE} elements, returns
986 <     * {@code Integer.MAX_VALUE}.
987 <     *
988 <     * @return the number of key-value mappings in this map
1480 >     * {@inheritDoc}
1481       */
1482      public int size() {
1483          long n = counter.sum();
1484 <        return ((n >>> 31) == 0) ? (int)n : (n < 0L) ? 0 : Integer.MAX_VALUE;
1484 >        return ((n < 0L) ? 0 :
1485 >                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
1486 >                (int)n);
1487 >    }
1488 >
1489 >    final long longSize() { // accurate version of size needed for views
1490 >        long n = counter.sum();
1491 >        return (n < 0L) ? 0L : n;
1492      }
1493  
1494      /**
# Line 1016 | Line 1515 | public class ConcurrentHashMapV8<K, V>
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 <     *         {@code equals} method; {@code false} otherwise.
1518 >     *         {@code equals} method; {@code false} otherwise
1519       * @throws NullPointerException if the specified key is null
1520       */
1521      public boolean containsKey(Object key) {
# Line 1027 | Line 1526 | public class ConcurrentHashMapV8<K, V>
1526  
1527      /**
1528       * Returns {@code true} if this map maps one or more keys to the
1529 <     * specified value. Note: This method requires a full internal
1530 <     * traversal of the hash table, and so is much slower than
1032 <     * method {@code containsKey}.
1529 >     * specified value. Note: This method may require a full traversal
1530 >     * of the map, and is much slower than method {@code containsKey}.
1531       *
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
# Line 1039 | Line 1537 | public class ConcurrentHashMapV8<K, V>
1537      public boolean containsValue(Object value) {
1538          if (value == null)
1539              throw new NullPointerException();
1540 <        return new HashIterator().containsVal(value);
1540 >        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      }
1549  
1550      /**
# Line 1078 | Line 1583 | public class ConcurrentHashMapV8<K, V>
1583      public V put(K key, V value) {
1584          if (key == null || value == null)
1585              throw new NullPointerException();
1586 <        return (V)internalPut(key, value, true);
1586 >        return (V)internalPut(key, value);
1587      }
1588  
1589      /**
# Line 1092 | Line 1597 | public class ConcurrentHashMapV8<K, V>
1597      public V putIfAbsent(K key, V value) {
1598          if (key == null || value == null)
1599              throw new NullPointerException();
1600 <        return (V)internalPut(key, value, false);
1600 >        return (V)internalPutIfAbsent(key, value);
1601      }
1602  
1603      /**
# Line 1103 | Line 1608 | public class ConcurrentHashMapV8<K, V>
1608       * @param m mappings to be stored in this map
1609       */
1610      public void putAll(Map<? extends K, ? extends V> m) {
1106        if (m == null)
1107            throw new NullPointerException();
1611          internalPutAll(m);
1612      }
1613  
1614      /**
1615       * If the specified key is not already associated with a value,
1616 <     * computes its value using the given mappingFunction, and if
1617 <     * non-null, enters it into the map.  This is equivalent to
1618 <     *
1619 <     * <pre>
1620 <     *   if (map.containsKey(key))
1621 <     *       return map.get(key);
1622 <     *   value = mappingFunction.map(key);
1623 <     *   if (value != null)
1624 <     *      map.put(key, value);
1625 <     *   return value;
1626 <     * </pre>
1616 >     * computes its value using the given mappingFunction and
1617 >     * enters it into the map.  This is equivalent to
1618 >     * <pre> {@code
1619 >     * if (map.containsKey(key))
1620 >     *   return map.get(key);
1621 >     * value = mappingFunction.map(key);
1622 >     * map.put(key, value);
1623 >     * return value;}</pre>
1624 >     *
1625 >     * 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 <     * except that the action is performed atomically.  Some attempted
1126 <     * update operations on this map by other threads may be blocked
1127 <     * while computation is in progress, so the computation should be
1128 <     * short and simple, and must not attempt to update any other
1129 <     * mappings of this Map. The most appropriate usage is to
1130 <     * construct a new object serving as an initial mapped value, or
1131 <     * memoized result, as in:
1132 <     * <pre>{@code
1637 >     *  <pre> {@code
1638       * map.computeIfAbsent(key, new MappingFunction<K, V>() {
1639 <     *   public V map(K k) { return new Value(f(k)); }};
1135 <     * }</pre>
1639 >     *   public V map(K k) { return new Value(f(k)); }});}</pre>
1640       *
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 <     *         the specified key, or {@code null} if the computation
1645 <     *         returned {@code null}.
1646 <     * @throws NullPointerException if the specified key or mappingFunction
1143 <     *         is null,
1644 >     *         the specified key.
1645 >     * @throws NullPointerException if the specified key, mappingFunction,
1646 >     *         or computed value is null
1647       * @throws IllegalStateException if the computation detectably
1648       *         attempts a recursive update to this map that would
1649 <     *         otherwise never complete.
1649 >     *         otherwise never complete
1650       * @throws RuntimeException or Error if the mappingFunction does so,
1651 <     *         in which case the mapping is left unestablished.
1651 >     *         in which case the mapping is left unestablished
1652       */
1653 +    @SuppressWarnings("unchecked")
1654      public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1655          if (key == null || mappingFunction == null)
1656              throw new NullPointerException();
1657 <        return internalCompute(key, mappingFunction, false);
1657 >        return (V)internalComputeIfAbsent(key, mappingFunction);
1658      }
1659  
1660      /**
1661 <     * Computes the value associated with the given key using the given
1662 <     * mappingFunction, and if non-null, enters it into the map.  This
1663 <     * is equivalent to
1664 <     *
1665 <     * <pre>
1666 <     *   value = mappingFunction.map(key);
1163 <     *   if (value != null)
1164 <     *      map.put(key, value);
1165 <     *   else
1166 <     *      value = map.get(key);
1167 <     *   return value;
1168 <     * </pre>
1661 >     * 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 >     *  <pre> {@code
1665 >     *  map.put(key, remappingFunction.remap(key, map.get(key));
1666 >     * }</pre>
1667       *
1668 <     * except that the action is performed atomically.  Some attempted
1668 >     * 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       * 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 <     * mappings of this Map.
1676 >     * 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 >     *    return (v == null) ? msg : v + msg;});}}</pre>
1685       *
1686       * @param key key with which the specified value is to be associated
1687 <     * @param mappingFunction the function to compute a value
1688 <     * @return the current value associated with
1689 <     *         the specified key, or {@code null} if the computation
1690 <     *         returned {@code null} and the value was not otherwise present.
1691 <     * @throws NullPointerException if the specified key or mappingFunction
1182 <     *         is null,
1687 >     * @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       * @throws IllegalStateException if the computation detectably
1693       *         attempts a recursive update to this map that would
1694 <     *         otherwise never complete.
1695 <     * @throws RuntimeException or Error if the mappingFunction does so,
1696 <     *         in which case the mapping is unchanged.
1694 >     *         otherwise never complete
1695 >     * @throws RuntimeException or Error if the remappingFunction does so,
1696 >     *         in which case the mapping is unchanged
1697       */
1698 <    public V compute(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1699 <        if (key == null || mappingFunction == null)
1698 >    @SuppressWarnings("unchecked")
1699 >    public V compute(K key, RemappingFunction<? super K, V> remappingFunction) {
1700 >        if (key == null || remappingFunction == null)
1701              throw new NullPointerException();
1702 <        return internalCompute(key, mappingFunction, true);
1702 >        return (V)internalCompute(key, remappingFunction);
1703      }
1704  
1705      /**
# Line 1270 | Line 1780 | public class ConcurrentHashMapV8<K, V>
1780       * reflect any modifications subsequent to construction.
1781       */
1782      public Set<K> keySet() {
1783 <        Set<K> ks = keySet;
1784 <        return (ks != null) ? ks : (keySet = new KeySet());
1783 >        KeySet<K,V> ks = keySet;
1784 >        return (ks != null) ? ks : (keySet = new KeySet<K,V>(this));
1785      }
1786  
1787      /**
# Line 1291 | Line 1801 | public class ConcurrentHashMapV8<K, V>
1801       * reflect any modifications subsequent to construction.
1802       */
1803      public Collection<V> values() {
1804 <        Collection<V> vs = values;
1805 <        return (vs != null) ? vs : (values = new Values());
1804 >        Values<K,V> vs = values;
1805 >        return (vs != null) ? vs : (values = new Values<K,V>(this));
1806      }
1807  
1808      /**
# Line 1312 | Line 1822 | public class ConcurrentHashMapV8<K, V>
1822       * reflect any modifications subsequent to construction.
1823       */
1824      public Set<Map.Entry<K,V>> entrySet() {
1825 <        Set<Map.Entry<K,V>> es = entrySet;
1826 <        return (es != null) ? es : (entrySet = new EntrySet());
1825 >        EntrySet<K,V> es = entrySet;
1826 >        return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
1827      }
1828  
1829      /**
# Line 1323 | Line 1833 | public class ConcurrentHashMapV8<K, V>
1833       * @see #keySet()
1834       */
1835      public Enumeration<K> keys() {
1836 <        return new KeyIterator();
1836 >        return new KeyIterator<K,V>(this);
1837      }
1838  
1839      /**
# Line 1333 | Line 1843 | public class ConcurrentHashMapV8<K, V>
1843       * @see #values()
1844       */
1845      public Enumeration<V> elements() {
1846 <        return new ValueIterator();
1846 >        return new ValueIterator<K,V>(this);
1847      }
1848  
1849      /**
# Line 1344 | Line 1854 | public class ConcurrentHashMapV8<K, V>
1854       * @return the hash code value for this map
1855       */
1856      public int hashCode() {
1857 <        return new HashIterator().mapHashCode();
1857 >        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      }
1865  
1866      /**
# Line 1359 | Line 1875 | public class ConcurrentHashMapV8<K, V>
1875       * @return a string representation of this map
1876       */
1877      public String toString() {
1878 <        return new HashIterator().mapToString();
1878 >        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      }
1895  
1896      /**
# Line 1373 | Line 1904 | public class ConcurrentHashMapV8<K, V>
1904       * @return {@code true} if the specified object is equal to this map
1905       */
1906      public boolean equals(Object o) {
1907 <        if (o == this)
1908 <            return true;
1909 <        if (!(o instanceof Map))
1910 <            return false;
1911 <        Map<?,?> m = (Map<?,?>) o;
1912 <        try {
1913 <            for (Map.Entry<K,V> e : this.entrySet())
1914 <                if (! e.getValue().equals(m.get(e.getKey())))
1907 >        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                      return false;
1917 +                it.advance();
1918 +            }
1919              for (Map.Entry<?,?> e : m.entrySet()) {
1920 <                Object k = e.getKey();
1921 <                Object v = e.getValue();
1922 <                if (k == null || v == null || !v.equals(get(k)))
1920 >                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                      return false;
1926              }
1391            return true;
1392        } catch (ClassCastException unused) {
1393            return false;
1394        } catch (NullPointerException unused) {
1395            return false;
1927          }
1928 +        return true;
1929      }
1930  
1931 +    /* ----------------Iterators -------------- */
1932 +
1933      /**
1934 <     * Custom Entry class used by EntryIterator.next(), that relays
1935 <     * setValue changes to the underlying map.
1934 >     * Base class for key, value, and entry iterators.  Adds a map
1935 >     * reference to InternalIterator to support Iterator.remove.
1936       */
1937 <    final class WriteThroughEntry extends AbstractMap.SimpleEntry<K,V> {
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 <        WriteThroughEntry(Object k, Object v) {
1961 <            super((K)k, (V)v);
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 >            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 >        }
2015 >    }
2016 >
2017 >    /**
2018 >     * Base of writeThrough and Snapshot entry classes
2019 >     */
2020 >    static abstract class MapEntry<K,V> implements Map.Entry<K, V> {
2021 >        final K key; // non-null
2022 >        V val;       // non-null
2023 >        MapEntry(K key, V val)        { this.key = key; this.val = val; }
2024 >        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 >        }
2037 >
2038 >        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          /**
# Line 1415 | Line 2059 | public class ConcurrentHashMapV8<K, V>
2059           * removed in which case the put will re-establish). We do not
2060           * and cannot guarantee more.
2061           */
2062 <        public V setValue(V value) {
2062 >        public final V setValue(V value) {
2063              if (value == null) throw new NullPointerException();
2064 <            V v = super.setValue(value);
2065 <            ConcurrentHashMapV8.this.put(getKey(), value);
2064 >            V v = val;
2065 >            val = value;
2066 >            map.put(key, value);
2067              return v;
2068          }
2069      }
2070  
2071 <    final class KeyIterator extends HashIterator
2072 <        implements Iterator<K>, Enumeration<K> {
2073 <        @SuppressWarnings("unchecked")
2074 <        public final K next()        { return (K)super.nextKey(); }
2075 <        @SuppressWarnings("unchecked")
2076 <        public final K nextElement() { return (K)super.nextKey(); }
2071 >    /**
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 <    final class ValueIterator extends HashIterator
2086 <        implements Iterator<V>, Enumeration<V> {
2087 <        @SuppressWarnings("unchecked")
2088 <        public final V next()        { return (V)super.nextValue(); }
2085 >    /* ----------------Views -------------- */
2086 >
2087 >    /**
2088 >     * Base class for views. This is done mainly to allow adding
2089 >     * customized parallel traversals (not yet implemented.)
2090 >     */
2091 >    static abstract class MapView<K, V> {
2092 >        final ConcurrentHashMapV8<K, V> map;
2093 >        MapView(ConcurrentHashMapV8<K, V> map)  { this.map = map; }
2094 >        public final int size()                 { return map.size(); }
2095 >        public final boolean isEmpty()          { return map.isEmpty(); }
2096 >        public final void clear()               { map.clear(); }
2097 >
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 V nextElement() { return (V)super.nextValue(); }
2130 <    }
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 <    final class EntryIterator extends HashIterator
2160 <        implements Iterator<Entry<K,V>> {
2161 <        public final Map.Entry<K,V> next() { return super.nextEntry(); }
2162 <    }
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 <    final class KeySet extends AbstractSet<K> {
2194 <        public int size() {
2195 <            return ConcurrentHashMapV8.this.size();
2193 >        public final boolean removeAll(Collection<?> c) {
2194 >            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 <        public boolean isEmpty() {
2204 <            return ConcurrentHashMapV8.this.isEmpty();
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 >        public final boolean contains(Object o) { return map.containsKey(o); }
2220 >        public final boolean remove(Object o)   { return map.remove(o) != null; }
2221 >
2222 >        public final Iterator<K> iterator() {
2223 >            return new KeyIterator<K,V>(map);
2224          }
2225 <        public void clear() {
2226 <            ConcurrentHashMapV8.this.clear();
2225 >        final Iterator<?> iter() {
2226 >            return new KeyIterator<K,V>(map);
2227          }
2228 <        public Iterator<K> iterator() {
2229 <            return new KeyIterator();
2228 >        public final boolean add(K e) {
2229 >            throw new UnsupportedOperationException();
2230          }
2231 <        public boolean contains(Object o) {
2232 <            return ConcurrentHashMapV8.this.containsKey(o);
2231 >        public final boolean addAll(Collection<? extends K> c) {
2232 >            throw new UnsupportedOperationException();
2233          }
2234 <        public boolean remove(Object o) {
2235 <            return ConcurrentHashMapV8.this.remove(o) != null;
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      }
2241  
2242 <    final class Values extends AbstractCollection<V> {
2243 <        public int size() {
2244 <            return ConcurrentHashMapV8.this.size();
2242 >    static final class Values<K,V> extends MapView<K,V>
2243 >        implements Collection<V> {
2244 >        Values(ConcurrentHashMapV8<K, V> map)   { super(map); }
2245 >        public final boolean contains(Object o) { return map.containsValue(o); }
2246 >
2247 >        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 <        public boolean isEmpty() {
2260 <            return ConcurrentHashMapV8.this.isEmpty();
2259 >        public final Iterator<V> iterator() {
2260 >            return new ValueIterator<K,V>(map);
2261          }
2262 <        public void clear() {
2263 <            ConcurrentHashMapV8.this.clear();
2262 >        final Iterator<?> iter() {
2263 >            return new ValueIterator<K,V>(map);
2264          }
2265 <        public Iterator<V> iterator() {
2266 <            return new ValueIterator();
2265 >        public final boolean add(V e) {
2266 >            throw new UnsupportedOperationException();
2267          }
2268 <        public boolean contains(Object o) {
2269 <            return ConcurrentHashMapV8.this.containsValue(o);
2268 >        public final boolean addAll(Collection<? extends V> c) {
2269 >            throw new UnsupportedOperationException();
2270          }
2271      }
2272  
2273 <    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
2274 <        public int size() {
2275 <            return ConcurrentHashMapV8.this.size();
2273 >    static final class EntrySet<K,V> extends MapView<K,V>
2274 >        implements Set<Map.Entry<K,V>> {
2275 >        EntrySet(ConcurrentHashMapV8<K, V> map) { super(map); }
2276 >
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          }
2285 <        public boolean isEmpty() {
2286 <            return ConcurrentHashMapV8.this.isEmpty();
2285 >
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          }
2293 <        public void clear() {
2294 <            ConcurrentHashMapV8.this.clear();
2293 >
2294 >        public final Iterator<Map.Entry<K,V>> iterator() {
2295 >            return new EntryIterator<K,V>(map);
2296          }
2297 <        public Iterator<Map.Entry<K,V>> iterator() {
2298 <            return new EntryIterator();
2297 >        final Iterator<?> iter() {
2298 >            return new SnapshotEntryIterator<K,V>(map);
2299          }
2300 <        public boolean contains(Object o) {
2301 <            if (!(o instanceof Map.Entry))
1501 <                return false;
1502 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1503 <            V v = ConcurrentHashMapV8.this.get(e.getKey());
1504 <            return v != null && v.equals(e.getValue());
2300 >        public final boolean add(Entry<K,V> e) {
2301 >            throw new UnsupportedOperationException();
2302          }
2303 <        public boolean remove(Object o) {
2304 <            if (!(o instanceof Map.Entry))
2305 <                return false;
2306 <            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2307 <            return ConcurrentHashMapV8.this.remove(e.getKey(), e.getValue());
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      }
2313  
2314      /* ---------------- Serialization Support -------------- */
2315  
2316      /**
2317 <     * Helper class used in previous version, declared for the sake of
2318 <     * serialization compatibility
2317 >     * Stripped-down version of helper class used in previous version,
2318 >     * declared for the sake of serialization compatibility
2319       */
2320 <    static class Segment<K,V> extends java.util.concurrent.locks.ReentrantLock
1521 <        implements Serializable {
2320 >    static class Segment<K,V> implements Serializable {
2321          private static final long serialVersionUID = 2249069246763182397L;
2322          final float loadFactor;
2323          Segment(float lf) { this.loadFactor = lf; }
# Line 1540 | Line 2339 | public class ConcurrentHashMapV8<K, V>
2339              segments = (Segment<K,V>[])
2340                  new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
2341              for (int i = 0; i < segments.length; ++i)
2342 <                segments[i] = new Segment<K,V>(loadFactor);
2342 >                segments[i] = new Segment<K,V>(LOAD_FACTOR);
2343          }
2344          s.defaultWriteObject();
2345 <        new HashIterator().writeEntries(s);
2345 >        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          s.writeObject(null);
2352          s.writeObject(null);
2353          segments = null; // throw away
2354      }
2355  
2356      /**
2357 <     * Reconstitutes the  instance from a
1554 <     * stream (i.e., deserializes it).
2357 >     * Reconstitutes the instance from a stream (that is, deserializes it).
2358       * @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();
1561        // find load factor in a segment, if one exists
1562        if (segments != null && segments.length != 0)
1563            this.loadFactor = segments[0].loadFactor;
1564        else
1565            this.loadFactor = DEFAULT_LOAD_FACTOR;
1566        this.initCap = DEFAULT_CAPACITY;
1567        LongAdder ct = new LongAdder(); // force final field write
1568        UNSAFE.putObjectVolatile(this, counterOffset, ct);
2364          this.segments = null; // unneeded
2365 +        // initialize transient final field
2366 +        UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
2367  
2368 <        // Read the keys and values, and put the mappings in the table
2368 >        // Create all nodes, then place in table once size is known
2369 >        long size = 0L;
2370 >        Node p = null;
2371          for (;;) {
2372 <            K key = (K) s.readObject();
2373 <            V value = (V) s.readObject();
2374 <            if (key == null)
2372 >            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                  break;
2380 <            put(key, value);
2380 >        }
2381 >        if (p != null) {
2382 >            boolean init = false;
2383 >            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 >                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 >                        sc = n - (n >>> 2);
2408 >                    }
2409 >                } finally {
2410 >                    sizeCtl = sc;
2411 >                }
2412 >            }
2413 >            if (!init) { // Can only happen if unsafely published.
2414 >                while (p != null) {
2415 >                    internalPut(p.key, p.val);
2416 >                    p = p.next;
2417 >                }
2418 >            }
2419          }
2420      }
2421  
2422      // Unsafe mechanics
2423      private static final sun.misc.Unsafe UNSAFE;
2424      private static final long counterOffset;
2425 <    private static final long resizingOffset;
2425 >    private static final long sizeCtlOffset;
2426      private static final long ABASE;
2427      private static final int ASHIFT;
2428  
# Line 1592 | Line 2433 | public class ConcurrentHashMapV8<K, V>
2433              Class<?> k = ConcurrentHashMapV8.class;
2434              counterOffset = UNSAFE.objectFieldOffset
2435                  (k.getDeclaredField("counter"));
2436 <            resizingOffset = UNSAFE.objectFieldOffset
2437 <                (k.getDeclaredField("resizing"));
2436 >            sizeCtlOffset = UNSAFE.objectFieldOffset
2437 >                (k.getDeclaredField("sizeCtl"));
2438              Class<?> sc = Node[].class;
2439              ABASE = UNSAFE.arrayBaseOffset(sc);
2440              ss = UNSAFE.arrayIndexScale(sc);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines