KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > FibVCB


1 import EDU.oswego.cs.dl.util.concurrent.*;
2
3
4 /**
5  * Callback version of Fibonacci. Computes:
6  * <pre>
7  * Computes fibonacci(n) = fibonacci(n-1) + fibonacci(n-2); for n> 1
8  * fibonacci(0) = 0;
9  * fibonacci(1) = 1.
10  * </pre>
11  **/

12
13 public class FibVCB extends FJTask {
14
15   // Performance-tuning constant:
16
static int sequentialThreshold = 1;
17   
18   public static void main(String JavaDoc[] args) {
19     try {
20       int procs;
21       int num;
22       try {
23         procs = Integer.parseInt(args[0]);
24         num = Integer.parseInt(args[1]);
25         if (args.length > 2) sequentialThreshold = Integer.parseInt(args[2]);
26       }
27       catch (Exception JavaDoc e) {
28         System.out.println("Usage: java FibVCB <threads> <number> [<sequntialThreshold>]");
29         return;
30       }
31
32       FJTaskRunnerGroup g = new FJTaskRunnerGroup(procs);
33       FibVCB f = new FibVCB(num, null);
34       g.invoke(f);
35       g.stats();
36
37       long result = f.getAnswer();
38       System.out.println("FibVCB: Size: " + num + " Answer: " + result);
39     }
40     catch (InterruptedException JavaDoc ex) {}
41   }
42
43
44   volatile int number = 0;
45   final FibVCB parent; // callback target
46
int callbacksExpected = 0;
47   volatile int callbacksReceived = 0;
48
49   FibVCB(int n, FibVCB p) { number = n; parent = p; }
50
51   // Callback method called from subtasks upon completion
52
synchronized void addResult(int n) {
53     number += n;
54     ++callbacksReceived;
55   }
56
57   synchronized int getAnswer() {
58     if (!isDone()) throw new Error JavaDoc("Not yet computed");
59     return number;
60   }
61   
62   public void run() { // same structure as join-based version
63
int n = number;
64     
65     if (n <= 1) {
66       // nothing
67
}
68
69     else if (n <= sequentialThreshold) {
70       number = seqFib(n);
71     }
72
73     else {
74       // clear number so subtasks can fill in
75
number = 0;
76
77       // establish number of callbacks expected
78
callbacksExpected = 2;
79
80
81       new FibVCB(n - 1, this).fork();
82       new FibVCB(n - 2, this).fork();
83
84       // Wait for callbacks from children
85
while (callbacksReceived < callbacksExpected) yield();
86     }
87
88     // Call back parent
89
if (parent != null) parent.addResult(number);
90   }
91
92
93   // Sequential version for arguments less than threshold
94
static int seqFib(int n) {
95     if (n <= 1)
96       return n;
97     else
98       return seqFib(n-1) + seqFib(n-2);
99   }
100
101 }
102
103
Popular Tags