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.CyclicBarrier; |
8 |
import java.util.concurrent.ExecutorService; |
9 |
import java.util.concurrent.Executors; |
10 |
import java.util.concurrent.locks.ReentrantLock; |
11 |
|
12 |
public final class LockOncePerThreadLoops { |
13 |
static final ExecutorService pool = Executors.newCachedThreadPool(); |
14 |
static final LoopHelpers.SimpleRandom rng = new LoopHelpers.SimpleRandom(); |
15 |
static boolean print = false; |
16 |
static int nlocks = 500000; |
17 |
static int nthreads = 100; |
18 |
static int replications = 20; |
19 |
|
20 |
public static void main(String[] args) throws Exception { |
21 |
if (args.length > 0) |
22 |
replications = Integer.parseInt(args[0]); |
23 |
|
24 |
if (args.length > 1) |
25 |
nlocks = Integer.parseInt(args[1]); |
26 |
|
27 |
print = true; |
28 |
|
29 |
for (int i = 0; i < replications; ++i) { |
30 |
System.out.print("Iteration: " + i); |
31 |
new ReentrantLockLoop().test(); |
32 |
Thread.sleep(100); |
33 |
} |
34 |
pool.shutdown(); |
35 |
} |
36 |
|
37 |
static final class ReentrantLockLoop implements Runnable { |
38 |
private int v = rng.next(); |
39 |
private volatile int result = 17; |
40 |
final ReentrantLock[]locks = new ReentrantLock[nlocks]; |
41 |
|
42 |
private final ReentrantLock lock = new ReentrantLock(); |
43 |
private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer(); |
44 |
private final CyclicBarrier barrier; |
45 |
ReentrantLockLoop() { |
46 |
barrier = new CyclicBarrier(nthreads+1, timer); |
47 |
for (int i = 0; i < nlocks; ++i) |
48 |
locks[i] = new ReentrantLock(); |
49 |
} |
50 |
|
51 |
final void test() throws Exception { |
52 |
for (int i = 0; i < nthreads; ++i) |
53 |
pool.execute(this); |
54 |
barrier.await(); |
55 |
barrier.await(); |
56 |
if (print) { |
57 |
long time = timer.getTime(); |
58 |
double secs = (double) time / 1000000000.0; |
59 |
System.out.println("\t " + secs + "s run time"); |
60 |
} |
61 |
|
62 |
int r = result; |
63 |
if (r == 0) // avoid overoptimization |
64 |
System.out.println("useless result: " + r); |
65 |
} |
66 |
|
67 |
public final void run() { |
68 |
try { |
69 |
barrier.await(); |
70 |
int sum = v; |
71 |
int x = 0; |
72 |
for (int i = 0; i < locks.length; ++i) { |
73 |
locks[i].lock(); |
74 |
try { |
75 |
v = x += ~(v - i); |
76 |
} |
77 |
finally { |
78 |
locks[i].unlock(); |
79 |
} |
80 |
// Once in a while, do something more expensive |
81 |
if ((~i & 255) == 0) { |
82 |
sum += LoopHelpers.compute1(LoopHelpers.compute2(x)); |
83 |
} |
84 |
else |
85 |
sum += sum ^ x; |
86 |
} |
87 |
barrier.await(); |
88 |
result += sum; |
89 |
} |
90 |
catch (Exception ie) { |
91 |
return; |
92 |
} |
93 |
} |
94 |
} |
95 |
|
96 |
} |