KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SFib


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

13
14 public class SFib extends FJTask {
15
16   // Performance-tuning constant:
17
static int sequentialThreshold = 0;
18   
19   public static void main(String JavaDoc[] args) {
20     try {
21       int procs;
22       // int num;
23
try {
24         procs = Integer.parseInt(args[0]);
25         // num = Integer.parseInt(args[1]);
26
if (args.length > 2) sequentialThreshold = Integer.parseInt(args[2]);
27       }
28       catch (Exception JavaDoc e) {
29         System.out.println("Usage: java SFib <threads> <number> [<sequntialThreshold>]");
30         return;
31       }
32
33       FJTaskRunnerGroup group = new FJTaskRunnerGroup(procs);
34       ServerSocket socket = new ServerSocket(1618);
35       for (;;) {
36          final Socket connection = socket.accept();
37          group.execute(new Handler(connection));
38       }
39
40     }
41     catch (Exception JavaDoc e) { e.printStackTrace(); }
42   }
43
44   static class Handler extends FJTask {
45     final Socket s;
46     Handler(Socket s) { this.s = s; }
47     public void run() {
48       try {
49         DataInputStream i = new DataInputStream(s.getInputStream());
50         DataOutputStream o = new DataOutputStream(s.getOutputStream());
51         int n = i.readInt();
52         SFib f = new SFib(n);
53         invoke(f);
54         o.writeInt(f.getAnswer());
55       }
56       catch (Exception JavaDoc e) { e.printStackTrace(); }
57     }
58   }
59
60
61   // Initialized with argument; replaced with result
62
volatile int number;
63
64   SFib(int n) { number = n; }
65
66   int getAnswer() {
67     if (!isDone()) throw new Error JavaDoc("Not yet computed");
68     return number;
69   }
70
71
72   public void run() {
73     int n = number;
74
75     // Handle base cases:
76
if (n <= 1) {
77       // Do nothing: fib(0) = 0; fib(1) = 1
78
}
79     // Use sequential code for small problems:
80
else if (n <= sequentialThreshold) {
81       number = seqFib(n);
82     }
83     // Otherwise use recursive parallel decomposition:
84
else {
85       // Construct subtasks:
86
SFib f1 = new SFib(n - 1);
87       SFib f2 = new SFib(n - 2);
88       
89       // Run them in parallel:
90
coInvoke(f1, f2);
91       
92       // Combine results:
93
number = f1.number + f2.number;
94       // (We know numbers are ready, so directly access them.)
95
}
96   }
97
98   // Sequential version for arguments less than threshold
99
static int seqFib(int n) {
100     if (n <= 1)
101       return n;
102     else
103       return seqFib(n-1) + seqFib(n-2);
104   }
105
106 }
107
108
Popular Tags