initial commit
[fleet.git] / src / edu / berkeley / fleet / Ship.java
1 package edu.berkeley.fleet;
2
3 import edu.berkeley.sbp.*;
4 import edu.berkeley.sbp.chr.*;
5 import edu.berkeley.sbp.misc.*;
6 import edu.berkeley.sbp.meta.*;
7 import edu.berkeley.sbp.bind.*;
8 import edu.berkeley.sbp.util.*;
9 import java.util.*;
10 import java.io.*;
11
12 public abstract class Ship {
13
14     HashMap<String,Inbox> inboxes = new HashMap<String,Inbox>();
15     HashMap<String,Outbox> outboxes = new HashMap<String,Outbox>();
16     private String name;
17     protected Fleet fleet;
18
19     /** You should instantiate a bunch of Inboxes and Outboxes in your constructor */
20     public Ship(Fleet fleet, String name) {
21         this.name = name;
22         this.fleet = fleet;
23         fleet.ships.put(name, this);
24     }
25
26     public String toString() { return name; }
27
28     /**
29      *  Override this method, check inboxes for the data you need, and
30      *  if you find it, deposit results in an outbox; we'll take care
31      *  of the rest.
32      */
33     public abstract void service();
34
35     public final void _service() {
36         for(Outbox ob : outboxes.values()) {
37             if (!ob.data.isEmpty() && !ob.destination.isEmpty()) {
38                 int data = ob.data.remove();
39                 Inbox destination = ob.destination.remove();
40                 destination.add(data);
41                 System.out.println("data:  " + ob + " ----("+data+")----> " + destination);
42             }
43         }
44         service();
45     }
46
47     public class Inbox {
48         private String name;
49         private Queue<Integer> queue = new LinkedList<Integer>();
50         public boolean empty() { return queue.isEmpty(); }
51         public void add(int data) { queue.add(data); }
52         public int remove() { return queue.remove(); }
53         public String toString() { return Ship.this.name+"."+name; }
54         public Inbox(String name) {
55             this.name = name;
56             Ship.this.inboxes.put(name, this);
57         }
58     }
59
60     public class Outbox {
61         private String name;
62         public Queue<Integer> data = new LinkedList<Integer>();
63         public Queue<Inbox> destination = new LinkedList<Inbox>();
64         public void add(int data) { this.data.add(data); }
65         public void addDestination(Inbox destination) { this.destination.add(destination); }
66         public boolean empty() { return data.isEmpty(); }
67         public String toString() { return Ship.this.name+"."+name; }
68         public Outbox(String name) {
69             this.name = name;
70             Ship.this.outboxes.put(name, this);
71         }
72     }
73 }