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.*; |
8 |
import java.util.concurrent.*; |
9 |
//import jsr166y.*; |
10 |
|
11 |
/** |
12 |
* Based loosely on Java Grande Forum barrierBench |
13 |
*/ |
14 |
public class FJPhaserLoops { |
15 |
static final int NCPUS = Runtime.getRuntime().availableProcessors(); |
16 |
static final int FIRST_SIZE = 10000; |
17 |
static final int LAST_SIZE = 1000000; |
18 |
/** for time conversion */ |
19 |
static final long NPS = (1000L * 1000 * 1000); |
20 |
|
21 |
static final class PhaserAction extends RecursiveAction { |
22 |
final int id; |
23 |
final int size; |
24 |
final Phaser phaser; |
25 |
public PhaserAction(int id, Phaser b, int size) { |
26 |
this.id = id; |
27 |
this.phaser = b; |
28 |
this.size = size; |
29 |
phaser.register(); |
30 |
} |
31 |
|
32 |
public void compute() { |
33 |
int n = size; |
34 |
Phaser b = phaser; |
35 |
for (int i = 0; i < n; ++i) |
36 |
b.arriveAndAwaitAdvance(); |
37 |
} |
38 |
} |
39 |
|
40 |
public static void main(String[] args) throws Exception { |
41 |
int nthreads = NCPUS; |
42 |
if (args.length > 0) |
43 |
nthreads = Integer.parseInt(args[0]); |
44 |
|
45 |
System.out.printf("max %d Threads\n", nthreads); |
46 |
|
47 |
for (int k = 2; k <= nthreads; k *= 2) { |
48 |
ForkJoinPool pool = new ForkJoinPool(k); |
49 |
|
50 |
for (int size = FIRST_SIZE; size <= LAST_SIZE; size *= 10) { |
51 |
long startTime = System.nanoTime(); |
52 |
|
53 |
Phaser phaser = new Phaser(); |
54 |
final PhaserAction[] actions = new PhaserAction[k]; |
55 |
for (int i = 0; i < k; ++i) { |
56 |
actions[i] = new PhaserAction(i, phaser, size); |
57 |
} |
58 |
|
59 |
pool.invoke(new RecursiveAction() { |
60 |
public void compute() { invokeAll(actions); }}); |
61 |
|
62 |
long elapsed = System.nanoTime() - startTime; |
63 |
long bs = (NPS * size) / elapsed; |
64 |
System.out.printf("%4d Threads %8d iters: %11d barriers/sec\n", |
65 |
k, size, bs); |
66 |
} |
67 |
pool.shutdown(); |
68 |
} |
69 |
} |
70 |
|
71 |
} |