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.21 by jsr166, Sat Sep 10 05:35:24 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 54 | Line 57 | import java.io.Serializable;
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. There may be
61 < * much variance around this average as mappings are added and
62 < * removed, but overall, this maintains a commonly accepted time/space
63 < * tradeoff for hash tables.  However, resizing this or any other kind
64 < * of hash table may be a relatively slow operation. When possible, it
65 < * is a good idea to provide a size estimate as an optional {@code
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
# Line 68 | Line 72 | import java.io.Serializable;
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
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
# Line 85 | Line 89 | import java.io.Serializable;
89   * <p><em>jsr166e note: This class is a candidate replacement for
90   * java.util.concurrent.ConcurrentHashMap.<em>
91   *
92 < * @since 1.8
92 > * @since 1.5
93   * @author Doug Lea
94   * @param <K> the type of keys maintained by this map
95   * @param <V> the type of mapped values
# Line 95 | 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
100 <     * 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
105 <         * mapping. If this function throws an (unchecked) exception,
106 <         * the exception is rethrown to its caller, and no mapping is
107 <         * recorded.  Because this function is invoked within
108 <         * atomicity control, the computation should be short and
109 <         * simple. The most common usage is to construct a new object
110 <         * 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 129 | 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 187 | Line 225 | public class ConcurrentHashMapV8<K, V>
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 a threshold.  Only
229 <     * a single thread performs the resize (using field "resizing", to
230 <     * arrange exclusion), but the table otherwise remains usable for
231 <     * reads and updates. Resizing proceeds by transferring bins, one
232 <     * by one, from the table to the next table.  Upon transfer, the
233 <     * old table bin contains only a special forwarding node (with
234 <     * negative hash field) that contains the next table as its
235 <     * key. On encountering a forwarding node, access and update
236 <     * operations restart, using the new table. To ensure concurrent
237 <     * readability of traversals, transfers must proceed from the last
238 <     * bin (table.length - 1) up towards the first.  Upon seeing a
239 <     * forwarding node, traversals (see class InternalIterator)
240 <     * arrange to move to the new table for the rest of the traversal
241 <     * without revisiting nodes.  This constrains bin transfers to a
242 <     * particular order, and so can block indefinitely waiting for the
243 <     * next lock, and other threads cannot help with the transfer.
244 <     * However, expected stalls are infrequent enough to not warrant
245 <     * the additional overhead of access and iteration schemes that
246 <     * could admit out-of-order or concurrent bin transfers.
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 218 | 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. These harmlessly fail to take effect in cases of
223 <     * races with other ongoing resizings. Uses of the threshold and
224 <     * targetCapacity during attempted initializations or resizings
225 <     * are racy but fall back on checks to preserve correctness.
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 uniform hash
286 <     * distributions, the probability of this occurring at threshold
287 <     * is around 13%, meaning that only about 1 in 8 puts check
288 <     * threshold (and after resizing, many fewer do so). But this
289 <     * approximation has high variance for small table sizes, so we
290 <     * check on any collision for sizes <= 64.  Further, to increase
291 <     * the probability that a resize occurs soon enough, we offset the
292 <     * threshold (see THRESHOLD_OFFSET) by the expected number of puts
293 <     * between checks.
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 -------------- */
# Line 250 | Line 308 | public class ConcurrentHashMapV8<K, V>
308      /**
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.
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 261 | Line 321 | public class ConcurrentHashMapV8<K, V>
321      private static final int DEFAULT_CAPACITY = 16;
322  
323      /**
324 +     * The largest possible (non-power of two) array size.
325 +     * Needed by toArray and related methods.
326 +     */
327 +    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
328 +
329 +    /**
330 +     * The default concurrency level for this table. Unused but
331 +     * defined for compatibility with previous versions of this class.
332 +     */
333 +    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
334 +
335 +    /**
336       * 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, because it is
339 <     * simpler to rely on the expression {@code n - (n >>> 2)} for the
340 <     * associated resizing threshold.
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 float LOAD_FACTOR = 0.75f;
343  
344      /**
345 <     * The count value to offset thresholds to compensate for checking
346 <     * for the need to resize only when inserting into bins with two
347 <     * or more elements. See above for explanation.
345 >     * The buffer size for skipped bins during transfers. The
346 >     * value is arbitrary but should be large enough to avoid
347 >     * most locking stalls during resizes.
348 >     */
349 >    private static final int TRANSFER_BUFFER_SIZE = 32;
350 >
351 >    /*
352 >     * Encodings for special uses of Node hash fields. See above for
353 >     * explanation.
354 >     */
355 >    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
356 >    static final int LOCKED    = 0x40000000; // set/tested only as a bit
357 >    static final int WAITING   = 0xc0000000; // both bits set/tested together
358 >    static final int HASH_BITS = 0x3fffffff; // usable bits of normal node hash
359 >
360 >    /* ---------------- Fields -------------- */
361 >
362 >    /**
363 >     * The array of bins. Lazily initialized upon first insertion.
364 >     * Size is always a power of two. Accessed directly by iterators.
365 >     */
366 >    transient volatile Node[] table;
367 >
368 >    /**
369 >     * The counter maintaining number of elements.
370       */
371 <    private static final int THRESHOLD_OFFSET = 8;
371 >    private transient final LongAdder counter;
372  
373      /**
374 <     * The default concurrency level for this table. Unused except as
375 <     * a sizing hint, but defined for compatibility with previous
376 <     * versions of this class.
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 static final int DEFAULT_CONCURRENCY_LEVEL = 16;
380 >    private transient volatile int sizeCtl;
381 >
382 >    // views
383 >    private transient KeySet<K,V> keySet;
384 >    private transient Values<K,V> values;
385 >    private transient EntrySet<K,V> entrySet;
386 >
387 >    /** For serialization compatibility. Null unless serialized; see below */
388 >    private Segment<K,V>[] segments;
389  
390      /* ---------------- Nodes -------------- */
391  
392      /**
393       * Key-value entry. Note that this is never exported out as a
394 <     * user-visible Map.Entry. Nodes with a negative hash field are
395 <     * special, and do not contain user keys or values.  Otherwise,
396 <     * keys are never null, and null val fields indicate that a node
397 <     * is in the process of being deleted or created. For purposes of
398 <     * read-only, access, a key may be read before a val, but can only
399 <     * be used after checking val.  (For an update operation, when a
400 <     * lock is held on a node, order doesn't matter.)
394 >     * user-visible Map.Entry (see WriteThroughEntry and SnapshotEntry
395 >     * below). Nodes with a hash field of MOVED are special, and do
396 >     * not contain user keys or values.  Otherwise, keys are never
397 >     * null, and null val fields indicate that a node is in the
398 >     * process of being deleted or created. For purposes of read-only
399 >     * access, a key may be read before a val, but can only be used
400 >     * after checking val to be non-null.
401       */
402      static final class Node {
403 <        final int hash;
403 >        volatile int hash;
404          final Object key;
405          volatile Object val;
406          volatile Node next;
# Line 307 | Line 411 | public class ConcurrentHashMapV8<K, V>
411              this.val = val;
412              this.next = next;
413          }
310    }
414  
415 <    /**
416 <     * Sign bit of node hash value indicating to use table in node.key.
417 <     */
418 <    private static final int SIGN_BIT = 0x80000000;
316 <
317 <    /* ---------------- Fields -------------- */
415 >        /** CompareAndSet the hash field */
416 >        final boolean casHash(int cmp, int val) {
417 >            return UNSAFE.compareAndSwapInt(this, hashOffset, cmp, val);
418 >        }
419  
420 <    /**
421 <     * The array of bins. Lazily initialized upon first insertion.
422 <     * Size is always a power of two. Accessed directly by iterators.
322 <     */
323 <    transient volatile Node[] table;
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 <    /** The counter maintaining number of elements. */
425 <    private transient final LongAdder counter;
426 <    /** Nonzero when table is being initialized or resized. Updated via CAS. */
427 <    private transient volatile int resizing;
428 <    /** The next element count value upon which to resize the table. */
429 <    private transient int threshold;
430 <    /** The target capacity; volatile to cover initialization races. */
431 <    private transient volatile int targetCapacity;
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 <    // views
467 <    private transient KeySet<K,V> keySet;
468 <    private transient Values<K,V> values;
337 <    private transient EntrySet<K,V> entrySet;
466 >        // Unsafe mechanics for casHash
467 >        private static final sun.misc.Unsafe UNSAFE;
468 >        private static final long hashOffset;
469  
470 <    /** For serialization compatibility. Null unless serialized; see below */
471 <    private Segment<K,V>[] segments;
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  
# Line 365 | Line 505 | public class ConcurrentHashMapV8<K, V>
505          UNSAFE.putObjectVolatile(tab, ((long)i<<ASHIFT)+ABASE, v);
506      }
507  
368    /* ----------------Table Initialization and Resizing -------------- */
369
370    /**
371     * Returns a power of two table size for the given desired capacity.
372     * See Hackers Delight, sec 3.2
373     */
374    private static final int tableSizeFor(int c) {
375        int n = c - 1;
376        n |= n >>> 1;
377        n |= n >>> 2;
378        n |= n >>> 4;
379        n |= n >>> 8;
380        n |= n >>> 16;
381        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
382    }
383
384    /**
385     * If not already resizing, initializes or creates next table and
386     * transfers bins. Initial table size uses the capacity recorded
387     * in targetCapacity.  Rechecks occupancy after a transfer to see
388     * if another resize is already needed because resizings are
389     * lagging additions.
390     *
391     * @return current table
392     */
393    private final Node[] growTable() {
394        if (resizing == 0 &&
395            UNSAFE.compareAndSwapInt(this, resizingOffset, 0, 1)) {
396            try {
397                for (;;) {
398                    Node[] tab = table;
399                    int n, c, m;
400                    if (tab == null)
401                        n = (c = targetCapacity) > 0 ? c : DEFAULT_CAPACITY;
402                    else if ((m = tab.length) < MAXIMUM_CAPACITY &&
403                             counter.sum() >= (long)threshold)
404                        n = m << 1;
405                    else
406                        break;
407                    threshold = n - (n >>> 2) - THRESHOLD_OFFSET;
408                    Node[] nextTab = new Node[n];
409                    if (tab != null)
410                        transfer(tab, nextTab,
411                                 new Node(SIGN_BIT, nextTab, null, null));
412                    table = nextTab;
413                    if (tab == null)
414                        break;
415                }
416            } finally {
417                resizing = 0;
418            }
419        }
420        else if (table == null)
421            Thread.yield(); // lost initialization race; just spin
422        return table;
423    }
424
425    /**
426     * Reclassifies nodes in each bin to new table.  Because we are
427     * using power-of-two expansion, the elements from each bin must
428     * either stay at same index, or move with a power of two
429     * offset. We eliminate unnecessary node creation by catching
430     * cases where old nodes can be reused because their next fields
431     * won't change.  Statistically, only about one-sixth of them need
432     * cloning when a table doubles. The nodes they replace will be
433     * garbage collectable as soon as they are no longer referenced by
434     * any reader thread that may be in the midst of concurrently
435     * traversing table.
436     *
437     * Transfers are done from the bottom up to preserve iterator
438     * traversability. On each step, the old bin is locked,
439     * moved/copied, and then replaced with a forwarding node.
440     */
441    private static final void transfer(Node[] tab, Node[] nextTab, Node fwd) {
442        int n = tab.length;
443        Node ignore = nextTab[n + n - 1]; // force bounds check
444        for (int i = n - 1; i >= 0; --i) {
445            for (Node e;;) {
446                if ((e = tabAt(tab, i)) != null) {
447                    boolean validated = false;
448                    synchronized (e) {
449                        if (tabAt(tab, i) == e) {
450                            validated = true;
451                            Node lo = null, hi = null, lastRun = e;
452                            int runBit = e.hash & n;
453                            for (Node p = e.next; p != null; p = p.next) {
454                                int b = p.hash & n;
455                                if (b != runBit) {
456                                    runBit = b;
457                                    lastRun = p;
458                                }
459                            }
460                            if (runBit == 0)
461                                lo = lastRun;
462                            else
463                                hi = lastRun;
464                            for (Node p = e; p != lastRun; p = p.next) {
465                                int ph = p.hash;
466                                Object pk = p.key, pv = p.val;
467                                if ((ph & n) == 0)
468                                    lo = new Node(ph, pk, pv, lo);
469                                else
470                                    hi = new Node(ph, pk, pv, hi);
471                            }
472                            setTabAt(nextTab, i, lo);
473                            setTabAt(nextTab, i + n, hi);
474                            setTabAt(tab, i, fwd);
475                        }
476                    }
477                    if (validated)
478                        break;
479                }
480                else if (casTabAt(tab, i, e, fwd))
481                    break;
482            }
483        }
484    }
485
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 &&
512 <                        ((ek = e.key) == k || k.equals(ek)))
513 <                        return ev;
514 <                }
515 <                else if (eh < 0) {          // sign bit set
516 <                    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;
556 >        for (Node[] tab = table;;) {
557 >            Node f; int i, fh;
558 >            if (tab == null ||
559 >                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
560 >                break;
561 >            else if ((fh = f.hash) == MOVED)
562 >                tab = (Node[])f.key;
563 >            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
564 >                break;                          // rules out possible existence
565 >            else if ((fh & LOCKED) != 0) {
566 >                checkForResize();               // try resizing if can't get lock
567 >                f.tryAwaitLock(tab, i);
568 >            }
569 >            else if (f.casHash(fh, fh | LOCKED)) {
570 >                boolean validated = false;
571 >                boolean deleted = false;
572 >                try {
573 >                    if (tabAt(tab, i) == f) {
574 >                        validated = true;
575 >                        for (Node e = f, pred = null;;) {
576 >                            Object ek, ev;
577 >                            if ((e.hash & HASH_BITS) == h &&
578 >                                ((ev = e.val) != null) &&
579 >                                ((ek = e.key) == k || k.equals(ek))) {
580 >                                if (cv == null || cv == ev || cv.equals(ev)) {
581 >                                    oldVal = ev;
582 >                                    if ((e.val = v) == null) {
583 >                                        deleted = true;
584 >                                        Node en = e.next;
585 >                                        if (pred != null)
586 >                                            pred.next = en;
587 >                                        else
588 >                                            setTabAt(tab, i, en);
589 >                                    }
590 >                                }
591 >                                break;
592 >                            }
593 >                            pred = e;
594 >                            if ((e = e.next) == null)
595 >                                break;
596 >                        }
597 >                    }
598 >                } finally {
599 >                    if (!f.casHash(fh | LOCKED, fh)) {
600 >                        f.hash = fh;
601 >                        synchronized (f) { f.notifyAll(); };
602 >                    }
603 >                }
604 >                if (validated) {
605 >                    if (deleted)
606 >                        counter.add(-1L);
607 >                    break;
608 >                }
609 >            }
610 >        }
611 >        return oldVal;
612 >    }
613 >
614 >    /*
615 >     * Internal versions of the five insertion methods, each a
616 >     * little more complicated than the last. All have
617 >     * the same basic structure as the first (internalPut):
618 >     *  1. If table uninitialized, create
619 >     *  2. If bin empty, try to CAS new node
620 >     *  3. If bin stale, use new table
621 >     *  4. Lock and validate; if valid, scan and add or update
622 >     *
623 >     * The others interweave other checks and/or alternative actions:
624 >     *  * Plain put checks for and performs resize after insertion.
625 >     *  * putIfAbsent prescans for mapping without lock (and fails to add
626 >     *    if present), which also makes pre-emptive resize checks worthwhile.
627 >     *  * computeIfAbsent extends form used in putIfAbsent with additional
628 >     *    mechanics to deal with, calls, potential exceptions and null
629 >     *    returns from function call.
630 >     *  * compute uses the same function-call mechanics, but without
631 >     *    the prescans
632 >     *  * putAll attempts to pre-allocate enough table space
633 >     *    and more lazily performs count updates and checks.
634 >     *
635 >     * Someday when details settle down a bit more, it might be worth
636 >     * some factoring to reduce sprawl.
637 >     */
638 >
639 >    /** Implementation for put */
640 >    private final Object internalPut(Object k, Object v) {
641          int h = spread(k.hashCode());
642 <        Object oldVal = null;               // previous value or null if none
642 >        boolean checkSize = false;
643          for (Node[] tab = table;;) {
644 <            Node e; int i; Object ek, ev;
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
542 <                    oldVal = ev;             // without lock for putIfAbsent
543 <                    break;
544 <                }
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
550 <                    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)
558 <                                    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() >= (long)threshold)
574 <                        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:
586 <     * Replaces node value with v, conditional upon match of cv if
587 <     * non-null.  If resulting value is null, delete.
588 <     */
589 <    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
619 <                                            setTabAt(tab, i, en);
620 <                                    }
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                                  }
622                                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,
640 <                                    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) {
675 <                    val = (V)ev;
676 <                    break;
677 <                }
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))
680 <                throw new IllegalStateException("Recursive map computation");
681 <            else {
903 >            else if (f.casHash(fh, fh | LOCKED)) {
904                  boolean validated = false;
905 <                boolean checkSize = false;
906 <                synchronized (e) {
685 <                    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) {
711 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
712 <                        resizing == 0 && counter.sum() >= (long)threshold)
713 <                        growTable();
936 >                if (validated)
937                      break;
715                }
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 +     * 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 nodes.
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;
742 <                        do {
743 <                            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 764 | 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 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 821 | Line 1352 | public class ConcurrentHashMapV8<K, V>
1352              this.tab = tab;
1353              baseSize = (tab == null) ? 0 : tab.length;
1354              baseLimit = (hi <= baseSize) ? hi : baseSize;
1355 <            index = baseIndex = lo;
1355 >            index = baseIndex = (lo >= 0) ? lo : 0;
1356              next = null;
1357              advance();
1358          }
# Line 830 | 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 855 | Line 1386 | public class ConcurrentHashMapV8<K, V>
1386       */
1387      public ConcurrentHashMapV8() {
1388          this.counter = new LongAdder();
858        this.targetCapacity = DEFAULT_CAPACITY;
1389      }
1390  
1391      /**
# Line 875 | Line 1405 | public class ConcurrentHashMapV8<K, V>
1405                     MAXIMUM_CAPACITY :
1406                     tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
1407          this.counter = new LongAdder();
1408 <        this.targetCapacity = cap;
1408 >        this.sizeCtl = cap;
1409      }
1410  
1411      /**
# Line 885 | Line 1415 | public class ConcurrentHashMapV8<K, V>
1415       */
1416      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
1417          this.counter = new LongAdder();
1418 <        this.targetCapacity = DEFAULT_CAPACITY;
1419 <        putAll(m);
1418 >        this.sizeCtl = DEFAULT_CAPACITY;
1419 >        internalPutAll(m);
1420      }
1421  
1422      /**
# Line 901 | Line 1431 | public class ConcurrentHashMapV8<K, V>
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(int initialCapacity, float loadFactor) {
1438          this(initialCapacity, loadFactor, 1);
# Line 931 | Line 1463 | public class ConcurrentHashMapV8<K, V>
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));
1466 >        int cap = ((size >= (long)MAXIMUM_CAPACITY) ?
1467 >                   MAXIMUM_CAPACITY: tableSizeFor((int)size));
1468          this.counter = new LongAdder();
1469 <        this.targetCapacity = cap;
1469 >        this.sizeCtl = cap;
1470      }
1471  
1472      /**
# Line 954 | Line 1486 | public class ConcurrentHashMapV8<K, V>
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 1046 | 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 1060 | 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 1071 | 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)
1075 <            throw new NullPointerException();
1076 <        /*
1077 <         * If uninitialized, try to adjust targetCapacity to
1078 <         * accommodate the given number of elements.
1079 <         */
1080 <        if (table == null) {
1081 <            int size = m.size();
1082 <            int cap = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1083 <                tableSizeFor(size + (size >>> 1) + 1);
1084 <            if (cap > targetCapacity)
1085 <                targetCapacity = cap;
1086 <        }
1087 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
1088 <            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)
1100 <     *   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 1114 | 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
1120 <     *         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
1650       * @throws RuntimeException or Error if the mappingFunction does so,
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)
1140 <     *   map.put(key, value);
1141 <     * else
1142 <     *   value = map.get(key);
1143 <     * 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
1157 <     *         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,
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 1460 | 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
1469 <     * 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> {
1472 <        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) {
1476 <            this.map = map; this.key = key; this.val = val;
1477 <        }
1478 <
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 1490 | 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 1508 | 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 <
1518 <    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; }
1521 <
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; }
1535 <
1536 <        public final int size()                 { return map.size(); }
1537 <        public final boolean isEmpty()          { return map.isEmpty(); }
1538 <        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; }
1548 <
1549 <        public final int size()                 { return map.size(); }
1550 <        public final boolean isEmpty()          { return map.isEmpty(); }
1551 <        public final void clear()               { map.clear(); }
1552 <        public final Iterator<Map.Entry<K,V>> iterator() {
1553 <            return new EntryIterator<K,V>(map);
1554 <        }
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 1569 | 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 1624 | Line 2364 | public class ConcurrentHashMapV8<K, V>
2364          this.segments = null; // unneeded
2365          // initialize transient final field
2366          UNSAFE.putObjectVolatile(this, counterOffset, new LongAdder());
1627        this.targetCapacity = DEFAULT_CAPACITY;
2367  
2368          // Create all nodes, then place in table once size is known
2369          long size = 0L;
# Line 1641 | 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;
1649                        int n;
1650                        if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
1651                            n = MAXIMUM_CAPACITY;
1652                        else {
1653                            int sz = (int)size;
1654                            n = tableSizeFor(sz + (sz >>> 1) + 1);
1655                        }
1656                        threshold = n - (n >>> 2) - THRESHOLD_OFFSET;
2396                          Node[] tab = new Node[n];
2397                          int mask = n - 1;
2398                          while (p != null) {
# Line 1665 | 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 1682 | 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 resizingOffset;
2425 >    private static final long sizeCtlOffset;
2426      private static final long ABASE;
2427      private static final int ASHIFT;
2428  
# Line 1693 | Line 2433 | public class ConcurrentHashMapV8<K, V>
2433              Class<?> k = ConcurrentHashMapV8.class;
2434              counterOffset = UNSAFE.objectFieldOffset
2435                  (k.getDeclaredField("counter"));
2436 <            resizingOffset = UNSAFE.objectFieldOffset
2437 <                (k.getDeclaredField("resizing"));
2436 >            sizeCtlOffset = UNSAFE.objectFieldOffset
2437 >                (k.getDeclaredField("sizeCtl"));
2438              Class<?> sc = Node[].class;
2439              ABASE = UNSAFE.arrayBaseOffset(sc);
2440              ss = UNSAFE.arrayIndexScale(sc);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines