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.Random; |
8 |
import java.util.Queue; |
9 |
|
10 |
public class UnboundedQueueFillEmptyLoops { |
11 |
static int maxSize = 50000; |
12 |
static Random rng = new Random(3153122688L); |
13 |
static volatile int total; |
14 |
static Integer[] numbers; |
15 |
|
16 |
public static void main(String[] args) throws Exception { |
17 |
if (args.length < 1) { |
18 |
System.out.printf( |
19 |
"Usage: UnboundedQueueFillEmptyLoops className [maxSize]%n"); |
20 |
System.exit(1); |
21 |
} |
22 |
|
23 |
final Class<?> klass; |
24 |
try { |
25 |
klass = Class.forName(args[0]); |
26 |
} catch (ClassNotFoundException e) { |
27 |
throw new RuntimeException("Class " + args[0] + " not found."); |
28 |
} |
29 |
|
30 |
if (args.length > 1) |
31 |
maxSize = Integer.parseInt(args[1]); |
32 |
|
33 |
System.out.printf("Class: %s size: %d%n", klass.getName(), maxSize); |
34 |
|
35 |
numbers = new Integer[maxSize]; |
36 |
for (int i = 0; i < maxSize; ++i) |
37 |
numbers[i] = rng.nextInt(128); |
38 |
|
39 |
oneRun(klass, maxSize); |
40 |
Thread.sleep(100); |
41 |
oneRun(klass, maxSize); |
42 |
Thread.sleep(100); |
43 |
oneRun(klass, maxSize); |
44 |
|
45 |
if (total == 0) System.out.print(" "); |
46 |
} |
47 |
|
48 |
static void oneRun(Class<?> klass, int n) throws Exception { |
49 |
Queue<Integer> q = |
50 |
(Queue<Integer>) klass.getConstructor().newInstance(); |
51 |
int sum = total; |
52 |
int m = rng.nextInt(numbers.length); |
53 |
long startTime = System.nanoTime(); |
54 |
for (int k = 0; k < n; ++k) { |
55 |
for (int i = 0; i < k; ++i) { |
56 |
if (m >= numbers.length) |
57 |
m = 0; |
58 |
q.offer(numbers[m++]); |
59 |
} |
60 |
for (Integer p; (p = q.poll()) != null; ) |
61 |
sum += p.intValue(); |
62 |
} |
63 |
total += sum; |
64 |
long endTime = System.nanoTime(); |
65 |
long time = endTime - startTime; |
66 |
double secs = (double) time / 1000000000.0; |
67 |
System.out.println("Time: " + secs); |
68 |
} |
69 |
|
70 |
} |