ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/Striped64.java
Revision: 1.9
Committed: Sun May 4 22:38:19 2014 UTC (10 years ago) by dl
Branch: MAIN
Changes since 1.8: +17 -25 lines
Log Message:
Use int[] instead of HashCode holder class to enable class-unloading

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package jsr166e;
8 import java.util.Random;
9
10 /**
11 * A package-local class holding common representation and mechanics
12 * for classes supporting dynamic striping on 64bit values. The class
13 * extends Number so that concrete subclasses must publicly do so.
14 */
15 abstract class Striped64 extends Number {
16 /*
17 * This class maintains a lazily-initialized table of atomically
18 * updated variables, plus an extra "base" field. The table size
19 * is a power of two. Indexing uses masked per-thread hash codes.
20 * Nearly all declarations in this class are package-private,
21 * accessed directly by subclasses.
22 *
23 * Table entries are of class Cell; a variant of AtomicLong padded
24 * to reduce cache contention on most processors. Padding is
25 * overkill for most Atomics because they are usually irregularly
26 * scattered in memory and thus don't interfere much with each
27 * other. But Atomic objects residing in arrays will tend to be
28 * placed adjacent to each other, and so will most often share
29 * cache lines (with a huge negative performance impact) without
30 * this precaution.
31 *
32 * In part because Cells are relatively large, we avoid creating
33 * them until they are needed. When there is no contention, all
34 * updates are made to the base field. Upon first contention (a
35 * failed CAS on base update), the table is initialized to size 2.
36 * The table size is doubled upon further contention until
37 * reaching the nearest power of two greater than or equal to the
38 * number of CPUS. Table slots remain empty (null) until they are
39 * needed.
40 *
41 * A single spinlock ("busy") is used for initializing and
42 * resizing the table, as well as populating slots with new Cells.
43 * There is no need for a blocking lock; when the lock is not
44 * available, threads try other slots (or the base). During these
45 * retries, there is increased contention and reduced locality,
46 * which is still better than alternatives.
47 *
48 * Per-thread hash codes are initialized to random values.
49 * Contention and/or table collisions are indicated by failed
50 * CASes when performing an update operation (see method
51 * retryUpdate). Upon a collision, if the table size is less than
52 * the capacity, it is doubled in size unless some other thread
53 * holds the lock. If a hashed slot is empty, and lock is
54 * available, a new Cell is created. Otherwise, if the slot
55 * exists, a CAS is tried. Retries proceed by "double hashing",
56 * using a secondary hash (Marsaglia XorShift) to try to find a
57 * free slot.
58 *
59 * The table size is capped because, when there are more threads
60 * than CPUs, supposing that each thread were bound to a CPU,
61 * there would exist a perfect hash function mapping threads to
62 * slots that eliminates collisions. When we reach capacity, we
63 * search for this mapping by randomly varying the hash codes of
64 * colliding threads. Because search is random, and collisions
65 * only become known via CAS failures, convergence can be slow,
66 * and because threads are typically not bound to CPUS forever,
67 * may not occur at all. However, despite these limitations,
68 * observed contention rates are typically low in these cases.
69 *
70 * It is possible for a Cell to become unused when threads that
71 * once hashed to it terminate, as well as in the case where
72 * doubling the table causes no thread to hash to it under
73 * expanded mask. We do not try to detect or remove such cells,
74 * under the assumption that for long-running instances, observed
75 * contention levels will recur, so the cells will eventually be
76 * needed again; and for short-lived ones, it does not matter.
77 */
78
79 /**
80 * Padded variant of AtomicLong supporting only raw accesses plus CAS.
81 * The value field is placed between pads, hoping that the JVM doesn't
82 * reorder them.
83 *
84 * JVM intrinsics note: It would be possible to use a release-only
85 * form of CAS here, if it were provided.
86 */
87 static final class Cell {
88 volatile long p0, p1, p2, p3, p4, p5, p6;
89 volatile long value;
90 volatile long q0, q1, q2, q3, q4, q5, q6;
91 Cell(long x) { value = x; }
92
93 final boolean cas(long cmp, long val) {
94 return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
95 }
96
97 // Unsafe mechanics
98 private static final sun.misc.Unsafe UNSAFE;
99 private static final long valueOffset;
100 static {
101 try {
102 UNSAFE = getUnsafe();
103 Class<?> ak = Cell.class;
104 valueOffset = UNSAFE.objectFieldOffset
105 (ak.getDeclaredField("value"));
106 } catch (Exception e) {
107 throw new Error(e);
108 }
109 }
110
111 }
112
113 /**
114 * ThreadLocal holding a single-slot int array holding hash code.
115 * Unlike the JDK8 version of this class, we use a suboptimal
116 * int[] representation to avoid introducing a new type that can
117 * impede class-unloading when ThreadLocals are not removed.
118 */
119 static final ThreadLocal<int[]> threadHashCode = new ThreadLocal<int[]>();
120
121 /**
122 * Generator of new random hash codes
123 */
124 static final Random rng = new Random();
125
126 /** Number of CPUS, to place bound on table size */
127 static final int NCPU = Runtime.getRuntime().availableProcessors();
128
129 /**
130 * Table of cells. When non-null, size is a power of 2.
131 */
132 transient volatile Cell[] cells;
133
134 /**
135 * Base value, used mainly when there is no contention, but also as
136 * a fallback during table initialization races. Updated via CAS.
137 */
138 transient volatile long base;
139
140 /**
141 * Spinlock (locked via CAS) used when resizing and/or creating Cells.
142 */
143 transient volatile int busy;
144
145 /**
146 * Package-private default constructor
147 */
148 Striped64() {
149 }
150
151 /**
152 * CASes the base field.
153 */
154 final boolean casBase(long cmp, long val) {
155 return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val);
156 }
157
158 /**
159 * CASes the busy field from 0 to 1 to acquire lock.
160 */
161 final boolean casBusy() {
162 return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1);
163 }
164
165 /**
166 * Computes the function of current and new value. Subclasses
167 * should open-code this update function for most uses, but the
168 * virtualized form is needed within retryUpdate.
169 *
170 * @param currentValue the current value (of either base or a cell)
171 * @param newValue the argument from a user update call
172 * @return result of the update function
173 */
174 abstract long fn(long currentValue, long newValue);
175
176 /**
177 * Handles cases of updates involving initialization, resizing,
178 * creating new Cells, and/or contention. See above for
179 * explanation. This method suffers the usual non-modularity
180 * problems of optimistic retry code, relying on rechecked sets of
181 * reads.
182 *
183 * @param x the value
184 * @param hc the hash code holder
185 * @param wasUncontended false if CAS failed before call
186 */
187 final void retryUpdate(long x, int[] hc, boolean wasUncontended) {
188 int h;
189 if (hc == null) {
190 threadHashCode.set(hc = new int[1]); // Initialize randomly
191 int r = rng.nextInt(); // Avoid zero to allow xorShift rehash
192 h = hc[0] = (r == 0) ? 1 : r;
193 }
194 else
195 h = hc[0];
196 boolean collide = false; // True if last slot nonempty
197 for (;;) {
198 Cell[] as; Cell a; int n; long v;
199 if ((as = cells) != null && (n = as.length) > 0) {
200 if ((a = as[(n - 1) & h]) == null) {
201 if (busy == 0) { // Try to attach new Cell
202 Cell r = new Cell(x); // Optimistically create
203 if (busy == 0 && casBusy()) {
204 boolean created = false;
205 try { // Recheck under lock
206 Cell[] rs; int m, j;
207 if ((rs = cells) != null &&
208 (m = rs.length) > 0 &&
209 rs[j = (m - 1) & h] == null) {
210 rs[j] = r;
211 created = true;
212 }
213 } finally {
214 busy = 0;
215 }
216 if (created)
217 break;
218 continue; // Slot is now non-empty
219 }
220 }
221 collide = false;
222 }
223 else if (!wasUncontended) // CAS already known to fail
224 wasUncontended = true; // Continue after rehash
225 else if (a.cas(v = a.value, fn(v, x)))
226 break;
227 else if (n >= NCPU || cells != as)
228 collide = false; // At max size or stale
229 else if (!collide)
230 collide = true;
231 else if (busy == 0 && casBusy()) {
232 try {
233 if (cells == as) { // Expand table unless stale
234 Cell[] rs = new Cell[n << 1];
235 for (int i = 0; i < n; ++i)
236 rs[i] = as[i];
237 cells = rs;
238 }
239 } finally {
240 busy = 0;
241 }
242 collide = false;
243 continue; // Retry with expanded table
244 }
245 h ^= h << 13; // Rehash
246 h ^= h >>> 17;
247 h ^= h << 5;
248 hc[0] = h; // Record index for next time
249 }
250 else if (busy == 0 && cells == as && casBusy()) {
251 boolean init = false;
252 try { // Initialize table
253 if (cells == as) {
254 Cell[] rs = new Cell[2];
255 rs[h & 1] = new Cell(x);
256 cells = rs;
257 init = true;
258 }
259 } finally {
260 busy = 0;
261 }
262 if (init)
263 break;
264 }
265 else if (casBase(v = base, fn(v, x)))
266 break; // Fall back on using base
267 }
268 }
269
270
271 /**
272 * Sets base and all cells to the given value.
273 */
274 final void internalReset(long initialValue) {
275 Cell[] as = cells;
276 base = initialValue;
277 if (as != null) {
278 int n = as.length;
279 for (int i = 0; i < n; ++i) {
280 Cell a = as[i];
281 if (a != null)
282 a.value = initialValue;
283 }
284 }
285 }
286
287 // Unsafe mechanics
288 private static final sun.misc.Unsafe UNSAFE;
289 private static final long baseOffset;
290 private static final long busyOffset;
291 static {
292 try {
293 UNSAFE = getUnsafe();
294 Class<?> sk = Striped64.class;
295 baseOffset = UNSAFE.objectFieldOffset
296 (sk.getDeclaredField("base"));
297 busyOffset = UNSAFE.objectFieldOffset
298 (sk.getDeclaredField("busy"));
299 } catch (Exception e) {
300 throw new Error(e);
301 }
302 }
303
304 /**
305 * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
306 * Replace with a simple call to Unsafe.getUnsafe when integrating
307 * into a jdk.
308 *
309 * @return a sun.misc.Unsafe
310 */
311 private static sun.misc.Unsafe getUnsafe() {
312 try {
313 return sun.misc.Unsafe.getUnsafe();
314 } catch (SecurityException tryReflectionInstead) {}
315 try {
316 return java.security.AccessController.doPrivileged
317 (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
318 public sun.misc.Unsafe run() throws Exception {
319 Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
320 for (java.lang.reflect.Field f : k.getDeclaredFields()) {
321 f.setAccessible(true);
322 Object x = f.get(null);
323 if (k.isInstance(x))
324 return k.cast(x);
325 }
326 throw new NoSuchFieldError("the Unsafe");
327 }});
328 } catch (java.security.PrivilegedActionException e) {
329 throw new RuntimeException("Could not initialize intrinsics",
330 e.getCause());
331 }
332 }
333 }