ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/StripedAdder.java
Revision: 1.6
Committed: Tue Jul 26 17:16:36 2011 UTC (12 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.5: +102 -86 lines
Log Message:
Performance improvements

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/publicdomain/zero/1.0/
5     */
6    
7     package jsr166e;
8     import java.util.Arrays;
9     import java.util.Random;
10     import java.util.concurrent.atomic.AtomicInteger;
11     import java.util.concurrent.atomic.AtomicLong;
12     import java.io.IOException;
13     import java.io.Serializable;
14     import java.io.ObjectInputStream;
15     import java.io.ObjectOutputStream;
16    
17     /**
18     * A set of variables that together maintain a sum. When updates
19 dl 1.3 * (method {@link #add}) are contended across threads, this set of
20     * adder variables may grow dynamically to reduce contention. Method
21     * {@link #sum} returns the current combined total across these
22     * adders. This value is <em>NOT</em> an atomic snapshot (concurrent
23     * updates may occur while the sum is being calculated), and so cannot
24     * be used alone for fine-grained synchronization control.
25 jsr166 1.2 *
26 dl 1.1 * <p> This class may be applicable when many threads frequently
27     * update a common sum that is used for purposes such as collecting
28     * statistics. In this case, performance may be significantly faster
29     * than using a shared {@link AtomicLong}, at the expense of using
30 dl 1.4 * much more space. On the other hand, if it is known that only one
31     * thread can ever update the sum, performance may be significantly
32     * slower than just updating a local variable.
33 dl 1.1 *
34 dl 1.3 * <p>A StripedAdder may optionally be constructed with a given
35     * expected contention level; i.e., the number of threads that are
36     * expected to concurrently update the sum. Supplying an accurate
37     * value may improve performance by reducing the need for dynamic
38     * adjustment.
39     *
40 jsr166 1.2 * @author Doug Lea
41 dl 1.1 */
42     public class StripedAdder implements Serializable {
43     private static final long serialVersionUID = 7249069246863182397L;
44    
45     /*
46 dl 1.4 * A StripedAdder maintains a table of Atomic long variables. The
47 dl 1.6 * table is indexed by per-thread hash codes.
48 dl 1.3 *
49 dl 1.6 * By default, the table is lazily initialized, to minimize
50     * footprint until adders are used. On first use, the table is set
51     * to size DEFAULT_INITIAL_SIZE (currently 8). Table size is
52     * bounded by the number of CPUS (if larger than the default
53     * size).
54     *
55     * Per-thread hash codes are initialized to random values.
56     * Collisions are indicated by failed CASes when performing an add
57     * operation (see method retryAdd). Upon a collision, if the table
58     * size is less than the capacity, it is doubled in size unless
59     * some other thread holds lock. If a hashed slot is empty, and
60     * lock is available, a new Adder is created. Otherwise, if the
61     * slot exists, a CAS is tried. Retries proceed by "double
62     * hashing", using a secondary hash (Marsaglia XorShift) to try to
63     * find a free slot.
64     *
65     * The table size is capped because, when there are more threads
66     * than CPUs, supposing that each thread were bound to a CPU,
67     * there would exist a perfect hash function mapping threads to
68     * slots that eliminates collisions. When we reach capacity, we
69     * search for this mapping by randomly varying the hash codes of
70     * colliding threads. Because search is random, and failures only
71     * become known via CAS failures, convergence will be slow, and
72     * because threads are typically not bound to CPUS forever, may
73     * not occur at all. However, despite these limitations, observed
74     * contention is typically low in these cases.
75 dl 1.3 *
76     * Table entries are of class Adder; a form of AtomicLong padded
77     * to reduce cache contention on most processors. Padding is
78 dl 1.6 * overkill for most Atomics because they are usually irregularly
79     * scattered in memory and thus don't interfere much with each
80     * other. But Atomic objects residing in arrays will tend to be
81     * placed adjacent to each other, and so will most often share
82     * cache lines without this precaution. Adders are by default
83 dl 1.4 * constructed upon first use, which further improves per-thread
84 dl 1.6 * locality and helps reduce footprint.
85 dl 1.3 *
86     * A single spinlock is used for resizing the table as well as
87 dl 1.1 * populating slots with new Adders. Upon lock contention, threads
88 dl 1.4 * try other slots rather than blocking. After initialization, at
89     * least one slot exists, so retries will eventually find a
90 dl 1.6 * candidate Adder. During these retries, there is increased
91 dl 1.3 * contention and reduced locality, which is still better than
92     * alternatives.
93 dl 1.1 */
94    
95 jsr166 1.2 /**
96 dl 1.6 * Padded version of AtomicLong
97 dl 1.1 */
98 dl 1.6 static final class Adder extends AtomicLong {
99     long p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
100     Adder(long x) { super(x); }
101     }
102 dl 1.1
103 dl 1.6 private static final int NCPU = Runtime.getRuntime().availableProcessors();
104 dl 1.5
105     /**
106 dl 1.6 * Table bounds. DEFAULT_INITIAL_SIZE is the table size set upon
107     * first use under default constructor, and must be a power of
108     * two. There is not much point in making size a lot smaller than
109     * that of Adders though. CAP is the maximum allowed table size.
110 dl 1.1 */
111 dl 1.6 private static final int DEFAULT_INITIAL_SIZE = 8;
112     private static final int CAP = Math.max(NCPU, DEFAULT_INITIAL_SIZE);
113 dl 1.1
114 jsr166 1.2 /**
115 dl 1.6 * Holder for the thread-local hash code. The code is initially
116     * random, but may be set to a different value upon collisions.
117 dl 1.1 */
118     static final class HashCode {
119 dl 1.6 static final Random rng = new Random();
120 dl 1.1 int code;
121 dl 1.6 HashCode() {
122     int h = rng.nextInt();
123     code = (h == 0) ? 1 : h; // ensure nonzero
124     }
125 dl 1.1 }
126    
127     /**
128     * The corresponding ThreadLocal class
129     */
130     static final class ThreadHashCode extends ThreadLocal<HashCode> {
131 dl 1.6 public HashCode initialValue() { return new HashCode(); }
132 dl 1.1 }
133    
134     /**
135     * Static per-thread hash codes. Shared across all StripedAdders
136 dl 1.6 * to reduce ThreadLocal pollution and because adjustments due to
137     * collisions in one table are likely to be appropriate for
138     * others.
139 dl 1.1 */
140     static final ThreadHashCode threadHashCode = new ThreadHashCode();
141    
142     /**
143 dl 1.6 * Table of adders. Size is power of two, grows to be at most CAP.
144 dl 1.1 */
145     private transient volatile Adder[] adders;
146    
147     /**
148     * Serves as a lock when resizing and/or creating Adders. There
149 dl 1.5 * is no need for a blocking lock: Except during initialization
150 dl 1.6 * races, when busy, other threads try other slots. However,
151     * during (double-checked) initializations, we use the
152     * "synchronized" lock on this object.
153 dl 1.1 */
154     private final AtomicInteger mutex;
155    
156     /**
157 dl 1.3 * Creates a new adder with zero sum.
158 dl 1.1 */
159     public StripedAdder() {
160 dl 1.4 this.mutex = new AtomicInteger();
161     // remaining initialization on first call to add.
162 dl 1.3 }
163    
164     /**
165     * Creates a new adder with zero sum, and with stripes presized
166     * for the given expected contention level.
167     *
168     * @param expectedContention the expected number of threads that
169     * will concurrently update the sum.
170     */
171     public StripedAdder(int expectedContention) {
172 dl 1.6 int cap = (expectedContention < CAP) ? expectedContention : CAP;
173     int size = 1;
174     while (size < cap)
175     size <<= 1;
176 dl 1.3 Adder[] as = new Adder[size];
177 dl 1.4 for (int i = 0; i < size; ++i)
178     as[i] = new Adder(0);
179 dl 1.1 this.adders = as;
180     this.mutex = new AtomicInteger();
181     }
182    
183     /**
184     * Adds the given value.
185     *
186     * @param x the value to add
187     */
188     public void add(long x) {
189 dl 1.4 Adder[] as; Adder a; int n; long v; // locals to hold volatile reads
190 dl 1.1 HashCode hc = threadHashCode.get();
191 dl 1.6 int h = hc.code;
192 dl 1.4 if ((as = adders) == null || (n = as.length) < 1 ||
193 dl 1.6 (a = as[(n - 1) & h]) == null ||
194 dl 1.4 !a.compareAndSet(v = a.get(), v + x))
195     retryAdd(x, hc);
196     }
197    
198     /**
199     * Handle cases of add involving initialization, resizing,
200 dl 1.6 * creating new Adders, and/or contention. See above for
201     * explanation.
202 dl 1.4 */
203     private void retryAdd(long x, HashCode hc) {
204     int h = hc.code;
205     final AtomicInteger mutex = this.mutex;
206 dl 1.6 int collisions = 1 - mutex.get(); // first guess: collides if not locked
207     for (;;) {
208     Adder[] as; Adder a; long v; int k, n;
209     while ((as = adders) == null || (n = as.length) < 1) {
210     synchronized(mutex) { // Try to initialize
211     if (adders == null) {
212     Adder[] rs = new Adder[DEFAULT_INITIAL_SIZE];
213     rs[h & (DEFAULT_INITIAL_SIZE - 1)] = new Adder(0);
214     adders = rs;
215     }
216     }
217     collisions = 0;
218     }
219    
220     if ((a = as[k = (n - 1) & h]) == null) { // Try to add slot
221 dl 1.5 if (mutex.get() == 0 && mutex.compareAndSet(0, 1)) {
222     try {
223 dl 1.6 if (adders == as && as[k] == null)
224     a = as[k] = new Adder(x);
225 dl 1.5 } finally {
226     mutex.set(0);
227     }
228 dl 1.6 if (a != null)
229     break;
230 dl 1.1 }
231 dl 1.6 collisions = 0;
232 dl 1.5 }
233 dl 1.6 else if (collisions != 0 && n < CAP && // Try to expand table
234 dl 1.5 mutex.get() == 0 && mutex.compareAndSet(0, 1)) {
235     try {
236     if (adders == as) {
237 dl 1.6 Adder[] rs = new Adder[n << 1];
238     for (int i = 0; i < n; ++i)
239     rs[i] = as[i];
240     adders = rs;
241 dl 1.1 }
242 dl 1.5 } finally {
243     mutex.set(0);
244 dl 1.1 }
245 dl 1.6 collisions = 0;
246 dl 1.5 }
247 dl 1.6 else if (a.compareAndSet(v = a.get(), v + x))
248     break;
249     else
250     collisions = 1;
251     h ^= h << 13; // Rehash
252     h ^= h >>> 17;
253     h ^= h << 5;
254 dl 1.1 }
255 dl 1.5 hc.code = h;
256 dl 1.1 }
257    
258     /**
259     * Returns an estimate of the current sum. The result is
260     * calculated by summing multiple variables, so may not be
261     * accurate if updates occur concurrently with this method.
262 jsr166 1.2 *
263 dl 1.1 * @return the estimated sum
264     */
265     public long sum() {
266 dl 1.4 long sum = 0L;
267 dl 1.1 Adder[] as = adders;
268 dl 1.4 if (as != null) {
269     int n = as.length;
270     for (int i = 0; i < n; ++i) {
271     Adder a = as[i];
272     if (a != null)
273     sum += a.get();
274     }
275 dl 1.1 }
276     return sum;
277     }
278    
279     /**
280     * Resets each of the variables to zero. This is effective in
281     * fully resetting the sum only if there are no concurrent
282     * updates.
283     */
284     public void reset() {
285     Adder[] as = adders;
286 dl 1.4 if (as != null) {
287     int n = as.length;
288     for (int i = 0; i < n; ++i) {
289     Adder a = as[i];
290     if (a != null)
291     a.set(0L);
292     }
293 dl 1.1 }
294     }
295    
296     /**
297     * Equivalent to {@code add(1)}.
298     */
299     public void increment() {
300     add(1L);
301     }
302    
303     /**
304     * Equivalent to {@code add(-1)}.
305     */
306     public void decrement() {
307     add(-1L);
308     }
309    
310     /**
311     * Equivalent to {@link #sum} followed by {@link #reset}.
312     *
313     * @return the estimated sum
314     */
315     public long sumAndReset() {
316 dl 1.4 long sum = 0L;
317 dl 1.1 Adder[] as = adders;
318 dl 1.4 if (as != null) {
319     int n = as.length;
320     for (int i = 0; i < n; ++i) {
321     Adder a = as[i];
322     if (a != null) {
323     sum += a.get();
324     a.set(0L);
325     }
326 dl 1.1 }
327     }
328     return sum;
329     }
330    
331     private void writeObject(java.io.ObjectOutputStream s)
332     throws java.io.IOException {
333     s.defaultWriteObject();
334     s.writeLong(sum());
335     }
336    
337     private void readObject(ObjectInputStream s)
338     throws IOException, ClassNotFoundException {
339     s.defaultReadObject();
340     mutex.set(0);
341 dl 1.4 add(s.readLong());
342 dl 1.1 }
343    
344     }