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.*; |
8 |
|
9 |
public final class DynamicFib extends RecursiveAction { |
10 |
static int procs; |
11 |
static long lastStealCount; // to display steal counts |
12 |
|
13 |
/** for time conversion */ |
14 |
static final long NPS = (1000L * 1000 * 1000); |
15 |
|
16 |
public static void main(String[] args) throws Exception { |
17 |
procs = 0; |
18 |
int num = 45; |
19 |
try { |
20 |
if (args.length > 0) |
21 |
procs = Integer.parseInt(args[0]); |
22 |
if (args.length > 1) |
23 |
num = Integer.parseInt(args[1]); |
24 |
} |
25 |
catch (Exception e) { |
26 |
System.out.println("Usage: java DynamicFib <threads> <number>"); |
27 |
return; |
28 |
} |
29 |
for (int reps = 0; reps < 2; ++reps) { |
30 |
ForkJoinPool pool = (procs == 0) ? new ForkJoinPool() : |
31 |
new ForkJoinPool(procs); |
32 |
for (int i = 0; i < 20; ++i) |
33 |
test(pool, num); |
34 |
System.out.println(pool); |
35 |
pool.shutdown(); |
36 |
} |
37 |
} |
38 |
|
39 |
static void test(ForkJoinPool pool, int num) throws Exception { |
40 |
int ps = pool.getParallelism(); |
41 |
long start = System.nanoTime(); |
42 |
DynamicFib f = new DynamicFib(num); |
43 |
pool.invoke(f); |
44 |
long time = System.nanoTime() - start; |
45 |
double secs = ((double)time) / NPS; |
46 |
long result = f.number; |
47 |
System.out.print("DynamicFib " + num + " = " + result); |
48 |
System.out.printf("\tTime: %9.3f", secs); |
49 |
long sc = pool.getStealCount(); |
50 |
long ns = sc - lastStealCount; |
51 |
lastStealCount = sc; |
52 |
System.out.printf(" Steals: %4d", ns/ps); |
53 |
System.out.printf(" Workers: %4d", pool.getPoolSize()); |
54 |
System.out.println(); |
55 |
} |
56 |
|
57 |
int number; // Initialized with argument; replaced with result |
58 |
DynamicFib(int n) { number = n; } |
59 |
public void compute() { |
60 |
number = fib(number); |
61 |
} |
62 |
|
63 |
static int fib(int n) { |
64 |
int res; |
65 |
if (n <= 1) |
66 |
res = n; |
67 |
else if (getSurplusQueuedTaskCount() >= 4) |
68 |
res = seqFib(n); |
69 |
else { |
70 |
DynamicFib f2 = new DynamicFib(n - 2); |
71 |
f2.fork(); |
72 |
res = fib(n - 1); |
73 |
if (f2.tryUnfork()) |
74 |
res += fib(n - 2); |
75 |
else { |
76 |
f2.quietlyJoin(); |
77 |
res += f2.number; |
78 |
} |
79 |
} |
80 |
return res; |
81 |
} |
82 |
|
83 |
// Sequential version for arguments less than threshold |
84 |
static final int seqFib(int n) { // unroll left only |
85 |
int r = 1; |
86 |
do { |
87 |
int m = n - 2; |
88 |
r += m <= 1 ? m : seqFib(m); |
89 |
} while (--n > 1); |
90 |
return r; |
91 |
} |
92 |
|
93 |
} |