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/licenses/publicdomain |
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 |
|
15 |
public class CyclicBarrierLoops { |
16 |
static final int NCPUS = Runtime.getRuntime().availableProcessors(); |
17 |
static final ExecutorService pool = Executors.newCachedThreadPool(); |
18 |
static final int FIRST_SIZE = 10000; |
19 |
static final int LAST_SIZE = 1000000; |
20 |
/** for time conversion */ |
21 |
static final long NPS = (1000L * 1000 * 1000); |
22 |
|
23 |
static final class CyclicBarrierAction implements Runnable { |
24 |
final int id; |
25 |
final int size; |
26 |
final CyclicBarrier barrier; |
27 |
public CyclicBarrierAction(int id, CyclicBarrier b, int size) { |
28 |
this.id = id; |
29 |
this.barrier = b; |
30 |
this.size = size; |
31 |
} |
32 |
|
33 |
|
34 |
public void run() { |
35 |
try { |
36 |
int n = size; |
37 |
CyclicBarrier b = barrier; |
38 |
for(int i = 0; i < n; ++i) |
39 |
b.await(); |
40 |
} |
41 |
catch(Exception ex) { |
42 |
throw new Error(ex); |
43 |
} |
44 |
} |
45 |
} |
46 |
|
47 |
public static void main(String[] args) throws Exception { |
48 |
int nthreads = NCPUS; |
49 |
|
50 |
if (args.length > 0) |
51 |
nthreads = Integer.parseInt(args[0]); |
52 |
|
53 |
System.out.printf("max %d Threads\n", nthreads); |
54 |
|
55 |
for (int k = 2; k <= nthreads; k *= 2) { |
56 |
for (int size = FIRST_SIZE; size <= LAST_SIZE; size *= 10) { |
57 |
long startTime = System.nanoTime(); |
58 |
|
59 |
CyclicBarrier barrier = new CyclicBarrier(k); |
60 |
CyclicBarrierAction[] actions = new CyclicBarrierAction[k]; |
61 |
for (int i = 0; i < k; ++i) { |
62 |
actions[i] = new CyclicBarrierAction(i, barrier, size); |
63 |
} |
64 |
|
65 |
Future[] futures = new Future[k]; |
66 |
for (int i = 0; i < k; ++i) { |
67 |
futures[i] = pool.submit(actions[i]); |
68 |
} |
69 |
for (int i = 0; i < k; ++i) { |
70 |
futures[i].get(); |
71 |
} |
72 |
long elapsed = System.nanoTime() - startTime; |
73 |
long bs = (NPS * size) / elapsed; |
74 |
System.out.printf("%4d Threads %8d iters: %11d barriers/sec\n", |
75 |
k, size, bs); |
76 |
} |
77 |
} |
78 |
pool.shutdown(); |
79 |
} |
80 |
|
81 |
} |
82 |
|
83 |
|