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.14 by dl, Tue Sep 6 00:26:27 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
# Line 116 | Line 145 | public class ConcurrentHashMapV8<K, V>
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.
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 list of
155 <     * Nodes (most often, zero or one Node).  Table accesses require
156 <     * volatile/atomic reads, writes, and CASes.  Because there is no
157 <     * other way to arrange this without adding further indirections,
158 <     * we use intrinsics (sun.misc.Unsafe) operations.  The lists of
159 <     * nodes within bins are always accurately traversable under
160 <     * volatile reads, so long as lookups check hash code and
161 <     * non-nullness of value before checking key equality. (All valid
162 <     * hash codes are nonnegative. Negative values are reserved for
163 <     * special forwarding nodes; see below.)
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 putIfAbsent) of the first node in an
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 <     * on average by far the most common case for put operations.
181 <     * Other update operations (insert, delete, and replace) require
182 <     * locks.  We do not want to waste the space required to associate
183 <     * a distinct lock object with each bin, so instead use the first
184 <     * node of a bin list itself as a lock, using plain "synchronized"
185 <     * locks. These save space and we can live with block-structured
186 <     * lock/unlock operations. Using the first node of a list as a
187 <     * lock does not by itself suffice though: When a node is locked,
188 <     * any update must first validate that it is still the first node,
189 <     * and retry if not. Because new nodes are always appended to
190 <     * lists, once a node is first in a bin, it remains first until
191 <     * deleted or the bin becomes invalidated.  However, operations
192 <     * that only conditionally update can and sometimes do inspect
193 <     * nodes until the point of update. This is a converse of sorts to
194 <     * the lazy locking technique described by Herlihy & Shavit.
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 this approach is that most update
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
# Line 156 | Line 207 | public class ConcurrentHashMapV8<K, V>
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 0.5 on average under the default loadFactor of
211 <     * 0.75. The expected number of locks covering different elements
212 <     * (i.e., bins with 2 or more nodes) is approximately 10% at
213 <     * steady state.  Lock contention probability for two threads
214 <     * accessing distinct elements is roughly 1 / (8 * #elements).
215 <     * Function "spread" performs hashCode randomization that improves
216 <     * the likelihood that these assumptions hold unless users define
217 <     * exactly the same value for too many hashCodes.
218 <     *
219 <     * The table is resized when occupancy exceeds a threshold.  Only
220 <     * a single thread performs the resize (using field "resizing", to
221 <     * arrange exclusion), but the table otherwise remains usable for
222 <     * reads and updates. Resizing proceeds by transferring bins, one
223 <     * by one, from the table to the next table.  Upon transfer, the
224 <     * old table bin contains only a special forwarding node (with
225 <     * negative hash field) that contains the next table as its
226 <     * key. On encountering a forwarding node, access and update
227 <     * operations restart, using the new table. To ensure concurrent
228 <     * readability of traversals, transfers must proceed from the last
229 <     * bin (table.length - 1) up towards the first.  Upon seeing a
230 <     * forwarding node, traversals (see class InternalIterator)
231 <     * arrange to move to the new table for the rest of the traversal
232 <     * without revisiting nodes.  This constrains bin transfers to a
233 <     * particular order, and so can block indefinitely waiting for the
234 <     * next lock, and other threads cannot help with the transfer.
235 <     * However, expected stalls are infrequent enough to not warrant
236 <     * the additional overhead of access and iteration schemes that
237 <     * could admit out-of-order or concurrent bin transfers.
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.
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 <     * This traversal scheme also applies to partial traversals of
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
# Line 196 | Line 275 | public class ConcurrentHashMapV8<K, V>
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 targetCapacity used in
279 <     * growTable (which may harmlessly fail to take effect in cases of
201 <     * races with other ongoing resizings).
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 access. 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 load
286 <     * factor 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,
292 <     * we 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 default
217 <     * is rarely overridden, and in any case is close enough to other
218 <     * plausible values not to waste dynamic probability computation
219 <     * for the sake of more precision.
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 also declare an unused "Segment" class
300 <     * that is instantiated in minimal form only when serializing.
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 largest allowed table capacity.  Must be a power of 2, at
310 <     * most 1<<30 to stay within Java array size limits.
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      private static final int MAXIMUM_CAPACITY = 1 << 30;
316  
# Line 240 | Line 321 | public class ConcurrentHashMapV8<K, V>
321      private static final int DEFAULT_CAPACITY = 16;
322  
323      /**
324 <     * The default load factor for this table, used when not otherwise
325 <     * specified in a constructor.
324 >     * The largest possible (non-power of two) array size.
325 >     * Needed by toArray and related methods.
326       */
327 <    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
327 >    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
328  
329      /**
330 <     * The default concurrency level for this table. Unused, but
330 >     * The default concurrency level for this table. Unused but
331       * defined for compatibility with previous versions of this class.
332       */
333      private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
334  
335      /**
336 <     * The count value to offset thresholds to compensate for checking
337 <     * for the need to resize only when inserting into bins with two
338 <     * or more elements. See above for explanation.
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 <    private static final int THRESHOLD_OFFSET = 8;
260 <
261 <    /* ---------------- Nodes -------------- */
342 >    private static final float LOAD_FACTOR = 0.75f;
343  
344      /**
345 <     * Key-value entry. Note that this is never exported out as a
346 <     * user-visible Map.Entry. Nodes with a negative hash field are
347 <     * special, and do not contain user keys or values.  Otherwise,
267 <     * keys are never null, and null val fields indicate that a node
268 <     * is in the process of being deleted or created. For purposes of
269 <     * read-only, access, a key may be read before a val, but can only
270 <     * be used after checking val.  (For an update operation, when a
271 <     * lock is held on a node, order doesn't matter.)
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 class Node {
274 <        final int hash;
275 <        final Object key;
276 <        volatile Object val;
277 <        volatile Node next;
349 >    private static final int TRANSFER_BUFFER_SIZE = 32;
350  
351 <        Node(int hash, Object key, Object val, Node next) {
352 <            this.hash = hash;
353 <            this.key = key;
282 <            this.val = val;
283 <            this.next = next;
284 <        }
285 <    }
286 <
287 <    /**
288 <     * Sign bit of node hash value indicating to use table in node.key.
351 >    /*
352 >     * Encodings for special uses of Node hash fields. See above for
353 >     * explanation.
354       */
355 <    private static final int SIGN_BIT = 0x80000000;
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  
# Line 297 | Line 365 | public class ConcurrentHashMapV8<K, V>
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 next element count value upon which to resize the table. */
375 <    private transient int threshold;
376 <    /** The target capacity; volatile to cover initialization races. */
377 <    private transient volatile int targetCapacity;
378 <    /** The target load factor for the table */
379 <    private transient final float loadFactor;
372 >
373 >    /**
374 >     * Table initialization and resizing control.  When negative, the
375 >     * table is being initialized or resized. Otherwise, when table is
376 >     * null, holds the initial table size to use upon creation, or 0
377 >     * for default. After initialization, holds the next element count
378 >     * value upon which to resize the table.
379 >     */
380 >    private transient volatile int sizeCtl;
381  
382      // views
383      private transient KeySet<K,V> keySet;
# Line 316 | Line 387 | public class ConcurrentHashMapV8<K, V>
387      /** For serialization compatibility. Null unless serialized; see below */
388      private Segment<K,V>[] segments;
389  
390 +    /* ---------------- Nodes -------------- */
391 +
392 +    /**
393 +     * Key-value entry. Note that this is never exported out as a
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 +        volatile int hash;
404 +        final Object key;
405 +        volatile Object val;
406 +        volatile Node next;
407 +
408 +        Node(int hash, Object key, Object val, Node next) {
409 +            this.hash = hash;
410 +            this.key = key;
411 +            this.val = val;
412 +            this.next = next;
413 +        }
414 +
415 +        /** 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      /*
# Line 342 | Line 505 | public class ConcurrentHashMapV8<K, V>
505          UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
506      }
507  
345    /* ----------------Table Initialization and Resizing -------------- */
346
347    /**
348     * Returns a power of two table size for the given desired capacity.
349     * See Hackers Delight, sec 3.2
350     */
351    private static final int tableSizeFor(int c) {
352        int n = c - 1;
353        n |= n >>> 1;
354        n |= n >>> 2;
355        n |= n >>> 4;
356        n |= n >>> 8;
357        n |= n >>> 16;
358        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
359    }
360
361    /**
362     * If not already resizing, initializes or creates next table and
363     * transfers bins. Initial table size uses the capacity recorded
364     * in targetCapacity.  Rechecks occupancy after a transfer to see
365     * if another resize is already needed because resizings are
366     * lagging additions.
367     *
368     * @return current table
369     */
370    private final Node[] growTable() {
371        if (resizing == 0 &&
372            UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
373            try {
374                for (;;) {
375                    Node[] tab = table;
376                    int n, c;
377                    if (tab == null)
378                        n = (c = targetCapacity) > 0 ? c : DEFAULT_CAPACITY;
379                    else if ((n = tab.length) < MAXIMUM_CAPACITY &&
380                             counter.sum() >= threshold)
381                        n <<= 1;
382                    else
383                        break;
384                    Node[] nextTab = new Node[n];
385                    threshold = (int)(n * loadFactor) - THRESHOLD_OFFSET;
386                    if (tab != null)
387                        transfer(tab, nextTab,
388                                 new Node(SIGN_BIT, nextTab, null, null));
389                    table = nextTab;
390                    if (tab == null)
391                        break;
392                }
393            } finally {
394                resizing = 0;
395            }
396        }
397        else if (table == null)
398            Thread.yield(); // lost initialization race; just spin
399        return table;
400    }
401
402    /*
403     * Reclassifies nodes in each bin to new table.  Because we are
404     * using power-of-two expansion, the elements from each bin must
405     * either stay at same index, or move with a power of two
406     * offset. We eliminate unnecessary node creation by catching
407     * cases where old nodes can be reused because their next fields
408     * won't change.  Statistically, at the default loadFactor, only
409     * about one-sixth of them need cloning when a table doubles. The
410     * nodes they replace will be garbage collectable as soon as they
411     * are no longer referenced by any reader thread that may be in
412     * the midst of concurrently traversing table.
413     *
414     * Transfers are done from the bottom up to preserve iterator
415     * traversability. On each step, the old bin is locked,
416     * moved/copied, and then replaced with a forwarding node.
417     */
418    private static final void transfer(Node[] tab, Node[] nextTab, Node fwd) {
419        int n = tab.length;
420        Node ignore = nextTab[n + n - 1]; // force bounds check
421        for (int i = n - 1; i >= 0; --i) {
422            for (Node e;;) {
423                if ((e = tabAt(tab, i)) != null) {
424                    boolean validated = false;
425                    synchronized (e) {
426                        if (tabAt(tab, i) == e) {
427                            validated = true;
428                            Node lo = null, hi = null, lastRun = e;
429                            int runBit = e.hash & n;
430                            for (Node p = e.next; p != null; p = p.next) {
431                                int b = p.hash & n;
432                                if (b != runBit) {
433                                    runBit = b;
434                                    lastRun = p;
435                                }
436                            }
437                            if (runBit == 0)
438                                lo = lastRun;
439                            else
440                                hi = lastRun;
441                            for (Node p = e; p != lastRun; p = p.next) {
442                                int ph = p.hash;
443                                Object pk = p.key, pv = p.val;
444                                if ((ph & n) == 0)
445                                    lo = new Node(ph, pk, pv, lo);
446                                else
447                                    hi = new Node(ph, pk, pv, hi);
448                            }
449                            setTabAt(nextTab, i, lo);
450                            setTabAt(nextTab, i + n, hi);
451                            setTabAt(tab, i, fwd);
452                        }
453                    }
454                    if (validated)
455                        break;
456                }
457                else if (casTabAt(tab, i, e, fwd))
458                    break;
459            }
460        }
461    }
462
508      /* ---------------- Internal access and update methods -------------- */
509  
510      /**
511       * Applies a supplemental hash function to a given hashCode, which
512       * defends against poor quality hash functions.  The result must
513 <     * be non-negative, and for reasonable performance must have good
514 <     * avalanche properties; i.e., that each bit of the argument
515 <     * affects each bit (except sign bit) of the result.
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 & 0x7fffffff); // mask out sign bit
526 >        return ((h >>> 16) ^ h) & HASH_BITS; // mask out top bits
527      }
528  
529      /** Implementation for get and containsKey */
530      private final Object internalGet(Object k) {
531          int h = spread(k.hashCode());
532          retry: for (Node[] tab = table; tab != null;) {
533 <            Node e; Object ek, ev; int eh;  // locals to read fields once
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) == h) {
536 <                    if ((ev = e.val) != null &&
489 <                        ((ek = e.key) == k || k.equals(ek)))
490 <                        return ev;
491 <                }
492 <                else if (eh < 0) {          // sign bit set
493 <                    tab = (Node[])e.key;    // bin was moved during resize
535 >                if ((eh = e.hash) == MOVED) {
536 >                    tab = (Node[])e.key;      // restart with new table
537                      continue retry;
538                  }
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;               // previous value or null if none
555 >        Object oldVal = null;
556          for (Node[] tab = table;;) {
557 <            Node e; int i; Object ek, ev;
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 = growTable();
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;                   // no lock when adding to empty bin
650              }
651 <            else if (e.hash < 0)             // resized -- restart with new table
652 <                tab = (Node[])e.key;
653 <            else if (!replace && e.hash == h && (ev = e.val) != null &&
654 <                     ((ek = e.key) == k || k.equals(ek))) {
655 <                if (tabAt(tab, i) == e) {    // inspect and validate 1st node
519 <                    oldVal = ev;             // without lock for putIfAbsent
520 <                    break;
521 <                }
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 {
657 >            else if (f.casHash(fh, fh | LOCKED)) {
658 >                Object oldVal = null;
659                  boolean validated = false;
660 <                boolean checkSize = false;
661 <                synchronized (e) {           // lock the 1st node of bin list
527 <                    if (tabAt(tab, i) == e) {
660 >                try {                        // needed in case equals() throws
661 >                    if (tabAt(tab, i) == f) {
662                          validated = true;    // retry if 1st already deleted
663 <                        for (Node first = e;;) {
664 <                            if (e.hash == h &&
665 <                                ((ek = e.key) == k || k.equals(ek)) &&
666 <                                (ev = e.val) != null) {
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)
535 <                                    e.val = v;
669 >                                e.val = v;
670                                  break;
671                              }
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                              }
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)
551 <                        growTable();
688 >                    if (oldVal != null)
689 >                        return oldVal;
690                      break;
691                  }
692              }
693          }
694 <        if (oldVal == null)
695 <            counter.increment();             // update counter outside of locks
696 <        return oldVal;
694 >        counter.add(1L);
695 >        if (checkSize)
696 >            checkForResize();
697 >        return null;
698      }
699  
700 <    /**
701 <     * Implementation for the four public remove/replace methods:
563 <     * Replaces node value with v, conditional upon match of cv if
564 <     * non-null.  If resulting value is null, delete.
565 <     */
566 <    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          for (Node[] tab = table;;) {
704 <            Node e; int i;
705 <            if (tab == null ||
706 <                (e = tabAt(tab, i = (tab.length - 1) & h)) == null)
707 <                return null;
708 <            else if (e.hash < 0)
709 <                tab = (Node[])e.key;
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 <                Object oldVal = null;
718 <                boolean validated = false;
719 <                boolean deleted = false;
720 <                synchronized (e) {
721 <                    if (tabAt(tab, i) == e) {
722 <                        validated = true;
723 <                        Node pred = null;
724 <                        do {
725 <                            Object ek, ev;
726 <                            if (e.hash == h &&
727 <                                ((ek = e.key) == k || k.equals(ek)) &&
728 <                                ((ev = e.val) != null)) {
729 <                                if (cv == null || cv == ev || cv.equals(ev)) {
717 >                Node g = f.next;
718 >                if (g != null) { // at least 2 nodes -- search and maybe resize
719 >                    for (Node e = g;;) {
720 >                        Object ek, ev;
721 >                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
722 >                            ((ek = e.key) == k || k.equals(ek)))
723 >                            return ev;
724 >                        if ((e = e.next) == null) {
725 >                            checkForResize();
726 >                            break;
727 >                        }
728 >                    }
729 >                }
730 >                if (((fh = f.hash) & LOCKED) != 0) {
731 >                    checkForResize();
732 >                    f.tryAwaitLock(tab, i);
733 >                }
734 >                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
735 >                    Object oldVal = null;
736 >                    boolean validated = false;
737 >                    try {
738 >                        if (tabAt(tab, i) == f) {
739 >                            validated = true;
740 >                            for (Node e = f;;) {
741 >                                Object ek, ev;
742 >                                if ((e.hash & HASH_BITS) == h &&
743 >                                    (ev = e.val) != null &&
744 >                                    ((ek = e.key) == k || k.equals(ek))) {
745                                      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
596 <                                            setTabAt(tab, i, en);
597 <                                    }
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                                  }
599                                break;
753                              }
754 <                        } while ((e = (pred = e).next) != null);
754 >                        }
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 <                if (validated) {
768 <                    if (deleted)
769 <                        counter.decrement();
770 <                    return oldVal;
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 >                            checkForResize();
817 >                            break;
818 >                        }
819 >                    }
820 >                }
821 >                if (((fh = f.hash) & LOCKED) != 0) {
822 >                    checkForResize();
823 >                    f.tryAwaitLock(tab, i);
824 >                }
825 >                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
826 >                    boolean validated = false;
827 >                    try {
828 >                        if (tabAt(tab, i) == f) {
829 >                            validated = true;
830 >                            for (Node e = f;;) {
831 >                                Object ek, ev;
832 >                                if ((e.hash & HASH_BITS) == h &&
833 >                                    (ev = e.val) != null &&
834 >                                    ((ek = e.key) == k || k.equals(ek))) {
835 >                                    val = ev;
836 >                                    break;
837 >                                }
838 >                                Node last = e;
839 >                                if ((e = e.next) == null) {
840 >                                    if ((val = mf.map(k)) != null)
841 >                                        last.next = new Node(h, k, val, null);
842 >                                    break;
843 >                                }
844 >                            }
845 >                        }
846 >                    } finally {
847 >                        if (!f.casHash(fh | LOCKED, fh)) {
848 >                            f.hash = fh;
849 >                            synchronized (f) { f.notifyAll(); };
850 >                        }
851 >                    }
852 >                    if (validated)
853 >                        break;
854                  }
855              }
856          }
857 +        if (val == null)
858 +            throw new NullPointerException();
859 +        counter.add(1L);
860 +        return val;
861      }
862  
863 <    /** Implementation for computeIfAbsent and compute. Like put, but messier. */
863 >    /** Implementation for compute */
864      @SuppressWarnings("unchecked")
865 <    private final V internalCompute(K k,
866 <                                    MappingFunction<? super K, ? extends V> f,
617 <                                    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 <        Node[] tab = table;
871 <        outer:for (;;) {
872 <            Node e; int i; Object ek, ev;
870 >        boolean checkSize = false;
871 >        for (Node[] tab = table;;) {
872 >            Node f; int i, fh;
873              if (tab == null)
874 <                tab = growTable();
875 <            else if ((e = tabAt(tab, i = (tab.length - 1) & h)) == null) {
876 <                Node node = new Node(h, k, null, 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 <                synchronized (node) {  // must lock while computing value
879 <                    if (casTabAt(tab, i, null, node)) {
880 <                        validated = true;
881 <                        try {
882 <                            val = f.map(k);
883 <                            if (val != null) {
884 <                                node.val = val;
885 <                                added = true;
886 <                            }
887 <                        } finally {
888 <                            if (!added)
889 <                                setTabAt(tab, i, null);
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 (!replace && e.hash == h && (ev = e.val) != null &&
900 <                     ((ek = e.key) == k || k.equals(ek))) {
901 <                if (tabAt(tab, i) == e) {
652 <                    val = (V)ev;
653 <                    break;
654 <                }
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 (Thread.holdsLock(e))
657 <                throw new IllegalStateException("Recursive map computation");
658 <            else {
903 >            else if (f.casHash(fh, fh | LOCKED)) {
904                  boolean validated = false;
905 <                boolean checkSize = false;
906 <                synchronized (e) {
662 <                    if (tabAt(tab, i) == e) {
905 >                try {
906 >                    if (tabAt(tab, i) == f) {
907                          validated = true;
908 <                        for (Node first = e;;) {
909 <                            if (e.hash == h &&
910 <                                ((ek = e.key) == k || k.equals(ek)) &&
911 <                                ((ev = e.val) != null)) {
912 <                                Object fv;
913 <                                if (replace && (fv = f.map(k)) != null)
914 <                                    ev = e.val = fv;
915 <                                val = (V)ev;
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                              Node last = e;
919                              if ((e = e.next) == null) {
920 <                                if ((val = f.map(k)) != 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                              }
928                          }
929                      }
930 +                } finally {
931 +                    if (!f.casHash(fh | LOCKED, fh)) {
932 +                        f.hash = fh;
933 +                        synchronized (f) { f.notifyAll(); };
934 +                    }
935                  }
936 <                if (validated) {
688 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
689 <                        resizing == 0 && counter.sum() >= threshold)
690 <                        growTable();
936 >                if (validated)
937                      break;
692                }
938              }
939          }
940 <        if (added)
941 <            counter.increment();
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 +    /** Implementation for putAll */
951 +    private final void internalPutAll(Map<?, ?> m) {
952 +        tryPresize(m.size());
953 +        long delta = 0L;     // number of uncommitted additions
954 +        boolean npe = false; // to throw exception on exit for nulls
955 +        try {                // to clean up counts on other exceptions
956 +            for (Map.Entry<?, ?> entry : m.entrySet()) {
957 +                Object k, v;
958 +                if (entry == null || (k = entry.getKey()) == null ||
959 +                    (v = entry.getValue()) == null) {
960 +                    npe = true;
961 +                    break;
962 +                }
963 +                int h = spread(k.hashCode());
964 +                for (Node[] tab = table;;) {
965 +                    int i; Node f; int fh;
966 +                    if (tab == null)
967 +                        tab = initTable();
968 +                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
969 +                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
970 +                            ++delta;
971 +                            break;
972 +                        }
973 +                    }
974 +                    else if ((fh = f.hash) == MOVED)
975 +                        tab = (Node[])f.key;
976 +                    else if ((fh & LOCKED) != 0) {
977 +                        counter.add(delta);
978 +                        delta = 0L;
979 +                        checkForResize();
980 +                        f.tryAwaitLock(tab, i);
981 +                    }
982 +                    else if (f.casHash(fh, fh | LOCKED)) {
983 +                        boolean validated = false;
984 +                        boolean tooLong = false;
985 +                        try {
986 +                            if (tabAt(tab, i) == f) {
987 +                                validated = true;
988 +                                for (Node e = f;;) {
989 +                                    Object ek, ev;
990 +                                    if ((e.hash & HASH_BITS) == h &&
991 +                                        (ev = e.val) != null &&
992 +                                        ((ek = e.key) == k || k.equals(ek))) {
993 +                                        e.val = v;
994 +                                        break;
995 +                                    }
996 +                                    Node last = e;
997 +                                    if ((e = e.next) == null) {
998 +                                        ++delta;
999 +                                        last.next = new Node(h, k, v, null);
1000 +                                        break;
1001 +                                    }
1002 +                                    tooLong = true;
1003 +                                }
1004 +                            }
1005 +                        } finally {
1006 +                            if (!f.casHash(fh | LOCKED, fh)) {
1007 +                                f.hash = fh;
1008 +                                synchronized (f) { f.notifyAll(); };
1009 +                            }
1010 +                        }
1011 +                        if (validated) {
1012 +                            if (tooLong) {
1013 +                                counter.add(delta);
1014 +                                delta = 0L;
1015 +                                checkForResize();
1016 +                            }
1017 +                            break;
1018 +                        }
1019 +                    }
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 +     * 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 +                break;
1065 +            }
1066 +        }
1067 +        return tab;
1068 +    }
1069 +
1070 +    /**
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 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 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 >            }
1117 >            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1118 >                break;
1119 >            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1120 >                try {
1121 >                    if (table == tab) {
1122 >                        table = rebuild(tab);
1123 >                        sc = (n << 1) - (n >>> 1);
1124 >                    }
1125 >                } finally {
1126 >                    sizeCtl = sc;
1127 >                }
1128 >            }
1129 >        }
1130 >    }
1131 >
1132 >    /*
1133 >     * Moves and/or copies the nodes in each bin to new table. See
1134 >     * above for explanation.
1135 >     *
1136 >     * @return the new table
1137 >     */
1138 >    private static final Node[] rebuild(Node[] tab) {
1139 >        int n = tab.length;
1140 >        Node[] nextTab = new Node[n << 1];
1141 >        Node fwd = new Node(MOVED, nextTab, null, null);
1142 >        int[] buffer = null;       // holds bins to revisit; null until needed
1143 >        Node rev = null;           // reverse forwarder; null until needed
1144 >        int nbuffered = 0;         // the number of bins in buffer list
1145 >        int bufferIndex = 0;       // buffer index of current buffered bin
1146 >        int bin = n - 1;           // current non-buffered bin or -1 if none
1147 >
1148 >        for (int i = bin;;) {      // start upwards sweep
1149 >            int fh; Node f;
1150 >            if ((f = tabAt(tab, i)) == null) {
1151 >                if (bin >= 0) {    // no lock needed (or available)
1152 >                    if (!casTabAt(tab, i, f, fwd))
1153 >                        continue;
1154 >                }
1155 >                else {             // transiently use a locked forwarding node
1156 >                    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 >                    }
1166 >                }
1167 >            }
1168 >            else if (((fh = f.hash) & LOCKED) == 0 && f.casHash(fh, fh|LOCKED)) {
1169 >                boolean validated = false;
1170 >                try {              // split to lo and hi lists; copying as needed
1171 >                    if (tabAt(tab, i) == f) {
1172 >                        validated = true;
1173 >                        Node e = f, lastRun = f;
1174 >                        Node lo = null, hi = null;
1175 >                        int runBit = e.hash & n;
1176 >                        for (Node p = e.next; p != null; p = p.next) {
1177 >                            int b = p.hash & n;
1178 >                            if (b != runBit) {
1179 >                                runBit = b;
1180 >                                lastRun = p;
1181 >                            }
1182 >                        }
1183 >                        if (runBit == 0)
1184 >                            lo = lastRun;
1185 >                        else
1186 >                            hi = lastRun;
1187 >                        for (Node p = e; p != lastRun; p = p.next) {
1188 >                            int ph = p.hash & HASH_BITS;
1189 >                            Object pk = p.key, pv = p.val;
1190 >                            if ((ph & n) == 0)
1191 >                                lo = new Node(ph, pk, pv, lo);
1192 >                            else
1193 >                                hi = new Node(ph, pk, pv, hi);
1194 >                        }
1195 >                        setTabAt(nextTab, i, lo);
1196 >                        setTabAt(nextTab, i + n, hi);
1197 >                        setTabAt(tab, i, fwd);
1198 >                    }
1199 >                } finally {
1200 >                    if (!f.casHash(fh | LOCKED, fh)) {
1201 >                        f.hash = fh;
1202 >                        synchronized (f) { f.notifyAll(); };
1203 >                    }
1204 >                }
1205 >                if (!validated)
1206 >                    continue;
1207 >            }
1208 >            else {
1209 >                if (buffer == null) // initialize buffer for revisits
1210 >                    buffer = new int[TRANSFER_BUFFER_SIZE];
1211 >                if (bin < 0 && bufferIndex > 0) {
1212 >                    int j = buffer[--bufferIndex];
1213 >                    buffer[bufferIndex] = i;
1214 >                    i = j;         // swap with another bin
1215 >                    continue;
1216 >                }
1217 >                if (bin < 0 || nbuffered >= TRANSFER_BUFFER_SIZE) {
1218 >                    f.tryAwaitLock(tab, i);
1219 >                    continue;      // no other options -- block
1220 >                }
1221 >                if (rev == null)   // initialize reverse-forwarder
1222 >                    rev = new Node(MOVED, tab, null, null);
1223 >                if (tabAt(tab, i) != f || (f.hash & LOCKED) == 0)
1224 >                    continue;      // recheck before adding to list
1225 >                buffer[nbuffered++] = i;
1226 >                setTabAt(nextTab, i, rev);     // install place-holders
1227 >                setTabAt(nextTab, i + n, rev);
1228 >            }
1229 >
1230 >            if (bin > 0)
1231 >                i = --bin;
1232 >            else if (buffer != null && nbuffered > 0) {
1233 >                bin = -1;
1234 >                i = buffer[bufferIndex = --nbuffered];
1235 >            }
1236 >            else
1237 >                return nextTab;
1238 >        }
1239 >    }
1240 >
1241 >    /**
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 <            Node e = tabAt(tab, i);
1251 <            if (e == null)
1250 >            int fh;
1251 >            Node f = tabAt(tab, i);
1252 >            if (f == null)
1253                  ++i;
1254 <            else if (e.hash < 0)
1255 <                tab = (Node[])e.key;
1256 <            else {
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 <                synchronized (e) {
1264 <                    if (tabAt(tab, i) == e) {
1263 >                try {
1264 >                    if (tabAt(tab, i) == f) {
1265                          validated = true;
1266 <                        Node en;
719 <                        do {
720 <                            en = e.next;
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 <                        } while ((e = en) != null);
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              }
1283          }
1284 <        counter.add(delta);
1284 >        if (delta != 0)
1285 >            counter.add(delta);
1286      }
1287  
1288 +
1289      /* ----------------Table Traversal -------------- */
1290  
1291      /**
# Line 741 | Line 1294 | public class ConcurrentHashMapV8<K, V>
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 nonnull user value). Because val fields can
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(nextKey); it.advance(); }}
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 encapulate the it.next check as hasNext();
1308 >     * and encapsulate the it.next check as hasNext();
1309       *
1310 <     * The iterator visits each valid node that was reachable upon
1311 <     * iterator construction once. It might miss some that were added
1312 <     * to a bin after the bin was visited, which is OK wrt consistency
1313 <     * guarantees. Maintaining this property in the face of possible
1314 <     * ongoing resizes requires a fair amount of bookkeeping state
1315 <     * that is difficult to optimize away amidst volatile accesses.
1316 <     * Even so, traversal maintains reasonable throughput.
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
# Line 797 | Line 1351 | public class ConcurrentHashMapV8<K, V>
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;
1354 >            baseLimit = (hi <= baseSize) ? hi : baseSize;
1355 >            index = baseIndex = (lo >= 0) ? lo : 0;
1356              next = null;
1357              advance();
1358          }
# Line 807 | Line 1361 | public class ConcurrentHashMapV8<K, V>
1361          final void advance() {
1362              Node e = last = next;
1363              outer: do {
1364 <                if (e != null)                   // pass used or skipped node
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
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 < 0)
1372 <                        tab = (Node[])e.key;     // restarts due to null val
1373 <                    else                         // visit upper slots if present
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
1377 >            } while ((nextVal = e.val) == null);// skip deleted or special nodes
1378              next = e;
1379          }
1380      }
# Line 828 | Line 1382 | public class ConcurrentHashMapV8<K, V>
1382      /* ---------------- Public operations -------------- */
1383  
1384      /**
1385 <     * Creates a new, empty map with the specified initial
832 <     * capacity, load factor and concurrency level.
833 <     *
834 <     * @param initialCapacity the initial capacity. The implementation
835 <     * performs internal sizing to accommodate this many elements.
836 <     * @param loadFactor  the load factor threshold, used to control resizing.
837 <     * Resizing may be performed when the average number of elements per
838 <     * bin exceeds this threshold.
839 <     * @param concurrencyLevel the estimated number of concurrently
840 <     * updating threads. The implementation may use this value as
841 <     * a sizing hint.
842 <     * @throws IllegalArgumentException if the initial capacity is
843 <     * negative or the load factor or concurrencyLevel are
844 <     * nonpositive.
1385 >     * Creates a new, empty map with the default initial table size (16),
1386       */
1387 <    public ConcurrentHashMapV8(int initialCapacity,
847 <                               float loadFactor, int concurrencyLevel) {
848 <        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
849 <            throw new IllegalArgumentException();
850 <        int cap = tableSizeFor(initialCapacity);
1387 >    public ConcurrentHashMapV8() {
1388          this.counter = new LongAdder();
852        this.loadFactor = loadFactor;
853        this.targetCapacity = cap;
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.
862     * @param loadFactor  the load factor threshold, used to control resizing.
863     * Resizing may be performed when the average number of elements per
864     * bin exceeds this threshold.
1398       * @throws IllegalArgumentException if the initial capacity of
1399 <     * elements is negative or the load factor is nonpositive
867 <     *
868 <     * @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,
876 <     * 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
879 <     * performs internal sizing to accommodate this many elements.
880 <     * @throws IllegalArgumentException if the initial capacity of
881 <     * 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 <        putAll(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      /**
# Line 917 | Line 1481 | public class ConcurrentHashMapV8<K, V>
1481       */
1482      public int size() {
1483          long n = counter.sum();
1484 <        return ((n < 0L)? 0 :
1485 <                (n > (long)Integer.MAX_VALUE)? 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      /**
1495       * Returns the value to which the specified key is mapped,
1496       * or {@code null} if this map contains no mapping for the key.
# Line 946 | 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 1014 | 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 1028 | 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 1039 | 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) {
1611 <        if (m == null)
1043 <            throw new NullPointerException();
1044 <        /*
1045 <         * If uninitialized, try to adjust targetCapacity to
1046 <         * accommodate the given number of elements.
1047 <         */
1048 <        if (table == null) {
1049 <            int size = m.size();
1050 <            int cap = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1051 <                tableSizeFor(size + (size >>> 1));
1052 <            if (cap > targetCapacity)
1053 <                targetCapacity = cap;
1054 <        }
1055 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1056 <            put(e.getKey(), e.getValue());
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 <     *  <pre> {@code
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 <     * if (value != null)
1068 <     *   map.put(key, value);
1622 >     * map.put(key, value);
1623       * return value;}</pre>
1624       *
1625 <     * except that the action is performed atomically.  Some attempted
1626 <     * update operations on this map by other threads may be blocked
1627 <     * while computation is in progress, so the computation should be
1628 <     * short and simple, and must not attempt to update any other
1629 <     * mappings of this Map. The most appropriate usage is to
1630 <     * construct a new object serving as an initial mapped value, or
1631 <     * memoized result, as in:
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       *  <pre> {@code
1638       * map.computeIfAbsent(key, new MappingFunction<K, V>() {
1639       *   public V map(K k) { return new Value(f(k)); }});}</pre>
# Line 1082 | Line 1641 | public class ConcurrentHashMapV8<K, V>
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
1088 <     *         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
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 <     * value = mappingFunction.map(key);
1666 <     * if (value != null)
1108 <     *   map.put(key, value);
1109 <     * else
1110 <     *   value = map.get(key);
1111 <     * return value;}</pre>
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
1125 <     *         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 1428 | Line 1995 | public class ConcurrentHashMapV8<K, V>
1995              Object k = nextKey;
1996              Object v = nextVal;
1997              advance();
1998 <            return new WriteThroughEntry<K,V>(map, (K)k, (V)v);
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 <     * Custom Entry class used by EntryIterator.next(), that relays
1437 <     * setValue changes to the underlying map.
2018 >     * Base of writeThrough and Snapshot entry classes
2019       */
2020 <    static final class WriteThroughEntry<K,V> implements Map.Entry<K, V> {
1440 <        final ConcurrentHashMapV8<K, V> map;
2020 >    static abstract class MapEntry<K,V> implements Map.Entry<K, V> {
2021          final K key; // non-null
2022          V val;       // non-null
2023 <        WriteThroughEntry(ConcurrentHashMapV8<K, V> map, K key, V val) {
1444 <            this.map = map; this.key = key; this.val = val;
1445 <        }
1446 <
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(); }
# Line 1458 | Line 2035 | public class ConcurrentHashMapV8<K, V>
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          /**
2054           * Sets our entry's value and writes through to the map. The
2055           * value to return is somewhat arbitrary here. Since a
# Line 1476 | Line 2068 | public class ConcurrentHashMapV8<K, V>
2068          }
2069      }
2070  
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      /* ----------------Views -------------- */
2086  
2087 <    /*
2088 <     * These currently just extend java.util.AbstractX classes, but
2089 <     * may need a new custom base to support partitioned traversal.
2087 >    /**
2088 >     * Base class for views. This is done mainly to allow adding
2089 >     * customized parallel traversals (not yet implemented.)
2090       */
2091 <
1486 <    static final class KeySet<K,V> extends AbstractSet<K> {
2091 >    static abstract class MapView<K, V> {
2092          final ConcurrentHashMapV8<K, V> map;
2093 <        KeySet(ConcurrentHashMapV8<K, V> map)   { this.map = map; }
1489 <
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 <T> T[] toArray(T[] a) {
2130 +            long sz = map.longSize();
2131 +            if (sz > (long)(MAX_ARRAY_SIZE))
2132 +                throw new OutOfMemoryError(oomeMsg);
2133 +            int m = (int)sz;
2134 +            T[] r = (a.length >= m) ? a :
2135 +                (T[])java.lang.reflect.Array
2136 +                .newInstance(a.getClass().getComponentType(), m);
2137 +            int n = r.length;
2138 +            int i = 0;
2139 +            Iterator<?> it = iter();
2140 +            while (it.hasNext()) {
2141 +                if (i == n) {
2142 +                    if (n >= MAX_ARRAY_SIZE)
2143 +                        throw new OutOfMemoryError(oomeMsg);
2144 +                    if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1)
2145 +                        n = MAX_ARRAY_SIZE;
2146 +                    else
2147 +                        n += (n >>> 1) + 1;
2148 +                    r = Arrays.copyOf(r, n);
2149 +                }
2150 +                r[i++] = (T)it.next();
2151 +            }
2152 +            if (a == r && i < n) {
2153 +                r[i] = null; // null-terminate
2154 +                return r;
2155 +            }
2156 +            return (i == n) ? r : Arrays.copyOf(r, i);
2157 +        }
2158 +
2159 +        public final int hashCode() {
2160 +            int h = 0;
2161 +            for (Iterator<?> it = iter(); it.hasNext();)
2162 +                h += it.next().hashCode();
2163 +            return h;
2164 +        }
2165 +
2166 +        public final String toString() {
2167 +            StringBuilder sb = new StringBuilder();
2168 +            sb.append('[');
2169 +            Iterator<?> it = iter();
2170 +            if (it.hasNext()) {
2171 +                for (;;) {
2172 +                    Object e = it.next();
2173 +                    sb.append(e == this ? "(this Collection)" : e);
2174 +                    if (!it.hasNext())
2175 +                        break;
2176 +                    sb.append(',').append(' ');
2177 +                }
2178 +            }
2179 +            return sb.append(']').toString();
2180 +        }
2181 +
2182 +        public final boolean containsAll(Collection<?> c) {
2183 +            if (c != this) {
2184 +                for (Iterator<?> it = c.iterator(); it.hasNext();) {
2185 +                    Object e = it.next();
2186 +                    if (e == null || !contains(e))
2187 +                        return false;
2188 +                }
2189 +            }
2190 +            return true;
2191 +        }
2192 +
2193 +        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 +
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 +        final Iterator<?> iter() {
2226 +            return new KeyIterator<K,V>(map);
2227 +        }
2228 +        public final boolean add(K e) {
2229 +            throw new UnsupportedOperationException();
2230 +        }
2231 +        public final boolean addAll(Collection<? extends K> c) {
2232 +            throw new UnsupportedOperationException();
2233 +        }
2234 +        public boolean equals(Object o) {
2235 +            Set<?> c;
2236 +            return ((o instanceof Set) &&
2237 +                    ((c = (Set<?>)o) == this ||
2238 +                     (containsAll(c) && c.containsAll(this))));
2239 +        }
2240      }
2241  
2242 <    static final class Values<K,V> extends AbstractCollection<V> {
2243 <        final ConcurrentHashMapV8<K, V> map;
2244 <        Values(ConcurrentHashMapV8<K, V> map)   { this.map = map; }
1503 <
1504 <        public final int size()                 { return map.size(); }
1505 <        public final boolean isEmpty()          { return map.isEmpty(); }
1506 <        public final void clear()               { map.clear(); }
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 final Iterator<V> iterator() {
2260              return new ValueIterator<K,V>(map);
2261          }
2262 +        final Iterator<?> iter() {
2263 +            return new ValueIterator<K,V>(map);
2264 +        }
2265 +        public final boolean add(V e) {
2266 +            throw new UnsupportedOperationException();
2267 +        }
2268 +        public final boolean addAll(Collection<? extends V> c) {
2269 +            throw new UnsupportedOperationException();
2270 +        }
2271      }
2272  
2273 <    static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> {
2274 <        final ConcurrentHashMapV8<K, V> map;
2275 <        EntrySet(ConcurrentHashMapV8<K, V> map) { this.map = map; }
1516 <
1517 <        public final int size()                 { return map.size(); }
1518 <        public final boolean isEmpty()          { return map.isEmpty(); }
1519 <        public final void clear()               { map.clear(); }
1520 <        public final Iterator<Map.Entry<K,V>> iterator() {
1521 <            return new EntryIterator<K,V>(map);
1522 <        }
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;
# Line 1537 | Line 2290 | public class ConcurrentHashMapV8<K, V>
2290                      (v = e.getValue()) != null &&
2291                      map.remove(k, v));
2292          }
2293 +
2294 +        public final Iterator<Map.Entry<K,V>> iterator() {
2295 +            return new EntryIterator<K,V>(map);
2296 +        }
2297 +        final Iterator<?> iter() {
2298 +            return new SnapshotEntryIterator<K,V>(map);
2299 +        }
2300 +        public final boolean add(Entry<K,V> e) {
2301 +            throw new UnsupportedOperationException();
2302 +        }
2303 +        public final boolean addAll(Collection<? extends Entry<K,V>> c) {
2304 +            throw new UnsupportedOperationException();
2305 +        }
2306 +        public boolean equals(Object o) {
2307 +            Set<?> c;
2308 +            return ((o instanceof Set) &&
2309 +                    ((c = (Set<?>)o) == this ||
2310 +                     (containsAll(c) && c.containsAll(this))));
2311 +        }
2312      }
2313  
2314      /* ---------------- Serialization Support -------------- */
# Line 1567 | 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>(DEFAULT_LOAD_FACTOR);
2342 >                segments[i] = new Segment<K,V>(LOAD_FACTOR);
2343          }
2344          s.defaultWriteObject();
2345          InternalIterator it = new InternalIterator(table);
# Line 1590 | Line 2362 | public class ConcurrentHashMapV8<K, V>
2362              throws java.io.IOException, ClassNotFoundException {
2363          s.defaultReadObject();
2364          this.segments = null; // unneeded
2365 <        // initalize transient final fields
2365 >        // initialize transient final field
2366          UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
1595        UNSAFE.putFloatVolatile(this, loadFactorOffset, DEFAULT_LOAD_FACTOR);
1596        this.targetCapacity = DEFAULT_CAPACITY;
2367  
2368          // Create all nodes, then place in table once size is known
2369          long size = 0L;
# Line 1610 | Line 2380 | public class ConcurrentHashMapV8<K, V>
2380          }
2381          if (p != null) {
2382              boolean init = false;
2383 <            if (resizing == 0 &&
2384 <                UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
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;
1618                        int n;
1619                        if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1620                            n = MAXIMUM_CAPACITY;
1621                        else {
1622                            int sz = (int)size;
1623                            n = tableSizeFor(sz + (sz >>> 1));
1624                        }
1625                        threshold = (n - (n >>> 2)) - THRESHOLD_OFFSET;
2396                          Node[] tab = new Node[n];
2397                          int mask = n - 1;
2398                          while (p != null) {
# Line 1634 | Line 2404 | public class ConcurrentHashMapV8<K, V>
2404                          }
2405                          table = tab;
2406                          counter.add(size);
2407 +                        sc = n - (n >>> 2);
2408                      }
2409                  } finally {
2410 <                    resizing = 0;
2410 >                    sizeCtl = sc;
2411                  }
2412              }
2413              if (!init) { // Can only happen if unsafely published.
2414                  while (p != null) {
2415 <                    internalPut(p.key, p.val, true);
2415 >                    internalPut(p.key, p.val);
2416                      p = p.next;
2417                  }
2418              }
# Line 1651 | Line 2422 | public class ConcurrentHashMapV8<K, V>
2422      // Unsafe mechanics
2423      private static final sun.misc.Unsafe UNSAFE;
2424      private static final long counterOffset;
2425 <    private static final long loadFactorOffset;
1655 <    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 1663 | Line 2433 | public class ConcurrentHashMapV8<K, V>
2433              Class<?> k = ConcurrentHashMapV8.class;
2434              counterOffset = UNSAFE.objectFieldOffset
2435                  (k.getDeclaredField("counter"));
2436 <            loadFactorOffset = UNSAFE.objectFieldOffset
2437 <                (k.getDeclaredField("loadFactor"));
1668 <            resizingOffset = UNSAFE.objectFieldOffset
1669 <                (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