1 |
/* |
2 |
* @test %I% %E% |
3 |
* @bug 166 |
4 |
* @compile -source 1.5 ExecutorCompletionServiceLoops.java |
5 |
* @run main/timeout=3600 ExecutorCompletionServiceLoops |
6 |
* @summary Exercise ExecutorCompletionServiceLoops |
7 |
*/ |
8 |
/* |
9 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
10 |
* Expert Group and released to the public domain. Use, modify, and |
11 |
* redistribute this code in any way without acknowledgement. |
12 |
*/ |
13 |
|
14 |
import java.util.concurrent.*; |
15 |
|
16 |
public class ExecutorCompletionServiceLoops { |
17 |
static final int POOLSIZE = 100; |
18 |
static final ExecutorService pool = |
19 |
Executors.newFixedThreadPool(POOLSIZE); |
20 |
static final ExecutorCompletionService<Integer> ecs = |
21 |
new ExecutorCompletionService<Integer>(pool); |
22 |
static boolean print = false; |
23 |
|
24 |
public static void main(String[] args) throws Exception { |
25 |
int max = 8; |
26 |
int base = 10000; |
27 |
|
28 |
if (args.length > 0) |
29 |
max = Integer.parseInt(args[0]); |
30 |
|
31 |
System.out.println("Warmup..."); |
32 |
oneTest( base ); |
33 |
Thread.sleep(100); |
34 |
print = true; |
35 |
|
36 |
for (int i = 1; i <= max; i += (i+1) >>> 1) { |
37 |
System.out.print("n: " + i * base); |
38 |
oneTest(i * base ); |
39 |
Thread.sleep(100); |
40 |
} |
41 |
pool.shutdown(); |
42 |
} |
43 |
|
44 |
static class Task implements Callable<Integer> { |
45 |
public Integer call() { |
46 |
int l = System.identityHashCode(this); |
47 |
l = LoopHelpers.compute2(l); |
48 |
int s = LoopHelpers.compute1(l); |
49 |
l = LoopHelpers.compute2(l); |
50 |
s += LoopHelpers.compute1(l); |
51 |
return new Integer(s); |
52 |
} |
53 |
} |
54 |
|
55 |
static class Producer implements Runnable { |
56 |
final ExecutorCompletionService cs; |
57 |
final int iters; |
58 |
Producer(ExecutorCompletionService ecs, int i) { |
59 |
cs = ecs; |
60 |
iters = i; |
61 |
} |
62 |
public void run() { |
63 |
for (int i = 0; i < iters; ++i) |
64 |
ecs.submit(new Task()); |
65 |
} |
66 |
} |
67 |
|
68 |
static void oneTest(int iters) throws Exception { |
69 |
long startTime = System.nanoTime(); |
70 |
new Thread(new Producer(ecs, iters)).start(); |
71 |
|
72 |
int r = 0; |
73 |
for (int i = 0; i < iters; ++i) |
74 |
r += ecs.take().get().intValue(); |
75 |
|
76 |
long elapsed = System.nanoTime() - startTime; |
77 |
long tpi = elapsed/ iters; |
78 |
|
79 |
if (print) |
80 |
System.out.println("\t: " + LoopHelpers.rightJustify(tpi) + " ns per task"); |
81 |
|
82 |
if (r == 0) // avoid overoptimization |
83 |
System.out.println("useless result: " + r); |
84 |
|
85 |
|
86 |
} |
87 |
|
88 |
} |