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 |
import java.util.concurrent.atomic.LongAdder; |
8 |
import java.util.concurrent.Executors; |
9 |
import java.util.concurrent.ExecutorService; |
10 |
import java.util.concurrent.Phaser; |
11 |
|
12 |
public class LongAdderLoops { |
13 |
static final int ITERS = 10000000; |
14 |
static final int NCPU = Runtime.getRuntime().availableProcessors(); |
15 |
static final int MAX_THREADS = NCPU * 2; |
16 |
static final long NPS = (1000L * 1000 * 1000); |
17 |
|
18 |
static final ExecutorService pool = Executors.newCachedThreadPool(); |
19 |
|
20 |
public static void main(String[] args) { |
21 |
for (int i = 1; i < MAX_THREADS; ++i) |
22 |
adderTest(i, ITERS); |
23 |
pool.shutdown(); |
24 |
} |
25 |
|
26 |
static void adderTest(int nthreads, int incs) { |
27 |
System.out.print("LongAdder "); |
28 |
Phaser phaser = new Phaser(nthreads + 1); |
29 |
LongAdder a = new LongAdder(); |
30 |
for (int i = 0; i < nthreads; ++i) |
31 |
pool.execute(new AdderTask(a, phaser, incs)); |
32 |
report(nthreads, incs, timeTasks(phaser), a.sum()); |
33 |
} |
34 |
|
35 |
static void report(int nthreads, int incs, long time, long sum) { |
36 |
long total = (long)nthreads * incs; |
37 |
if (sum != total) |
38 |
throw new Error(sum + " != " + total); |
39 |
double secs = (double)time / (1000L * 1000 * 1000); |
40 |
long rate = total * (1000L) / time; |
41 |
System.out.printf("threads:%3d Time: %7.3fsec Incs per microsec: %4d\n", |
42 |
nthreads, secs, rate); |
43 |
} |
44 |
|
45 |
static long timeTasks(Phaser phaser) { |
46 |
phaser.arriveAndAwaitAdvance(); |
47 |
long start = System.nanoTime(); |
48 |
phaser.arriveAndAwaitAdvance(); |
49 |
phaser.arriveAndAwaitAdvance(); |
50 |
return System.nanoTime() - start; |
51 |
} |
52 |
|
53 |
static final class AdderTask implements Runnable { |
54 |
final LongAdder adder; |
55 |
final Phaser phaser; |
56 |
final int incs; |
57 |
volatile long result; |
58 |
AdderTask(LongAdder adder, Phaser phaser, int incs) { |
59 |
this.adder = adder; |
60 |
this.phaser = phaser; |
61 |
this.incs = incs; |
62 |
} |
63 |
|
64 |
public void run() { |
65 |
phaser.arriveAndAwaitAdvance(); |
66 |
phaser.arriveAndAwaitAdvance(); |
67 |
LongAdder a = adder; |
68 |
for (int i = 0; i < incs; ++i) |
69 |
a.increment(); |
70 |
result = a.sum(); |
71 |
phaser.arrive(); |
72 |
} |
73 |
} |
74 |
|
75 |
} |