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