1 |
/* |
2 |
* Written by Martin Buchholz 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.Collections; |
8 |
import java.util.concurrent.Callable; |
9 |
import java.util.concurrent.CyclicBarrier; |
10 |
import java.util.concurrent.ExecutorService; |
11 |
import java.util.concurrent.Executors; |
12 |
import java.util.concurrent.TimeUnit; |
13 |
import java.util.concurrent.locks.ReentrantLock; |
14 |
|
15 |
/** |
16 |
* Measures repeated futile timed attempts to acquire a ReentrantLock. |
17 |
* Hard to draw any conclusions from. |
18 |
*/ |
19 |
public final class FutileTimedTryLockLoops { |
20 |
|
21 |
static Callable<Void> tryLocker(ReentrantLock lock, long iters, long nanos) { |
22 |
return new Callable<Void>() { |
23 |
public Void call() throws InterruptedException { |
24 |
for (long i = 0; i < iters; i++) |
25 |
if (lock.tryLock(nanos, TimeUnit.NANOSECONDS)) |
26 |
throw new AssertionError(); |
27 |
return null; |
28 |
}}; |
29 |
} |
30 |
|
31 |
public static void main(String[] args) throws Exception { |
32 |
int minThreads = 1; |
33 |
int maxThreads = 4; |
34 |
long nanos = 1001L; |
35 |
long iters = 60_000_000L; |
36 |
nextArg: for (String arg : args) { |
37 |
String[] fields = arg.split("="); |
38 |
if (fields.length == 2) { |
39 |
String prop = fields[0], val = fields[1]; |
40 |
switch (prop) { |
41 |
case "threads": |
42 |
minThreads = maxThreads = Integer.valueOf(val); |
43 |
continue nextArg; |
44 |
case "minThreads": |
45 |
minThreads = Integer.valueOf(val); |
46 |
continue nextArg; |
47 |
case "maxThreads": |
48 |
maxThreads = Integer.valueOf(val); |
49 |
continue nextArg; |
50 |
case "nanos": |
51 |
nanos = Long.valueOf(val); |
52 |
continue nextArg; |
53 |
case "iters": |
54 |
iters = Long.valueOf(val); |
55 |
continue nextArg; |
56 |
} |
57 |
} |
58 |
throw new Error("Usage: FutileTimedTryLockLoops minThreads=n maxThreads=n threads=n nanos=n iters=n"); |
59 |
} |
60 |
final ExecutorService pool = Executors.newCachedThreadPool(); |
61 |
final ReentrantLock lock = new ReentrantLock(); |
62 |
final Callable<Void> task = tryLocker(lock, iters, nanos); |
63 |
lock.lock(); |
64 |
|
65 |
for (int i = minThreads; i <= maxThreads; i += (i+1) >>> 1) { |
66 |
// warmup |
67 |
if (i == minThreads) |
68 |
pool.invokeAll(Collections.nCopies(i, task)); |
69 |
|
70 |
long startTime = System.nanoTime(); |
71 |
pool.invokeAll(Collections.nCopies(i, task)); |
72 |
long elapsed = System.nanoTime() - startTime; |
73 |
System.out.printf |
74 |
("Threads: %d, %d ms total, %d ns/iter, overhead %d ns/iter%n", |
75 |
i, |
76 |
elapsed / (1000*1000), |
77 |
elapsed / iters, |
78 |
(elapsed / iters) - nanos); |
79 |
} |
80 |
pool.shutdown(); |
81 |
} |
82 |
} |